Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: implement WebGL context budget management and lazy rendering for avatars
nirholasc6cd3323f420
diff --git a/.gitignore b/.gitignoreindex 3fb7ea72a..ee04f2b94 100644--- a/.gitignore+++ b/.gitignore@@ -124,3 +124,6 @@ scripts/load-test-fleet.sh# CDK synth output (build artifact)infra/cdk.out++# SoundCloud backup — local only, never commit+sc/diff --git a/docs/aws-marketplace-listing-kit.md b/docs/aws-marketplace-listing-kit.mdnew file mode 100644index 000000000..78f90680f--- /dev/null+++ b/docs/aws-marketplace-listing-kit.md@@ -0,0 +1,199 @@+# AWS Marketplace — AI Agents & Tools Listing Kit (three.ws / x402)++Paste-ready content and the exact step sequence to create the **AI agents & tools**+product in the AWS Marketplace Management Portal (AMMP). The backend integration+(register URL, SNS webhook, key issuance, account linking) is already built and+deployed — see [aws-marketplace.md](./aws-marketplace.md). This doc covers the+listing itself, which has not yet been created (the AMMP "AI agents & tools+products" page shows "No products to display").++- **Seller account:** three-ws @ 155407237916+- **Delivery method:** API-based (SaaS fulfillment) — **not** container/Bedrock+ AgentCore. The whole backend is SaaS-style (ResolveCustomer + SNS + entitlements),+ so choose the API path. Container listings require Bedrock AgentCore and different infra you don't have.+- **Pricing decision:** **Free** AWS Marketplace listing — usage is priced the **same+ as all other x402 endpoints**. The AWS subscription is a free front door: subscribing+ links the AWS customer to a three.ws account and issues an x402 key+ (`/api/aws-marketplace/issue-key`). Every actual API call is then paid per-call in+ USDC over the x402 / HTTP 402 protocol, identical to a non-AWS caller. AWS Marketplace+ does **not** meter or bill usage — there are no AWS pricing dimensions. This matches the+ current EULA ("offered free of charge through AWS Marketplace") and clears AWS review+ fastest (no tax/bank/dimension interview).++> Note: `docs/aws-marketplace.md` and the unused `AWS_MP_METERING_DIMENSION` /+> `AWS_MP_DEFAULT_RATE_LIMIT_PER_MINUTE` env references describe an earlier+> AWS-metered-billing plan. That is superseded: billing is x402-per-call, not AWS-metered.+> Reconcile `docs/aws-marketplace.md` so it stops promising per-call/per-agent-minute AWS+> billing.++---++## Prerequisites (run where your seller AWS creds live — NOT in this codespace)++This codespace has no AWS credentials, so these must be run on a machine with+admin creds on account 155407237916.++### 1. Provision SNS topic + IAM user++```bash+./scripts/aws-marketplace-provision.sh+```++Outputs `AWS_MP_SNS_TOPIC_ARN`, `AWS_MP_ACCESS_KEY_ID`, `AWS_MP_SECRET_ACCESS_KEY`,+`AWS_MP_REGION`. Set all four in Vercel (production + preview). `AWS_MP_PRODUCT_CODE`+is assigned by AMMP after the product is created — add it last.++### 2. Publish the EULA to public S3 (currently returns 403 — must be fixed)++```bash+./scripts/aws-eula-publish.sh+```++As of this writing `https://three-ws-legal-155407237916.s3.amazonaws.com/aws-marketplace-eula.html`+returns **404 Not Found** — the bucket/object has never been published, so AMMP's+custom-EULA validator will reject it. The EULA IS live on the site+(`https://three.ws/legal/aws-marketplace-eula.html` → 200), but AMMP requires the S3+copy. Run the publish script, then confirm:++```bash+curl -sI "https://three-ws-legal-155407237916.s3.amazonaws.com/aws-marketplace-eula.html" | head -1+# expect: HTTP/1.1 200 OK+```++Alternative if S3 public access is blocked at the org level: in the wizard choose the+**Standard Contract for AWS Marketplace (SCMP)** instead of a custom EULA.++---++## Listing fields (paste into the AMMP "Create AI agents & tools product" wizard)++### Product title+```+three.ws — On-chain 3D AI Agents & x402 Paid API+```++### Short description (≤ 256 chars)+```+Deploy autonomous 3D AI agents that run natively in the browser, each with an on-chain identity and a wallet. A pay-per-call x402 API (HTTP 402 / USDC) for 3D model analysis, Solana token visualization, pump.fun launches, and agent reputation.+```++### Long / product description+```+three.ws is an open-source stack for autonomous 3D AI agents that run natively in+the browser. Every <agent-3d> tag deploys an agent with a Solana NFT identity+(Metaplex Core), an ERC-8004 cross-chain agent wallet, a browser-native 3D body+(WebGL via three.js), a Claude-powered brain, and native x402 / HTTP 402 payments+that settle in USDC on Base, BSC, and Solana.++The same platform exposes an agent-first paid API. Endpoints follow the x402 v2+protocol: every call returns a structured HTTP 402 challenge, the caller's wallet+or facilitator pays in USDC, and the request retries automatically. No API keys to+rotate, no monthly minimum — pay only for what you call.++Capabilities available through the API:+- 3D model analysis — fetch a glTF/GLB and return vertex/triangle counts, materials,+ textures, animations, extensions, and optimization hints.+- Solana token visualization — turn any SPL mint into a themed binary glTF (GLB),+ individually or in batches.+- pump.fun token launch — deploy a brand-new pump.fun token in one paid call; the+ service fronts the SOL deploy cost and signs the create-coin transaction, with+ optional vanity mint addresses.+- Agent analytics — reputation snapshots, pump.fun agent operational audits, and+ on-chain identity verification.+- MCP server — the same surface exposed as JSON-RPC 2.0 tools for MCP clients.++Subscribe through AWS Marketplace to manage access from your AWS account. The+product is currently offered at no charge through AWS Marketplace.+```++### Highlights (3, ≤ 500 chars each)+```+1. Browser-native autonomous agents — every <agent-3d> tag is a 3D AI agent with a Solana NFT identity, an ERC-8004 wallet, and a Claude brain. No SDK lock-in; open source.+2. Agent-first x402 paid API — pay-per-call over HTTP 402, settled in USDC on Base, BSC, and Solana. Covers 3D model analysis, token-to-mesh, pump.fun launches, and agent reputation. Also available as an MCP server.+3. Enterprise procurement on AWS — subscribe from your AWS account, no new vendor in procurement, eligible for AWS credits and EDP commitments. Currently free through AWS Marketplace.+```++### Categories (select up to 3)+```+- AI agents and tools / Developer tools+- Machine learning+- Blockchain+```++### Search keywords+```+ai agent, 3d, webgl, three.js, x402, http 402, usdc, solana, base, pump.fun, metaplex, erc-8004, mcp, glTF, GLB, claude, on-chain identity, agent payments+```++### Product logo+```+public/aws-logo-512.png — generated 512×512 PNG, the brand mark centered on black.+Within AMMP's required square 120–640px range. Upload this as the product logo.+(Regenerate from public/pwa-icon.svg via scripts/gen-aws-logo.mjs if the brand changes.)+```++### Support / resources+```+- Support: https://github.com/nirholas/three.ws/issues+- Support email: [email protected]+- Website: https://three.ws+- API discovery (x402): https://three.ws/.well-known/x402.json+- OpenAPI: https://three.ws/openapi.json+- MCP endpoint: https://three.ws/api/mcp+- Docs: https://three.ws/docs/aws-marketplace.md+```++### Pricing+```+Free. No AWS pricing dimensions, no contract, no AWS metering.+Usage is paid per-call in USDC via x402 (HTTP 402) — same as every other x402 endpoint.+The free AWS subscription only grants the x402 access key.+```++---++## SaaS fulfillment & integration fields++| AMMP field | Value |+|---|---|+| Fulfillment / SaaS URL (Registration URL) | `https://three.ws/api/aws-marketplace/register` |+| SNS notification topic ARN | output of `aws-marketplace-provision.sh` (`arn:aws:sns:us-east-1:155407237916:three-ws-marketplace-subscription`) |+| Custom EULA URL | `https://three-ws-legal-155407237916.s3.amazonaws.com/aws-marketplace-eula.html` (must return 200 — see prereq #2) — or pick Standard Contract |+| Post-subscribe redirect | `https://three.ws/aws-marketplace/welcome` (handled by register.js) |++Lifecycle events land on `POST /api/aws-marketplace/subscription` (SNS webhook —+already deployed; handles subscribe-success, unsubscribe-success, subscribe-fail,+entitlement-updated, and the SubscriptionConfirmation handshake).++---++## Step sequence in AMMP++1. Run prereqs #1 and #2 above; set the five `AWS_MP_*` env vars in Vercel.+2. AMMP → **AI agents & tools products** → **Create AI agents & tools product**.+3. Delivery method: **API-based** (SaaS). (Until you finish the wizard the draft may+ appear under **SaaS products**, per AMMP's own note — that's expected.)+4. Fill product detail fields from the "Listing fields" section above; upload the logo.+5. Pricing: choose **Free**.+6. Fulfillment: paste the Registration URL and SNS Topic ARN from the table.+7. EULA: paste the S3 Custom EULA URL (confirm 200 first) or select Standard Contract.+8. Save → AMMP assigns a **Product Code**. Set `AWS_MP_PRODUCT_CODE` in Vercel and redeploy.+9. Submit as a **limited (private) offer** first and run one end-to-end subscribe →+ redirect → welcome → issue-key test before requesting public visibility.+10. Once the private round-trip works, request **public** visibility.++---++## What is and isn't done++Done (in repo, deployed):+- Registration URL, SNS webhook, key issuance, account linking endpoints.+- `aws_marketplace_customers` schema + x402 bridge.+- EULA HTML, S3 publish script, SNS/IAM provision script.+- Welcome onboarding page.++Not done (requires AWS console / seller creds — cannot be done from this repo):+- Running the provision + EULA-publish scripts (no AWS CLI/creds in codespace).+- Publishing the S3 EULA (currently 404 — never uploaded).+- Creating the product in the AMMP wizard (manual web UI).+- Obtaining and wiring `AWS_MP_PRODUCT_CODE`.diff --git a/pages/home.html b/pages/home.htmlindex 92977a3a0..20a2436b1 100644--- a/pages/home.html+++ b/pages/home.html@@ -4982,16 +4982,42 @@<script type="module">import * as THREE from 'three';import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { reserveWebGLContext } from '/src/webgl-budget.js';const canvas = document.getElementById('pricing-canvas');const tiers = [...document.querySelectorAll('#pricing-stage .pricing-card')];if (canvas && tiers.length && window.matchMedia('(min-width: 861px)').matches) {- const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });- renderer.setPixelRatio(Math.min(devicePixelRatio, 2));- renderer.outputColorSpace = THREE.SRGBColorSpace;- renderer.toneMapping = THREE.ACESFilmicToneMapping;- renderer.toneMappingExposure = 1.1;+ // The renderer is created lazily, only when the pricing section nears the+ // viewport. Creating it at page load would make it one of the oldest WebGL+ // contexts on a page full of <agent-3d> avatars, so the browser's "oldest+ // context wins" eviction would kill the pricing avatar first. Deferring it+ // keeps it young; the webglcontextlost/restored handlers let it recover if+ // it is ever evicted anyway.+ let renderer = null;+ let contextLost = false;+ let sectionVisible = false;+ function ensureRenderer() {+ if (renderer) return renderer;+ renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });+ renderer.setPixelRatio(Math.min(devicePixelRatio, 2));+ renderer.outputColorSpace = THREE.SRGBColorSpace;+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.1;+ // Count this context against the shared budget so <agent-3d> grids on the+ // same page leave room for it (see /src/webgl-budget.js).+ reserveWebGLContext();+ canvas.addEventListener('webglcontextlost', (e) => {+ e.preventDefault();+ contextLost = true;+ }, false);+ canvas.addEventListener('webglcontextrestored', () => {+ contextLost = false;+ resize();+ }, false);+ resize();+ return renderer;+ }const scene = new THREE.Scene();const PX_PER_UNIT = 120;@@ -5027,7 +5053,7 @@ if (canvas && tiers.length && window.matchMedia('(min-width: 861px)').matches) {function resize() {const r = canvas.getBoundingClientRect();if (!r.width || !r.height) return;- renderer.setSize(r.width, r.height, false);+ if (renderer) renderer.setSize(r.width, r.height, false);updateFrustum();if (avatar && activeTier && phase === 'idle') {const t = standOnTopOf(activeTier);@@ -5183,6 +5209,7 @@ if (canvas && tiers.length && window.matchMedia('(min-width: 861px)').matches) {if (!entries[0].isIntersecting || loaded) return;loaded = true;io.disconnect();+ ensureRenderer();resize();new GLTFLoader().load('/avatars/cz.glb', gltf => {@@ -5218,6 +5245,13 @@ if (canvas && tiers.length && window.matchMedia('(min-width: 861px)').matches) {}, { threshold: 0, rootMargin: '400px' });io.observe(document.getElementById('pricing-stage'));+ // Only draw while the section is actually on screen — saves GPU/CPU and+ // avoids rendering onto a context the browser may have evicted.+ const visObs = new IntersectionObserver(entries => {+ sectionVisible = entries.some(e => e.isIntersecting);+ });+ visObs.observe(document.getElementById('pricing-stage'));+const clock = new THREE.Clock();(function tick() {requestAnimationFrame(tick);@@ -5245,7 +5279,7 @@ if (canvas && tiers.length && window.matchMedia('(min-width: 861px)').matches) {camera.position.x += (targetCamX - camera.position.x) * 0.04;camera.position.y += (targetCamY - camera.position.y) * 0.04;- renderer.render(scene, camera);+ if (renderer && !contextLost && sectionVisible) renderer.render(scene, camera);} catch (_) {}})();}diff --git a/public/aws-logo-512.png b/public/aws-logo-512.pngnew file mode 100644index 000000000..448bd44deBinary files /dev/null and b/public/aws-logo-512.png differdiff --git a/public/features.json b/public/features.jsonindex 870a18be8..9c0179a28 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-05-30T01:04:04.148Z",+ "generated_at": "2026-05-30T08:53:32.741Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scratch/embed-env.tmp.mjs b/scratch/embed-env.tmp.mjsnew file mode 100644index 000000000..d840b3e58--- /dev/null+++ b/scratch/embed-env.tmp.mjs@@ -0,0 +1,46 @@+import { chromium } from 'playwright';++const PORT = process.env.PORT || '3000';+const browser = await chromium.launch({+ args: ['--use-gl=swiftshader', '--enable-unsafe-swiftshader', '--no-sandbox', '--disable-dev-shm-usage'],+});++async function probeEmbed(query, label) {+ const ctx = await browser.newContext({ viewport: { width: 360, height: 540 } });+ const page = await ctx.newPage();+ const errs = [];+ page.on('pageerror', (e) => errs.push(e.message));+ await page.goto(`http://localhost:${PORT}/walk-embed${query}`, { waitUntil: 'domcontentloaded', timeout: 15000 });+ await page.waitForTimeout(4500);+ const info = await page.evaluate(() => {+ const w = window;+ const r = w.__walkRenderer || null;+ return {+ // Read the live three.js scene state via the canvas pixel as a proxy:+ // sample the center-top pixel (sky region) of the WebGL canvas.+ topPixel: (() => {+ const c = document.getElementById('walk-canvas');+ if (!c) return null;+ // Use a 2d snapshot via drawImage into an offscreen canvas.+ const off = document.createElement('canvas');+ off.width = c.width; off.height = c.height;+ const g = off.getContext('2d');+ g.drawImage(c, 0, 0);+ const px = g.getImageData(Math.floor(c.width/2), 6, 1, 1).data;+ return { r: px[0], g: px[1], b: px[2], a: px[3] };+ })(),+ status: document.getElementById('walk-status')?.textContent || null,+ };+ });+ const fatal = errs.filter((m) => !/swiftshader|webgl|GroupMarker|TextureProxy|GL_/i.test(m));+ console.log(label.padEnd(26), JSON.stringify(info.topPixel), 'errs:', fatal.length ? fatal : 'none');+ await ctx.close();+}++await probeEmbed('?env=studio', 'studio (transparent)');+await probeEmbed('?env=beach', 'beach (sky blue)');+await probeEmbed('?env=sunset', 'sunset (orange)');+await probeEmbed('?env=night', 'night (dark)');+await probeEmbed('?bg=%23101820&env=beach', 'bg #101820 + env=beach');++await browser.close();diff --git a/scratch/embed-env2.tmp.mjs b/scratch/embed-env2.tmp.mjsnew file mode 100644index 000000000..51570059f--- /dev/null+++ b/scratch/embed-env2.tmp.mjs@@ -0,0 +1,28 @@+import { chromium } from 'playwright';+const PORT = process.env.PORT || '3000';++async function probe(query, label) {+ const browser = await chromium.launch({+ args: ['--use-gl=swiftshader', '--enable-unsafe-swiftshader', '--no-sandbox', '--disable-dev-shm-usage'],+ });+ const page = await browser.newPage();+ const errs = [];+ page.on('pageerror', (e) => errs.push(e.message));+ await page.goto(`http://localhost:${PORT}/walk-embed${query}`, { waitUntil: 'domcontentloaded', timeout: 15000 });+ await page.waitForTimeout(4500);+ const px = await page.evaluate(() => {+ const c = document.getElementById('walk-canvas');+ const off = document.createElement('canvas');+ off.width = c.width; off.height = c.height;+ const g = off.getContext('2d');+ g.drawImage(c, 0, 0);+ const p = g.getImageData(Math.floor(c.width/2), 6, 1, 1).data;+ return { r: p[0], g: p[1], b: p[2], a: p[3] };+ });+ const fatal = errs.filter((m) => !/swiftshader|webgl|GroupMarker|TextureProxy|GL_/i.test(m));+ console.log(label.padEnd(26), JSON.stringify(px), 'errs:', fatal.length ? fatal : 'none');+ await browser.close();+}++await probe('?env=night', 'night → 0x10141f');+await probe('?bg=%23ff0000&env=beach', 'bg=red wins over env');diff --git a/scratch/one.tmp.mjs b/scratch/one.tmp.mjsnew file mode 100644index 000000000..e156e19d0--- /dev/null+++ b/scratch/one.tmp.mjs@@ -0,0 +1,8 @@+import { chromium } from 'playwright';+const b = await chromium.launch({ args: ['--use-gl=swiftshader','--enable-unsafe-swiftshader','--no-sandbox','--disable-dev-shm-usage'] });+const p = await b.newPage();+await p.goto('http://localhost:3000/walk-embed?bg=%23ff0000&env=beach', { waitUntil:'domcontentloaded', timeout:15000 });+await p.waitForTimeout(4500);+const px = await p.evaluate(() => { const c=document.getElementById('walk-canvas'); const o=document.createElement('canvas'); o.width=c.width;o.height=c.height; const g=o.getContext('2d'); g.drawImage(c,0,0); const d=g.getImageData(Math.floor(c.width/2),6,1,1).data; return {r:d[0],g:d[1],b:d[2],a:d[3]}; });+process.stdout.write('RESULT bg=red+env=beach => ' + JSON.stringify(px) + '\n');+await b.close();diff --git a/scripts/gen-aws-logo.mjs b/scripts/gen-aws-logo.mjsnew file mode 100644index 000000000..98d7266c8--- /dev/null+++ b/scripts/gen-aws-logo.mjs@@ -0,0 +1,32 @@+#!/usr/bin/env node+// Generate the square AWS Marketplace product logo from the brand mark.+//+// AMMP requires a square PNG, 120–640px per side. The repo's og-image.png is+// 1200×630 (wrong aspect), so we render public/pwa-icon.svg centered on a black+// canvas (matching the brand / EULA background) at 512×512.+//+// Usage: node scripts/gen-aws-logo.mjs++import sharp from 'sharp';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';++const root = join(dirname(fileURLToPath(import.meta.url)), '..');+const SRC = join(root, 'public/pwa-icon.svg');+const OUT = join(root, 'public/aws-logo-512.png');+const SIZE = 512;+const INNER = 384; // mark inset, leaving even padding inside the square++const mark = await sharp(readFileSync(SRC), { density: 300 })+ .resize(INNER, INNER, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } })+ .png()+ .toBuffer();++await sharp({ create: { width: SIZE, height: SIZE, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 1 } } })+ .composite([{ input: mark, gravity: 'center' }])+ .png()+ .toFile(OUT);++const meta = await sharp(OUT).metadata();+console.log(`Wrote ${OUT} (${meta.width}x${meta.height} ${meta.format})`);diff --git a/scripts/verify-context-budget.html b/scripts/verify-context-budget.htmlnew file mode 100644index 000000000..6cd3ff94a--- /dev/null+++ b/scripts/verify-context-budget.html@@ -0,0 +1,37 @@+<!doctype html>+<html>+<head>+ <meta charset="utf-8" />+ <title>agent-3d WebGL context budget check</title>+ <style>+ body { margin: 0; background: #000; }+ .row { height: 600px; display: block; }+ agent-3d { width: 320px; height: 560px; display: block; }+ </style>+</head>+<body>+ <!-- Imports the LOCAL (patched) source through the Vite dev server. -->+ <script type="module" src="/src/element.js"></script>+ <script type="module">+ // Stack 14 avatars (> the budget of 8). With the LRU context budget,+ // offscreen viewers release their contexts, so the browser should never+ // log "Too many active WebGL contexts".+ const N = 14;+ for (let i = 0; i < N; i++) {+ const row = document.createElement('div');+ row.className = 'row';+ const el = document.createElement('agent-3d');+ el.setAttribute('body', '/avatars/cz.glb');+ el.setAttribute('mode', 'inline');+ el.setAttribute('responsive', '');+ el.setAttribute('background', 'transparent');+ el.setAttribute('name-plate', 'off');+ el.setAttribute('avatar-chat', 'off');+ el.setAttribute('kiosk', '');+ row.appendChild(el);+ document.body.appendChild(row);+ }+ window.__AGENT_COUNT__ = N;+ </script>+</body>+</html>diff --git a/scripts/verify-context-budget.mjs b/scripts/verify-context-budget.mjsnew file mode 100644index 000000000..92f0e4d82--- /dev/null+++ b/scripts/verify-context-budget.mjs@@ -0,0 +1,79 @@+// Verifies the <agent-3d> WebGL context budget: stacks 14 avatars (> budget),+// scrolls top→bottom→top, and asserts the browser never logs "Too many active+// WebGL contexts" — i.e. offscreen viewers released their contexts. Run while+// `npm run dev` is up on port 3000.+import puppeteer from 'puppeteer';++const URL = process.env.URL || 'http://localhost:3000/scripts/verify-context-budget.html';+const CHROME = '/home/codespace/.cache/puppeteer/chrome/linux-147.0.7727.57/chrome-linux64/chrome';++const browser = await puppeteer.launch({+ executablePath: CHROME,+ args: ['--no-sandbox', '--disable-dev-shm-usage'],+ defaultViewport: { width: 1280, height: 800 },+});+const page = await browser.newPage();++let tooMany = 0;+let contextLost = 0;+const errors = [];+page.on('console', (msg) => {+ const t = msg.text();+ if (/Too many active WebGL contexts/i.test(t)) tooMany++;+ if (/Context Lost/i.test(t)) contextLost++;+ if (msg.type() === 'error') errors.push(t);+ if (process.env.LOG_ALL) console.log(`[${msg.type()}] ${t}`);+});+page.on('pageerror', (e) => errors.push(`pageerror: ${e.message}`));++await page.goto(URL, { waitUntil: 'domcontentloaded', timeout: 90000 });+// Let Vite transform the module graph and the avatars boot.+await new Promise((r) => setTimeout(r, 6000));++// Scroll through the whole stack and back so every viewer boots, then the+// offscreen ones get evicted by the budget.+const height = await page.evaluate(() => document.body.scrollHeight);+for (let y = 0; y <= height; y += 500) {+ await page.evaluate((yy) => window.scrollTo(0, yy), y);+ await new Promise((r) => setTimeout(r, 250));+}+await page.evaluate(() => window.scrollTo(0, 0));+await new Promise((r) => setTimeout(r, 1500));++// Count canvases / live WebGL contexts across the page, piercing shadow DOM+// (each <agent-3d> renders inside its own shadow root).+const { canvases, live } = await page.evaluate(() => {+ const all = [];+ const walk = (root) => {+ for (const el of root.querySelectorAll('*')) {+ if (el.tagName === 'CANVAS') all.push(el);+ if (el.shadowRoot) walk(el.shadowRoot);+ }+ };+ walk(document);+ let live = 0;+ for (const c of all) {+ const gl = c.getContext('webgl2') || c.getContext('webgl');+ if (gl && !gl.isContextLost()) live++;+ }+ return { canvases: all.length, live };+});++await browser.close();++console.log(`agents stacked : 14`);+console.log(`canvases (all roots): ${canvases}`);+console.log(`live WebGL contexts : ${live}`);+console.log(`"Too many" warnings : ${tooMany}`);+console.log(`page errors : ${errors.length}`);+if (errors.length) console.log(errors.slice(0, 5).join('\n'));++if (tooMany > 0) {+ console.error('\nFAIL: browser exhausted its WebGL context budget.');+ process.exit(1);+}+if (errors.length > 0) {+ console.error('\nFAIL: page errors detected.');+ process.exit(1);+}+console.log('\nPASS: context budget held — no WebGL exhaustion.');diff --git a/src/avatar-drop.js b/src/avatar-drop.jsindex af5235be5..eccc77ce5 100644--- a/src/avatar-drop.js+++ b/src/avatar-drop.js@@ -14,6 +14,7 @@ import {LoopOnce,} from 'three';import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { reserveWebGLContext } from './webgl-budget.js';export function initAvatarDrop(sectionEl) {const canvas = sectionEl.querySelector('#drop-canvas');@@ -26,6 +27,9 @@ export function initAvatarDrop(sectionEl) {renderer.outputColorSpace = SRGBColorSpace;renderer.toneMapping = ACESFilmicToneMapping;renderer.toneMappingExposure = 1.1;+ // Count this context against the shared budget so <agent-3d> grids on the+ // same page leave room for it (see webgl-budget.js / element.js).+ reserveWebGLContext();const scene = new Scene();@@ -399,9 +403,10 @@ export function initAvatarDrop(sectionEl) {}).catch(e => console.warn('[avatar-drop] boot failed', e));- // Render loop with visibility pause+ // Render loop — paused when the section is offscreen or the tab is hidden.const clock = new Clock();- let running = true;+ let running = false;+ let onScreen = true;function tick() {if (!running) return;@@ -414,12 +419,19 @@ export function initAvatarDrop(sectionEl) {renderer.render(scene, camera);} catch (_) {}}- tick();++ function syncRunning() {+ const next = onScreen && document.visibilityState !== 'hidden';+ if (next === running) return;+ running = next;+ if (running) { clock.getDelta(); tick(); }+ }const visObs = new IntersectionObserver(entries => {- const vis = entries[0].isIntersecting;- if (vis && !running) { running = true; clock.getDelta(); tick(); }- else if (!vis && running) { running = false; }+ onScreen = entries[0].isIntersecting;+ syncRunning();}, { threshold: 0 });visObs.observe(sectionEl);+ document.addEventListener('visibilitychange', syncRunning);+ syncRunning();}diff --git a/src/element.js b/src/element.jsindex 8e3fec1ce..b1a840ca6 100644--- a/src/element.js+++ b/src/element.js@@ -27,6 +27,86 @@ import { AgentNotifier } from './agent-notifier.js';const MODES = ['inline', 'floating', 'section', 'fullscreen'];+// ── WebGL context budget ────────────────────────────────────────────────+// Browsers cap the number of simultaneous WebGL contexts (~16 in Chrome).+// Each booted <agent-3d> holds one (two when axes are shown) for its whole+// lifetime, so a page with many avatars — a showcase grid, a marketplace, a+// long landing page — silently exhausts the budget. The browser then evicts+// the *oldest* context ("Too many active WebGL contexts. Oldest context will+// be lost.") and that avatar freezes or turns blank, with no way to recover+// while every other context stays alive.+//+// We cap the number of *live* viewers instead. When a new one boots over+// budget, the least-recently-visible offscreen viewer releases its context+// (full teardown → forceContextLoss) and re-arms its viewport observer, so it+// re-boots automatically the moment it scrolls back into view. Whatever the+// user is actually looking at is never evicted.+const MAX_LIVE_VIEWERS = (() => {+ try {+ const n = Number(+ typeof window !== 'undefined' ? window.AGENT3D_MAX_LIVE_VIEWERS : 0,+ );+ if (Number.isFinite(n) && n > 0) return Math.floor(n);+ } catch {}+ return 8;+})();+const _liveViewers = new Set();+const _nowMs = () =>+ typeof performance !== 'undefined' && performance.now+ ? performance.now()+ : Date.now();++function _trackLiveViewer(el) {+ _liveViewers.add(el);+ _enforceViewerBudget(el);+}++function _untrackLiveViewer(el) {+ _liveViewers.delete(el);+}++// Standalone renderers elsewhere on the page (homepage avatar-drop, walk+// preview, footer bot, …) reserve slots via window.__agent3dReservedContexts+// (see webgl-budget.js). Subtract them so the page-wide total stays under the+// browser's ~16-context cap, never below one live viewer.+function _effectiveViewerBudget() {+ let reserved = 0;+ try {+ const n = Number(+ typeof window !== 'undefined' ? window.__agent3dReservedContexts : 0,+ );+ if (Number.isFinite(n) && n > 0) reserved = Math.floor(n);+ } catch {}+ return Math.max(1, MAX_LIVE_VIEWERS - reserved);+}++function _enforceViewerBudget(justBooted) {+ const budget = _effectiveViewerBudget();+ if (_liveViewers.size <= budget) return;+ const evictable = [];+ for (const v of _liveViewers) {+ if (v !== justBooted && v._isEvictable && v._isEvictable()) evictable.push(v);+ }+ // Least-recently-visible first.+ evictable.sort((a, b) => (a._lastVisibleAt || 0) - (b._lastVisibleAt || 0));+ let over = _liveViewers.size - budget;+ for (const v of evictable) {+ if (over <= 0) break;+ v._releaseForBudget();+ over--;+ }+}++// Let standalone renderers trigger an eviction the moment they reserve a slot,+// instead of waiting for the next viewer to boot.+if (typeof window !== 'undefined') {+ window.__agent3dEnforceBudget = () => {+ try {+ _enforceViewerBudget(null);+ } catch {}+ };+}+function _parsePx(val) {const n = parseFloat(val);return n > 0 && typeof val === 'string' && val.trim().endsWith('px') ? n : 0;@@ -581,6 +661,9 @@ class Agent3DElement extends HTMLElement {this._streamingChatRafPending = false;this._chatAutoScroll = true;this._pendingSay = null;+ // WebGL context budget bookkeeping.+ this._inViewport = false;+ this._lastVisibleAt = 0;}connectedCallback() {@@ -1179,20 +1262,67 @@ class Agent3DElement extends HTMLElement {}_observeViewport() {- if (this.hasAttribute('eager')) return;+ if (this.hasAttribute('eager')) {+ // Eager viewers boot immediately and are never released by the budget;+ // treat them as permanently in-viewport so they sort to the top.+ this._inViewport = true;+ this._lastVisibleAt = _nowMs();+ return;+ }if (typeof IntersectionObserver === 'undefined') {+ this._inViewport = true;this._boot();return;}- this._io = new IntersectionObserver((entries) => {- if (entries.some((e) => e.isIntersecting)) {- this._io.disconnect();- this._boot();- }- });+ if (this._io) return;+ // Persistent observer (not disconnected after first boot): it both lazily+ // boots the viewer and tracks visibility so the context budget can evict+ // the least-recently-visible offscreen viewer and re-boot it on return.+ // The 300px margin gives lead time to boot before the avatar is on screen+ // and damps thrash at the viewport edge.+ this._io = new IntersectionObserver(+ (entries) => {+ const isVis = entries.some((e) => e.isIntersecting);+ this._inViewport = isVis;+ if (isVis) {+ this._lastVisibleAt = _nowMs();+ if (!this._mounted && !this._booting) this._boot();+ }+ },+ { rootMargin: '300px 0px' },+ );this._io.observe(this);}+ // Eligible for budget eviction only when offscreen and not holding live+ // state a user would lose (voice, an open chat pill, an eager/keep-alive+ // pin). Whatever is on screen or mid-conversation is always spared.+ _isEvictable() {+ return (+ this._mounted &&+ !this._inViewport &&+ !this.hasAttribute('eager') &&+ !this.hasAttribute('keep-alive') &&+ !this._hasActiveSession()+ );+ }++ _hasActiveSession() {+ return !!(+ this._livekitVoice ||+ this._voiceClient ||+ this._listening ||+ this._pillActive+ );+ }++ _releaseForBudget() {+ if (!this._mounted) return;+ this._teardown(); // disposes the viewer → frees the WebGL context(s)+ this._io = null; // _teardown disconnected it; re-arm a fresh observer+ this._observeViewport(); // re-boots automatically when scrolled back in+ }+async _boot() {if (this._booting || this._mounted) return;this._renderShell();@@ -1554,6 +1684,10 @@ class Agent3DElement extends HTMLElement {}this._mounted = true;+ // Join the live-viewer set and evict an offscreen viewer if this boot+ // pushed us over the WebGL context budget.+ this._lastVisibleAt = _nowMs();+ _trackLiveViewer(this);// ── Skill payment ─────────────────────────────────────────────────// When a paid skill is invoked, render an inline payment chip inside@@ -2326,9 +2460,11 @@ class Agent3DElement extends HTMLElement {}this._autoResolvedManifest = false;}+ _untrackLiveViewer(this);try {this._io?.disconnect();} catch {}+ this._io = null;try {this._ro?.disconnect();} catch {}diff --git a/src/footer-bot.js b/src/footer-bot.jsindex c2dc3c0b7..e2a9239c2 100644--- a/src/footer-bot.js+++ b/src/footer-bot.js@@ -11,6 +11,7 @@ import {AnimationMixer,} from 'three';import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';+import { reserveWebGLContext } from './webgl-budget.js';const canvas = document.getElementById('footer-bot-canvas');if (!canvas) throw new Error('[footer-bot] canvas not found');@@ -25,6 +26,9 @@ renderer.setPixelRatio(Math.min(devicePixelRatio, 2));renderer.toneMapping = ACESFilmicToneMapping;renderer.toneMappingExposure = 0.7;renderer.outputColorSpace = SRGBColorSpace;+// Count this context against the shared budget so <agent-3d> grids on the same+// page leave room for it (see webgl-budget.js / element.js).+reserveWebGLContext();const scene = new Scene();@@ -59,13 +63,38 @@ new GLTFLoader().load('/animations/robotexpressive.glb', (gltf) => {// 20deg/sec auto-rotate, matching model-viewer rotation-per-second="20deg"const rotSpeed = MathUtils.degToRad(20);-(function animate() {+// The footer sits at the bottom of long pages, so it is offscreen most of the+// time. Only render while it is actually visible and the tab is focused —+// otherwise it burns a GPU context and a RAF loop for nothing.+let running = false;+let onScreen = true;++function animate() {+ if (!running) return;requestAnimationFrame(animate);const dt = clock.getDelta();if (mixer) mixer.update(dt);if (robot) robot.rotation.y += rotSpeed * dt;renderer.render(scene, camera);-})();+}++function syncRunning() {+ const next = onScreen && document.visibilityState !== 'hidden';+ if (next === running) return;+ running = next;+ if (running) { clock.getDelta(); animate(); }+}++if (typeof IntersectionObserver !== 'undefined') {+ new IntersectionObserver((entries) => {+ onScreen = entries[0].isIntersecting;+ syncRunning();+ }, { threshold: 0 }).observe(canvas);+} else {+ onScreen = true;+}+document.addEventListener('visibilitychange', syncRunning);+syncRunning();if (typeof ResizeObserver !== 'undefined' && parent) {new ResizeObserver(() => {diff --git a/src/viewer.js b/src/viewer.jsindex 0f8c297e9..fcf54c135 100644--- a/src/viewer.js+++ b/src/viewer.js@@ -574,6 +574,7 @@ export class Viewer {render() {this.renderer.render(this.scene, this.activeCamera);if (this.state.grid) {+ this._ensureAxesRenderer();this.axesCamera.position.copy(this.defaultCamera.position);this.axesCamera.lookAt(this.axesScene.position);this.axesRenderer.render(this.axesScene, this.axesCamera);@@ -786,7 +787,7 @@ export class Viewer {this.axesCamera.aspect = this.axesDiv.clientWidth / this.axesDiv.clientHeight;this.axesCamera.updateProjectionMatrix();- this.axesRenderer.setSize(this.axesDiv.clientWidth, this.axesDiv.clientHeight);+ this.axesRenderer?.setSize(this.axesDiv.clientWidth, this.axesDiv.clientHeight);// Re-frame so the full avatar stays visible after the canvas changes// shape — the initial framing uses the aspect at load time, which is@@ -1145,6 +1146,7 @@ export class Viewer {if (this.state.grid !== Boolean(this.gridHelper)) {if (this.state.grid) {+ this._ensureAxesRenderer();this.gridHelper = new GridHelper();this.axesHelper = new AxesHelper();this.axesHelper.renderOrder = 999;@@ -1156,7 +1158,7 @@ export class Viewer {this.scene.remove(this.axesHelper);this.gridHelper = null;this.axesHelper = null;- this.axesRenderer.clear();+ this.axesRenderer?.clear();}}@@ -1265,15 +1267,26 @@ export class Viewer {this.axesCamera = new PerspectiveCamera(50, clientWidth / clientHeight, 0.1, 10);this.axesScene.add(this.axesCamera);- this.axesRenderer = new WebGLRenderer({ alpha: true });- this.axesRenderer.setPixelRatio(window.devicePixelRatio);- this.axesRenderer.setSize(this.axesDiv.clientWidth, this.axesDiv.clientHeight);+ // The axes gizmo is a debug helper, shown only when the "grid" display+ // toggle is on (off by default, and the GUI is closed entirely in kiosk/+ // embed mode). Its WebGLRenderer is a whole second GL context, so we+ // create it lazily — otherwise every <agent-3d> on a page would burn two+ // contexts and exhaust the browser's ~16-context budget twice as fast.+ this.axesRenderer = null;this.axesCamera.up = this.defaultCamera.up;this.axesCorner = new AxesHelper(5);this.axesScene.add(this.axesCorner);+ }++ _ensureAxesRenderer() {+ if (this.axesRenderer || !this.axesDiv) return this.axesRenderer;+ this.axesRenderer = new WebGLRenderer({ alpha: true });+ this.axesRenderer.setPixelRatio(window.devicePixelRatio);+ this.axesRenderer.setSize(this.axesDiv.clientWidth, this.axesDiv.clientHeight);this.axesDiv.appendChild(this.axesRenderer.domElement);+ return this.axesRenderer;}addGUI() {diff --git a/src/walk-embed-preview.js b/src/walk-embed-preview.jsindex fac05c49f..db77ee908 100644--- a/src/walk-embed-preview.js+++ b/src/walk-embed-preview.js@@ -28,6 +28,7 @@ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';import nipplejs from 'nipplejs';import { AnimationManager } from './animation-manager.js';+import { reserveWebGLContext } from './webgl-budget.js';const AVATAR_URL = '/avatars/default.glb';const ANIMATIONS_MANIFEST_URL = '/animations/manifest.json';@@ -65,6 +66,9 @@ export function initWalkPreview(container) {renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));renderer.shadowMap.enabled = true;renderer.shadowMap.type = PCFSoftShadowMap;+ // Count this context against the shared budget so <agent-3d> grids on the+ // same page leave room for it (see webgl-budget.js / element.js).+ reserveWebGLContext();const scene = new Scene();const pmrem = new PMREMGenerator(renderer);@@ -317,7 +321,7 @@ export function initWalkPreview(container) {const moveForward = new Vector3();const moveRight = new Vector3();const upY = new Vector3(0, 1, 0);- let running = true;+ let running = false;function tick() {if (!running) return;@@ -436,30 +440,35 @@ export function initWalkPreview(container) {// ── Lazy init — only start when visible ─────────────────────────let started = false;+ let onScreen = true;++ // Start/stop the loop based on both viewport visibility and tab visibility.+ function syncRunning() {+ if (!started) return;+ const next = onScreen && document.visibilityState !== 'hidden';+ if (next === running) return;+ running = next;+ if (running) { clock.start(); tick(); }+ else clock.stop();+ }+const observer = new IntersectionObserver((entries) => {for (const entry of entries) {if (entry.isIntersecting && !started) {started = true;loadAvatar().catch((err) => console.warn('[walk-preview] load failed', err));- tick();+ syncRunning();observer.disconnect();}}}, { threshold: 0.1 });observer.observe(container);- // Pause rendering when off-screen+ // Pause rendering when off-screen or when the tab is hidden.const visObserver = new IntersectionObserver((entries) => {- for (const entry of entries) {- if (!entry.isIntersecting && running) {- running = false;- clock.stop();- } else if (entry.isIntersecting && !running && started) {- running = true;- clock.start();- tick();- }- }+ onScreen = entries[0].isIntersecting;+ syncRunning();}, { threshold: 0 });visObserver.observe(container);+ document.addEventListener('visibilitychange', syncRunning);}diff --git a/src/walk-embed.js b/src/walk-embed.jsindex 9280330b7..ce855540a 100644--- a/src/walk-embed.js+++ b/src/walk-embed.js@@ -133,7 +133,10 @@ function postToHost(payload) {const renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true });renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));renderer.setSize(window.innerWidth, window.innerHeight, false);-renderer.setClearColor(0x000000, BG_PARAM && BG_PARAM !== 'transparent' ? 1 : 0);+const HAS_SOLID_BG = !!(BG_PARAM && BG_PARAM !== 'transparent');+// Paint the actual bg color (not opaque black) so ?bg=#101820 renders the+// requested color. Transparent embeds keep alpha 0 so the host shows through.+renderer.setClearColor(HAS_SOLID_BG ? new Color(BG_PARAM) : 0x000000, HAS_SOLID_BG ? 1 : 0);renderer.shadowMap.enabled = true;renderer.shadowMap.type = PCFSoftShadowMap;@@ -179,6 +182,31 @@ groundShadowCatcher.receiveShadow = true;groundShadowCatcher.visible = !SHOW_GROUND;scene.add(groundShadowCatcher);+// Apply the requested environment preset. studio/void keep the canvas+// transparent (avatar floats on the host page); scenic presets paint a sky ++// matching fog and tint the ground. An explicit ?bg color always wins as the+// clear color, so bg + env compose predictably.+function applyEmbedEnvironment(envId) {+ const env = WALK_ENVIRONMENTS[envId] || WALK_ENVIRONMENTS.studio;++ if (env.ground != null && groundOpaque.material) {+ groundOpaque.material.color.setHex(env.ground);+ }++ if (env.sky == null) {+ if (!HAS_SOLID_BG) { scene.background = null; scene.fog = null; }+ return;+ }++ scene.fog = new Fog(env.fog, 18, 55);+ hemi.color.setHex(env.sky);+ if (!HAS_SOLID_BG) {+ scene.background = new Color(env.sky);+ renderer.setClearColor(env.sky, 1);+ }+}+applyEmbedEnvironment(ENV_PARAM);+// Apply a scene preset. An explicit ?bg= wins over the preset background so// transparent/custom embeds keep working; otherwise the preset paints the// clear color and matching fog. Live-swappable via the `walk:setEnv` message.diff --git a/src/webgl-budget.js b/src/webgl-budget.jsnew file mode 100644index 000000000..e62a23dcd--- /dev/null+++ b/src/webgl-budget.js@@ -0,0 +1,34 @@+// Shared WebGL context accounting.+//+// Browsers cap simultaneous WebGL contexts (~16 in Chrome). The <agent-3d>+// element (see element.js) caps how many live viewers it keeps so a grid of+// avatars never exhausts that budget — but it only counts *its own* viewers.+// Standalone renderers on the same page (the homepage avatar-drop, walk+// preview, footer bot, pricing avatar, …) are invisible to that accounting,+// so a busy landing page can still cross the limit and trigger+// "Too many active WebGL contexts. Oldest context will be lost."+//+// These helpers let any standalone renderer reserve a slot against the shared+// budget. element.js subtracts the reserved count from its own cap, so the+// total number of live contexts on the page stays within the browser limit.+// State lives on `window` so it is shared across the CDN agent-3d bundle and+// the app's own modules, which are separate module graphs.++export function reserveWebGLContext() {+ if (typeof window === 'undefined') return;+ const n = Number(window.__agent3dReservedContexts) || 0;+ window.__agent3dReservedContexts = n + 1;+ // Re-run the agent-3d budget now that fewer slots are available, so an+ // offscreen viewer is evicted immediately instead of on the next boot.+ if (typeof window.__agent3dEnforceBudget === 'function') {+ try {+ window.__agent3dEnforceBudget();+ } catch {}+ }+}++export function releaseWebGLContext() {+ if (typeof window === 'undefined') return;+ const n = Number(window.__agent3dReservedContexts) || 0;+ window.__agent3dReservedContexts = Math.max(0, n - 1);+}diff --git a/vercel.json b/vercel.jsonindex de15cfd0e..de063330f 100644--- a/vercel.json+++ b/vercel.json@@ -333,6 +333,10 @@"src": "/communities/?","dest": "/communities.html"},+ {+ "src": "/town/?",+ "dest": "/communities.html"+ },{"src": "/wk/([A-Za-z0-9_-]+)","dest": "/walk?avatar=$1",@@ -1335,6 +1339,10 @@"src": "/api/pump/recent-graduations","dest": "/api/pump/[action]?action=recent-graduations"},+ {+ "src": "/api/pump/coin-trades",+ "dest": "/api/pump/[action]?action=coin-trades"+ },{"src": "/api/demo/coin/state","dest": "/api/demo/coin/[action]?action=state"diff --git a/vite.config.js b/vite.config.jsindex a125d2497..2b18bdafa 100644--- a/vite.config.js+++ b/vite.config.js@@ -686,6 +686,9 @@ const appConfig = {// /avatars/:id → avatar studio page (mirrors vercel.json rewrite)else if (!filePath && /^\/avatars\/[^/.]+\/?$/.test(path))filePath = resolve(root, 'pages/avatar-page.html');+ // /town → communities (alias; mirrors vercel.json rewrite)+ else if (!filePath && /^\/town\/?$/.test(path))+ filePath = resolve(root, 'pages/communities.html');// /@<handle> → public live profile pageelse if (!filePath && /^\/@[a-z0-9_-]{3,30}\/?$/i.test(path))filePath = resolve(root, 'pages/handle.html');