Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

Money pulse, animated USDZ, 500 page; galaxy, marketplace and IRL pins updates

nirholas642695a2730d
diff --git a/api/_lib/http.js b/api/_lib/http.js
index 4cba72835..9d98227cc 100644
--- a/api/_lib/http.js
+++ b/api/_lib/http.js
@@ -126,6 +126,30 @@ export function redactUrl(rawUrl) {
return qs ? `${path}?${qs}` : path;
}
+// Distinguish a real top-level browser navigation from a programmatic API / agent
+// call. Browsers stamp `Sec-Fetch-Mode: navigate` ONLY on top-level navigations;
+// fetch()/XHR send cors|same-origin|no-cors. Clients without Sec-Fetch headers
+// fall back to an Accept that prefers HTML. Used so a human who hits a 5xx is
+// sent to the branded /500 page (carrying their support ref) while every API /
+// agent caller keeps receiving the JSON error envelope it expects.
+function wantsHtmlNavigation(req) {
+ const m = req?.method || 'GET';
+ if (m !== 'GET' && m !== 'HEAD') return false;
+ const mode = req?.headers?.['sec-fetch-mode'];
+ if (mode) return mode === 'navigate';
+ const accept = String(req?.headers?.['accept'] || '');
+ return accept.includes('text/html');
+}
+
+// Build the /500 redirect target for a browser navigation that 5xx'd: the ref so
+// the page can show + copy it, and the original (redacted) path so "Try again"
+// retries the request that actually failed. redactUrl() keeps geo / tokens out of
+// this URL too, since it ends up in the address bar and any referrer log.
+function serverErrorPageLocation(ref, req) {
+ const from = redactUrl(req?.url || '/').slice(0, 512);
+ return `/500?ref=${encodeURIComponent(ref)}&from=${encodeURIComponent(from)}`;
+}
+
// Short, URL-safe correlation id for tying a sanitized 5xx response back to the
// full server-side log line. Not security-sensitive — just needs to be unique.
function correlationId() {
@@ -365,11 +389,18 @@ export function wrap(handler) {
// so err.message would leak HELIUS_API_KEY to the client. Hand back a
// sanitized envelope keyed to the same ref we just logged.
if (!res.headersSent && !res.writableEnded) {
- json(res, status, {
- error: err.code || 'internal_error',
- error_description: `internal error — quote ref ${ref} to support`,
- ref,
- }, { 'cache-control': 'no-store' });
+ if (wantsHtmlNavigation(req)) {
+ // A human navigated into this 5xx — send them to the branded
+ // error page with their ref instead of a raw JSON blob. API and
+ // agent callers (no `Sec-Fetch-Mode: navigate`) keep the envelope.
+ redirect(res, serverErrorPageLocation(ref, req), 303);
+ } else {
+ json(res, status, {
+ error: err.code || 'internal_error',
+ error_description: `internal error — quote ref ${ref} to support`,
+ ref,
+ }, { 'cache-control': 'no-store' });
+ }
}
} else if (!res.headersSent && !res.writableEnded) {
if (err.code === 'validation_error' && Array.isArray(err.issues)) {
diff --git a/api/irl/pins.js b/api/irl/pins.js
index 1e6108fce..12fafb255 100644
--- a/api/irl/pins.js
+++ b/api/irl/pins.js
@@ -900,6 +900,84 @@ export default wrap(async (req, res) => {
// req.query / lat / lng on this path. Privacy-minded clients additionally
// coarsen the origin they send (see discoveryOrigin() in src/irl.js), so the
// exact device position need never reach the server at all.
+
+ // ── GET — marker room read (Epic M) ──────────────────────────────────────
+ // Indoor colocalization can't use the GPS proximity feed: GPS is ±20–50 m
+ // inside a building and never agrees phone-to-phone. Instead a MARKER room is
+ // keyed by a QR both phones can see — its id (`m-<hash>`) is derived from the
+ // QR payload (src/irl/marker-anchor.js markerRoomId), so a viewer who scanned
+ // the marker can read its pins by room_id with NO location at all. This is
+ // capability-gated by knowing the QR: the id is unguessable without having
+ // physically seen the marker, which is the same "be present to discover"
+ // contract the proximity feed enforces with GPS. Restricted to marker rooms
+ // (`m-` prefix) so a GPS room (`r-…`) can never be read here, bypassing its
+ // fix-token gate. Still IP rate-limited by the publicIp ceiling applied above.
+ if (req.method === 'GET' && req.query.room != null) {
+ const roomId = String(req.query.room);
+ if (!ROOM_ID_RE.test(roomId)) {
+ return json(res, 400, { error: 'invalid room id' });
+ }
+ if (!roomId.startsWith('m-')) {
+ // GPS rooms are readable only through the fix-gated proximity feed.
+ return json(res, 404, { error: 'not a marker room' });
+ }
+
+ const session = await getSessionUser(req).catch(() => null);
+ const myId = session?.id ?? null;
+ const myTok = readDeviceToken(req);
+
+ const rows = await sql`
+ SELECT id, user_id, device_token, agent_id, lat, lng, heading,
+ avatar_url, avatar_name, caption, x402_endpoint, placed_at, view_count,
+ anchor_height_m, anchor_yaw_deg, anchor_quat,
+ gps_accuracy_m, altitude_m, anchor_source, avatar_version,
+ vps_provider, vps_id,
+ room_id, rel_east_m, rel_north_m, origin_lat, origin_lng, origin_yaw_deg
+ FROM irl_pins
+ WHERE room_id = ${roomId}
+ AND hidden_at IS NULL
+ AND published IS NOT FALSE
+ AND (expires_at IS NULL OR expires_at > NOW())
+ ORDER BY placed_at DESC
+ LIMIT 50
+ `;
+
+ // Same allow-list projection as the nearby feed: NEVER expose user_id or
+ // device_token. The marker frame (rel_east_m / rel_north_m) is the render-
+ // authoritative pose; lat/lng is only a coarse index here, so coarsen it.
+ const pins = rows.map(r => ({
+ id: r.id,
+ agent_id: r.agent_id,
+ lat: roundCoord(r.lat),
+ lng: roundCoord(r.lng),
+ heading: r.heading,
+ avatar_url: r.avatar_url,
+ avatar_name: r.avatar_name,
+ caption: r.caption,
+ x402_endpoint: r.x402_endpoint,
+ placed_at: r.placed_at,
+ view_count: r.view_count,
+ anchor_height_m: r.anchor_height_m,
+ anchor_yaw_deg: r.anchor_yaw_deg,
+ anchor_quat: r.anchor_quat,
+ gps_accuracy_m: r.gps_accuracy_m,
+ altitude_m: r.altitude_m,
+ anchor_source: r.anchor_source,
+ vps_provider: r.vps_provider ?? null,
+ vps_id: r.vps_id ?? null,
+ room_id: r.room_id ?? null,
+ rel_east_m: r.rel_east_m,
+ rel_north_m: r.rel_north_m,
+ origin_lat: roundCoord(r.origin_lat),
+ origin_lng: roundCoord(r.origin_lng),
+ origin_yaw_deg: r.origin_yaw_deg,
+ avatar_version: Number(r.avatar_version) || 0,
+ is_mine: (!!myId && r.user_id === myId) || (!!myTok && r.device_token === myTok),
+ }));
+
+ return json(res, 200, { pins, room_id: roomId });
+ }
+
if (req.method === 'GET') {
const lat = parseFloat(req.query.lat);
const lng = parseFloat(req.query.lng);
@@ -1164,11 +1242,26 @@ export default wrap(async (req, res) => {
// 'webxr' (A1) · 'gyro-gps' (absolute compass heading) · 'gyro-gps:rel'
// (page-relative heading only — A3 down-weights its cross-user bearing) ·
// 'map' (L2: a point chosen on the map, not a live fix — its bearing isn't
- // compass-trustworthy, same down-weighting as ':rel').
+ // compass-trustworthy, same down-weighting as ':rel') · 'marker' (Epic M: a
+ // visual QR marker is the shared origin; GPS is only a coarse index and the
+ // frame is reconstructed live per viewer from the marker, not from compass).
const anchorSource = pose.source === 'webxr' ? 'webxr'
: pose.source === 'map' ? 'map'
+ : pose.source === 'marker' ? 'marker'
: pose.source === 'gyro-gps:rel' ? 'gyro-gps:rel' : 'gyro-gps';
+ // Visual-positioning identity (Epic M) — the long-reserved vps_* columns,
+ // now first written by the marker path: provider is the positioning system
+ // ('qr' for a QR marker) and id is its opaque token (the marker payload).
+ // Both phones derive the room_id from this same token, so it is the key that
+ // lets a second viewer read the room with no GPS. Length-clamped; absent on
+ // every non-marker placement (every existing caller), leaving the columns NULL.
+ const vps = (body.vps && typeof body.vps === 'object') ? body.vps : {};
+ const vpsProvider = anchorSource === 'marker' && typeof vps.provider === 'string'
+ ? vps.provider.slice(0, 32) : null;
+ const vpsId = anchorSource === 'marker' && typeof vps.id === 'string'
+ ? vps.id.slice(0, 256) : null;
+
// Room frame (optional) — when the client places into a shared room it sends
// the exact offset from the room origin. We persist origin + offset as the
// render-authoritative pose; lat/lng above stays the GPS index. An invalid or
@@ -1209,7 +1302,7 @@ export default wrap(async (req, res) => {
anchor_height_m, anchor_yaw_deg, anchor_quat,
gps_accuracy_m, altitude_m, anchor_source, geocell7,
room_id, rel_east_m, rel_north_m, origin_lat, origin_lng, origin_yaw_deg,
- placement_kind, fuzz_radius_m)
+ placement_kind, fuzz_radius_m, vps_provider, vps_id)
VALUES (
${userId},
${body.agentId ?? null},
@@ -1235,7 +1328,9 @@ export default wrap(async (req, res) => {
${originLngV},
${originYawV},
${placementKind},
- ${fuzzRadiusM}
+ ${fuzzRadiusM},
+ ${vpsProvider},
+ ${vpsId}
)
RETURNING *
`;
diff --git a/pages/ibm/hello.html b/pages/ibm/hello.html
index e1763dc6d..dab1bbe9a 100644
--- a/pages/ibm/hello.html
+++ b/pages/ibm/hello.html
@@ -938,59 +938,92 @@ agent-3d:defined ~ .agent-skel{display:none}
</section>
<!-- ══ LIVE DEMO ══ -->
+<!-- ══ DEMO 02 · AVATARS (free text→mesh→auto-rig→animated) ══ -->
+<style id="av-styles">
+.av-forge{margin-top:28px;border:1px solid var(--ibm-divider);background:var(--ibm-surface)}
+.av-head{padding:22px 24px 18px;border-bottom:1px solid var(--ibm-border)}
+.av-head h3{font-size:20px;font-weight:600}
+.av-head h3 span{color:var(--ibm-blue)}
+.av-head p{font-size:13px;color:var(--ibm-muted);font-weight:300;max-width:540px;margin-top:4px;line-height:1.55}
+.av-body{padding:22px 24px}
+.av-field{display:flex;gap:1px;flex-wrap:wrap;background:var(--ibm-border)}
+.av-input{flex:1 1 280px;min-width:0;font-family:var(--font-sans);font-size:15px;color:var(--ibm-ink);background:var(--ibm-surface);border:none;padding:0 16px;height:48px;outline:none}
+.av-input:focus-visible{outline:2px solid var(--ibm-blue);outline-offset:-2px}
+.av-btn{display:inline-flex;align-items:center;justify-content:center;gap:10px;background:var(--ibm-blue-fill);color:#fff;border:none;cursor:pointer;font-family:var(--font-sans);font-size:15px;font-weight:500;padding:0 24px;height:48px;transition:background .12s,transform .04s}
+.av-btn:hover:not(:disabled){background:var(--ibm-blue-fill-hover)}
+.av-btn:active:not(:disabled){transform:translateY(1px)}
+.av-btn:disabled{opacity:.7;cursor:not-allowed}
+.av-btn:focus-visible{outline:2px solid var(--ibm-blue);outline-offset:2px;box-shadow:0 0 0 4px rgba(15,98,254,.25)}
+.av-spin{width:15px;height:15px;border:2px solid rgba(255,255,255,.4);border-top-color:#fff;border-radius:50%;animation:spin .7s linear infinite;display:none}
+.av-btn.loading .av-spin{display:inline-block}
+.av-suggest{display:flex;flex-wrap:wrap;gap:8px;margin-top:14px}
+.av-suggest button{font-family:inherit;font-size:13px;color:var(--ibm-muted);background:transparent;border:1px solid var(--ibm-border);padding:6px 12px;cursor:pointer;transition:border-color .12s,color .12s}
+.av-suggest button:hover{border-color:var(--ibm-blue);color:var(--ibm-blue)}
+/* pipeline step indicator — mesh → rig → animate */
+.av-steps{display:flex;flex-wrap:wrap;gap:8px;margin:20px 0 0;list-style:none;padding:0;counter-reset:av}
+.av-steps li{display:inline-flex;align-items:center;gap:8px;font-size:12px;color:var(--ibm-subtle);font-weight:500;border:1px solid var(--ibm-border);padding:6px 12px;border-radius:2px;transition:color .2s,border-color .2s}
+.av-steps li .dot{width:7px;height:7px;border-radius:50%;background:var(--ibm-divider);flex:0 0 auto;transition:background .2s}
+.av-steps li.active{color:var(--ibm-blue);border-color:var(--ibm-blue)}
+.av-steps li.active .dot{background:var(--ibm-blue);animation:dotpulse 1.2s var(--ease) infinite}
+.av-steps li.done{color:var(--ibm-green-ink);border-color:var(--ibm-green)}
+.av-steps li.done .dot{background:var(--ibm-green)}
+.av-result{margin-top:20px;border:1px solid var(--ibm-border);background:var(--ibm-field)}
+.av-result.is-empty{padding:44px 20px;text-align:center;font-size:14px;color:var(--ibm-subtle);border-style:dashed}
+.av-stage{position:relative;min-height:460px;background:radial-gradient(circle at 50% 30%,#1c2530,#0c1116 70%)}
+.av-stage agent-3d,.av-stage model-viewer{display:block;width:100%;height:460px}
+.av-load{padding:44px 20px}
+.av-bar{display:block;height:3px;background:var(--ibm-border);overflow:hidden;margin-bottom:16px}
+.av-bar span{display:block;height:100%;width:40%;background:var(--ibm-blue);animation:g3dslide 1.3s ease-in-out infinite}
+.av-loadmsg{font-size:14px;color:var(--ibm-muted);text-align:center}
+.av-err{padding:28px 20px;text-align:center}
+.av-err p{font-size:14px;color:var(--ibm-muted);margin:0 auto 16px;max-width:460px;line-height:1.6}
+.av-retry{font-family:inherit;font-size:14px;font-weight:500;color:#fff;background:var(--ibm-blue-fill);border:none;padding:10px 20px;cursor:pointer;transition:background .12s}
+.av-retry:hover{background:var(--ibm-blue-fill-hover)}
+.av-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:14px 16px;border-top:1px solid var(--ibm-border);background:var(--ibm-surface)}
+.av-act{display:inline-flex;align-items:center;font-family:inherit;font-size:14px;font-weight:500;text-decoration:none;padding:9px 16px;border:1px solid var(--ibm-blue);color:var(--ibm-blue);cursor:pointer;transition:background .12s}
+.av-act:hover{background:rgba(15,98,254,.08);text-decoration:none}
+.av-act.primary{background:var(--ibm-blue-fill);color:#fff;border-color:var(--ibm-blue-fill)}
+.av-act.primary:hover{background:var(--ibm-blue-fill-hover)}
+.av-engine{font-size:12px;color:var(--ibm-subtle);margin-left:auto}
+@media(max-width:560px){.av-btn{width:100%}.av-engine{margin-left:0;width:100%}}
+@media(pointer:coarse){.av-act,.av-retry,.av-suggest button{min-height:44px}}
+</style>
<section class="section" id="demo" aria-labelledby="demo-h">
<div class="inner">
- <div class="section-tag">Demo 02 · Payments</div>
- <h2 id="demo-h">Buy a <strong>data call</strong> for $0.001</h2>
- <p class="section-lead">This calls a real three.ws API — a ticker-symbol availability check — for one tenth of a cent in USDC, settled on-chain. The price below is read live from the server's own 402 response.</p>
-
- <div class="demo">
- <div class="demo-head">
- <div>
- <h3 class="demo-title">three<span>.ws</span> Symbol Check</h3>
- <div class="demo-desc">Is a ticker already taken? Returns exact and look-alike matches across symbols indexed by three.ws.</div>
- </div>
- <div class="price-tag">
- <div class="amt" id="priceAmt" aria-hidden="true">$<strong>0.001</strong></div>
- <div class="net" aria-hidden="true">USDC · per call</div>
- <span class="sr-only" id="priceSr">Price: one tenth of a cent in USDC per call.</span>
- </div>
+ <div class="section-tag">Demo 02 · Avatars</div>
+ <h2 id="demo-h">Forge a <strong>living avatar</strong> from a sentence</h2>
+ <p class="section-lead">Describe a character; three.ws generates the textured mesh, auto-rigs a skeleton, and drops it straight into the avatar engine — where it stands, breathes, and waves. Free, no wallet. The same universal rig that lets <em>any</em> humanoid wear our animation library, running live in your browser.</p>
+
+ <div class="av-forge">
+ <div class="av-head">
+ <h3 class="demo-title">three<span>.ws</span> Avatar Forge</h3>
+ <p>Text → textured mesh (Microsoft TRELLIS on NVIDIA NIM) → auto-rigged skeleton → animated avatar. No payment, no API key — a generation lane kept free for everyone.</p>
</div>
-
- <div class="demo-body">
- <!-- live 402 preview -->
- <div class="preview" role="region" aria-label="Live HTTP 402 payment challenge" aria-live="polite" aria-busy="true">
- <div class="preview-label" id="pvLabel"><span class="dot" aria-hidden="true"></span><span id="pvLabelText">Reading the server's 402 challenge…</span></div>
- <div id="pvRows">
- <div class="preview-row"><span class="sk" style="width:38%"></span></div>
- <div class="preview-row"><span class="sk" style="width:54%"></span></div>
- <div class="preview-row"><span class="sk" style="width:46%"></span></div>
- </div>
+ <div class="av-body">
+ <div class="av-field">
+ <label for="avPrompt" class="sr-only">Describe a character to generate</label>
+ <input id="avPrompt" class="av-input" value="a brass steampunk knight, full body" maxlength="600" autocomplete="off" spellcheck="true" inputmode="text">
+ <button id="avBtn" class="av-btn" type="button"><span class="av-spin" aria-hidden="true"></span><span class="av-label">Forge avatar</span> <span aria-hidden="true">→</span></button>
</div>
-
- <!-- input -->
- <div class="field-row">
- <div class="field-wrap">
- <label for="ticker">Ticker to check</label>
- <input id="ticker" class="field" value="GRANITE" maxlength="32" autocomplete="off" spellcheck="false" autocapitalize="characters" inputmode="text" aria-describedby="tickerHint">
- <div class="field-hint" id="tickerHint">A–Z and 0–9, up to 32 characters.</div>
- </div>
- <button id="payBtn" class="btn" type="button"><span class="spin" aria-hidden="true"></span><span class="label">Pay $0.001 &amp; run</span> <span class="arrow" aria-hidden="true">→</span></button>
+ <div class="av-suggest" id="avSuggest" aria-label="Example characters">
+ <button type="button" data-p="a brass steampunk knight, full body">Steampunk knight</button>
+ <button type="button" data-p="a friendly cartoon astronaut, full body">Cartoon astronaut</button>
+ <button type="button" data-p="a wise wizard in a flowing blue robe, full body">Blue wizard</button>
+ <button type="button" data-p="a sleek cyberpunk ninja, full body">Cyberpunk ninja</button>
</div>
- <div class="wallet-hint" id="walletHint">On a phone? Open this page inside your <b>MetaMask</b> or <b>Phantom</b> in-app browser to pay.</div>
- <!-- result. The visible panel is NOT a live region (its success state
- contains a raw-JSON block that would otherwise be read aloud in full).
- Concise spoken updates go to #announcer instead. -->
- <div id="result" class="result is-empty">
- Run the call to see live, on-chain-paid data appear here.
- </div>
- <p id="announcer" class="sr-only" role="status" aria-live="polite"></p>
+ <ol class="av-steps" id="avSteps" aria-hidden="true">
+ <li data-step="mesh"><span class="dot" aria-hidden="true"></span>Generate mesh</li>
+ <li data-step="rig"><span class="dot" aria-hidden="true"></span>Auto-rig skeleton</li>
+ <li data-step="animate"><span class="dot" aria-hidden="true"></span>Animate</li>
+ </ol>
+
+ <div id="avResult" class="av-result is-empty">Forge a character to watch it come to life here.</div>
+ <p id="avStatus" class="sr-only" role="status" aria-live="polite"></p>
- <!-- requirements -->
<div class="note">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>
- <p>You'll need a browser wallet — <b>MetaMask</b> (Base) or <b>Phantom</b> (Solana) — holding at least <b>$0.001 USDC</b> on mainnet. This spends <b>real USDC</b> — one tenth of a cent — from your own wallet. The payment itself is a gasless signature: the network fee is sponsored by the x402 facilitator, so it isn't added to your cost (it isn't zero, just not yours to pay). No wallet? You can still watch the live 402 challenge above and read the <a href="https://three.ws/docs/x402" target="_blank" rel="noopener">protocol docs</a>. <span class="note-aside">Paying with <b>MetaMask</b> on Base is fully self-contained — it talks only to three.ws. Paying with <b>Phantom</b> on Solana additionally loads a small library from <span class="mono">esm.sh</span>; if a strict host security policy blocks it, the Solana button reports it clearly and the Base path keeps working.</span></p>
+ <p>Every avatar here is generated and rigged on demand — <b>no template library, no canned characters</b>. The rig maps to three.ws's canonical skeleton, so the same idle, walk and emote clips play on whatever you describe. Want image→3D, your own GLB upload, or AR preview? <a href="https://three.ws/forge" target="_blank" rel="noopener">Open the full Forge tool ↗</a> <span class="note-aside">The free lane has an hourly cap so it stays free for everyone; if it's busy it tells you exactly when to retry. Generation runs on NVIDIA NIM and auto-falls back across lanes, so a model always comes back.</span></p>
</div>
</div>
</div>
@@ -1121,19 +1154,7 @@ agent-3d:defined ~ .agent-skel{display:none}
(function () {
'use strict';
- // The paid endpoint this demo calls. Swap to any three.ws x402 GET endpoint
- // and the price tag + 402 preview adapt automatically (the result renderer is
- // shaped for symbol-availability — update renderResultDone if you change it).
- var ENDPOINT = 'https://three.ws/api/x402/symbol-availability';
- // Per-call spend ceiling (micro-USD) handed to the widget as a safety rail:
- // $0.01, so a $0.001 call always clears but a misconfigured price can't drain.
- var MAX_PER_CALL_MICRO_USD = 10000;
-
var $ = function (id) { return document.getElementById(id); };
- var inFlight = false;
- // Networks the live 402 challenge is currently quoting (e.g. "Base or Solana").
- // Used to make error guidance specific — "top up USDC on <network>".
- var quotedNetworks = '';
// ── global resilience net ────────────────────────────────────────────────
// Last-ditch catch for an unexpected throw or rejected promise, so a visitor
@@ -1171,58 +1192,11 @@ agent-3d:defined ~ .agent-skel{display:none}
$('errBanner').classList.remove('show'); bannerShown = false;
});
- function escapeHtml(s) {
- return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {
- return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c];
- });
- }
- function prefersReducedMotion() {
- return !!(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches);
- }
- // Replay a one-shot CSS animation class, no-op under reduced motion.
- function flashPrice(el) {
- if (!el || prefersReducedMotion()) return;
- el.classList.remove('flash');
- void el.offsetWidth; // reflow so the animation restarts on repeat changes
- el.classList.add('flash');
- el.addEventListener('animationend', function once() {
- el.classList.remove('flash');
- el.removeEventListener('animationend', once);
- });
- }
- function sanitizeTicker(raw) {
- return String(raw || '').toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 32);
- }
- function shortAddr(a) {
- if (!a) return '—';
- a = String(a);
- return a.length > 16 ? a.slice(0, 6) + '…' + a.slice(-4) : a;
- }
- function fmtUsd(atomics, decimals) {
- var n = Number(atomics) / Math.pow(10, decimals == null ? 6 : decimals);
- if (!isFinite(n)) return '$—';
- if (n < 0.01) return '$' + n.toFixed(6).replace(/0+$/, '').replace(/\.$/, '');
- return '$' + n.toFixed(2);
- }
- function networkLabel(net) {
- if (!net) return '—';
- if (net.indexOf('solana') === 0) return 'Solana';
- if (net === 'eip155:8453') return 'Base';
- if (net.indexOf('eip155:') === 0) return 'EVM ' + net.split(':')[1];
- return net;
- }
- function explorerUrl(net, tx) {
- if (!tx || !net) return null;
- if (net.indexOf('solana') === 0) return 'https://solscan.io/tx/' + tx;
- if (net === 'eip155:8453') return 'https://basescan.org/tx/' + tx;
- return null;
- }
-
// ── 3D agent layer ────────────────────────────────────────────────────────
// The <agent-3d> element exposes scripted, LLM-free reactions (expressEmotion,
- // playEmote, wave, notify). We drive those from the real payment lifecycle so
- // the agent visibly responds to the same on-chain events the demo renders —
- // no faked timing, no canned animation loop.
+ // playEmote, wave, notify). We drive those from the avatar-forge lifecycle above
+ // (the window 'avatar:*' events it dispatches) so the agent visibly responds to a
+ // real generation as it happens — no faked timing, no canned animation loop.
var agentReady = false;
function agentEl() { return document.getElementById('guideAgent'); }
// Fire a reaction only once the component has booted; calls before that no-op
@@ -1251,8 +1225,13 @@ agent-3d:defined ~ .agent-skel{display:none}
function agentOnError() {
agentReact(function (el) { if (el.expressEmotion) el.expressEmotion('concern', 0.8); });
}
+ // Bridge: the avatar forge (Demo 02) dispatches these as it runs, so the guide
+ // agent waits, celebrates, or shows concern in lockstep with a real generation.
+ window.addEventListener('avatar:generating', agentOnWaiting);
+ window.addEventListener('avatar:done', agentOnSettled);
+ window.addEventListener('avatar:error', agentOnError);
- // ── full-size demo embeds (Forge / Play / IRL) ─────────────────────────────
+ // ── full-size demo embeds (Play / IRL) ─────────────────────────────────────
// Each presents a real, framable production surface at full size. The iframe
// is created only as the section nears the viewport (IntersectionObserver),
// so three heavy apps never load at once on first paint. A load timeout falls
diff --git a/public/500.html b/public/500.html
new file mode 100644
index 000000000..3a682a7a3
--- /dev/null
+++ b/public/500.html
@@ -0,0 +1,322 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>three.ws — something broke on our end</title>
+ <meta name="robots" content="noindex" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <style>
+ :root { color-scheme: dark; }
+ *, *::before, *::after { box-sizing: border-box; }
+ html, body { height: 100%; margin: 0; background: #090909; color: #ccc; font: 15px/1.5 'Inter', -apple-system, system-ui, sans-serif; overflow: hidden; }
+
+ #avatar-canvas {
+ position: fixed; inset: 0;
+ width: 100vw; height: 100vh;
+ pointer-events: none; z-index: 999;
+ }
+
+ .stage {
+ min-height: calc(100vh - 58px);
+ display: flex; flex-direction: column; align-items: center; justify-content: center;
+ gap: 26px; padding: 40px 24px 60px;
+ text-align: center;
+ }
+ .eyebrow {
+ display: inline-flex; align-items: center; gap: 9px;
+ font-size: 11px; font-weight: 600;
+ letter-spacing: 0.17em; text-transform: uppercase;
+ color: #999;
+ font-family: 'Space Grotesk', 'Inter', sans-serif;
+ }
+ .eyebrow-dot {
+ width: 7px; height: 7px; border-radius: 50%;
+ background: #ff5d5d; box-shadow: 0 0 8px rgba(255,93,93,0.55);
+ animation: blink 1.6s ease-in-out infinite;
+ }
+ @keyframes blink { 0%,100%{opacity:1} 50%{opacity:0.18} }
+
+ .bignum {
+ position: relative;
+ font-family: 'Space Grotesk', 'Inter', sans-serif;
+ font-weight: 800; letter-spacing: -0.06em;
+ font-size: clamp(140px, 28vw, 320px);
+ line-height: 0.85;
+ margin: 0;
+ color: #fff;
+ text-shadow: var(--agent-shadow, none);
+ transition: text-shadow 90ms linear;
+ user-select: none;
+ }
+ .bignum em { color: #666; font-style: normal; }
+ /* A restrained RGB-split flicker — signals "glitch" without the seizure
+ risk of a fast strobe. Disabled under reduced-motion below. */
+ .bignum .glitch { position: relative; animation: jitter 3.8s steps(1) infinite; }
+ .bignum .glitch::before,
+ .bignum .glitch::after {
+ content: attr(data-ch);
+ position: absolute; inset: 0;
+ opacity: 0.0;
+ }
+ .bignum .glitch::before { color: #ff4d6d; }
+ .bignum .glitch::after { color: #4dd2ff; }
+ @keyframes jitter {
+ 0%, 92%, 100% {} /* mostly clean */
+ 93% { transform: translateX(-2px); }
+ 94% { transform: translateX(3px); }
+ 95% { transform: translateX(-1px); }
+ 96% { transform: translateX(0); }
+ }
+
+ .line {
+ font-family: 'Space Grotesk', 'Inter', sans-serif;
+ font-size: clamp(20px, 2.4vw, 28px); font-weight: 700;
+ margin: 0; color: #ddd; letter-spacing: -0.015em;
+ }
+ .sub { color: #6a6a6a; max-width: 46ch; margin: 0; font-size: 15px; }
+ .sub strong { color: #9a9a9a; font-weight: 600; }
+
+ /* Support reference chip — only shown when the error carried a ref. */
+ .refrow {
+ display: none;
+ align-items: center; gap: 10px;
+ padding: 9px 12px 9px 16px;
+ background: rgba(255,255,255,0.035);
+ border: 1.5px solid rgba(255,255,255,0.09);
+ border-radius: 12px;
+ max-width: 92vw;
+ }
+ .refrow.show { display: inline-flex; animation: rise 360ms cubic-bezier(.2,.7,.2,1) both; }
+ @keyframes rise { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
+ .ref-label { font-size: 11px; letter-spacing: 0.14em; text-transform: uppercase; color: #6a6a6a; font-weight: 600; }
+ .ref-value {
+ font-family: 'Space Grotesk', ui-monospace, 'SF Mono', Menlo, monospace;
+ font-size: 14px; font-weight: 700; color: #eee; letter-spacing: 0.04em;
+ }
+ .copy-btn {
+ display: inline-flex; align-items: center; gap: 6px;
+ margin-left: 2px; padding: 7px 11px;
+ border: 1.5px solid rgba(255,255,255,0.12); border-radius: 9px;
+ background: rgba(255,255,255,0.04); color: #bbb;
+ font: 700 12px/1 'Inter', inherit; cursor: pointer;
+ transition: color 120ms, border-color 120ms, background 120ms, transform 90ms;
+ }
+ .copy-btn:hover { color: #fff; border-color: rgba(255,255,255,0.3); background: rgba(255,255,255,0.08); }
+ .copy-btn:active { transform: scale(0.94); }
+ .copy-btn:focus-visible { outline: 2px solid #4dd2ff; outline-offset: 2px; }
+ .copy-btn.copied { color: #6ee7a8; border-color: rgba(110,231,168,0.5); }
+ .copy-icon { width: 13px; height: 13px; }
+
+ .actions { display: flex; gap: 12px; flex-wrap: wrap; justify-content: center; margin-top: 6px; }
+ .btn {
+ display: inline-flex; align-items: center; gap: 10px;
+ padding: 14px 26px; border: none; border-radius: 12px;
+ font: 700 14.5px/1 'Inter', inherit; cursor: pointer; text-decoration: none;
+ user-select: none;
+ transform-origin: bottom center;
+ will-change: transform;
+ transition: background 120ms, color 120ms, border-color 120ms, transform 90ms, box-shadow 90ms;
+ }
+ .btn:active { transform: translateY(2px); }
+ .btn:focus-visible { outline: 2px solid #4dd2ff; outline-offset: 3px; }
+ .btn-primary {
+ background: #fff;
+ color: #0b0b0b;
+ box-shadow: 0 7px 0 0 #555, 0 9px 24px rgba(0,0,0,0.4);
+ }
+ .btn-primary:hover { background: #e8e8e8; }
+ .btn-primary:active { box-shadow: 0 5px 0 0 #555, 0 7px 18px rgba(0,0,0,0.4); }
+ .btn-ghost {
+ background: rgba(255,255,255,0.04); color: #888;
+ border: 1.5px solid rgba(255,255,255,0.1);
+ box-shadow: 0 4px 0 0 rgba(255,255,255,0.03);
+ }
+ .btn-ghost:hover { color: #ccc; border-color: rgba(255,255,255,0.25); }
+ .btn-ghost:active { box-shadow: 0 2px 0 0 rgba(255,255,255,0.03); }
+
+ .sr-only {
+ position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
+ overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0;
+ }
+
+ /* Respect users who opt out of motion: no fall, no glitch, no blink. */
+ @media (prefers-reduced-motion: reduce) {
+ .eyebrow-dot { animation: none; }
+ .bignum .glitch { animation: none; }
+ .refrow.show { animation: none; }
+ }
+ </style>
+ <!-- Resolve the bare @three-ws/agent-ui specifier without a bundler (this
+ file is served verbatim from public/). esm.sh ships the package's ESM
+ build and resolves its peer deps (three, etc.) transitively. -->
+ <script type="importmap">
+ { "imports": { "@three-ws/agent-ui": "https://esm.sh/@three-ws/[email protected]" } }
+ </script>
+ </head>
+ <body>
+ <div id="nav-container"></div>
+ <script src="/nav.js"></script>
+
+ <div class="stage">
+ <div class="eyebrow"><span class="eyebrow-dot"></span><span>Server hiccup</span></div>
+ <h1 class="bignum" id="bignum"><span id="five">5</span><em id="zero">0</em><span class="glitch" data-ch="0" id="zero-b">0</span></h1>
+ <p class="line">Something broke on our end.</p>
+ <p class="sub">This one's on us, not you — and it isn't silent: the team was <strong>alerted automatically</strong> the moment it happened. Give it a moment and try again.</p>
+
+ <div class="refrow" id="refrow" role="group" aria-label="Support reference">
+ <span class="ref-label">Reference</span>
+ <span class="ref-value" id="ref-value"></span>
+ <button type="button" class="copy-btn" id="copy-btn" aria-label="Copy support reference to clipboard">
+ <svg class="copy-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>
+ <span id="copy-label">Copy</span>
+ </button>
+ </div>
+
+ <div class="actions">
+ <a href="/" class="btn btn-primary" id="retry-btn">
+ <span id="retry-label">Try again</span>
+ <span>&rarr;</span>
+ </a>
+ <a href="/" class="btn btn-ghost" id="home-btn">
+ <span>Take me home</span>
+ </a>
+ <a href="/support" class="btn btn-ghost" id="support-btn">
+ <span>Contact support</span>
+ </a>
+ </div>
+ <p class="sr-only" id="live-region" role="status" aria-live="polite"></p>
+ </div>
+
+ <canvas id="avatar-canvas" aria-hidden="true"></canvas>
+
+ <script>
+ // Wire the support reference + smart "Try again" before the 3D agent
+ // loads, so the page is fully useful even if the module/CDN is slow or
+ // the GPU is unavailable. The boundary (api/_lib/http.js) redirects a
+ // browser navigation that 5xx'd to /500?ref=<id>&from=<original-path>.
+ (function () {
+ var params = new URLSearchParams(location.search);
+ var ref = (params.get('ref') || '').trim();
+ // Defend the static page against reflected junk: a ref is short and
+ // hex-ish; anything else is ignored rather than rendered verbatim.
+ if (ref && /^[a-zA-Z0-9_-]{4,64}$/.test(ref)) {
+ document.getElementById('ref-value').textContent = ref;
+ document.getElementById('refrow').classList.add('show');
+ }
+
+ // "Try again" retries the page that actually failed, not this one.
+ // Only honor a same-origin absolute path so the param can't be used
+ // as an open-redirect.
+ var from = params.get('from') || '';
+ var safeFrom = /^\/(?!\/)[^\s]*$/.test(from) ? from : '';
+ if (safeFrom) {
+ var retry = document.getElementById('retry-btn');
+ retry.setAttribute('href', safeFrom);
+ document.getElementById('retry-label').textContent = 'Try that again';
+ }
+
+ var live = document.getElementById('live-region');
+ var copyBtn = document.getElementById('copy-btn');
+ var copyLabel = document.getElementById('copy-label');
+ copyBtn.addEventListener('click', function () {
+ var value = document.getElementById('ref-value').textContent || '';
+ if (!value) return;
+ var done = function () {
+ copyBtn.classList.add('copied');
+ copyLabel.textContent = 'Copied';
+ live.textContent = 'Reference ' + value + ' copied to clipboard';
+ setTimeout(function () {
+ copyBtn.classList.remove('copied');
+ copyLabel.textContent = 'Copy';
+ }, 1800);
+ };
+ if (navigator.clipboard && navigator.clipboard.writeText) {
+ navigator.clipboard.writeText(value).then(done).catch(fallbackCopy);
+ } else {
+ fallbackCopy();
+ }
+ function fallbackCopy() {
+ try {
+ var ta = document.createElement('textarea');
+ ta.value = value; ta.style.position = 'fixed'; ta.style.opacity = '0';
+ document.body.appendChild(ta); ta.focus(); ta.select();
+ document.execCommand('copy');
+ document.body.removeChild(ta);
+ done();
+ } catch (e) {
+ live.textContent = 'Could not copy automatically — the reference is ' + value;
+ }
+ }
+ });
+ })();
+ </script>
+
+ <script type="module">
+ import { createAgentUI } from '@three-ws/agent-ui';
+
+ const prefersReduced = window.matchMedia
+ && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+ const zero = document.getElementById('zero');
+ const retryBtn = document.getElementById('retry-btn');
+ const homeBtn = document.getElementById('home-btn');
+
+ let agent;
+ try {
+ agent = await createAgentUI({
+ canvas: document.getElementById('avatar-canvas'),
+ clips: ['idle', 'walk', 'falling', 'facepalm'],
+ });
+ } catch (e) {
+ // The page works without the avatar — a WebGL-less device or a blocked
+ // CDN simply gets the static layout. Never let a render failure throw.
+ agent = null;
+ }
+
+ if (agent) {
+ agent.fx.proximityShadow(document.getElementById('bignum'));
+
+ if (prefersReduced) {
+ // No theatrics for motion-sensitive users: just stand on the mark.
+ agent.standOn(zero, { anchor: 'top-center', offsetY: -8 });
+ agent.play('idle', { loop: true });
+ } else {
+ await agent.fallOnto(zero, {
+ duration: 1.3,
+ landingOffsetPx: 86,
+ tumble: 0.3,
+ onLand: () => {
+ agent.fx.dust(zero);
+ agent.fx.impactPulse(zero);
+ },
+ });
+
+ // The reaction: a one-shot facepalm at the broken server, then
+ // settle into idle and glance around.
+ agent.faceFront?.();
+ agent.play('facepalm', { loop: false });
+ const dur = (agent.clip?.('facepalm') || 1.4) * 1000;
+ setTimeout(() => {
+ if (agent.currentClip === 'facepalm' || !agent.currentClip) {
+ agent.play('idle', { loop: true });
+ }
+ }, dur);
+
+ const t0 = performance.now();
+ (function lookAround() {
+ if (agent._runningOff) return;
+ const t = (performance.now() - t0) / 1000;
+ agent.avatar.rotation.y = Math.sin(t * 1.1) * 0.32;
+ requestAnimationFrame(lookAround);
+ })();
+
+ agent.interceptNavigation(retryBtn, { direction: 'right', delay: 900 });
+ agent.interceptNavigation(homeBtn, { direction: 'left', delay: 900 });
+ }
+ }
+ </script>
+ <script src="/brand.js" defer></script>
+ </body>
+</html>
diff --git a/src/galaxy.js b/src/galaxy.js
index d34911e44..70479a7f6 100644
--- a/src/galaxy.js
+++ b/src/galaxy.js
@@ -13,6 +13,7 @@
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { track, ANALYTICS_EVENTS } from './analytics.js';
+import { walletChipHTML, wireWalletChips } from './shared/agent-wallet-chip.js';
const REDUCED_MOTION =
typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
@@ -414,8 +415,14 @@ function selectAgent(index, fly = false) {
const chips = [];
if (a.chat_count) chips.push(chip(`✦ ${formatCount(a.chat_count)} chats`));
if (a.token && a.token.symbol) chips.push(chip(`$${escapeHtml(a.token.symbol)}`));
- if (a.wallet) chips.push(chip(`<code>${shortAddr(a.wallet)}</code>`));
+ // The agent's custodial wallet identity — the SAME shared chip every other
+ // surface renders (copy, Solscan, vanity tier, tip), so the galaxy inspect card
+ // shows the wallet exactly as the profile/marketplace/dashboard do. The galaxy
+ // is a public read-only map, so the viewer is always a non-owner here.
+ const walletChip = walletChipHTML(a, { isOwner: false, showPending: false, link: true, tip: true });
+ if (walletChip) chips.push(walletChip);
els.gxCardMeta.innerHTML = chips.join('');
+ wireWalletChips(els.gxCardMeta);
els.gxCardView.href = `/agents/${a.id}`;
els.gxCardChat.href = `/agent/${a.id}`;
@@ -711,10 +718,6 @@ function formatCount(n) {
if (n >= 1000) return (n / 1000).toFixed(n >= 10000 ? 0 : 1).replace(/\.0$/, '') + 'k';
return String(n);
}
-function shortAddr(a) {
- a = String(a);
- return a.length > 12 ? `${a.slice(0, 5)}…${a.slice(-4)}` : a;
-}
function easeInOut(t) {
return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
}
diff --git a/src/marketplace-detail.js b/src/marketplace-detail.js
index 45ff1d537..fb08ad64b 100644
--- a/src/marketplace-detail.js
+++ b/src/marketplace-detail.js
@@ -16,6 +16,11 @@ import { walletChipHTML } from './shared/agent-wallet-chip.js';
import { agentAvatarGlb, hasCustomAvatar, seeInWorldHref } from './shared/agent-3d.js';
import { log } from './shared/log.js';
import { resolveDevR2Url } from './shared/dev-r2-proxy.js';
+import { hydrateAvatarWallet } from './shared/wallet-aura.js';
+
+// The detail stage's wallet aura — torn down before each remount so its live
+// poll + rAF never leak across agents.
+let detailStageAura = null;
const API = '/api';
const $ = (id) => document.getElementById(id);
@@ -104,6 +109,8 @@ export function renderDetailModelStage(a) {
stageVisibilityObserver.disconnect();
stageVisibilityObserver = null;
}
+ detailStageAura?.destroy?.();
+ detailStageAura = null;
stage.innerHTML = '';
const hint = $('d-model-hint');
@@ -148,6 +155,11 @@ export function renderDetailModelStage(a) {
clearTimeout(loadTimeout);
progressEl.remove();
mv.style.opacity = '1';
+ // Net-Worth-Reactive Avatar: the model now wears its real wallet here
+ // exactly as on its profile and in the galaxy.
+ hydrateAvatarWallet(stage, a, { lod: 'full', live: true, network: 'mainnet' })
+ .then((c) => { detailStageAura = c; })
+ .catch(() => { /* dormant baseline already shown */ });
},
{ once: true },
);
diff --git a/src/shared/money-pulse.js b/src/shared/money-pulse.js
new file mode 100644
index 000000000..1c24e26d6
--- /dev/null
+++ b/src/shared/money-pulse.js
@@ -0,0 +1,683 @@
+/**
+ * Money Pulse — the shared, embeddable live wallet-activity component.
+ *
+ * One component, three variants, every row a REAL event from /api/pulse (the
+ * real agent_custody_events ledger + real launch records). There are no
+ * synthetic events: a quiet platform shows an honest empty state, never a fake
+ * scroll.
+ *
+ * variant: 'full' — the /pulse page feed (filters + load-more + live)
+ * variant: 'agent' — one wallet's public story (scoped to agentId)
+ * variant: 'ticker' — a compact horizontal marquee for home/launches/galaxy
+ *
+ * Live updates poll a cheap delta (`?since=<cursor>`) and PAUSE when the tab is
+ * hidden (visibilitychange) or the component scrolls offscreen
+ * (IntersectionObserver) — no runaway intervals, no fabricated cadence. New
+ * events animate in; an opt-in "money sound" chimes on arrival.
+ *
+ * Usage:
+ * import { mountMoneyPulse } from './shared/money-pulse.js';
+ * const handle = mountMoneyPulse({ mount, variant: 'full', network: 'mainnet' });
+ * // handle.destroy(), handle.setType('tips'), handle.setNetwork('devnet')
+ */
+
+import { walletChipEl } from './agent-wallet-chip.js';
+
+const POLL_MS = 15_000; // delta poll cadence when live + visible
+const TICKER_POLL_MS = 30_000;
+const MAX_RENDERED = 200; // hard cap on DOM rows (virtualization floor)
+
+const KIND_META = {
+ tip: { glyph: '◎', label: 'Tip', verb: 'received a tip', cls: 'mp-k-tip' },
+ trade: { glyph: '⇄', label: 'Trade', verb: 'traded', cls: 'mp-k-trade' },
+ snipe: { glyph: '⚡', label: 'Snipe', verb: 'sniped', cls: 'mp-k-snipe' },
+ payment: { glyph: '→', label: 'Payment', verb: 'paid', cls: 'mp-k-pay' },
+ launch: { glyph: '✦', label: 'Launch', verb: 'launched', cls: 'mp-k-launch' },
+};
+
+const FILTERS = [
+ { id: 'all', label: 'All' },
+ { id: 'tips', label: 'Tips' },
+ { id: 'launches', label: 'Launches' },
+ { id: 'trades', label: 'Trades' },
+ { id: 'payments', label: 'Payments' },
+];
+
+let _stylesInjected = false;
+function injectStyles() {
+ if (_stylesInjected || typeof document === 'undefined') return;
+ _stylesInjected = true;
+ const css = `
+.mp { --mp-accent: var(--wallet-accent, #c4b5fd); --mp-accent-soft: var(--wallet-accent-soft, rgba(139,92,246,.16));
+ font-family: var(--font-body, system-ui, sans-serif); color: var(--ink, #e8e8e8); }
+.mp-toolbar { display: flex; flex-wrap: wrap; gap: var(--space-xs, 8px); align-items: center; margin-bottom: var(--space-md, 16px); }
+.mp-filters { display: flex; gap: 4px; flex-wrap: wrap; }
+.mp-filter { appearance: none; font: inherit; font-size: var(--text-sm, .8rem); font-weight: 500; color: var(--ink-dim, #888);
+ background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.08));
+ border-radius: var(--radius-pill, 999px); padding: 6px 13px; cursor: pointer;
+ transition: color var(--duration-fast,140ms) ease, background var(--duration-fast,140ms) ease, border-color var(--duration-fast,140ms) ease; }
+.mp-filter:hover { color: var(--ink, #e8e8e8); background: var(--surface-2, rgba(255,255,255,.05)); }
+.mp-filter[aria-pressed="true"] { color: var(--ink-bright, #fff); background: var(--mp-accent-soft); border-color: var(--mp-accent); }
+.mp-filter:focus-visible { outline: 2px solid var(--mp-accent); outline-offset: 2px; }
+.mp-spacer { flex: 1 1 auto; }
+.mp-livedot { display: inline-flex; align-items: center; gap: 6px; font-size: var(--text-2xs, .68rem); letter-spacing: .08em;
+ text-transform: uppercase; color: var(--ink-dim, #888); }
+.mp-livedot::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: var(--success, #4ade80);
+ box-shadow: 0 0 0 0 rgba(74,222,128,.6); animation: mp-pulse 2.4s var(--ease-standard, ease) infinite; }
+.mp-livedot[data-state="paused"]::before { background: var(--ink-faint, #555); animation: none; box-shadow: none; }
+.mp-livedot[data-state="error"]::before { background: var(--warn, #fbbf24); animation: none; }
+@keyframes mp-pulse { 0% { box-shadow: 0 0 0 0 rgba(74,222,128,.5);} 70% { box-shadow: 0 0 0 7px rgba(74,222,128,0);} 100% { box-shadow: 0 0 0 0 rgba(74,222,128,0);} }
+.mp-sound { appearance: none; background: transparent; border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-pill,999px);
+ color: var(--ink-dim,#888); cursor: pointer; font-size: var(--text-xs,.72rem); padding: 5px 11px; transition: color .14s ease, border-color .14s ease; }
+.mp-sound:hover { color: var(--ink,#e8e8e8); border-color: var(--mp-accent); }
+.mp-sound[aria-pressed="true"] { color: var(--mp-accent); border-color: var(--mp-accent); }
+
+.mp-list { display: flex; flex-direction: column; gap: 6px; list-style: none; margin: 0; padding: 0; }
+.mp-row { display: flex; align-items: center; gap: var(--space-sm, 12px); padding: 11px 13px; border-radius: var(--radius-md, 10px);
+ background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.06));
+ text-decoration: none; color: inherit; transition: background .14s ease, border-color .14s ease, transform .14s ease; }
+.mp-row:hover { background: var(--surface-2, rgba(255,255,255,.05)); border-color: var(--stroke-strong, rgba(255,255,255,.14)); }
+.mp-row:focus-visible { outline: 2px solid var(--mp-accent); outline-offset: 1px; }
+.mp-row.mp-new { animation: mp-land .6s var(--ease-standard, cubic-bezier(.2,.8,.2,1)); }
+@keyframes mp-land { 0% { opacity: 0; transform: translateY(-8px) scale(.99); background: var(--mp-accent-soft); }
+ 100% { opacity: 1; transform: none; } }
+.mp-av { width: 36px; height: 36px; border-radius: 50%; flex: 0 0 auto; object-fit: cover; background: var(--surface-3, rgba(255,255,255,.08));
+ border: 1px solid var(--stroke, rgba(255,255,255,.08)); display: grid; place-items: center; font-weight: 600; color: var(--ink-dim,#888); font-size: .8rem; overflow: hidden; }
+.mp-glyph { position: relative; flex: 0 0 auto; width: 20px; text-align: center; font-size: 1rem; }
+.mp-k-tip .mp-glyph { color: var(--success, #4ade80); }
+.mp-k-launch .mp-glyph { color: var(--mp-accent); }
+.mp-k-snipe .mp-glyph { color: var(--warn, #fbbf24); }
+.mp-k-trade .mp-glyph, .mp-k-pay .mp-glyph { color: var(--ink-dim, #9aa); }
+.mp-body { flex: 1 1 auto; min-width: 0; }
+.mp-line { font-size: var(--text-md, .84rem); line-height: 1.3; color: var(--ink, #e8e8e8); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.mp-name { font-weight: 600; color: var(--ink-bright, #fff); }
+.mp-amount { font-family: var(--font-mono, ui-monospace, monospace); color: var(--ink-bright, #fff); }
+.mp-usd { color: var(--ink-dim, #888); }
+.mp-meta { display: flex; align-items: center; gap: 8px; margin-top: 3px; font-size: var(--text-2xs, .68rem); color: var(--ink-faint, #666); }
+.mp-chip-slot { display: inline-flex; }
+.mp-time { white-space: nowrap; }
+.mp-explore { color: var(--ink-faint, #666); text-decoration: none; }
+.mp-explore:hover { color: var(--mp-accent); }
+.mp-right { flex: 0 0 auto; display: flex; flex-direction: column; align-items: flex-end; gap: 2px; }
+.mp-kindtag { font-size: var(--text-2xs,.66rem); text-transform: uppercase; letter-spacing: .06em; color: var(--ink-faint,#666); }
+
+.mp-skeleton { height: 60px; border-radius: var(--radius-md,10px); background: linear-gradient(90deg, var(--surface-1,rgba(255,255,255,.03)) 25%, var(--surface-2,rgba(255,255,255,.06)) 37%, var(--surface-1,rgba(255,255,255,.03)) 63%); background-size: 400% 100%; animation: mp-shimmer 1.4s ease infinite; }
+@keyframes mp-shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }
+.mp-empty, .mp-error { text-align: center; padding: var(--space-xl, 40px) var(--space-md,16px); color: var(--ink-dim, #888); border: 1px dashed var(--stroke, rgba(255,255,255,.1)); border-radius: var(--radius-lg,14px); }
+.mp-empty-icon { font-size: 2rem; opacity: .6; }
+.mp-empty-title { color: var(--ink-bright, #fff); font-weight: 600; margin: 10px 0 4px; }
+.mp-empty-sub { font-size: var(--text-sm, .8rem); }
+.mp-empty-sub a { color: var(--mp-accent); }
+.mp-more { display: block; width: 100%; margin-top: var(--space-md,16px); appearance: none; font: inherit; font-weight: 600;
+ background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); color: var(--ink, #e8e8e8);
+ border-radius: var(--radius-md,10px); padding: 11px; cursor: pointer; transition: background .14s ease; }
+.mp-more:hover { background: var(--surface-2, rgba(255,255,255,.05)); }
+.mp-more[disabled] { opacity: .5; cursor: default; }
+
+/* Ticker variant */
+.mp-ticker { --mp-accent: var(--wallet-accent, #c4b5fd); position: relative; overflow: hidden; mask-image: linear-gradient(90deg, transparent, #000 6%, #000 94%, transparent); -webkit-mask-image: linear-gradient(90deg, transparent, #000 6%, #000 94%, transparent); }
+.mp-ticker-track { display: inline-flex; gap: 26px; white-space: nowrap; will-change: transform; animation: mp-marquee var(--mp-dur, 60s) linear infinite; }
+.mp-ticker:hover .mp-ticker-track { animation-play-state: paused; }
+@keyframes mp-marquee { from { transform: translateX(0); } to { transform: translateX(-50%); } }
+.mp-tick { display: inline-flex; align-items: center; gap: 7px; font-size: var(--text-sm,.8rem); color: var(--ink-dim,#9aa); text-decoration: none; }
+.mp-tick:hover { color: var(--ink-bright,#fff); }
+.mp-tick .mp-glyph { width: auto; }
+.mp-tick b { color: var(--ink-bright,#fff); font-weight: 600; }
+.mp-tick .mp-amount { color: var(--ink, #e8e8e8); }
+@media (prefers-reduced-motion: reduce) {
+ .mp-row.mp-new, .mp-livedot::before, .mp-skeleton { animation: none; }
+ .mp-ticker-track { animation: none; }
+}
+@media (max-width: 560px) { .mp-line { white-space: normal; } .mp-kindtag { display: none; } }
+`;
+ const tag = document.createElement('style');
+ tag.id = 'mp-styles';
+ tag.textContent = css;
+ document.head.appendChild(tag);
+}
+
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+
+function timeAgo(iso) {
+ const t = new Date(iso).getTime();
+ if (!Number.isFinite(t)) return '';
+ const s = Math.max(0, Math.round((Date.now() - t) / 1000));
+ if (s < 5) return 'just now';
+ if (s < 60) return `${s}s ago`;
+ const m = Math.round(s / 60);
+ if (m < 60) return `${m}m ago`;
+ const h = Math.round(m / 60);
+ if (h < 24) return `${h}h ago`;
+ const d = Math.round(h / 24);
+ return `${d}d ago`;
+}
+
+function fmtAmount(ev) {
+ if (ev.kind === 'launch') return '';
+ if (ev.sol != null && (ev.asset === 'SOL' || !ev.asset)) {
+ const v = ev.sol;
+ const s = v >= 1 ? v.toFixed(2) : v.toFixed(4).replace(/0+$/, '').replace(/\.$/, '');
+ return `◎${s}`;
+ }
+ if (ev.amount_raw != null) {
+ // USDC (6dp) is the only non-SOL asset we record a price for; show $ when priced.
+ if (ev.usd != null) return `$${Number(ev.usd).toFixed(2)}`;
+ return `${(Number(ev.amount_raw) / 1e6).toFixed(2)}`;
+ }
+ return '';
+}
+
+function usdLabel(ev) {
+ if (ev.usd == null || ev.kind === 'launch') return '';
+ // Don't double-print $ for a USDC payment we already showed as $.
+ if (ev.amount_raw != null && (ev.sol == null)) return '';
+ return ` · $${Number(ev.usd).toFixed(2)}`;
+}
+
+// Build the human sentence fragment (the part after the avatar). Returns HTML.
+function sentenceHTML(ev) {
+ const k = KIND_META[ev.kind] || KIND_META.trade;
+ const name = esc(ev.agent?.name || 'An agent');
+ const amt = fmtAmount(ev);
+ const amtHTML = amt ? ` <span class="mp-amount">${esc(amt)}</span>` : '';
+ const usd = usdLabel(ev);
+ const usdHTML = usd ? `<span class="mp-usd">${esc(usd)}</span>` : '';
+ switch (ev.kind) {
+ case 'tip':
+ return `<span class="mp-name">${name}</span> received a${amtHTML} tip${usdHTML}`;
+ case 'launch':
+ return `<span class="mp-name">${name}</span> launched ${ev.symbol ? `$${esc(ev.symbol)}` : esc(ev.coin_name || 'a coin')}`;
+ case 'snipe':
+ return `<span class="mp-name">${name}</span> sniped${amtHTML}${usdHTML}`;
+ case 'payment':
+ return `<span class="mp-name">${name}</span> paid${amtHTML}${usdHTML}`;
+ case 'trade':
+ default:
+ return `<span class="mp-name">${name}</span> traded${amtHTML}${usdHTML}`;
+ }
+}
+
+// Avatar element: image when available, else a monogram.
+function avatarEl(agent) {
+ const url = agent?.avatar_thumbnail_url;
+ if (url) {
+ const img = document.createElement('img');
+ img.className = 'mp-av';
+ img.src = url;
+ img.alt = '';
+ img.loading = 'lazy';
+ img.onerror = () => { img.replaceWith(monogram(agent)); };
+ return img;
+ }
+ return monogram(agent);
+}
+function monogram(agent) {
+ const d = document.createElement('div');
+ d.className = 'mp-av';
+ d.setAttribute('aria-hidden', 'true');
+ d.textContent = (agent?.name || '?').trim().charAt(0).toUpperCase();
+ return d;
+}
+
+// One full feed row (anchor → agent profile).
+function rowEl(ev) {
+ const k = KIND_META[ev.kind] || KIND_META.trade;
+ const a = document.createElement('a');
+ a.className = `mp-row ${k.cls}`;
+ a.href = ev.agent?.url || (ev.mint ? `/launches/${ev.mint}` : '#');
+ a.dataset.id = ev.id;
+ a.setAttribute('aria-label', `${ev.agent?.name || 'Agent'} ${k.verb} — ${timeAgo(ev.ts)}`);
+
+ a.appendChild(avatarEl(ev.agent));
+
+ const glyph = document.createElement('span');
+ glyph.className = 'mp-glyph';
+ glyph.setAttribute('aria-hidden', 'true');
+ glyph.textContent = k.glyph;
+ a.appendChild(glyph);
+
+ const body = document.createElement('div');
+ body.className = 'mp-body';
+ const line = document.createElement('div');
+ line.className = 'mp-line';
+ line.innerHTML = sentenceHTML(ev);
+ body.appendChild(line);
+
+ const meta = document.createElement('div');
+ meta.className = 'mp-meta';
+ // Wallet chip (link:false so the chip's own links don't nest inside the row anchor).
+ if (ev.agent?.solana_address) {
+ const chip = walletChipEl(
+ {
+ name: ev.agent.name,
+ meta: {
+ solana_address: ev.agent.solana_address,
+ solana_vanity_prefix: ev.agent.solana_vanity_prefix,
+ solana_vanity_suffix: ev.agent.solana_vanity_suffix,
+ },
+ },
+ { link: false, tip: false, showPending: false },
+ );
+ if (chip) {
+ const slot = document.createElement('span');
+ slot.className = 'mp-chip-slot';
+ slot.appendChild(chip);
+ meta.appendChild(slot);
+ }
+ }
+ const time = document.createElement('span');
+ time.className = 'mp-time';
+ time.textContent = timeAgo(ev.ts);
+ time.dateTime = ev.ts;
+ meta.appendChild(time);
+
+ if (ev.explorer || ev.mint_explorer) {
+ const ex = document.createElement('a');
+ ex.className = 'mp-explore';
+ ex.href = ev.explorer || ev.mint_explorer;
+ ex.target = '_blank';
+ ex.rel = 'noopener noreferrer';
+ ex.textContent = ev.kind === 'launch' ? 'mint ↗' : 'tx ↗';
+ ex.addEventListener('click', (e) => e.stopPropagation());
+ meta.appendChild(ex);
+ }
+ body.appendChild(meta);
+ a.appendChild(body);
+
+ const right = document.createElement('div');
+ right.className = 'mp-right';
+ const tag = document.createElement('span');
+ tag.className = 'mp-kindtag';
+ tag.textContent = k.label;
+ right.appendChild(tag);
+ a.appendChild(right);
+
+ return a;
+}
+
+// Compact ticker item.
+function tickEl(ev) {
+ const k = KIND_META[ev.kind] || KIND_META.trade;
+ const a = document.createElement('a');
+ a.className = `mp-tick ${k.cls}`;
+ a.href = ev.agent?.url || (ev.mint ? `/launches/${ev.mint}` : '/pulse');
+ const amt = fmtAmount(ev);
+ a.innerHTML =
+ `<span class="mp-glyph" aria-hidden="true">${k.glyph}</span>` +
+ `<b>${esc(ev.agent?.name || 'Agent')}</b> ${esc(k.verb)}` +
+ (amt ? ` <span class="mp-amount">${esc(amt)}</span>` : '') +
+ (ev.kind === 'launch' && ev.symbol ? ` <span class="mp-amount">$${esc(ev.symbol)}</span>` : '');
+ return a;
+}
+
+// A tiny, opt-in "money sound": a soft two-note chime synthesized on the fly.
+// No audio files, no autoplay — only fires after the user toggles it on.
+function makeChime() {
+ let ctx = null;
+ return {
+ play() {
+ try {
+ ctx = ctx || new (window.AudioContext || window.webkitAudioContext)();
+ if (ctx.state === 'suspended') ctx.resume();
+ const now = ctx.currentTime;
+ [880, 1320].forEach((freq, i) => {
+ const o = ctx.createOscillator();
+ const g = ctx.createGain();
+ o.type = 'sine';
+ o.frequency.value = freq;
+ const t = now + i * 0.07;
+ g.gain.setValueAtTime(0, t);
+ g.gain.linearRampToValueAtTime(0.06, t + 0.02);
+ g.gain.exponentialRampToValueAtTime(0.0001, t + 0.22);
+ o.connect(g).connect(ctx.destination);
+ o.start(t);
+ o.stop(t + 0.24);
+ });
+ } catch { /* audio unavailable — silent, never throws */ }
+ },
+ };
+}
+
+async function fetchPulse(params) {
+ const qs = new URLSearchParams();
+ for (const [k, v] of Object.entries(params)) if (v != null && v !== '') qs.set(k, v);
+ const res = await fetch(`/api/pulse?${qs.toString()}`, { headers: { accept: 'application/json' } });
+ if (!res.ok) {
+ const e = new Error(`pulse ${res.status}`);
+ e.status = res.status;
+ throw e;
+ }
+ const json = await res.json();
+ return json.data;
+}
+
+/**
+ * Mount a Money Pulse surface.
+ * @param {object} o
+ * @param {HTMLElement} o.mount
+ * @param {'full'|'agent'|'ticker'} [o.variant='full']
+ * @param {string} [o.agentId]
+ * @param {string} [o.network='mainnet']
+ * @param {string} [o.type='all']
+ * @param {boolean} [o.live=true]
+ * @param {boolean} [o.controls] show the filter/sound toolbar (default: full only)
+ * @param {number} [o.pageSize=30]
+ * @param {string} [o.emptyHint] override empty-state CTA copy
+ * @returns {{ destroy(): void, setType(t:string): void, setNetwork(n:string): void, refresh(): void }}
+ */
+export function mountMoneyPulse({
+ mount,
+ variant = 'full',
+ agentId = null,
+ network = 'mainnet',
+ type = 'all',
+ live = true,
+ controls,
+ pageSize = 30,
+ emptyHint,
+} = {}) {
+ if (!mount) throw new Error('mountMoneyPulse requires { mount }');
+ injectStyles();
+ const showControls = controls ?? variant === 'full';
+
+ const state = {
+ type,
+ network,
+ events: [],
+ seen: new Set(),
+ headCursor: null,
+ nextCursor: null,
+ hasMore: false,
+ loading: false,
+ errored: false,
+ paused: false,
+ destroyed: false,
+ };
+ const chime = makeChime();
+ let soundOn = false;
+ let pollTimer = null;
+
+ mount.classList.add('mp');
+ if (variant === 'ticker') mount.classList.add('mp-ticker');
+
+ // ── scaffold ──
+ let listEl, moreBtn, liveDot, statusHost;
+ function scaffold() {
+ mount.innerHTML = '';
+ if (variant === 'ticker') {
+ const track = document.createElement('div');
+ track.className = 'mp-ticker-track';
+ track.setAttribute('role', 'list');
+ mount.appendChild(track);
+ listEl = track;
+ return;
+ }
+ if (showControls) {
+ const bar = document.createElement('div');
+ bar.className = 'mp-toolbar';
+ const filters = document.createElement('div');
+ filters.className = 'mp-filters';
+ filters.setAttribute('role', 'group');
+ filters.setAttribute('aria-label', 'Filter activity by type');
+ for (const f of FILTERS) {
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.className = 'mp-filter';
+ b.textContent = f.label;
+ b.dataset.type = f.id;
+ b.setAttribute('aria-pressed', String(f.id === state.type));
+ b.addEventListener('click', () => api.setType(f.id));
+ filters.appendChild(b);
+ }
+ bar.appendChild(filters);
+ const spacer = document.createElement('div');
+ spacer.className = 'mp-spacer';
+ bar.appendChild(spacer);
+ liveDot = document.createElement('span');
+ liveDot.className = 'mp-livedot';
+ liveDot.textContent = live ? 'Live' : 'Paused';
+ bar.appendChild(liveDot);
+ if (live) {
+ const sound = document.createElement('button');
+ sound.type = 'button';
+ sound.className = 'mp-sound';
+ sound.setAttribute('aria-pressed', 'false');
+ sound.textContent = '🔇 Sound';
+ sound.addEventListener('click', () => {
+ soundOn = !soundOn;
+ sound.setAttribute('aria-pressed', String(soundOn));
+ sound.textContent = soundOn ? '🔊 Sound' : '🔇 Sound';
+ if (soundOn) chime.play();
+ });
+ bar.appendChild(sound);
+ }
+ mount.appendChild(bar);
+ }
+ statusHost = document.createElement('div');
+ mount.appendChild(statusHost);
+ listEl = document.createElement('ul');
+ listEl.className = 'mp-list';
+ listEl.setAttribute('role', 'feed');
+ listEl.setAttribute('aria-busy', 'true');
+ mount.appendChild(listEl);
+ if (variant !== 'agent' || true) {
+ moreBtn = document.createElement('button');
+ moreBtn.type = 'button';
+ moreBtn.className = 'mp-more';
+ moreBtn.textContent = 'Load more';
+ moreBtn.hidden = true;
+ moreBtn.addEventListener('click', loadMore);
+ mount.appendChild(moreBtn);
+ }
+ }
+
+ function setLiveState(s) {
+ if (liveDot) {
+ liveDot.dataset.state = s;
+ liveDot.textContent = s === 'error' ? 'Reconnecting…' : s === 'paused' ? 'Paused' : 'Live';
+ }
+ }
+
+ function renderSkeletons() {
+ if (variant === 'ticker') return;
+ listEl.innerHTML = '';
+ for (let i = 0; i < 5; i++) {
+ const li = document.createElement('li');
+ li.className = 'mp-skeleton';
+ li.style.animationDelay = `${i * 0.08}s`;
+ listEl.appendChild(li);
+ }
+ }
+
+ function renderEmpty() {
+ if (variant === 'ticker') { mount.style.display = 'none'; return; }
+ listEl.innerHTML = '';
+ const hint = emptyHint
+ || (agentId
+ ? 'This wallet has no public activity yet.'
+ : 'All quiet on three.ws right now. <a href="/agents">Tip an agent</a> and be the first beat.');
+ statusHost.innerHTML =
+ `<div class="mp-empty"><div class="mp-empty-icon" aria-hidden="true">◎</div>` +
+ `<div class="mp-empty-title">No money moving — yet</div>` +
+ `<div class="mp-empty-sub">${hint}</div></div>`;
+ }
+
+ function renderError(keepRows) {
+ if (variant === 'ticker') { if (!state.events.length) mount.style.display = 'none'; return; }
+ setLiveState('error');
+ if (keepRows && state.events.length) return; // degrade to last-known; banner via livedot
+ statusHost.innerHTML =
+ `<div class="mp-error">Couldn’t reach the pulse. <button class="mp-filter" data-retry>Retry</button></div>`;
+ statusHost.querySelector('[data-retry]')?.addEventListener('click', () => api.refresh());
+ }
+
+ function clearStatus() { if (statusHost) statusHost.innerHTML = ''; }
+
+ function renderAll() {
+ if (!state.events.length) { renderEmpty(); return; }
+ clearStatus();
+ listEl.innerHTML = '';
+ if (variant === 'ticker') {
+ // Duplicate the sequence so the marquee loops seamlessly (-50% keyframe).
+ const items = state.events.slice(0, 20);
+ for (const ev of [...items, ...items]) listEl.appendChild(tickEl(ev));
+ mount.style.removeProperty('display');
+ const track = listEl;
+ track.style.setProperty('--mp-dur', `${Math.max(30, items.length * 4)}s`);
+ return;
+ }
+ for (const ev of state.events.slice(0, MAX_RENDERED)) listEl.appendChild(rowEl(ev));
+ listEl.setAttribute('aria-busy', 'false');
+ if (moreBtn) moreBtn.hidden = !state.hasMore;
+ }
+
+ // Prepend newly-arrived events with a landing animation + optional chime.
+ function prepend(newEvents) {
+ const fresh = newEvents.filter((e) => !state.seen.has(e.id));
+ if (!fresh.length) return;
+ for (const e of fresh) state.seen.add(e.id);
+ state.events = [...fresh, ...state.events].slice(0, MAX_RENDERED + 50);
+ if (!state.events.length) return;
+ if (variant === 'ticker') { renderAll(); return; }
+ clearStatus();
+ // Insert at the top with animation.
+ const frag = document.createDocumentFragment();
+ for (const ev of fresh) {
+ const node = rowEl(ev);
+ node.classList.add('mp-new');
+ frag.appendChild(node);
+ }
+ listEl.prepend(frag);
+ // Trim overflow rows from the bottom (virtualization floor).
+ while (listEl.children.length > MAX_RENDERED) listEl.lastElementChild?.remove();
+ if (soundOn) chime.play();
+ }
+
+ async function loadInitial() {
+ state.loading = true;
+ state.errored = false;
+ renderSkeletons();
+ try {
+ const data = await fetchPulse({
+ network: state.network, type: state.type, agent_id: agentId, limit: pageSize,
+ });
+ if (state.destroyed) return;
+ state.events = data.events || [];
+ state.seen = new Set(state.events.map((e) => e.id));
+ state.headCursor = data.head_cursor;
+ state.nextCursor = data.next_cursor;
+ state.hasMore = data.has_more;
+ renderAll();
+ setLiveState(state.paused ? 'paused' : 'live');
+ } catch (e) {
+ if (state.destroyed) return;
+ state.errored = true;
+ renderError(false);
+ } finally {
+ state.loading = false;
+ }
+ }
+
+ async function loadMore() {
+ if (!state.nextCursor || state.loading) return;
+ state.loading = true;
+ if (moreBtn) { moreBtn.disabled = true; moreBtn.textContent = 'Loading…'; }
+ try {
+ const data = await fetchPulse({
+ network: state.network, type: state.type, agent_id: agentId,
+ limit: pageSize, cursor: state.nextCursor,
+ });
+ if (state.destroyed) return;
+ const fresh = (data.events || []).filter((e) => !state.seen.has(e.id));
+ for (const e of fresh) state.seen.add(e.id);
+ state.events = [...state.events, ...fresh];
+ state.nextCursor = data.next_cursor;
+ state.hasMore = data.has_more;
+ for (const ev of fresh) listEl.appendChild(rowEl(ev));
+ } catch { /* keep last-known; user can retry */ }
+ finally {
+ state.loading = false;
+ if (moreBtn) { moreBtn.disabled = false; moreBtn.textContent = 'Load more'; moreBtn.hidden = !state.hasMore; }
+ }
+ }
+
+ async function pollDelta() {
+ if (state.paused || state.destroyed || !state.headCursor) return;
+ try {
+ const data = await fetchPulse({
+ network: state.network, type: state.type, agent_id: agentId,
+ since: state.headCursor, limit: pageSize,
+ });
+ if (state.destroyed) return;
+ if (data.events?.length) {
+ prepend(data.events);
+ if (data.head_cursor) state.headCursor = data.head_cursor;
+ }
+ setLiveState('live');
+ } catch {
+ setLiveState('error'); // degrade to last-known, keep polling
+ }
+ }
+
+ // ── live scheduling: pause when hidden or offscreen ──
+ const interval = variant === 'ticker' ? TICKER_POLL_MS : POLL_MS;
+ function startPolling() {
+ if (!live || pollTimer) return;
+ pollTimer = setInterval(() => { if (!document.hidden && !state.paused) pollDelta(); }, interval);
+ }
+ function stopPolling() { if (pollTimer) { clearInterval(pollTimer); pollTimer = null; } }
+
+ function onVisibility() {
+ if (document.hidden) { setLiveState('paused'); }
+ else { setLiveState(state.paused ? 'paused' : 'live'); pollDelta(); }
+ }
+ document.addEventListener('visibilitychange', onVisibility);
+
+ // Offscreen pause via IntersectionObserver.
+ let io = null;
+ if (live && 'IntersectionObserver' in window) {
+ io = new IntersectionObserver((entries) => {
+ const visible = entries.some((e) => e.isIntersecting);
+ state.paused = !visible;
+ setLiveState(state.paused ? 'paused' : (state.errored ? 'error' : 'live'));
+ if (!state.paused) pollDelta();
+ }, { rootMargin: '120px' });
+ io.observe(mount);
+ }
+
+ const api = {
+ setType(t) {
+ if (t === state.type) return;
+ state.type = t;
+ if (showControls) {
+ for (const b of mount.querySelectorAll('.mp-filter[data-type]')) {
+ b.setAttribute('aria-pressed', String(b.dataset.type === t));
+ }
+ }
+ loadInitial();
+ },
+ setNetwork(n) {
+ const net = n === 'devnet' ? 'devnet' : 'mainnet';
+ if (net === state.network) return;
+ state.network = net;
+ loadInitial();
+ },
+ refresh() { loadInitial(); },
+ destroy() {
+ state.destroyed = true;
+ stopPolling();
+ document.removeEventListener('visibilitychange', onVisibility);
+ io?.disconnect();
+ mount.innerHTML = '';
+ },
+ };
+
+ scaffold();
+ loadInitial().then(() => { if (!state.destroyed) startPolling(); });
+
+ return api;
+}
+
+if (typeof window !== 'undefined') {
+ window.twsMoneyPulse = { mountMoneyPulse };
+}
diff --git a/src/usdz-animated.js b/src/usdz-animated.js
new file mode 100644
index 000000000..94677c04a
--- /dev/null
+++ b/src/usdz-animated.js
@@ -0,0 +1,301 @@
+// Animated USDZ pipeline — gives iOS AR Quick Look a *living* avatar.
+//
+// three.js's USDZExporter drops skeletons entirely, so the static pipeline
+// (usdz-pipeline.js) bakes one frozen pose. This module goes one step further:
+// it drives the avatar through an animation clip, samples the skinned vertices
+// at a handful of keyframes, and writes them into the USDA as time-sampled
+// `point3f[] points`. Quick Look interpolates and loops those samples on its
+// own, so the avatar breathes / idles / walks in the user's room instead of
+// standing there as a mannequin.
+//
+// Design: we lean on the *proven* static exporter for everything Quick Look is
+// fussy about — materials, textures, the 64-byte-aligned zip — by exporting a
+// frame-0 scene through three's USDZExporter, then surgically rewriting only
+// each animated mesh's `points` into `.timeSamples` and adding the stage's
+// playback timing. The single hand-authored part (vertex time samples) is pure
+// string work and fully unit-tested; the rest is byte-identical to the shipping
+// static path. Any failure (no rig, no usable clip, format drift) throws so the
+// caller can fall back to the static USDZ — AR never regresses.
+
+import { AnimationMixer, Mesh, BufferAttribute } from 'three';
+import { USDZExporter } from 'three/addons/exporters/USDZExporter.js';
+import { strToU8, strFromU8, zipSync, unzipSync } from 'three/addons/libs/fflate.module.js';
+
+import {
+ _loadGlbBlob,
+ _bakedLocalPositions,
+ _coerceMaterialsToStandard,
+} from './usdz-pipeline.js';
+import { retargetClipToObject } from './animation-retarget.js';
+
+// Default idle that ships in public/animations — a slow breathing loop that
+// reads as "alive" the instant the avatar lands in AR.
+export const DEFAULT_AR_ANIMATION = '/animations/Idle_Breath.glb';
+
+const DEFAULTS = {
+ targetFps: 15, // sampling density; Quick Look interpolates between samples
+ maxFrames: 30, // hard cap so a long clip can't balloon the .usdz over cellular
+ minFrames: 2,
+ precision: 5, // ASCII float digits — 5 keeps idle silhouettes crisp at ~⅓ the bytes of 7
+};
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Pure serialization helpers (unit-tested directly)
+ * ────────────────────────────────────────────────────────────────────────── */
+
+/**
+ * Serialize a flat [x,y,z,x,y,z,…] Float32Array into USD point-array text:
+ * `(x, y, z), (x, y, z), …`.
+ */
+export function _vec3ArrayToUsd(flat, precision = DEFAULTS.precision) {
+ const parts = new Array(flat.length / 3);
+ for (let i = 0, p = 0; i < flat.length; i += 3, p++) {
+ parts[p] = `(${flat[i].toPrecision(precision)}, ${flat[i + 1].toPrecision(
+ precision,
+ )}, ${flat[i + 2].toPrecision(precision)})`;
+ }
+ return parts.join(', ');
+}
+
+/**
+ * Build the `point3f[] points.timeSamples = { … }` block from per-frame
+ * position arrays. Frame index doubles as the USD time code; the stage's
+ * timeCodesPerSecond (see _injectStageTiming) governs real playback speed.
+ */
+export function _pointsTimeSamplesBlock(framesPositions, precision = DEFAULTS.precision) {
+ const lines = framesPositions.map(
+ (flat, frame) => `\t\t\t\t${frame}: [${_vec3ArrayToUsd(flat, precision)}],`,
+ );
+ return `point3f[] points.timeSamples = {\n${lines.join('\n')}\n\t\t\t}`;
+}
+
+// Matches three's single-line static `point3f[] points = [ … ]` property. The
+// array body holds only numbers, commas, parens and spaces — never a `]` — so a
+// negated-class run is a safe, unambiguous match.
+const STATIC_POINTS_RE = /point3f\[\] points = \[[^\]]*\]/;
+
+/**
+ * Replace a geometry file's static points with time-sampled animation.
+ * Throws if the expected static-points property isn't present (format drift) so
+ * the caller can fall back rather than ship a silently-broken file.
+ */
+export function _patchGeometryPoints(usda, framesPositions, precision = DEFAULTS.precision) {
+ if (!STATIC_POINTS_RE.test(usda)) {
+ throw new Error('animated-usdz: geometry has no static points property to animate');
+ }
+ return usda.replace(STATIC_POINTS_RE, _pointsTimeSamplesBlock(framesPositions, precision));
+}
+
+const HEADER_UPAXIS_RE = /\tupAxis = "Y"\n\)/;
+
+/**
+ * Add playback timing to the stage's layer metadata so Quick Look knows the
+ * clip's frame range and speed. `timeCodesPerSecond` is set so the whole sample
+ * set plays back over the clip's real duration (i.e. true-to-life tempo).
+ */
+export function _injectStageTiming(modelUsda, { frameCount, durationSeconds }) {
+ if (!HEADER_UPAXIS_RE.test(modelUsda)) {
+ throw new Error('animated-usdz: unexpected USDA header — cannot inject timing');
+ }
+ const endTimeCode = Math.max(0, frameCount - 1);
+ // frames are evenly spaced over the clip; codes/sec = (count-1)/duration keeps
+ // real-time tempo. Guard a zero/tiny duration so we never divide by ~0.
+ const tps = durationSeconds > 1e-3 ? endTimeCode / durationSeconds : DEFAULTS.targetFps;
+ const timing = [
+ '\tupAxis = "Y"',
+ '\tstartTimeCode = 0',
+ `\tendTimeCode = ${endTimeCode}`,
+ `\ttimeCodesPerSecond = ${tps.toPrecision(6)}`,
+ `\tframesPerSecond = ${tps.toPrecision(6)}`,
+ ')',
+ ].join('\n');
+ return modelUsda.replace(HEADER_UPAXIS_RE, timing);
+}
+
+/**
+ * Re-pack a USDZ from a {filename: Uint8Array} map, mirroring three's
+ * USDZExporter exactly: model.usda first, stored (level 0), each每 entry padded so
+ * its payload starts on a 64-byte boundary (required for mmap'd USD reads).
+ */
+export function _packUsdz(files) {
+ // model.usda must be the first archive entry.
+ const ordered = {};
+ if (files['model.usda']) ordered['model.usda'] = files['model.usda'];
+ for (const name in files) {
+ if (name !== 'model.usda') ordered[name] = files[name];
+ }
+
+ let offset = 0;
+ for (const filename in ordered) {
+ const file = ordered[filename];
+ const headerSize = 34 + filename.length;
+ offset += headerSize;
+ const offsetMod64 = offset & 63;
+ if (offsetMod64 !== 4) {
+ const padding = new Uint8Array(64 - offsetMod64);
+ ordered[filename] = [file, { extra: { 12345: padding } }];
+ }
+ offset = file.length;
+ }
+ return zipSync(ordered, { level: 0 });
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Sampling
+ * ────────────────────────────────────────────────────────────────────────── */
+
+function collectSkinnedMeshes(root) {
+ const out = [];
+ root.traverse((o) => {
+ if (o.isSkinnedMesh && o.skeleton?.bones?.length && o.geometry?.getAttribute('position')) {
+ out.push(o);
+ }
+ });
+ return out;
+}
+
+/**
+ * Drive `mixer` through `clip` and capture each skinned mesh's deformed
+ * local-space vertices at `frameCount` evenly-spaced times across the clip.
+ *
+ * @returns {Map<SkinnedMesh, Float32Array[]>} mesh → array of per-frame positions
+ */
+export function _sampleSkinnedFrames(scene, mixer, action, meshes, { frameCount, duration }) {
+ const perMesh = new Map(meshes.map((m) => [m, []]));
+ action.play();
+ for (let f = 0; f < frameCount; f++) {
+ const t = (f / frameCount) * duration; // [0, duration) so frame N wraps to frame 0
+ mixer.setTime(t);
+ scene.updateMatrixWorld(true);
+ for (const mesh of meshes) {
+ perMesh.get(mesh).push(_bakedLocalPositions(mesh));
+ }
+ }
+ return perMesh;
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Orchestration
+ * ────────────────────────────────────────────────────────────────────────── */
+
+/**
+ * Resolve an AnimationClip that targets `scene`'s nodes. Priority:
+ * 1. an explicit clip passed by the caller (retargeted onto the avatar),
+ * 2. a clip loaded from `animationGlbBlob` (retargeted),
+ * 3. a clip already embedded in the avatar GLB (used as-is).
+ * Returns null if nothing usable is found.
+ */
+async function resolveClip(scene, avatarGltf, { clip, animationGlbBlob }) {
+ if (clip) {
+ const { clip: retargeted } = retargetClipToObject(clip, scene);
+ if (retargeted) return retargeted;
+ }
+ if (animationGlbBlob) {
+ const animGltf = await _loadGlbBlob(animationGlbBlob);
+ const source = animGltf.animations?.[0];
+ if (source) {
+ const { clip: retargeted } = retargetClipToObject(source, scene);
+ if (retargeted) return retargeted;
+ }
+ }
+ // Already authored against this rig — no retarget needed.
+ if (avatarGltf.animations?.length) return avatarGltf.animations[0];
+ return null;
+}
+
+/**
+ * Replace skinned meshes with frame-0 static meshes for the base export, and
+ * record each one's geometry id alongside its captured frames so we can find
+ * and rewrite the matching `geometries/Geometry_<id>.usda` after export. Static
+ * (non-skinned) meshes are left untouched and simply stay un-animated.
+ */
+function buildFrame0Scene(scene, framesByMesh) {
+ const animated = []; // { geomId, frames }
+ for (const [skinned, frames] of framesByMesh) {
+ const geo = skinned.geometry.clone();
+ geo.setAttribute('position', new BufferAttribute(frames[0], 3));
+ geo.deleteAttribute('skinIndex');
+ geo.deleteAttribute('skinWeight');
+ geo.computeVertexNormals();
+
+ const mesh = new Mesh(geo, skinned.material);
+ mesh.name = skinned.name;
+ mesh.visible = skinned.visible;
+ mesh.position.copy(skinned.position);
+ mesh.quaternion.copy(skinned.quaternion);
+ mesh.scale.copy(skinned.scale);
+
+ (skinned.parent || scene).add(mesh);
+ (skinned.parent || scene).remove(skinned);
+
+ animated.push({ geomId: geo.id, frames });
+ }
+ return animated;
+}
+
+/**
+ * Convert a GLB Blob to an *animated* USDZ Blob for iOS Quick Look.
+ *
+ * @param {Blob} glbBlob — the avatar GLB
+ * @param {object} [opts]
+ * @param {Blob} [opts.animationGlbBlob] — clip source GLB (e.g. Idle_Breath.glb)
+ * @param {import('three').AnimationClip} [opts.clip] — pre-loaded clip (alternative to a blob)
+ * @param {number} [opts.targetFps]
+ * @param {number} [opts.maxFrames]
+ * @param {number} [opts.precision]
+ * @returns {Promise<Blob>} an animated .usdz blob
+ */
+export async function glbBlobToAnimatedUsdzBlob(glbBlob, opts = {}) {
+ const cfg = { ...DEFAULTS, ...opts };
+
+ const avatarGltf = await _loadGlbBlob(glbBlob);
+ const scene = avatarGltf.scene || avatarGltf.scenes?.[0];
+ if (!scene) throw new Error('animated-usdz: glb contained no scene');
+
+ const meshes = collectSkinnedMeshes(scene);
+ if (!meshes.length) throw new Error('animated-usdz: avatar has no skinned meshes to animate');
+
+ const clip = await resolveClip(scene, avatarGltf, opts);
+ if (!clip || !(clip.duration > 0)) {
+ throw new Error('animated-usdz: no usable animation clip for this avatar');
+ }
+
+ const frameCount = Math.min(
+ cfg.maxFrames,
+ Math.max(cfg.minFrames, Math.round(clip.duration * cfg.targetFps)),
+ );
+
+ const mixer = new AnimationMixer(scene);
+ const action = mixer.clipAction(clip);
+ const framesByMesh = _sampleSkinnedFrames(scene, mixer, action, meshes, {
+ frameCount,
+ duration: clip.duration,
+ });
+
+ const animated = buildFrame0Scene(scene, framesByMesh);
+ _coerceMaterialsToStandard(scene);
+
+ // Base export: proven materials / textures / alignment from the static path.
+ const exporter = new USDZExporter();
+ const baseBytes = await exporter.parseAsync(scene);
+
+ // Rewrite only the animated geometry + stage timing, then re-pack.
+ const files = unzipSync(baseBytes);
+ if (!files['model.usda']) throw new Error('animated-usdz: base export missing model.usda');
+
+ for (const { geomId, frames } of animated) {
+ const name = `geometries/Geometry_${geomId}.usda`;
+ const usda = files[name];
+ if (!usda) throw new Error(`animated-usdz: missing geometry file ${name}`);
+ files[name] = strToU8(_patchGeometryPoints(strFromU8(usda), frames, cfg.precision));
+ }
+
+ files['model.usda'] = strToU8(
+ _injectStageTiming(strFromU8(files['model.usda']), {
+ frameCount,
+ durationSeconds: clip.duration,
+ }),
+ );
+
+ return new Blob([_packUsdz(files)], { type: 'model/vnd.usdz+zip' });
+}