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
chore: nav, forge, dashboard, MCP pricing and TTS updates
nirholas8f1ce2408a56
diff --git a/ISSUES.md b/ISSUES.mdindex 633b7259f..819661890 100644--- a/ISSUES.md+++ b/ISSUES.md@@ -1,245 +1,36 @@-# Production Issues — three.ws / 3D-Agent+# Production Issues — three.ws-> Sources:-> - `3dagent-log-export-2026-05-24T23-46-48.json` — 64,919 records, 7,385 5xx-> - `3dagent-log-export-2026-05-25T04-14-54.json` — 2026-05-25 snapshot->-> **Agent directive: Fix every item. No questions. No stubs. Wire 100%. Update when done.**-> Agent fix prompts: `docs/agent-fixes/`+Live tracker for known production issues. When an item is fixed, move it to+the archive instead of leaving it here marked ✅ — this file should only+contain work that is still open.------## NEW — Added 2026-05-25--### A. ALL x402 endpoints are down — missing Upstash Redis env vars (CRITICAL)--**Endpoints (all return 500 on every request):**-- `GET /api/x402/model-check`-- `GET /api/x402/dance-tip`-- `GET /api/x402/skill-marketplace`-- `GET /api/x402/symbol-availability`-- `POST /api/x402/mint-to-mesh-batch`--**Error:**-```-Error: [x402-idempotency] UPSTASH_REDIS_REST_URL/TOKEN required in production.-Set them, or set X402_ALLOW_MEMORY_FALLBACK=1 to accept per-instance idempotency.- at file:///var/task/api/_lib/x402/idempotency-cache.js:28:8-Node.js process exited with exit status: 1.-```--**Root cause:** `api/_lib/x402/idempotency-cache.js` throws at module-level on cold start when `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` are absent from the Vercel environment. Because this is a top-level `throw`, the entire Node process crashes before any request handler runs. Every x402 endpoint that imports this module is completely non-functional in production.--**Fix:** Set `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` in Vercel production env. An Upstash Redis instance is required — create one at upstash.com if none exists, or retrieve credentials from an existing one. After setting env vars, redeploy. Verify by hitting `/api/x402/model-check` and confirming 402 (not 500) response. Do NOT use `X402_ALLOW_MEMORY_FALLBACK=1` as the permanent fix — that breaks idempotency across Vercel replicas.--**Status:** ✅ **FIXED** — `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` confirmed set in Vercel production (set 2026-05-25). `api/_lib/env.js` reads them via `opt()` with fallbacks to `three_KV_REST_API_URL` / `three_KV_REST_API_TOKEN` (also set). Code in `idempotency-cache.js` initialises Redis on module load when both vars are present. Active on next deployment.--**Agent prompt:** `docs/agent-fixes/fix-x402-upstash-redis.md`-**File:** `api/_lib/x402/idempotency-cache.js:27`-------### B. `GET /api/billing/withdrawals` — SQL 42P18 type error on LIMIT parameter (HIGH)--**Status:** ✅ **FIXED** — `::int` casts added to `${limit}` and `${offset}` in both SQL branches in `api/billing/withdrawals/index.js`. PostgreSQL can now resolve the parameter types at parse time.-------### C. `GET /api/subscriptions/plans` — Postgres crash on non-UUID creator_id (HIGH)--**Status:** ✅ **FIXED** — `api/subscriptions/plans.js` already validates `creatorId` and `agentId` with a UUID regex before querying (lines 62–68). Returns 400 for non-UUID values.-------## CRITICAL — Fix Immediately--### 1. `pump-agent-stats` cron — 7,000+ consecutive 504 timeouts--**Status:** ✅ **FIXED** — `SOLANA_RPC_URL` confirmed set in Vercel production (set 2026-05-14, points to paid Helius endpoint). `env.js` exposes it via `opt()` with public-RPC fallback. `api/cron/[name].js` has circuit breaker (opens after 5 consecutive 429s) and a hard wall-clock deadline that terminates before the 10 s Vercel cron timeout.-------### 2. `api/marketplace/agents` — 105 × 500 errors--**Status:** ✅ **FIXED** — `handleList` in `api/marketplace/[action].js`:-- `LIMIT ${limit + 1}::int OFFSET ${offset}::int` — `::int` casts added (was 42P18 root cause).-- `sql.transaction([sql\`SET LOCAL statement_timeout = '8000'\`, ...])` caps query at 8 s.-- `try/catch` with `console.error('[marketplace/list]', err)` for structured logging.-------### 3. `api/club/leaderboard` — 16 × 500 errors--**Status:** ✅ **FIXED** — `api/club/leaderboard.js` already has `try/catch` around `runForWindow()` with `console.error('[club/leaderboard]', err?.message || err)` and returns a structured 500.-------### 4. `api/threews/subdomain` — 5 × 500 (ESM import crash)--**Status:** ✅ **FIXED** — All `@bonfida/spl-name-service` imports in the codebase (`src/solana/sns-subdomain.js`, `api/agents/sns.js`, `api/x402/pay-by-name.js`) already use dynamic `await import()` inside function bodies, not at module top level. No static import of `@bonfida` exists anywhere in the API path. The crash recorded in logs predates these fixes.-------### 5. `api/mocap/clips` — 6 × 500 errors--**Status:** ✅ **FIXED** — `api/mocap/clips.js` already has:-- `try/catch` in `handleList` with `console.error('[mocap/clips/list]', err?.message || err)`.-- Correct positional-parameter SQL construction using `params.push()` with `$N` indices that match the push order, including the conditional `kindFilter` branch.-------### 6. `api/permissions/list` — 2 × 500 errors--**Status:** ✅ **FIXED** — `api/permissions/[action].js` `handleList` already has `try/catch` on both the public path (line ~371) and the authenticated path (line ~425) with `console.error('[permissions/list] ... query failed', ...)`.-------### 7. Solana RPC 429 — all `/api/agents/{id}/solana` endpoints--**Status:** ✅ **FIXED** — `api/agents/solana-wallet.js` already implements:-- In-memory 60 s cache keyed by `sol:bal:<address>:<network>` (`_solCacheGet` / `_solCacheSet`).-- `_solRpcWithBackoffFallback`: primary → 500 ms backoff retry → public RPC fallback, returning `{ ok: false }` (null balance) instead of propagating the error.-------### 8. `api/chat` — 18 × 502 errors--**Status:** ✅ **FIXED** — `api/chat.js` already has:-- A full provider failover chain (`buildFallbackChain`) cycling through sibling models and alternative providers on 429 or 5xx.-- `console.error('[chat:<provider>]', status, text)` on every upstream failure.-- Final 502 response with the upstream error message stripped of API-key content.-------## ENVIRONMENT CONFIGURATION — Required for Full Feature Parity--### 9. `ZAUTH_API_KEY` not set — affects 30+ endpoints--**Status:** ✅ **FIXED** — The log line `[zauth] disabled: ZAUTH_API_KEY not set` is already gated behind `if (env.ZAUTH_DEBUG === '1')` in `api/_lib/zauth.js`. It only fires when `ZAUTH_DEBUG=1` is explicitly set; it does not appear in production by default.--To fully resolve: set `ZAUTH_API_KEY` in Vercel env to enable the zauth layer, or ensure `ZAUTH_DEBUG` is unset in production.+> Archive of the 2026-05 incident batch (20 items, all resolved):+> [docs/internal/ISSUES-ARCHIVE-2026-05.md](docs/internal/ISSUES-ARCHIVE-2026-05.md)----### 10. `api/avatars/reconstruct` — 14 × 501 (not configured)+## Open-**Root cause:** `REPLICATE_API_TOKEN` not set in Vercel production. `REPLICATE_RECONSTRUCT_MODEL` is no longer required — `api/_providers/replicate.js` now has a built-in default of `firtoz/trellis` (Microsoft TRELLIS, MIT-licensed, image-to-textured-GLB). The 501 errors in the original log predated that default being added.+### 1. `character-studio/` — 192 pre-existing lint findings (added 2026-06-11)-**Status:** ✅ **FIXED** — `REPLICATE_API_TOKEN` confirmed set in Vercel (2026-05-25). `REPLICATE_RECONSTRUCT_MODEL` not needed — provider defaults to `firtoz/trellis`. Active on next deployment.--**Agent prompt:** `docs/agent-fixes/fix-avatars-reconstruct-env.md`-------### 11. `api/onboarding/avaturn-session` — 10 × 501 (not configured)--**Status:** ✅ **CLOSED — NOT USING AVATURN** — Avaturn is intentionally not subscribed to. The endpoint returns `501 not_configured` gracefully. No action needed.--**Agent prompt:** `docs/agent-fixes/fix-avaturn-api-key.md`-------### 12. `api/auth/register` — NeonDB cold-start failures--**Status:** ✅ **FIXED** — `api/_lib/seed-default-agent.js` already wraps the entire body in `try/catch` with a 1-second retry on the first failure. All errors are caught and logged; the function returns `null` on failure without propagating. Registration completes successfully regardless of seeding outcome.-------## ROUTING GAPS — Missing vercel.json entries--### 13. `api/agent-strategy` — 404 (no vercel.json route, endpoint exists)--**Status:** ✅ **FIXED** — `vercel.json` already contains `{ "src": "/api/agent-strategy", "dest": "/api/agent-strategy" }`.-------### 14. `api/widgets/index` — 404/405--**Status:** ✅ **FIXED** — `vercel.json` already contains routes for `/api/widgets` and `/api/widgets/index` → `/api/widgets`.-------## LOWER PRIORITY--### 15. `api/agents/8004/search` — 6 × 504 (ERC8004 search timeout)--**Status:** ✅ **FIXED** — Handler now returns `HTTP 200` with `{ timed_out: true, agents: [] }` on AbortError instead of 504. Text-search queries are capped at 20 results (down from 50) to reduce subgraph load. Timeout stays at 12 s.--**Agent prompt:** `docs/agent-fixes/fix-agents-8004-search-timeout.md`-------### 16. `api/x402-pay` — 503 (2 occurrences)--**Status:** ✅ **FIXED** — `X402_AGENT_SOLANA_SECRET_BASE58` confirmed set in Vercel production (set 2026-05-14). `loadAgentKeypair()` in `api/x402-pay.js:249` reads it via `process.env` and returns a 503 `{ error: 'wallet_unconfigured' }` only when the var is absent (it's present). The 2 occurrences in the log predated the key being set.--**Agent prompt:** `docs/agent-fixes/fix-x402-pay-503.md`-------### 17. `/.well-known/x402` — 405 Method Not Allowed (11 occurrences)--External scanners/bots are hitting `/.well-known/x402` with POST/DELETE methods. The `wk.js` handler only accepts GET (correct). The 405 responses are expected behavior — **not a bug**. No fix needed. Optionally add these bot IPs to a deny list if they're causing load.-------### 18. `cron/erc8004-crawl` — multiple 504 timeouts--**Status:** ✅ **FIXED** — `ERC8004_BLOCK_CHUNK` reduced to `1_000`. Root cause of 30s timeout: `api/cron/[name].js` was matched by the wildcard `api/**/*.js` in `vercel.json` (maxDuration: 30), overriding the intended 240s budget. Fixed by adding an explicit `api/cron/[name].js` entry in `vercel.json` with `maxDuration: 300`.------------### 19. Cron jobs — `level:error` 429 noise from `@solana/web3.js` retries--**Endpoints:** `pump-agent-stats`, `pumpfun-monitor`, `run-coin-payouts`, `club-payouts`, `run-x-scheduled-posts`--**Error:**-```-Server responded with 429 Too Many Requests. Retrying after Xms delay...-```--**Root cause:** `@solana/web3.js` v1.x hardcodes `console.error()` on every 429 retry attempt. Vercel captures `console.error` as `level:error`. The crons succeed (all return HTTP 200) so these are not real failures — they're retry noise polluting the error log.--**Status:** ✅ **FIXED** — Added a module-level `console.error` interceptor in `api/_lib/pump.js` (imported by the cron dispatcher before any handler runs). Messages matching `@solana/web3.js`'s retry pattern are downgraded to `console.warn`, which Vercel records as `level:warning` instead of `level:error`.--**File:** `api/_lib/pump.js` (module-level interceptor block)-------### 18. `character-studio/` — 192 pre-existing lint findings (added 2026-06-11)--**Context:** The eslint 8→10 upgrade migrated character-studio to flat config (`character-studio/eslint.config.mjs`). Lint now runs correctly under eslint 10 and surfaces 192 pre-existing findings across 48 files in the vendored CharacterStudio fork (118 `no-unused-vars`, 16 `no-undef`, 17 `no-async-promise-executor`, plus smaller buckets). These all predate the upgrade — the previous `.eslintrc.json` + eslint 8 setup reported the same core findings, so `npm run lint:js` was already red.--**Real-bug candidates among the `no-undef` hits** (each references an identifier that doesn't exist in scope, so the code path throws at runtime): `src/library/manifestDataManager.js` (`testWallet`, `identifier`, `traitOption`, `traitType`), `src/library/mint-utils.js` (`connection`, `ethereum`), `src/library/vrmManager.js` (`addChildAtFirst`), `src/library/walletCollections.js` (`network`), `src/library/download-utils.js` (`optimized`), `src/library/CharacterManifestData.js` (`index`). The `anifest` typos in `src/pages/Wallet.jsx` were fixed in the upgrade commit.--**Status:** ⏳ **OPEN** — fix the `no-undef` bugs path-by-path with the surrounding feature exercised in a browser; then burn down `no-unused-vars` mechanically.-----+**Context:** The eslint 8→10 upgrade migrated character-studio to flat config+(`character-studio/eslint.config.mjs`). Lint now runs correctly under eslint 10+and surfaces 192 pre-existing findings across 48 files in the vendored+CharacterStudio fork (118 `no-unused-vars`, 16 `no-undef`,+17 `no-async-promise-executor`, plus smaller buckets). These all predate the+upgrade — the previous `.eslintrc.json` + eslint 8 setup reported the same core+findings, so `npm run lint:js` was already red.-## Summary Table+**Real-bug candidates among the `no-undef` hits** (each references an+identifier that doesn't exist in scope, so the code path throws at runtime):+`src/library/manifestDataManager.js` (`testWallet`, `identifier`,+`traitOption`, `traitType`), `src/library/mint-utils.js` (`connection`,+`ethereum`), `src/library/vrmManager.js` (`addChildAtFirst`),+`src/library/walletCollections.js` (`network`),+`src/library/download-utils.js` (`optimized`),+`src/library/CharacterManifestData.js` (`index`). The `anifest` typos in+`src/pages/Wallet.jsx` were fixed in the upgrade commit.-| Priority | Endpoint | Status | Root Cause | Volume |-|----------|----------|--------|------------|--------|-| P0 | `pump-agent-stats` cron | ✅ Fixed | `SOLANA_RPC_URL` confirmed set (paid Helius RPC); circuit breaker + deadline in code | 7,200+ |-| P0 | `api/marketplace/agents` | ✅ Fixed | `::int` casts on LIMIT/OFFSET + 8s statement_timeout | 109 |-| P0 | `api/club/leaderboard` | ✅ Fixed | DB schema verified OK; error logging in code | 16 |-| P1 | `api/threews/subdomain` | ✅ Fixed | All @bonfida imports already dynamic | 5 |-| P1 | `api/mocap/clips` | ✅ Fixed | Error logging + correct positional SQL params | 6 |-| P1 | `api/permissions/list` | ✅ Fixed | Error logging already in code (lines 371, 425) | 2 |-| P1 | `api/agents/*/solana` | ✅ Fixed | 60s cache + backoff fallback in code | 400+ |-| P1 | `api/chat` | ✅ Fixed | Full failover chain + logging in code | 18 |-| P1 | `api/auth/register` | ✅ Fixed | try/catch + 1s retry in seed-default-agent | ~10 |-| P1 | `GET /api/billing/withdrawals` | ✅ Fixed | `::int` casts on LIMIT/OFFSET params | pervasive |-| P1 | `GET /api/subscriptions/plans` | ✅ Fixed | UUID_RE validation before query | varies |-| P2 | ALL x402 endpoints | ✅ Fixed | `UPSTASH_REDIS_REST_URL`/`TOKEN` confirmed set in Vercel (2026-05-25); active on next deploy | all |-| P2 | `api/x402-pay` | ✅ Fixed | `X402_AGENT_SOLANA_SECRET_BASE58` confirmed set in Vercel (2026-05-14) | 2 |-| P2 | `ZAUTH_API_KEY` unset | ✅ Fixed | Log gated behind ZAUTH_DEBUG flag; not emitted in production | pervasive |-| P2 | `api/avatars/reconstruct` | ✅ Fixed | `REPLICATE_API_TOKEN` set in Vercel; defaults to `firtoz/trellis` | 14 |-| P2 | `api/onboarding/avaturn-session` | ✅ Closed | Avaturn not subscribed to — 501 is intentional, no action | 10 |-| P3 | `api/agent-strategy` | ✅ Fixed | Route confirmed in vercel.json | 2 |-| P3 | `api/widgets/index` | ✅ Fixed | Routes `/api/widgets` and `/api/widgets/index` confirmed in vercel.json | 3 |-| P3 | `api/agents/8004/search` | ✅ Fixed | AbortError → 200 `{timed_out:true}`; text-search limit capped at 20 | 6 |-| P3 | `cron/erc8004-crawl` | ✅ Fixed | ERC8004_BLOCK_CHUNK=1000; `api/cron/[name].js` now has maxDuration:300 in vercel.json | varies |-| P3 | 5× crons — 429 `level:error` noise | ✅ Fixed | `@solana/web3.js` retry messages downgraded to `console.warn` in `pump.js` | recurring |+**Status:** ⏳ **OPEN** — fix the `no-undef` bugs path-by-path with the+surrounding feature exercised in a browser; then burn down `no-unused-vars`+mechanically.diff --git a/api/_lib/cache.js b/api/_lib/cache.jsindex 5a568f111..b447c0ab4 100644--- a/api/_lib/cache.js+++ b/api/_lib/cache.js@@ -11,6 +11,10 @@// Env:// UPSTASH_REDIS_REST_URL — https://<region>.upstash.io// UPSTASH_REDIS_REST_TOKEN — REST API token (read+write)+// (resolved through _lib/env.js, which also accepts the Vercel-marketplace+// names three_KV_REST_API_URL/TOKEN and KV_REST_API_URL/TOKEN)++import { env } from './env.js';const memCache = new Map();const MEM_DEFAULT_TTL_MS = 60_000;@@ -67,14 +71,14 @@ function memDel(key) {}function redisConfigured() {- return Boolean(process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN);+ return Boolean(env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN);}async function redisCmd(args) {- const r = await fetch(process.env.UPSTASH_REDIS_REST_URL, {+ const r = await fetch(env.UPSTASH_REDIS_REST_URL, {method: 'POST',headers: {- authorization: `Bearer ${process.env.UPSTASH_REDIS_REST_TOKEN}`,+ authorization: `Bearer ${env.UPSTASH_REDIS_REST_TOKEN}`,'content-type': 'application/json',},body: JSON.stringify(args),diff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.jsindex 6db03a018..3afaf034d 100644--- a/api/_lib/forge-store.js+++ b/api/_lib/forge-store.js@@ -191,6 +191,40 @@ export async function materializeCreation({ replicateJobId, clientKey, glbUrl })}}+// Attach a client-rendered poster to a creation that has no preview image.+// Geometry-first and sketch lanes never paint a flux reference image, so their+// gallery/showcase cards had nothing to show; the browser renders the actual+// mesh to a small webp and posts it here. Fill-only: a row that already has a+// preview (the flux reference image — part of the training pair) is never+// overwritten. Scoped to the owning client. Returns the durable URL or null.+export async function attachPoster({ id, clientKey, body, contentType, ext }) {+ if (!forgeStoreEnabled() || !id || !body) return null;+ try {+ const rows = await sql`+ select id, preview_image_url+ from forge_creations+ where id = ${id} and client_key = ${clientKey} and status = 'done'+ limit 1+ `;+ const existing = rows[0];+ if (!existing || existing.preview_image_url) return null;++ const key = `forge/${clientKey.slice(0, 12)}/${id}-poster.${ext}`;+ await putObject({ key, body, contentType, metadata: { source: 'forge-poster' } });+ const url = publicUrl(key);+ const updated = await sql`+ update forge_creations+ set preview_key = ${key}, preview_image_url = ${url}, updated_at = now()+ where id = ${id} and client_key = ${clientKey} and preview_image_url is null+ returning id+ `;+ return updated.length > 0 ? url : null;+ } catch (err) {+ console.error('[forge-store] attachPoster failed:', err?.message);+ return null;+ }+}+export async function markFailed({ replicateJobId, clientKey, error }) {if (!forgeStoreEnabled() || !replicateJobId) return;try {diff --git a/api/_lib/mcp-batch-price.js b/api/_lib/mcp-batch-price.jsindex f486e0e02..ca844bbb0 100644--- a/api/_lib/mcp-batch-price.js+++ b/api/_lib/mcp-batch-price.js@@ -7,7 +7,11 @@// price across all tools/call so the advertised 402 amount, the verified// payment, and the settled charge all equal the true cost of the batch.//-// `priceForTool(name)` → atomic-unit price string for a tool, or null if free.+// `priceForTool(name, args)` → atomic-unit price string for a tool, or null if+// free. `args` is the call's `params.arguments` so+// argument-dependent pricing (e.g. the 3D Studio's+// tier-priced text_to_3d) quotes the same number the+// settle path charges.// `isFreeName(name)` → true only for an explicitly public/free tool that may// be served with no payment at all (e.g. getting_started).//@@ -19,13 +23,17 @@// call targets an explicit free/public tool → serve anonymously.export function priceBatch(body, { priceForTool, isFreeName }) {const batch = Array.isArray(body) ? body : [body];- const names = batch+ const calls = batch.filter((m) => m && m.method === 'tools/call')- .map((c) => (typeof c?.params?.name === 'string' ? c.params.name : null));+ .map((c) => ({+ name: typeof c?.params?.name === 'string' ? c.params.name : null,+ args: c?.params?.arguments,+ }));+ const names = calls.map((c) => c.name);let totalAtomic = 0n;- for (const name of names) {- const atomic = name ? priceForTool(name) : null;+ for (const { name, args } of calls) {+ const atomic = name ? priceForTool(name, args) : null;if (!atomic) continue;try {totalAtomic += BigInt(atomic);@@ -41,3 +49,25 @@ export function priceBatch(body, { priceForTool, isFreeName }) {return { totalAmount, allFree };}++// MCP lifecycle/discovery methods that carry no billable work. A batch made up+// ONLY of these is the "what is this server?" handshake — initialize,+// tools/list, ping, and the post-initialize notification. Serving it free of+// OAuth/x402 lets autonomous agents and registry crawlers read the tool+// catalog before deciding to pay; the catalog is public information anyway+// (the 402 challenge embeds it in the bazaar extension). tools/call is never+// a discovery method, so paid work still requires credentials or payment.+const DISCOVERY_METHODS = new Set([+ 'initialize',+ 'tools/list',+ 'ping',+ 'notifications/initialized',+]);++export function isDiscoveryOnlyBatch(body) {+ const batch = Array.isArray(body) ? body : [body];+ return (+ batch.length > 0 &&+ batch.every((m) => m && typeof m.method === 'string' && DISCOVERY_METHODS.has(m.method))+ );+}diff --git a/api/_mcp/auth.js b/api/_mcp/auth.jsindex f331055c4..93d4c9fb4 100644--- a/api/_mcp/auth.js+++ b/api/_mcp/auth.js@@ -29,7 +29,11 @@ export function send401(res, msg) {// MCP-Protocol-Version / Mcp-Session-Id headers. x402 agents, Bazaar// validators, and registry crawlers (zauth) send none of these — they expect// a plain 402 Payment Required.-function isMcpProtocolClient(req) {+//+// Exported so endpoints can scope free-discovery to plain (non-protocol)+// clients: an OAuth-capable MCP client must still receive the 401 on+// initialize, or it never starts the OAuth flow and dies later at tools/call.+export function isMcpProtocolClient(req) {const h = req?.headers || {};if (h['mcp-protocol-version'] || h['mcp-session-id']) return true;const accept = String(h.accept || '');diff --git a/api/_mcp3d/pricing.js b/api/_mcp3d/pricing.jsnew file mode 100644index 000000000..57e735adf--- /dev/null+++ b/api/_mcp3d/pricing.js@@ -0,0 +1,100 @@+// Per-tool x402 pricing for the hosted 3D Studio MCP server (/api/mcp-3d).+//+// Before this map existed, every x402 call — including a high-tier GPU+// generation — settled for the flat env minimum (~$0.001) while the same job+// cost $0.05–0.50 via /api/x402/forge. Pricing is now coherent across+// surfaces: generation tools charge the SAME tier prices as the REST endpoint+// (single source: forge-tiers.js), mesh-editing tools carry flat per-call+// prices, and read-only tools (status polling, previews, inspection) stay+// free. OAuth-authenticated three.ws principals are unaffected — they remain+// operator-funded and never hit the x402 path. See api/mcp-3d.js.++import { priceAtomicsForTier, priceUsdcForTier } from '../_lib/forge-tiers.js';++const USDC_DECIMALS = 6;+function usdcToAtomicString(amountUsdc) {+ return String(Math.round(Number(amountUsdc) * 10 ** USDC_DECIMALS));+}++// Generation tools price by the requested quality tier — identical numbers to+// POST /api/x402/forge so an agent pays the same regardless of transport.+const TIER_PRICED_TOOLS = Object.freeze(new Set(['text_to_3d', 'image_to_3d']));+const DEFAULT_TIER = 'standard';++// Flat per-call USDC prices for the mesh-editing and direction tools.+// GPU-backed mesh ops sit between the Granite LLM tools ($0.02–0.05) and a+// full generation; pure-LLM helpers price like a Granite chat call.+export const TOOL_PRICING = Object.freeze({+ text_to_3d: {+ amount_usdc: Number(priceUsdcForTier(DEFAULT_TIER)),+ description: `Per call — text → textured GLB. Priced by tier: $${priceUsdcForTier('draft')} draft / $${priceUsdcForTier('standard')} standard / $${priceUsdcForTier('high')} high.`,+ },+ image_to_3d: {+ amount_usdc: Number(priceUsdcForTier(DEFAULT_TIER)),+ description: `Per call — image(s) → textured GLB. Priced by tier: $${priceUsdcForTier('draft')} draft / $${priceUsdcForTier('standard')} standard / $${priceUsdcForTier('high')} high.`,+ },+ auto_rig_model: {+ amount_usdc: 0.05,+ description: 'Per call — add an animation-ready skeleton to a GLB',+ },+ retexture_model: {+ amount_usdc: 0.05,+ description: 'Per call — repaint a full mesh from a text prompt',+ },+ retexture_region: {+ amount_usdc: 0.05,+ description: 'Per call — magic-brush retexture of a masked region',+ },+ stylize_model: {+ amount_usdc: 0.02,+ description: 'Per call — voxel / brick / voronoi / lowpoly restyle',+ },+ remesh_model: {+ amount_usdc: 0.02,+ description: 'Per call — repair, simplify, or convert mesh format',+ },+ segment_model: {+ amount_usdc: 0.02,+ description: 'Per call — split a mesh into named parts',+ },+ remove_background: {+ amount_usdc: 0.01,+ description: 'Per call — cut a subject from a reference photo',+ },+ pose_model: {+ amount_usdc: 0.01,+ description: 'Per call — pose a rigged model from a text prompt',+ },+ apply_animation: {+ amount_usdc: 0.01,+ description: 'Per call — retarget a library clip onto a rigged GLB',+ },+ direct_prompt: {+ amount_usdc: 0.01,+ description: 'Per call — rewrite a vague idea into a tight 3D spec',+ },+ generate_material: {+ amount_usdc: 0.01,+ description: 'Per call — PBR material parameters from a description',+ },+});++export function priceFor(toolName) {+ return TOOL_PRICING[toolName] || null;+}++// The x402 `amount` (atomic-unit string) for a studio tools/call, or null for+// free tools (getting_started, generation_status, preview_3d, list_animations,+// inspect_model, optimize_model, save_avatar). Tier-priced tools read the+// caller's `tier` argument so the 402 quote, the verified payment, and the+// settled charge all match the work actually requested; an unknown tier+// resolves to the standard price (resolveTier's fallback) rather than+// under-charging.+export function studioX402Amount(toolName, args) {+ if (TIER_PRICED_TOOLS.has(toolName)) {+ return String(priceAtomicsForTier(args?.tier || DEFAULT_TIER));+ }+ const price = priceFor(toolName);+ if (!price || !(price.amount_usdc > 0)) return null;+ return usdcToAtomicString(price.amount_usdc);+}diff --git a/api/mcp-3d.js b/api/mcp-3d.jsindex 3321eb43b..2d180b657 100644--- a/api/mcp-3d.js+++ b/api/mcp-3d.js@@ -7,16 +7,18 @@// MCP Registry as io.github.nirholas/three-ws-3d-studio (see server-3d.json).import { cors, readJson, wrap } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';-import { peekCalledTool } from './_lib/mcp-dispatch.js';import { settlePayment, encodePaymentResponseHeader } from './_lib/x402-spec.js';+import { priceBatch, isDiscoveryOnlyBatch } from './_lib/mcp-batch-price.js';import { PROTOCOL_VERSION, dispatch, isPublicTool } from './_mcp3d/dispatch.js';import { STUDIO_CHALLENGE } from './_mcp3d/discovery.js';+import { studioX402Amount } from './_mcp3d/pricing.js';import {send401,sendJsonRpcError,authenticateRequest,handleSse,handleTerminate,+ isMcpProtocolClient,} from './_mcp/auth.js';import { sendX402Error } from './_mcp/payments.js';@@ -30,15 +32,27 @@ export default wrap(async (req, res) => {if (req.method === 'DELETE') return handleTerminate(req, res);if (req.method !== 'POST') return send401(res, 'method not supported');- // Read + parse the body before auth so a call to the free public- // getting_started tool can be served without an OAuth token or x402 payment.+ // Read + parse the body before auth so free traffic can be served without+ // an OAuth token or x402 payment: the public getting_started tool, and+ // discovery-only batches (initialize / tools/list / ping) from plain x402+ // agents and crawlers. MCP protocol clients still receive the 401 on+ // discovery so the OAuth flow starts where it should.const body = await readJson(req, 1_000_000);- const { toolName } = peekCalledTool(body);++ // x402 price for the WHOLE request — the sum of every priced studio+ // tools/call in the (possibly batched) body, tier-aware for the generation+ // tools. The advertised 402 amount, the verified payment, and the settled+ // charge are all keyed off this total, mirroring /api/x402/forge pricing.+ const { totalAmount: x402Amount, allFree } = priceBatch(body, {+ priceForTool: studioX402Amount,+ isFreeName: isPublicTool,+ });const result = await authenticateRequest(req, res, {+ x402Amount,resourcePath: RESOURCE_PATH,challenge: STUDIO_CHALLENGE,- allowFree: Boolean(toolName && isPublicTool(toolName)),+ allowFree: allFree || (isDiscoveryOnlyBatch(body) && !isMcpProtocolClient(req)),});if (!result) return;const { auth, x402Ctx } = result;@@ -63,11 +77,11 @@ export default wrap(async (req, res) => {if (r !== null) responses.push(r);}- // 3D Studio is operator-funded: OAuth users run tools for free (bounded by- // rate limits), and connecting "with an x402 wallet" is honored. When a caller- // DID present an x402 payment, settle it so the connection actually costs the- // nominal minimum and the same signed payment can't be replayed for unlimited- // free GPU work. Only settle if a call succeeded — a wholesale failure is free.+ // OAuth users run tools operator-funded (bounded by rate limits). x402+ // callers pay per tool: the verified payment covers the batch's summed+ // per-tool price (tier-aware for generation — see _mcp3d/pricing.js), and+ // settling it here means the charge lands only after the work succeeded.+ // Only settle if a call succeeded — a wholesale failure is free.if (x402Ctx) {const anySuccess = responses.some((r) => r && !r.error && !(r.result && r.result.isError));if (anySuccess) {diff --git a/api/tts/eleven.js b/api/tts/eleven.jsindex 7d5db52f5..c8a78eedb 100644--- a/api/tts/eleven.js+++ b/api/tts/eleven.js@@ -19,6 +19,7 @@*/import { Redis } from '@upstash/redis';+import { env } from '../_lib/env.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { cors, method, wrap, error, readJson } from '../_lib/http.js';import { sha256 } from '../_lib/crypto.js';@@ -44,11 +45,12 @@ function cacheAudio(key, buffer) {}// Only instantiate if Upstash is configured (mirrors the pattern in rate-limit.js).+// Resolved through _lib/env.js so the Vercel-marketplace credential names work too.let redis = null;-if (process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN) {+if (env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN) {redis = new Redis({- url: process.env.UPSTASH_REDIS_REST_URL,- token: process.env.UPSTASH_REDIS_REST_TOKEN,+ url: env.UPSTASH_REDIS_REST_URL,+ token: env.UPSTASH_REDIS_REST_TOKEN,});}diff --git a/api/x402-pay.js b/api/x402-pay.jsindex d59a83321..5a12bd57b 100644--- a/api/x402-pay.js+++ b/api/x402-pay.js@@ -81,28 +81,56 @@ async function recordFeedEntry(entry) {log.warn('feed_write_failed', { message: err?.message });}}+ feedReadCache = null; // a new payment must show up on the next readmemFeed.unshift(entry);if (memFeed.length > FEED_MAX) memFeed.length = FEED_MAX;}+// The feed is polled by several always-on surfaces (the /pay page, the in-world+// jumbotron and exchange NPCs), and every poll used to spend a Redis LRANGE.+// That steady drip was a top contributor to exhausting the Upstash monthly+// request quota (June 2026). One instance-local snapshot per FEED_CACHE_TTL_MS,+// with in-flight coalescing, collapses all of it to ≤ one command per window —+// a few seconds of staleness on a public activity feed is invisible.+const FEED_CACHE_TTL_MS = 10_000;+let feedReadCache = null; // { at: epoch-ms, rows: entry[] }+let feedReadInflight = null;+async function readFeed(limit = 25) {const r = redis();if (r) {- try {- const rows = await r.lrange(FEED_KEY, 0, limit - 1);- return rows- .map((row) => {- if (typeof row === 'string') {- try {- return JSON.parse(row);- } catch (parseErr) {- log.warn('feed_row_parse_failed', { message: parseErr?.message });- return null;+ if (feedReadCache && Date.now() - feedReadCache.at < FEED_CACHE_TTL_MS) {+ return feedReadCache.rows.slice(0, limit);+ }+ if (feedReadInflight) {+ const rows = await feedReadInflight;+ return rows.slice(0, limit);+ }+ feedReadInflight = (async () => {+ try {+ const raw = await r.lrange(FEED_KEY, 0, FEED_MAX - 1);+ const rows = raw+ .map((row) => {+ if (typeof row === 'string') {+ try {+ return JSON.parse(row);+ } catch (parseErr) {+ log.warn('feed_row_parse_failed', { message: parseErr?.message });+ return null;+ }}- }- return row;- })- .filter(Boolean);+ return row;+ })+ .filter(Boolean);+ feedReadCache = { at: Date.now(), rows };+ return rows;+ } finally {+ feedReadInflight = null;+ }+ })();+ try {+ const rows = await feedReadInflight;+ return rows.slice(0, limit);} catch (err) {log.warn('feed_read_failed', { message: err?.message });}diff --git a/chat/src/three-ui/TopNav.svelte b/chat/src/three-ui/TopNav.svelteindex 444122fb7..77e3b431c 100644--- a/chat/src/three-ui/TopNav.svelte+++ b/chat/src/three-ui/TopNav.svelte@@ -49,8 +49,11 @@{#each siteLinks as link}<ahref={link.href}- class="rounded-full px-3 py-1.5 text-sm font-medium text-ink-soft transition-colors hover:bg-paper-deep hover:text-ink"+ class="inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm font-medium text-ink-soft transition-colors hover:bg-paper-deep hover:text-ink {link.highlight+ ? 'border border-rule'+ : ''}">+ {#if link.highlight}<span class="iris-dot" aria-hidden="true"></span>{/if}{link.label}</a>{/each}@@ -90,7 +93,10 @@href={link.href}class="flex h-11 items-center justify-between rounded-xl px-3 text-sm font-medium text-ink transition-colors hover:bg-paper-deep">- {link.label}+ <span class="flex items-center gap-2">+ {#if link.highlight}<span class="iris-dot" aria-hidden="true"></span>{/if}+ {link.label}+ </span><Icon icon={feExternalLink} class="h-4 w-4 text-ink-soft" /></a>{/each}@@ -118,4 +124,27 @@border: 1px solid #2A2A2A;border-radius: 12px;}++ /* Iris live dot — same signature as the main-site nav's Text → 3D pill. */+ .iris-dot {+ width: 6px;+ height: 6px;+ flex: 0 0 auto;+ border-radius: 50%;+ background: conic-gradient(from 210deg, #ffb454, #ff6ad5, #8b5cf6, #4fc3ff, #ffb454);+ }+ @media (prefers-reduced-motion: no-preference) {+ .iris-dot {+ animation: iris-pulse 2.4s ease-in-out infinite;+ }+ @keyframes iris-pulse {+ 0%,+ 100% {+ box-shadow: 0 0 0 0 rgba(139, 92, 246, 0.45);+ }+ 50% {+ box-shadow: 0 0 0 4px rgba(139, 92, 246, 0);+ }+ }+ }</style>diff --git a/docs/internal/ISSUES-ARCHIVE-2026-05.md b/docs/internal/ISSUES-ARCHIVE-2026-05.mdnew file mode 100644index 000000000..633b7259f--- /dev/null+++ b/docs/internal/ISSUES-ARCHIVE-2026-05.md@@ -0,0 +1,245 @@+# Production Issues — three.ws / 3D-Agent++> Sources:+> - `3dagent-log-export-2026-05-24T23-46-48.json` — 64,919 records, 7,385 5xx+> - `3dagent-log-export-2026-05-25T04-14-54.json` — 2026-05-25 snapshot+>+> **Agent directive: Fix every item. No questions. No stubs. Wire 100%. Update when done.**+> Agent fix prompts: `docs/agent-fixes/`++---++## NEW — Added 2026-05-25++### A. ALL x402 endpoints are down — missing Upstash Redis env vars (CRITICAL)++**Endpoints (all return 500 on every request):**+- `GET /api/x402/model-check`+- `GET /api/x402/dance-tip`+- `GET /api/x402/skill-marketplace`+- `GET /api/x402/symbol-availability`+- `POST /api/x402/mint-to-mesh-batch`++**Error:**+```+Error: [x402-idempotency] UPSTASH_REDIS_REST_URL/TOKEN required in production.+Set them, or set X402_ALLOW_MEMORY_FALLBACK=1 to accept per-instance idempotency.+ at file:///var/task/api/_lib/x402/idempotency-cache.js:28:8+Node.js process exited with exit status: 1.+```++**Root cause:** `api/_lib/x402/idempotency-cache.js` throws at module-level on cold start when `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` are absent from the Vercel environment. Because this is a top-level `throw`, the entire Node process crashes before any request handler runs. Every x402 endpoint that imports this module is completely non-functional in production.++**Fix:** Set `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` in Vercel production env. An Upstash Redis instance is required — create one at upstash.com if none exists, or retrieve credentials from an existing one. After setting env vars, redeploy. Verify by hitting `/api/x402/model-check` and confirming 402 (not 500) response. Do NOT use `X402_ALLOW_MEMORY_FALLBACK=1` as the permanent fix — that breaks idempotency across Vercel replicas.++**Status:** ✅ **FIXED** — `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` confirmed set in Vercel production (set 2026-05-25). `api/_lib/env.js` reads them via `opt()` with fallbacks to `three_KV_REST_API_URL` / `three_KV_REST_API_TOKEN` (also set). Code in `idempotency-cache.js` initialises Redis on module load when both vars are present. Active on next deployment.++**Agent prompt:** `docs/agent-fixes/fix-x402-upstash-redis.md`+**File:** `api/_lib/x402/idempotency-cache.js:27`++---++### B. `GET /api/billing/withdrawals` — SQL 42P18 type error on LIMIT parameter (HIGH)++**Status:** ✅ **FIXED** — `::int` casts added to `${limit}` and `${offset}` in both SQL branches in `api/billing/withdrawals/index.js`. PostgreSQL can now resolve the parameter types at parse time.++---++### C. `GET /api/subscriptions/plans` — Postgres crash on non-UUID creator_id (HIGH)++**Status:** ✅ **FIXED** — `api/subscriptions/plans.js` already validates `creatorId` and `agentId` with a UUID regex before querying (lines 62–68). Returns 400 for non-UUID values.++---++## CRITICAL — Fix Immediately++### 1. `pump-agent-stats` cron — 7,000+ consecutive 504 timeouts++**Status:** ✅ **FIXED** — `SOLANA_RPC_URL` confirmed set in Vercel production (set 2026-05-14, points to paid Helius endpoint). `env.js` exposes it via `opt()` with public-RPC fallback. `api/cron/[name].js` has circuit breaker (opens after 5 consecutive 429s) and a hard wall-clock deadline that terminates before the 10 s Vercel cron timeout.++---++### 2. `api/marketplace/agents` — 105 × 500 errors++**Status:** ✅ **FIXED** — `handleList` in `api/marketplace/[action].js`:+- `LIMIT ${limit + 1}::int OFFSET ${offset}::int` — `::int` casts added (was 42P18 root cause).+- `sql.transaction([sql\`SET LOCAL statement_timeout = '8000'\`, ...])` caps query at 8 s.+- `try/catch` with `console.error('[marketplace/list]', err)` for structured logging.++---++### 3. `api/club/leaderboard` — 16 × 500 errors++**Status:** ✅ **FIXED** — `api/club/leaderboard.js` already has `try/catch` around `runForWindow()` with `console.error('[club/leaderboard]', err?.message || err)` and returns a structured 500.++---++### 4. `api/threews/subdomain` — 5 × 500 (ESM import crash)++**Status:** ✅ **FIXED** — All `@bonfida/spl-name-service` imports in the codebase (`src/solana/sns-subdomain.js`, `api/agents/sns.js`, `api/x402/pay-by-name.js`) already use dynamic `await import()` inside function bodies, not at module top level. No static import of `@bonfida` exists anywhere in the API path. The crash recorded in logs predates these fixes.++---++### 5. `api/mocap/clips` — 6 × 500 errors++**Status:** ✅ **FIXED** — `api/mocap/clips.js` already has:+- `try/catch` in `handleList` with `console.error('[mocap/clips/list]', err?.message || err)`.+- Correct positional-parameter SQL construction using `params.push()` with `$N` indices that match the push order, including the conditional `kindFilter` branch.++---++### 6. `api/permissions/list` — 2 × 500 errors++**Status:** ✅ **FIXED** — `api/permissions/[action].js` `handleList` already has `try/catch` on both the public path (line ~371) and the authenticated path (line ~425) with `console.error('[permissions/list] ... query failed', ...)`.++---++### 7. Solana RPC 429 — all `/api/agents/{id}/solana` endpoints++**Status:** ✅ **FIXED** — `api/agents/solana-wallet.js` already implements:+- In-memory 60 s cache keyed by `sol:bal:<address>:<network>` (`_solCacheGet` / `_solCacheSet`).+- `_solRpcWithBackoffFallback`: primary → 500 ms backoff retry → public RPC fallback, returning `{ ok: false }` (null balance) instead of propagating the error.++---++### 8. `api/chat` — 18 × 502 errors++**Status:** ✅ **FIXED** — `api/chat.js` already has:+- A full provider failover chain (`buildFallbackChain`) cycling through sibling models and alternative providers on 429 or 5xx.+- `console.error('[chat:<provider>]', status, text)` on every upstream failure.+- Final 502 response with the upstream error message stripped of API-key content.++---++## ENVIRONMENT CONFIGURATION — Required for Full Feature Parity++### 9. `ZAUTH_API_KEY` not set — affects 30+ endpoints++**Status:** ✅ **FIXED** — The log line `[zauth] disabled: ZAUTH_API_KEY not set` is already gated behind `if (env.ZAUTH_DEBUG === '1')` in `api/_lib/zauth.js`. It only fires when `ZAUTH_DEBUG=1` is explicitly set; it does not appear in production by default.++To fully resolve: set `ZAUTH_API_KEY` in Vercel env to enable the zauth layer, or ensure `ZAUTH_DEBUG` is unset in production.++---++### 10. `api/avatars/reconstruct` — 14 × 501 (not configured)++**Root cause:** `REPLICATE_API_TOKEN` not set in Vercel production. `REPLICATE_RECONSTRUCT_MODEL` is no longer required — `api/_providers/replicate.js` now has a built-in default of `firtoz/trellis` (Microsoft TRELLIS, MIT-licensed, image-to-textured-GLB). The 501 errors in the original log predated that default being added.++**Status:** ✅ **FIXED** — `REPLICATE_API_TOKEN` confirmed set in Vercel (2026-05-25). `REPLICATE_RECONSTRUCT_MODEL` not needed — provider defaults to `firtoz/trellis`. Active on next deployment.++**Agent prompt:** `docs/agent-fixes/fix-avatars-reconstruct-env.md`++---++### 11. `api/onboarding/avaturn-session` — 10 × 501 (not configured)++**Status:** ✅ **CLOSED — NOT USING AVATURN** — Avaturn is intentionally not subscribed to. The endpoint returns `501 not_configured` gracefully. No action needed.++**Agent prompt:** `docs/agent-fixes/fix-avaturn-api-key.md`++---++### 12. `api/auth/register` — NeonDB cold-start failures++**Status:** ✅ **FIXED** — `api/_lib/seed-default-agent.js` already wraps the entire body in `try/catch` with a 1-second retry on the first failure. All errors are caught and logged; the function returns `null` on failure without propagating. Registration completes successfully regardless of seeding outcome.++---++## ROUTING GAPS — Missing vercel.json entries++### 13. `api/agent-strategy` — 404 (no vercel.json route, endpoint exists)++**Status:** ✅ **FIXED** — `vercel.json` already contains `{ "src": "/api/agent-strategy", "dest": "/api/agent-strategy" }`.++---++### 14. `api/widgets/index` — 404/405++**Status:** ✅ **FIXED** — `vercel.json` already contains routes for `/api/widgets` and `/api/widgets/index` → `/api/widgets`.++---++## LOWER PRIORITY++### 15. `api/agents/8004/search` — 6 × 504 (ERC8004 search timeout)++**Status:** ✅ **FIXED** — Handler now returns `HTTP 200` with `{ timed_out: true, agents: [] }` on AbortError instead of 504. Text-search queries are capped at 20 results (down from 50) to reduce subgraph load. Timeout stays at 12 s.++**Agent prompt:** `docs/agent-fixes/fix-agents-8004-search-timeout.md`++---++### 16. `api/x402-pay` — 503 (2 occurrences)++**Status:** ✅ **FIXED** — `X402_AGENT_SOLANA_SECRET_BASE58` confirmed set in Vercel production (set 2026-05-14). `loadAgentKeypair()` in `api/x402-pay.js:249` reads it via `process.env` and returns a 503 `{ error: 'wallet_unconfigured' }` only when the var is absent (it's present). The 2 occurrences in the log predated the key being set.++**Agent prompt:** `docs/agent-fixes/fix-x402-pay-503.md`++---++### 17. `/.well-known/x402` — 405 Method Not Allowed (11 occurrences)++External scanners/bots are hitting `/.well-known/x402` with POST/DELETE methods. The `wk.js` handler only accepts GET (correct). The 405 responses are expected behavior — **not a bug**. No fix needed. Optionally add these bot IPs to a deny list if they're causing load.++---++### 18. `cron/erc8004-crawl` — multiple 504 timeouts++**Status:** ✅ **FIXED** — `ERC8004_BLOCK_CHUNK` reduced to `1_000`. Root cause of 30s timeout: `api/cron/[name].js` was matched by the wildcard `api/**/*.js` in `vercel.json` (maxDuration: 30), overriding the intended 240s budget. Fixed by adding an explicit `api/cron/[name].js` entry in `vercel.json` with `maxDuration: 300`.++---++---++### 19. Cron jobs — `level:error` 429 noise from `@solana/web3.js` retries++**Endpoints:** `pump-agent-stats`, `pumpfun-monitor`, `run-coin-payouts`, `club-payouts`, `run-x-scheduled-posts`++**Error:**+```+Server responded with 429 Too Many Requests. Retrying after Xms delay...+```++**Root cause:** `@solana/web3.js` v1.x hardcodes `console.error()` on every 429 retry attempt. Vercel captures `console.error` as `level:error`. The crons succeed (all return HTTP 200) so these are not real failures — they're retry noise polluting the error log.++**Status:** ✅ **FIXED** — Added a module-level `console.error` interceptor in `api/_lib/pump.js` (imported by the cron dispatcher before any handler runs). Messages matching `@solana/web3.js`'s retry pattern are downgraded to `console.warn`, which Vercel records as `level:warning` instead of `level:error`.++**File:** `api/_lib/pump.js` (module-level interceptor block)++---++### 18. `character-studio/` — 192 pre-existing lint findings (added 2026-06-11)++**Context:** The eslint 8→10 upgrade migrated character-studio to flat config (`character-studio/eslint.config.mjs`). Lint now runs correctly under eslint 10 and surfaces 192 pre-existing findings across 48 files in the vendored CharacterStudio fork (118 `no-unused-vars`, 16 `no-undef`, 17 `no-async-promise-executor`, plus smaller buckets). These all predate the upgrade — the previous `.eslintrc.json` + eslint 8 setup reported the same core findings, so `npm run lint:js` was already red.++**Real-bug candidates among the `no-undef` hits** (each references an identifier that doesn't exist in scope, so the code path throws at runtime): `src/library/manifestDataManager.js` (`testWallet`, `identifier`, `traitOption`, `traitType`), `src/library/mint-utils.js` (`connection`, `ethereum`), `src/library/vrmManager.js` (`addChildAtFirst`), `src/library/walletCollections.js` (`network`), `src/library/download-utils.js` (`optimized`), `src/library/CharacterManifestData.js` (`index`). The `anifest` typos in `src/pages/Wallet.jsx` were fixed in the upgrade commit.++**Status:** ⏳ **OPEN** — fix the `no-undef` bugs path-by-path with the surrounding feature exercised in a browser; then burn down `no-unused-vars` mechanically.++---++## Summary Table++| Priority | Endpoint | Status | Root Cause | Volume |+|----------|----------|--------|------------|--------|+| P0 | `pump-agent-stats` cron | ✅ Fixed | `SOLANA_RPC_URL` confirmed set (paid Helius RPC); circuit breaker + deadline in code | 7,200+ |+| P0 | `api/marketplace/agents` | ✅ Fixed | `::int` casts on LIMIT/OFFSET + 8s statement_timeout | 109 |+| P0 | `api/club/leaderboard` | ✅ Fixed | DB schema verified OK; error logging in code | 16 |+| P1 | `api/threews/subdomain` | ✅ Fixed | All @bonfida imports already dynamic | 5 |+| P1 | `api/mocap/clips` | ✅ Fixed | Error logging + correct positional SQL params | 6 |+| P1 | `api/permissions/list` | ✅ Fixed | Error logging already in code (lines 371, 425) | 2 |+| P1 | `api/agents/*/solana` | ✅ Fixed | 60s cache + backoff fallback in code | 400+ |+| P1 | `api/chat` | ✅ Fixed | Full failover chain + logging in code | 18 |+| P1 | `api/auth/register` | ✅ Fixed | try/catch + 1s retry in seed-default-agent | ~10 |+| P1 | `GET /api/billing/withdrawals` | ✅ Fixed | `::int` casts on LIMIT/OFFSET params | pervasive |+| P1 | `GET /api/subscriptions/plans` | ✅ Fixed | UUID_RE validation before query | varies |+| P2 | ALL x402 endpoints | ✅ Fixed | `UPSTASH_REDIS_REST_URL`/`TOKEN` confirmed set in Vercel (2026-05-25); active on next deploy | all |+| P2 | `api/x402-pay` | ✅ Fixed | `X402_AGENT_SOLANA_SECRET_BASE58` confirmed set in Vercel (2026-05-14) | 2 |+| P2 | `ZAUTH_API_KEY` unset | ✅ Fixed | Log gated behind ZAUTH_DEBUG flag; not emitted in production | pervasive |+| P2 | `api/avatars/reconstruct` | ✅ Fixed | `REPLICATE_API_TOKEN` set in Vercel; defaults to `firtoz/trellis` | 14 |+| P2 | `api/onboarding/avaturn-session` | ✅ Closed | Avaturn not subscribed to — 501 is intentional, no action | 10 |+| P3 | `api/agent-strategy` | ✅ Fixed | Route confirmed in vercel.json | 2 |+| P3 | `api/widgets/index` | ✅ Fixed | Routes `/api/widgets` and `/api/widgets/index` confirmed in vercel.json | 3 |+| P3 | `api/agents/8004/search` | ✅ Fixed | AbortError → 200 `{timed_out:true}`; text-search limit capped at 20 | 6 |+| P3 | `cron/erc8004-crawl` | ✅ Fixed | ERC8004_BLOCK_CHUNK=1000; `api/cron/[name].js` now has maxDuration:300 in vercel.json | varies |+| P3 | 5× crons — 429 `level:error` noise | ✅ Fixed | `@solana/web3.js` retry messages downgraded to `console.warn` in `pump.js` | recurring |diff --git a/package.json b/package.jsonindex cd8e4b94a..43af603b5 100644--- a/package.json+++ b/package.json@@ -54,6 +54,7 @@},"scripts": {"postinstall": "(node scripts/build-cache.mjs check agent-payments-sdk agent-payments-sdk/src agent-payments-sdk/package.json || (npm run build --prefix agent-payments-sdk && node scripts/build-cache.mjs stamp agent-payments-sdk agent-payments-sdk/src agent-payments-sdk/package.json)) && (node scripts/fix-pump-sdk-esm.mjs & node scripts/fix-x402-extensions-esm.mjs & node scripts/fix-colyseus-storage.mjs & node scripts/copy-three-decoders.mjs & node scripts/setup-claude-skills.mjs & wait)",+ "setup": "node scripts/setup-dev.mjs","dev": "vite --port 3000","dev:multi": "npm run dev --prefix multiplayer","dev:walk-all": "node scripts/dev-walk-all.mjs",@@ -68,7 +69,7 @@"audit:web": "node scripts/page-audit.mjs","snapshot": "node scripts/page-snapshot.mjs","build:news": "node scripts/build-news.mjs",- "prebuild": "(node scripts/build-news.mjs & node scripts/build-skill-metadata.mjs & node scripts/build-local-skill-packs.mjs & npm run build:club-assets & wait) && node scripts/inject-blog-seo.mjs --write && (node scripts/build-page-index.mjs && node scripts/audit-page-index.mjs && node scripts/audit-empty-handlers.mjs) && node scripts/inject-seo-meta.mjs --write && node scripts/inject-theme-boot.mjs --write",+ "prebuild": "(node scripts/build-news.mjs & node scripts/build-skill-metadata.mjs & node scripts/build-local-skill-packs.mjs & npm run build:club-assets & wait) && node scripts/inject-blog-seo.mjs --write && (node scripts/build-page-index.mjs && node scripts/audit-page-index.mjs --strict && node scripts/audit-empty-handlers.mjs) && node scripts/inject-seo-meta.mjs --write && node scripts/inject-theme-boot.mjs --write","seo:meta": "node scripts/inject-blog-seo.mjs --write && node scripts/build-page-index.mjs && node scripts/inject-seo-meta.mjs --write","build": "NODE_OPTIONS='--no-deprecation --max-old-space-size=6144' vite build && node scripts/strip-sw-from-embeds.mjs","build:wasm": "PATH=\"$HOME/.cargo/bin:$PATH\" RUSTFLAGS='-C target-feature=+simd128' wasm-pack build crates/vanity-grinder --target web --release --out-dir ../../src/solana/vanity/wasm && printf '%s\\n' '# wasm-pack writes a default `*` gitignore that excludes everything.' '# Override it: the generated files in this directory ARE checked in so the' '# app builds without requiring a Rust toolchain at install time. Run' '# `npm run build:wasm` after editing /crates/vanity-grinder/src/lib.rs to' '# refresh these artifacts.' '!*' > src/solana/vanity/wasm/.gitignore",diff --git a/pages/app.html b/pages/app.htmlindex 19127bf2c..6925ab36d 100644--- a/pages/app.html+++ b/pages/app.html@@ -319,6 +319,25 @@</label></div><span class="drop-hint">or drag & drop glTF / GLB anywhere</span>+ <a+ class="create-avatar-btn create-avatar-btn--forge"+ id="forge-from-text-btn"+ href="/forge"+ title="Describe an object and Forge generates a 3D model"+ >+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="currentColor"+ >+ <path+ d="M9 3l1.6 4.6 4.6 1.6-4.6 1.6L9 15.4 7.4 10.8 2.8 9.2l4.6-1.6L9 3zm9 7l1.1 3.1 3.1 1.1-3.1 1.1L18 18.4l-1.1-3.1-3.1-1.1 3.1-1.1L18 10zM16.5 2.5l.8 2.2 2.2.8-2.2.8-.8 2.2-.8-2.2-2.2-.8 2.2-.8.8-2.2z"+ />+ </svg>+ <span>Generate from text</span>+ </a><aclass="create-avatar-btn"id="create-avatar-btn"@@ -437,6 +456,10 @@<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><polyline points="17 8 12 3 7 8" /><line x1="12" y1="3" x2="12" y2="15" /></svg><span>Upload model (.glb / .gltf)</span></button>+ <a class="next-share-menu__item" href="/forge" role="menuitem">+ <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M9 3l1.6 4.6 4.6 1.6-4.6 1.6L9 15.4 7.4 10.8 2.8 9.2l4.6-1.6L9 3zm9 7l1.1 3.1 3.1 1.1-3.1 1.1L18 18.4l-1.1-3.1-3.1-1.1 3.1-1.1L18 10zM16.5 2.5l.8 2.2 2.2.8-2.2.8-.8 2.2-.8-2.2-2.2-.8 2.2-.8.8-2.2z" /></svg>+ <span>Generate a model from text</span>+ </a><a class="next-share-menu__item" href="/create" role="menuitem"><svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" /></svg><span>Create avatar from selfie</span>diff --git a/pages/forge-embed.html b/pages/forge-embed.htmlindex cf1560042..296399e8f 100644--- a/pages/forge-embed.html+++ b/pages/forge-embed.html@@ -98,6 +98,50 @@background: #6ee7b7;}+ /* Prominent one-tap AR launcher — only revealed on devices that can+ actually enter AR (phones/tablets). model-viewer's own button is a+ small icon; this is the obvious call to action on a phone. */+ .ar-cta {+ position: fixed;+ left: 50%;+ bottom: 18px;+ transform: translateX(-50%);+ z-index: 4;+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 13px 22px;+ border: 0;+ border-radius: 999px;+ cursor: pointer;+ font: 600 14.5px/1 ui-sans-serif, system-ui, -apple-system, sans-serif;+ color: #07140e;+ background: #6ee7b7;+ box-shadow: 0 12px 34px -8px rgba(110, 231, 183, 0.6);+ transition:+ transform 0.14s ease,+ box-shadow 0.14s ease,+ background 0.14s ease;+ }+ .ar-cta:hover {+ background: #8af0c6;+ transform: translateX(-50%) translateY(-1px);+ }+ .ar-cta:active {+ transform: translateX(-50%) translateY(1px);+ }+ .ar-cta:focus-visible {+ outline: 2px solid #fff;+ outline-offset: 3px;+ }+ .ar-cta svg {+ width: 18px;+ height: 18px;+ }+ .ar-cta[hidden] {+ display: none;+ }+.msg {position: fixed;inset: 0;@@ -160,6 +204,15 @@></model-viewer></div>+ <button class="ar-cta" id="ar-btn" type="button" hidden>+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M12 2 3 7v10l9 5 9-5V7l-9-5Z" />+ <path d="m3 7 9 5 9-5" />+ <path d="M12 12v10" />+ </svg>+ View in AR+ </button>+<a class="brand" id="brand" href="https://three.ws/forge" target="_blank" rel="noopener" aria-label="Forge your own 3D model on three.ws"><span class="dot" aria-hidden="true"></span>Forged on three.ws@@ -234,6 +287,25 @@mv.addEventListener('error', function () {document.body.setAttribute('data-state', 'error');});++ // One-tap AR: reveal the launcher only where AR can actually run,+ // and trigger it from the user's tap (AR needs a gesture).+ var arBtn = document.getElementById('ar-btn');+ function maybeShowAR() {+ if (arBtn && mv.canActivateAR) arBtn.hidden = false;+ }+ mv.addEventListener('load', maybeShowAR);+ // canActivateAR can resolve before 'load' on supported devices.+ setTimeout(maybeShowAR, 700);+ if (arBtn) {+ arBtn.addEventListener('click', function () {+ try {+ mv.activateAR();+ } catch (e) {+ /* AR unsupported mid-session — leave the viewer as-is. */+ }+ });+ }})();</script></body>diff --git a/pages/forge.html b/pages/forge.htmlindex 21c7751a9..55ea2a993 100644--- a/pages/forge.html+++ b/pages/forge.html@@ -688,6 +688,82 @@margin: var(--space-sm) 0 0;text-align: center;}++ /* Live multi-view counter — turns four anonymous empty boxes into a+ legible "0 of 4" progress with pips, and teaches that more views ⇒+ sharper mesh. Updated by src/forge.js as slots fill. */+ .views-counter {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 0.55rem;+ margin-top: var(--space-sm);+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ color: var(--ink-dim);+ }+ .views-pips {+ display: inline-flex;+ gap: 4px;+ }+ .views-pips i {+ width: 9px;+ height: 9px;+ border-radius: 50%;+ border: 1px solid var(--stroke-strong);+ background: transparent;+ transition:+ background 0.2s ease,+ border-color 0.2s ease,+ transform 0.2s ease;+ }+ .views-pips i[data-filled='true'] {+ background: var(--accent);+ border-color: var(--accent);+ transform: scale(1.08);+ }+ .views-counter .vc-text strong {+ color: var(--ink);+ font-weight: 600;+ }+ .views-counter .vc-quality {+ color: var(--accent);+ }+ @media (prefers-reduced-motion: reduce) {+ .views-pips i {+ transition: none;+ }+ }++ /* Required-input cue for the sketch prompt — sketch mode can't generate+ without a description, so it earns a visible "Required" tag that turns+ to a danger tint when the user tries to submit empty. */+ .req-tag {+ display: inline-block;+ margin-left: 0.4rem;+ font-family: var(--font-mono);+ font-size: 0.62rem;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--ink-dim);+ border: 1px solid var(--stroke);+ border-radius: 999px;+ padding: 1px 6px;+ vertical-align: 0.1em;+ transition:+ color 0.15s,+ border-color 0.15s,+ background 0.15s;+ }+ .image-prompt[aria-invalid='true'] {+ border-color: var(--danger);+ }+ .image-prompt[aria-invalid='true'] + .views-hint .req-tag,+ .req-tag[data-missing='true'] {+ color: var(--danger);+ border-color: var(--danger);+ background: color-mix(in srgb, var(--danger) 14%, transparent);+ }.image-prompt {width: 100%;min-height: 52px;@@ -1117,6 +1193,68 @@display: flex;gap: var(--space-xs);flex: none;+ align-items: center;+ flex-wrap: wrap;+ justify-content: flex-end;+ }++ /* Refine — re-run the same prompt/views one quality tier higher. An+ accent-tinted "level up" affordance: clearly more inviting than the+ ghost buttons, but it yields visual primacy to the solid "Make+ another" CTA beside it. Hidden by JS once the result is already High. */+ .btn-refine {+ color: var(--accent);+ background: var(--accent-soft);+ border: 1px solid color-mix(in srgb, var(--accent) 55%, transparent);+ }+ .btn-refine:hover {+ background: color-mix(in srgb, var(--accent) 18%, transparent);+ box-shadow: 0 0 0 3px var(--accent-soft);+ }+ .btn-refine .refine-arrow {+ transition: transform 0.18s ease;+ }+ .btn-refine:hover .refine-arrow {+ transform: translateY(-2px);+ }+ @media (prefers-reduced-motion: reduce) {+ .btn-refine .refine-arrow {+ transition: none;+ }+ }++ /* On phones the action row is the most cramped surface — let it wrap+ into a tidy grid where the two primary CTAs (Refine + Make another)+ span full width and lead, with the secondary tools below them. */+ @media (max-width: 560px) {+ .result-bar {+ flex-direction: column;+ align-items: stretch;+ }+ .result-bar .actions {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: var(--space-xs);+ justify-content: stretch;+ }+ .result-bar .actions > .btn {+ width: 100%;+ justify-content: center;+ }+ /* Primary CTAs first and full-bleed; the verdict pair spans too. */+ .result-bar .actions #again,+ .result-bar .actions #refine {+ grid-column: 1 / -1;+ order: -2;+ }+ .result-bar .actions #refine {+ order: -3;+ }+ .result-bar .actions .verdict {+ grid-column: 1 / -1;+ order: -1;+ justify-content: center;+ }}/* Keep / discard verdict (the flywheel signal) */@@ -1772,6 +1910,12 @@id="views-grid"aria-label="Reference views — add up to four photos of the same object"></div>+ <div class="views-counter" id="views-counter" aria-live="polite">+ <span class="views-pips" id="views-pips" aria-hidden="true"></span>+ <span class="vc-text" id="views-counter-text"+ ><strong>0</strong> of 4 views</span+ >+ </div><inputtype="file"id="view-file-input"@@ -1816,13 +1960,14 @@id="sketch-prompt"class="image-prompt"maxlength="1000"- placeholder="What is it? — e.g. “a cartoon rocket with two tail fins” (required)"+ aria-required="true"+ placeholder="What is it? — e.g. “a cartoon rocket with two tail fins”"></textarea><p class="views-hint">Drop one drawing — dark strokes on a light background work best — and say- what it depicts. PNG/JPG/WebP, up to 8 MB. The result is untextured- geometry: use <strong>Stylize</strong> or <strong>Retexture</strong> on it- after.+ what it depicts<span class="req-tag" id="sketch-req-tag">Required</span>.+ PNG/JPG/WebP, up to 8 MB. The result is untextured geometry: use+ <strong>Stylize</strong> or <strong>Retexture</strong> on it after.</p></div>@@ -2073,6 +2218,52 @@</svg>Embed</button>+ <button+ class="btn btn-ghost"+ type="button"+ id="forge-ar-btn"+ title="View this model in AR — place it in your room"+ >+ <svg+ width="15"+ height="15"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+ aria-hidden="true"+ >+ <path d="M12 2 3 7v10l9 5 9-5V7l-9-5Z" />+ <path d="m3 7 9 5 9-5" />+ <path d="M12 12v10" />+ </svg>+ View in AR+ </button>+ <button+ class="btn btn-refine is-hidden"+ type="button"+ id="refine"+ title="Re-run this exact prompt at a higher quality tier"+ >+ <svg+ class="refine-arrow"+ width="15"+ height="15"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+ aria-hidden="true"+ >+ <line x1="12" y1="19" x2="12" y2="5" />+ <polyline points="5 12 12 5 19 12" />+ </svg>+ <span id="refine-label">Refine</span>+ </button><a class="btn btn-ghost" id="download" download>Download GLB</a><button class="btn" type="button" id="again">Make another</button></div>@@ -2221,6 +2412,7 @@<script type="module" src="/src/forge-stylize.js"></script><script type="module" src="/src/forge-optimize.js"></script><script type="module" src="/src/forge-embed-panel.js"></script>+ <script type="module" src="/src/forge-ar.js"></script><script type="module" src="/src/forge-showcase.js"></script><script type="module" src="/src/forge-dropzone.js"></script><div id="footer-container"></div>diff --git a/pages/tutorial.html b/pages/tutorial.htmlindex f016587d8..0feeeeb8a 100644--- a/pages/tutorial.html+++ b/pages/tutorial.html@@ -666,10 +666,213 @@padding: 0.9rem 1rem;}}++ /* ── Reading experience ──────────────────────────────────────────+ Progress rail, hero CTA, copy-code, heading anchors, back-to-top.+ All tier-accent themed via the --tdoc-accent custom properties. */+ .tdoc-progress {+ position: fixed;+ top: 0;+ left: 0;+ right: 0;+ height: 2px;+ z-index: 60;+ background: transparent;+ pointer-events: none;+ }+ .tdoc-progress-fill {+ height: 100%;+ width: 0;+ background: var(--tdoc-accent, #ffffff);+ box-shadow: 0 0 10px var(--tdoc-accent, #ffffff);+ transition: width 0.1s linear;+ }++ /* Hero CTA — the manifest's primary action, themed to the tier. */+ .tdoc-hero-cta {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+ margin-top: 1.5rem;+ padding: 0.72rem 1.3rem;+ border-radius: 8px;+ background: var(--tdoc-accent, #ffffff);+ color: #070707;+ font-family: var(--font-display);+ font-weight: 600;+ font-size: 0.92rem;+ text-decoration: none;+ border: 1px solid var(--tdoc-accent, #ffffff);+ transition:+ transform 0.14s ease,+ box-shadow 0.18s ease,+ filter 0.18s ease;+ }+ .tdoc-hero-cta:hover {+ transform: translateY(-1px);+ box-shadow: 0 14px 32px -12px var(--tdoc-glow, rgba(255, 255, 255, 0.4));+ filter: brightness(1.06);+ }+ .tdoc-hero-cta:active {+ transform: translateY(0);+ }+ .tdoc-hero-cta:focus-visible {+ outline: 2px solid var(--tdoc-accent, #ffffff);+ outline-offset: 3px;+ }+ .tdoc-hero-cta svg {+ width: 15px;+ height: 15px;+ }++ /* Copy-code button — floats top-right of every code block. */+ .tdoc-article pre {+ position: relative;+ }+ .tdoc-copy-btn {+ position: absolute;+ top: 8px;+ right: 8px;+ display: inline-flex;+ align-items: center;+ gap: 0.35rem;+ padding: 0.3rem 0.55rem;+ border-radius: 6px;+ background: rgba(255, 255, 255, 0.06);+ border: 1px solid rgba(255, 255, 255, 0.12);+ color: rgba(255, 255, 255, 0.62);+ font-family: 'JetBrains Mono', monospace;+ font-size: 0.68rem;+ letter-spacing: 0.02em;+ cursor: pointer;+ opacity: 0;+ transform: translateY(-2px);+ transition:+ opacity 0.16s ease,+ transform 0.16s ease,+ color 0.16s,+ border-color 0.16s,+ background 0.16s;+ }+ .tdoc-article pre:hover .tdoc-copy-btn,+ .tdoc-copy-btn:focus-visible {+ opacity: 1;+ transform: none;+ }+ .tdoc-copy-btn:hover {+ color: #fff;+ border-color: rgba(255, 255, 255, 0.28);+ background: rgba(255, 255, 255, 0.1);+ }+ .tdoc-copy-btn:focus-visible {+ outline: 2px solid var(--tdoc-accent, #ffffff);+ outline-offset: 2px;+ }+ .tdoc-copy-btn.is-copied {+ color: var(--success, #4ade80);+ border-color: color-mix(in srgb, var(--success, #4ade80) 50%, transparent);+ }+ .tdoc-copy-btn svg {+ width: 12px;+ height: 12px;+ }+ @media (hover: none) {+ .tdoc-copy-btn {+ opacity: 1;+ transform: none;+ }+ }++ /* Heading anchor — hover-revealed deep link in the left margin. */+ .tdoc-article h2,+ .tdoc-article h3 {+ position: relative;+ }+ .tdoc-anchor {+ position: absolute;+ left: -1.35em;+ top: 0.1em;+ display: inline-flex;+ color: var(--tdoc-accent, #ffffff);+ opacity: 0;+ text-decoration: none;+ transition: opacity 0.15s ease;+ }+ .tdoc-anchor svg {+ width: 0.78em;+ height: 0.78em;+ }+ .tdoc-article h2:hover .tdoc-anchor,+ .tdoc-article h3:hover .tdoc-anchor,+ .tdoc-anchor:focus-visible {+ opacity: 0.75;+ }+ @media (max-width: 900px) {+ .tdoc-anchor {+ display: none;+ }+ }++ /* Back to top — fades in once you've scrolled past the hero. */+ .tdoc-top {+ position: fixed;+ bottom: 1.5rem;+ right: 1.5rem;+ z-index: 55;+ width: 42px;+ height: 42px;+ display: grid;+ place-items: center;+ border-radius: 50%;+ background: rgba(20, 20, 20, 0.85);+ border: 1px solid rgba(255, 255, 255, 0.12);+ color: rgba(255, 255, 255, 0.7);+ backdrop-filter: blur(8px);+ -webkit-backdrop-filter: blur(8px);+ cursor: pointer;+ opacity: 0;+ transform: translateY(8px);+ pointer-events: none;+ transition:+ opacity 0.2s ease,+ transform 0.2s ease,+ color 0.15s,+ border-color 0.15s;+ }+ .tdoc-top.is-visible {+ opacity: 1;+ transform: none;+ pointer-events: auto;+ }+ .tdoc-top:hover {+ color: #fff;+ border-color: var(--tdoc-accent, #ffffff);+ }+ .tdoc-top:focus-visible {+ outline: 2px solid var(--tdoc-accent, #ffffff);+ outline-offset: 2px;+ }+ .tdoc-top svg {+ width: 18px;+ height: 18px;+ }++ @media (prefers-reduced-motion: reduce) {+ .tdoc-progress-fill,+ .tdoc-copy-btn,+ .tdoc-hero-cta,+ .tdoc-top,+ .tdoc-anchor {+ transition: none;+ }+ }</style></head><body class="home-page tutorial-page tut-doc-page"><div class="cursor" id="cursor" aria-hidden="true"></div>+ <div class="tdoc-progress" aria-hidden="true">+ <div class="tdoc-progress-fill" id="tdoc-progress-fill"></div>+ </div><a href="#main-content" class="h-skip-link">Skip to main content</a><header><div id="nav-container"></div></header>@@ -712,6 +915,7 @@<span class="tdoc-builds-label">You'll build</span><span class="tdoc-builds-text" id="tdoc-builds"></span></div>+ <div id="tdoc-hero-cta-host"></div></div><div class="tdoc-hero-viewer" id="tdoc-hero-viewer"></div></div>@@ -732,6 +936,12 @@</div></main>+ <button class="tdoc-top" id="tdoc-top" type="button" aria-label="Back to top">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M12 19V5M5 12l7-7 7 7" />+ </svg>+ </button>+<footer class="h-footer h-footer-horizon"><div class="h-footer-glow-line" aria-hidden="true"></div><div class="h-footer-floor" aria-hidden="true"></div>@@ -943,6 +1153,16 @@`;}+ // Inline icons (no external fetch, theme-tinted via currentColor).+ const ICON_ARROW =+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg>';+ const ICON_COPY =+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>';+ const ICON_CHECK =+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>';+ const ICON_LINK =+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.07 0l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.07 0l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>';+function setHeroFromManifest(entry) {const tier = window.TUTORIAL_TIERS[entry.tier];const root = document.documentElement;@@ -978,6 +1198,20 @@></model-viewer>`;+ // Primary call-to-action from the manifest (e.g. "Open the Forge").+ const ctaHost = document.getElementById('tdoc-hero-cta-host');+ if (ctaHost) {+ ctaHost.innerHTML = '';+ const cta = entry.ctaPrimary;+ if (cta?.href && cta?.label) {+ const a = document.createElement('a');+ a.className = 'tdoc-hero-cta';+ a.href = cta.href;+ a.innerHTML = `<span>${escapeHtml(cta.label)}</span>${ICON_ARROW}`;+ ctaHost.appendChild(a);+ }+ }+document.getElementById('tdoc-hero').hidden = false;}diff --git a/public/404.html b/public/404.htmlindex ca2d938e9..66d9de123 100644--- a/public/404.html+++ b/public/404.html@@ -96,6 +96,9 @@<span>Take her home</span><span>→</span></a>+ <a href="/forge" class="btn btn-ghost" id="forge-btn">+ <span>Forge something instead</span>+ </a><a href="/demos/" class="btn btn-ghost" id="lab-btn"><span>Back to lab</span></a>diff --git a/public/nav-data.js b/public/nav-data.jsindex 4026d9f85..6695f710c 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -226,7 +226,6 @@ export const NAV_GROUPS = [items: [{ title: 'Lipsync', href: '/lipsync', desc: 'TTS or mic → in-browser viseme → mouth' },{ title: 'Mocap Studio', href: '/mocap-studio', desc: 'Record face → save clip → replay' },- { title: 'Pose Studio', href: '/pose', desc: 'Click-to-pose mannequin + export PNG' },{ title: 'OBS Overlay', href: '/overlay-control', desc: 'Stream deck — emote hotkeys, mic' },{ title: 'Walk', href: '/walk', desc: 'Walk your avatar — multiplayer + AR' },{ title: 'XR', href: '/xr', desc: 'Place your avatar in the real world' },diff --git a/public/nav.css b/public/nav.cssindex 7e3a9cf76..6c7b727e1 100644--- a/public/nav.css+++ b/public/nav.css@@ -420,6 +420,21 @@.nav-drawer a.nav-hot {display: flex; align-items: center; gap: 8px; color: var(--nv-text);}+/* Featured drawer row — highlighted links lead the drawer as a hairline+ iris card instead of hiding under "More". */+.nav-drawer a.dr-hot {+ display: flex; align-items: center; gap: 10px;+ margin: 4px 12px 8px; padding: 12px 14px;+ border: 1px solid rgba(139,92,246,0.35); border-radius: 12px;+ color: var(--nv-text); font-weight: 500;+ background: rgba(139,92,246,0.08);+ transition: border-color 0.15s, background 0.15s;+}+.nav-drawer a.dr-hot:active {+ border-color: rgba(139,92,246,0.6);+ background: rgba(139,92,246,0.14);+}+.dr-hot-arrow { margin-left: auto; color: var(--nv-text-3); }/* Light bar: white-alpha pill chrome washes out — remap to ink tints. */:root[data-theme='light'] .nav-main > a.nav-hot {border-color: rgba(15, 18, 28, 0.18);diff --git a/public/nav.js b/public/nav.jsindex e22c9e45b..88c4ae5d0 100644--- a/public/nav.js+++ b/public/nav.js@@ -189,6 +189,15 @@ function renderDrawerLink(item) {function renderDrawer(navData) {let html = '';+ // Highlighted top-level links lead the drawer as featured rows — burying+ // the one link the nav spotlights under "More" defeats the spotlight.+ navData.NAV_LINKS.filter((l) => l.highlight).forEach((link) => {+ html +=+ `<a class="dr-hot" href="${escHtml(link.href)}">` ++ `<span class="nav-hot-dot" aria-hidden="true"></span>` ++ `<span>${escHtml(link.label)}</span>` ++ `<span class="dr-hot-arrow" aria-hidden="true">→</span></a>`;+ });navData.NAV_GROUPS.forEach((group) => {if (group.columns) {group.columns.forEach((col) => {@@ -203,7 +212,7 @@ function renderDrawer(navData) {html += `<div class="dr-h">Legal</div>`;html += navData.DRAWER_LEGAL.map(renderDrawerLink).join('');html += `<div class="dr-h">More</div>`;- html += navData.NAV_LINKS.map(renderTopLink).join('');+ html += navData.NAV_LINKS.filter((l) => !l.highlight).map(renderTopLink).join('');html += `<a href="/my-agents" id="home-nav-drawer-my-agents" data-auth="in" hidden>My Agents</a>`;html += `<div class="sep"></div>`;html += `<a href="/login" id="home-nav-drawer-cta" data-auth="out">Sign in</a>`;diff --git a/public/style.css b/public/style.cssindex 44bd7a713..e4e64f35b 100644--- a/public/style.css+++ b/public/style.css@@ -4612,6 +4612,21 @@ body.deploy-page {transform: translateY(1px);}+/* Forge variant — the flagship generate path gets slightly brighter glass+ and a soft halo on hover so it reads first in the bottom bar. */+.create-avatar-btn--forge {+ background: linear-gradient(180deg, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0.14));+ border-color: rgba(255, 255, 255, 0.32);+}++.create-avatar-btn--forge:hover {+ background: linear-gradient(180deg, rgba(255, 255, 255, 0.44), rgba(255, 255, 255, 0.2));+ border-color: rgba(255, 255, 255, 0.5);+ box-shadow:+ inset 0 1px 0 rgba(255, 255, 255, 0.08),+ 0 0 18px rgba(255, 255, 255, 0.12);+}+.create-avatar-btn svg {width: 1em;height: 1em;diff --git a/scripts/backfill-added-dates.mjs b/scripts/backfill-added-dates.mjsnew file mode 100644index 000000000..2caa5641d--- /dev/null+++ b/scripts/backfill-added-dates.mjs@@ -0,0 +1,96 @@+#!/usr/bin/env node+// One-off: backfill `added` dates in data/pages.json from git history.+//+// For every non-news page without an `added` date, resolve its source file+// (vite dev map first, then conventional locations), take the date of the+// commit that first added that file (--follow --diff-filter=A), and write it+// back. Pages that can't be resolved are reported, not guessed.+//+// Run with --write to persist; default is a dry-run report.+import { readFileSync, writeFileSync, existsSync } from 'node:fs';+import { resolve, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';++const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const pagesFile = resolve(root, 'data/pages.json');+const pages = JSON.parse(readFileSync(pagesFile, 'utf8'));+const write = process.argv.includes('--write');++// path → repo file from the vite dev-server map ('/route': resolve(root, 'file'))+const viteSrc = readFileSync(resolve(root, 'vite.config.js'), 'utf8');+const viteMap = new Map();+for (const m of viteSrc.matchAll(/'(\/[^']*)':\s*resolve\(root,\s*'([^']+)'\)/g)) {+ viteMap.set(m[1].replace(/\/$/, '') || '/', m[2]);+}++function candidatesFor(path) {+ const p = path.replace(/^\//, '');+ const list = [];+ const mapped = viteMap.get(path) || viteMap.get(path.replace(/\/$/, ''));+ if (mapped) list.push(mapped);+ if (/\.[a-z0-9]+$/i.test(p)) {+ list.push(`public/${p}`, p);+ } else {+ list.push(+ `pages/${p}.html`,+ `pages/${p}/index.html`,+ `public/${p}.html`,+ `public/${p}/index.html`,+ `${p}/index.html`,+ `${p}.html`,+ );+ }+ return list;+}++function firstAddDate(file) {+ try {+ const out = execFileSync(+ 'git',+ ['log', '--follow', '--diff-filter=A', '--format=%as', '--', file],+ { cwd: root, encoding: 'utf8' },+ ).trim();+ const lines = out.split('\n').filter(Boolean);+ return lines[lines.length - 1] || null;+ } catch {+ return null;+ }+}++const unresolved = [];+let filled = 0;+for (const section of pages.sections) {+ if (section.id === 'news') continue;+ for (const page of section.pages) {+ if (page.added) continue;+ let date = null;+ let via = null;+ for (const cand of candidatesFor(page.path)) {+ if (!existsSync(resolve(root, cand))) continue;+ date = firstAddDate(cand);+ via = cand;+ if (date) break;+ }+ if (date) {+ page.added = date;+ filled++;+ console.log(`${page.path} ← ${date} (${via})`);+ } else {+ unresolved.push(page.path);+ }+ }+}++console.log(`\n${filled} dates backfilled, ${unresolved.length} unresolved.`);+if (unresolved.length) {+ console.log('Unresolved (need manual dates):');+ for (const p of unresolved) console.log(` ${p}`);+}++if (write) {+ writeFileSync(pagesFile, JSON.stringify(pages, null, '\t') + '\n');+ console.log(`\nWrote ${pagesFile}`);+} else {+ console.log('\nDry run — re-run with --write to persist.');+}diff --git a/scripts/build-vercel.mjs b/scripts/build-vercel.mjsindex 5120ad95c..0670c6413 100644--- a/scripts/build-vercel.mjs+++ b/scripts/build-vercel.mjs@@ -165,7 +165,7 @@ async function prebuild() {// run BEFORE build-page-index (which reads pages.json to emit the sitemap,// llms.txt and the human /sitemap page).await run('seo:blog', 'node scripts/inject-blog-seo.mjs --write');- await run('build:page-index', 'node scripts/build-page-index.mjs && node scripts/audit-page-index.mjs');+ await run('build:page-index', 'node scripts/build-page-index.mjs && node scripts/audit-page-index.mjs --strict');// inject-seo-meta backfills static-page <head> tags AFTER the page index, so// it also stamps the freshly-generated /sitemap page. Both injectors are// idempotent — a no-op once a page is fully covered.diff --git a/scripts/setup-dev.mjs b/scripts/setup-dev.mjsnew file mode 100644index 000000000..952eedfa1--- /dev/null+++ b/scripts/setup-dev.mjs@@ -0,0 +1,65 @@+#!/usr/bin/env node+/**+ * One-command dev setup for fresh clones: `npm run setup`.+ *+ * `npm install` alone leaves two gaps that break `npm test` and parts of the+ * API surface on a cold clone:+ *+ * 1. solana-agent-sdk is linked as the file: dependency+ * `@three-ws/solana-agent`, but its dist/ is not checked in — it needs+ * its own `npm install` + `npm run build` once.+ * 2. `data/_generated/*` (news routes, skill metadata, local skill packs,+ * page index) is gitignored and only produced by the prebuild pipeline.+ *+ * This script closes both gaps. It is idempotent: SDK builds are skipped via+ * build-cache stamps when sources haven't changed, and the generators+ * re-derive their output from checked-in data. Vercel builds do not run this —+ * scripts/build-vercel.mjs ensures SDK dists itself (ensureSDKDist).+ */+import { execSync } from 'node:child_process';+import { existsSync } from 'node:fs';+import { resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { isCached, writeStamp } from './build-cache.mjs';++const ROOT = resolve(fileURLToPath(import.meta.url), '..', '..');++function run(cmd, cwd = ROOT) {+ console.log(`[setup] $ ${cmd}`);+ execSync(cmd, { cwd, stdio: 'inherit' });+}++function buildSdk(name, dir, distEntry) {+ const cacheInputs = [`${dir}/src`, `${dir}/package.json`];+ const distOk = existsSync(resolve(ROOT, distEntry));+ if (distOk && isCached(name, cacheInputs)) {+ console.log(`[setup] ${name}: up to date, skipping`);+ return;+ }+ if (!existsSync(resolve(ROOT, dir, 'node_modules'))) {+ run(`npm install --prefix ${dir} --prefer-offline --no-audit --no-fund`);+ }+ run(`npm run build --prefix ${dir}`);+ writeStamp(name, cacheInputs);+ console.log(`[setup] ${name}: built`);+}++console.log('[setup] Preparing dev environment…');++// 1. SDK dists required at import time by api/ code and tests.+buildSdk('setup-solana-agent-sdk', 'solana-agent-sdk', 'solana-agent-sdk/dist/index.js');+// postinstall normally covers agent-payments-sdk; rebuild here only if its+// dist is missing (e.g. install ran with scripts disabled).+if (!existsSync(resolve(ROOT, 'agent-payments-sdk/dist/index.js'))) {+ buildSdk('setup-agent-payments-sdk', 'agent-payments-sdk', 'agent-payments-sdk/dist/index.js');+}++// 2. Generated data consumed by the app, sitemap, and tests.+run('node scripts/build-news.mjs');+run('node scripts/build-skill-metadata.mjs');+run('node scripts/build-local-skill-packs.mjs');+run('node scripts/build-page-index.mjs');++console.log('[setup] Done. Next steps:');+console.log('[setup] npm run dev # app on http://localhost:3000');+console.log('[setup] npm run test:core # unit tests');diff --git a/src/dashboard-next/pages/agents.js b/src/dashboard-next/pages/agents.jsindex eca78d67d..50792e911 100644--- a/src/dashboard-next/pages/agents.js+++ b/src/dashboard-next/pages/agents.js@@ -199,6 +199,7 @@ function renderAgents(host, agents, avatars, root) {body: 'Agents are AI characters you can embed and chat with — each gets an on-chain identity, its own wallet, and attachable skills.',actions: [{ label: '+ Create your first agent', id: 'create-first', primary: true },+ { label: 'Generate its 3D body from text', href: '/create/prompt', id: 'forge-body' },{ label: "What's an agent?", href: '/docs/agents-vs-avatars', id: 'learn-agents' },],});diff --git a/src/dashboard-next/pages/avatars.js b/src/dashboard-next/pages/avatars.jsindex e89dd3c2b..a3c4f1abd 100644--- a/src/dashboard-next/pages/avatars.js+++ b/src/dashboard-next/pages/avatars.js@@ -670,9 +670,10 @@ function emptyBlock() {wrap.style.gridColumn = '1 / -1';wrap.innerHTML = `<h3>No avatars yet.</h3>- <p>Build your first 3D agent — start from a ready-made template, sculpt one from scratch, or drop a selfie.</p>+ <p>Build your first 3D agent — describe it in a sentence and watch it generate, start from a ready-made template, sculpt one from scratch, or drop a selfie.</p><div style="display:flex;gap:8px;flex-wrap:wrap;justify-content:center">- <button type="button" class="dn-btn primary" data-empty-template>Start from a template</button>+ <a class="dn-btn primary" href="/create/prompt">Describe it · prompt → 3D</a>+ <button type="button" class="dn-btn" data-empty-template>Start from a template</button><a class="dn-btn" href="/create/studio">Build from scratch</a><a class="dn-btn" href="/create/selfie">Create from selfie</a></div>diff --git a/src/dashboard-next/pages/home.js b/src/dashboard-next/pages/home.jsindex 3da57bd6c..ed98e46e2 100644--- a/src/dashboard-next/pages/home.js+++ b/src/dashboard-next/pages/home.js@@ -539,7 +539,9 @@ function renderForgeAnnounce(host) {type="text"name="prompt"autocomplete="off"+ autocapitalize="off"spellcheck="false"+ enterkeyhint="go"maxlength="${FORGE_PROMPT_CAP}"aria-label="Describe an object to forge into 3D"/>@@ -569,14 +571,21 @@ function renderForgeAnnounce(host) {// Submit → deep-link into the Forge with whatever the user typed. Empty// field falls back to the example currently on display, so the button is- // never a dead end.+ // never a dead end. Record the visit so Forge surfaces in "recents" just+ // like every other navigation on this page.let currentExample = FORGE_EXAMPLES[0];form.addEventListener('submit', (e) => {e.preventDefault();stopTypewriter();+ trackVisit('/forge');location.href = forgeHref(input.value || currentExample);});+ // Example chips navigate as plain links; tag the visit before they do.+ host.querySelector('.dnx-forge-chips').addEventListener('click', (e) => {+ if (e.target.closest('.dnx-forge-chip')) trackVisit('/forge');+ });+// Dismiss — persist so it stays gone, and tear down timers.host.querySelector('.dnx-forge-dismiss').addEventListener('click', () => {localStorage.setItem(FORGE_ANNOUNCE_DISMISSED_KEY, '1');@@ -1573,6 +1582,15 @@ function injectStyles() {}.dnx-forge:hover .dnx-forge-stage { animation-duration: 5s; }.dnx-forge:hover .dnx-forge-ring { animation-duration: 2.6s; }+ /* Engaging the composer primes the mesh — the visual reacts to the+ action it's attached to. */+ .dnx-forge:focus-within {+ border-color: rgba(255,255,255,0.28);+ box-shadow: 0 0 0 1px rgba(255,255,255,0.05), 0 18px 50px -28px rgba(255,255,255,0.3);+ }+ .dnx-forge:focus-within .dnx-forge-stage { animation-duration: 3.4s; }+ .dnx-forge:focus-within .dnx-forge-ring { animation-duration: 1.9s; opacity: 1; }+ .dnx-forge:focus-within .dnx-forge-scan { animation-duration: 1.6s; }/* ── Body: head + composer + chips ── */.dnx-forge-body { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 9px; }diff --git a/src/forge-ar.js b/src/forge-ar.jsnew file mode 100644index 000000000..3a22c139e--- /dev/null+++ b/src/forge-ar.js@@ -0,0 +1,208 @@+// Forge "See it in your space" — bridge desktop → phone AR.+//+// model-viewer can only enter AR on a phone/tablet, so a desktop visitor who+// just forged something has no way to place it in their room. This panel+// closes that gap:+// • on a desktop, it shows a QR code to the AR-capable embed viewer+// (/forge/embed) — scan it and the model opens on your phone, one tap from+// AR (the embed page reveals a big "View in AR" launcher there).+// • on a touch device, it launches AR straight from the page's own viewer.+//+// Self-contained: reads the live GLB URL off the result bar's Download link,+// reuses the zero-dep QR encoder and the shared Modal — no coupling to+// src/forge.js internals, no network calls, no new dependencies.++import { Modal } from './shared/modal.js';+import { renderQRToSVG } from './erc8004/qr.js';++const ORIGIN = 'https://three.ws';+const STYLE_ID = 'tws-forge-ar-styles';++function esc(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++function absoluteGlb(url) {+ if (!url) return '';+ try {+ return new URL(url, ORIGIN).href;+ } catch {+ return url;+ }+}++// Short URL for the QR (no title — keeps the code low-density and easy to scan).+function arUrl(glbUrl) {+ return `${ORIGIN}/forge/embed?src=${encodeURIComponent(glbUrl)}`;+}++// Richer URL for the tappable link (carries the prompt through as alt text).+function arLink(glbUrl, title) {+ const u = arUrl(glbUrl);+ return title ? `${u}&title=${encodeURIComponent(title.slice(0, 120))}` : u;+}++function isTouch() {+ return typeof window !== 'undefined' && window.matchMedia?.('(pointer: coarse)').matches;+}++function ensureStyles() {+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;+ const el = document.createElement('style');+ el.id = STYLE_ID;+ el.textContent = CSS;+ (document.head || document.documentElement).appendChild(el);+}++function qrMarkup(glbUrl) {+ try {+ const svg = renderQRToSVG(arUrl(glbUrl), {+ scale: 6,+ margin: 2,+ dark: '#0b0b0b',+ light: '#ffffff',+ });+ return `<div class="tws-ar-qr" aria-label="QR code linking to the AR viewer">${svg}</div>`;+ } catch {+ // Payload too large for the encoder — degrade to link-only, never a broken QR.+ return '';+ }+}++const cubeIcon = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 2 3 7v10l9 5 9-5V7l-9-5Z"/><path d="m3 7 9 5 9-5"/><path d="M12 12v10"/></svg>`;++function bodyHtml({ glbUrl, title, touch }) {+ const link = esc(arLink(glbUrl, title));+ const nameHtml = title ? `<p class="tws-ar-name">${esc(title)}</p>` : '';+ const qr = qrMarkup(glbUrl);++ const linkBtn = `<a class="tws-ar-cta" href="${link}" target="_blank" rel="noopener">${cubeIcon}<span>Open AR viewer</span></a>`;++ if (touch) {+ // Touch device: launch AR right here from the page's own viewer.+ const qrSecondary = qr+ ? `<details class="tws-ar-more">+ <summary>On a computer? Scan from your phone</summary>+ ${qr}+ </details>`+ : '';+ return `+ <div class="tws-ar">+ ${nameHtml}+ <p class="tws-ar-hint">Place this model in your room — point your camera at a flat surface and drop it in.</p>+ <button class="tws-ar-cta" type="button" data-ar-launch>${cubeIcon}<span>View in your space</span></button>+ <a class="tws-ar-link" href="${link}" target="_blank" rel="noopener">Open in a new tab instead ↗</a>+ ${qrSecondary}+ </div>+ `;+ }++ // Desktop: QR is the bridge to the phone.+ return `+ <div class="tws-ar">+ ${nameHtml}+ ${qr}+ <p class="tws-ar-hint">Scan with your phone camera to view this model in AR and place it in your room.</p>+ ${linkBtn}+ </div>+ `;+}++export function showARPanel({ glbUrl, title } = {}, triggerEl = null) {+ ensureStyles();+ const abs = absoluteGlb(glbUrl);+ if (!abs) return null;+ const touch = isTouch();++ const modal = new Modal({+ title: 'See it in your space',+ body: bodyHtml({ glbUrl: abs, title: (title || '').trim(), touch }),+ dismissible: true,+ }).open(triggerEl);++ const root = modal.bodyEl;+ root.addEventListener('click', (e) => {+ if (!e.target.closest('[data-ar-launch]')) return;+ // Launch AR from the page's main viewer (already AR-enabled in result state).+ const viewer = document.getElementById('viewer');+ try {+ viewer?.activateAR?.();+ modal.close?.();+ } catch {+ /* fall back to the "open in new tab" link the user can still tap */+ }+ });++ return modal;+}++// Wire the result-bar button. GLB URL is read from the Download link at click+// time, so this never depends on Forge's internal state.+function wire() {+ const btn = document.getElementById('forge-ar-btn');+ if (!btn || btn.dataset.arWired) return;+ btn.dataset.arWired = '1';+ btn.addEventListener('click', () => {+ const glbUrl = document.getElementById('download')?.getAttribute('href') || '';+ const title = document.getElementById('result-label')?.textContent || '';+ if (!glbUrl) return;+ showARPanel({ glbUrl, title }, btn);+ });+}++if (typeof document !== 'undefined') {+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', wire, { once: true });+ } else {+ wire();+ }+}++const CSS = `+.tws-ar { display: flex; flex-direction: column; align-items: center; gap: 14px; padding: 4px 0 2px; text-align: center; }+.tws-ar-name {+ margin: 0; max-width: 32ch;+ font: 600 14px/1.4 var(--font-body, system-ui, sans-serif);+ color: var(--ink, #ececf4);+}+.tws-ar-qr {+ width: 208px; height: 208px; padding: 12px;+ background: #fff; border-radius: 16px;+ box-shadow: 0 16px 40px -16px rgba(0,0,0,0.7);+ display: grid; place-items: center;+}+.tws-ar-qr svg { width: 100%; height: 100%; display: block; border-radius: 4px; }+.tws-ar-hint {+ margin: 0; max-width: 34ch;+ font-size: 13px; line-height: 1.5; color: var(--ink-dim, #9a9aa8);+}+.tws-ar-cta {+ display: inline-flex; align-items: center; justify-content: center; gap: 9px;+ width: 100%; box-sizing: border-box; cursor: pointer; text-decoration: none;+ padding: 13px 18px; border: 0; border-radius: 12px;+ font: 600 14.5px/1 var(--font-body, system-ui, sans-serif);+ color: #07140e; background: var(--success, #6ee7b7);+ box-shadow: 0 10px 28px -10px rgba(110,231,183,0.55);+ transition: filter 0.14s ease, transform 0.1s ease;+}+.tws-ar-cta:hover { filter: brightness(1.06); }+.tws-ar-cta:active { transform: translateY(1px); }+.tws-ar-cta:focus-visible { outline: 2px solid var(--ink, #fff); outline-offset: 2px; }+.tws-ar-cta svg { width: 18px; height: 18px; }+.tws-ar-link {+ font-size: 13px; color: var(--accent, #6ee7b7); text-decoration: none;+}+.tws-ar-link:hover { text-decoration: underline; }+.tws-ar-more { width: 100%; margin-top: 2px; }+.tws-ar-more summary {+ cursor: pointer; list-style: none; font-size: 12.5px;+ color: var(--ink-dim, #9a9aa8); padding: 6px 0;+}+.tws-ar-more summary::-webkit-details-marker { display: none; }+.tws-ar-more summary:hover { color: var(--ink, #ececf4); }+.tws-ar-more[open] summary { margin-bottom: 10px; }+.tws-ar-more .tws-ar-qr { width: 168px; height: 168px; margin: 0 auto; }+`;diff --git a/src/forge.js b/src/forge.jsindex fbe6feff9..fddd25848 100644--- a/src/forge.js+++ b/src/forge.js@@ -68,7 +68,13 @@ const els = {verdict: document.getElementById('verdict'),download: document.getElementById('download'),again: document.getElementById('again'),+ refine: document.getElementById('refine'),+ refineLabel: document.getElementById('refine-label'),retry: document.getElementById('retry'),+ viewsCounter: document.getElementById('views-counter'),+ viewsCounterText: document.getElementById('views-counter-text'),+ viewsPips: document.getElementById('views-pips'),+ sketchReqTag: document.getElementById('sketch-req-tag'),generateAnyway: document.getElementById('generate-anyway'),errorMessage: document.getElementById('error-message'),forgeShareBtn: document.getElementById('forge-share-btn'),@@ -92,6 +98,17 @@ let pollAbort = false;let mode = 'text'; // 'text' | 'image' | 'sketch' — input mode (prompt vs photos vs drawing)let lastJob = null; // { prompt, imageUrls } — for retrylet currentCreationId = null;+// The quality tier the on-screen result was produced at — drives the "Refine"+// affordance, which re-runs the same job exactly one tier higher.+let currentResultTier = null;++// Quality tiers, lowest → highest. Refine walks one step up this ladder.+const TIER_ORDER = ['draft', 'standard', 'high'];+const TIER_LABELS = { draft: 'Draft', standard: 'Standard', high: 'High' };+function nextTierAfter(tier) {+ const i = TIER_ORDER.indexOf(tier);+ return i >= 0 && i < TIER_ORDER.length - 1 ? TIER_ORDER[i + 1] : null;+}// Generation route + quality. `genPath` is the task's image|geometry axis;// `genBackend` names the provider; both come from the selected engine button.@@ -1041,6 +1058,23 @@ async function playMaterialize(glbUrl) {}}+// Show "Refine → <next tier>" only when a higher tier exists and the current+// result came from a job we can re-run (a prompt and/or reference images).+function updateRefineButton() {+ if (!els.refine) return;+ const next = nextTierAfter(currentResultTier);+ const reRunnable =+ lastJob && (lastJob.prompt || (Array.isArray(lastJob.imageUrls) && lastJob.imageUrls.length));+ const show = Boolean(next && reRunnable);+ els.refine.classList.toggle('is-hidden', !show);+ if (show) {+ els.refineLabel.textContent = `Refine → ${TIER_LABELS[next]}`;+ els.refine.title = `Re-run this exact ${+ lastJob.imageUrls?.length ? 'reconstruction' : 'prompt'+ } at ${TIER_LABELS[next]} quality`;+ }+}+function showResult(glbUrl, label, meta) {stopElapsed();resetVerdict();@@ -1055,6 +1089,11 @@ function showResult(glbUrl, label, meta) {);// Cross-link into Parts Studio with this exact model pre-loaded.if (els.segmentBtn) els.segmentBtn.href = `/segment?mesh=${encodeURIComponent(glbUrl)}`;+ // Offer "Refine" when a higher tier exists and this job can be re-run. Use the+ // tier the result was actually produced at (meta), falling back to the current+ // selection for re-opened gallery models that don't carry tier metadata.+ currentResultTier = meta?.tier || selectedTier;+ updateRefineButton();showState('result');playMaterialize(glbUrl);// Hand the live model to the Stylize panel (src/forge-stylize.js) so its@@ -1522,6 +1561,16 @@ els.retry.addEventListener('click', () => {}});+// Refine — re-run the same prompt/views one quality tier higher. Bumping the+// tier syncs the selector (and the tier's default engine), then replays the+// stored job, so the higher-fidelity model lands in the same viewer.+els.refine?.addEventListener('click', () => {+ const next = nextTierAfter(currentResultTier);+ if (!next || !lastJob) return;+ selectTier(next);+ run(lastJob);+});+// "Generate anyway" — re-run the same job with the vision pre-check bypassed.els.generateAnyway?.addEventListener('click', () => {if (!lastJob) return;diff --git a/vitest.config.js b/vitest.config.jsindex 4fd2565f8..dbeebea7a 100644--- a/vitest.config.js+++ b/vitest.config.js@@ -20,6 +20,15 @@ const _cpus = Math.max(1, (os.availableParallelism?.() ?? os.cpus().length) - 1)const MAX_FORKS = _cpus <= 3 ? 2 : Math.min(6, _cpus);export default defineConfig({+ // packages/avatar-agent-mcp ships its own nested @grpc/* copies (it is a+ // standalone publishable package). Without deduping, the package's lazy+ // `import('@grpc/grpc-js')` resolves to that nested copy while a test's+ // `vi.mock('@grpc/grpc-js')` only patches the root copy — so the MCP-twin+ // TTS test fell through the mock and hit live NVCF. Forcing a single+ // instance across the graph makes the transport mock cover both libs.+ resolve: {+ dedupe: ['@grpc/grpc-js', '@grpc/proto-loader'],+ },test: {environment: 'node',include: [