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
Avatar agent, forge viewer, MCP server docs, chat tools, and changelog updates
nirholasffb49ab88d1a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c07caddf8..3e106fe7f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -42,6 +42,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Everyone at a location now sees your IRL agent in the same real spot** — three.ws/irl agents now line up across phones. A placed agent renders from its own saved compass bearing and ground height instead of whichever way your phone happens to face, so two people standing in the same place see it standing in the same place, facing the same way. To keep it steady, your own GPS position is now smoothed so anchored agents stop drifting and swimming as your location jitters, and noisy fixes are ignored. Every agent now sits inside a ground ring whose size reflects the real GPS accuracy — honest about the fact that phone GPS is roughly 5–15 metres, and wider (and amber) when the signal is poor — so it never pretends to be pinpoint-perfect. And if an agent landed a little off, its owner can fine-tune it: long-press your own agent (or tap Calibrate position on its card) and drag to nudge it a few centimetres, twist with two fingers to rotate it, or step its floor height up and down. Saving the nudge updates the spot for everyone nearby. Only the owner can calibrate an agent, nudges are capped to small corrections so this can never be used to drag someone's agent across the map, and a failed save keeps your change on screen with a one-tap retry. (`/irl`) `[feature, improvement]`- **Filter the marketplace by Free or Paid** — The marketplace now has working Free / Paid filters. "Paid" surfaces every agent that charges in any way — a one-time price to own it or per-call pricing on its skills — and "Free" shows the rest. Filtering happens on the server, so the result count and "load more" stay accurate no matter how many pages deep you browse, and your choice is saved in the URL so you can bookmark or share a filtered view. (`/marketplace`) `[feature, improvement]`- **Forge resilience: HuggingFace fallback now covers text→3D; club-payout log noise reduced** — When the NVIDIA NIM free lane returns a 5xx and the Replicate TRELLIS lane is also unavailable, the forge now falls through to the HuggingFace Spaces fallback for text→3D requests (using the FLUX-synthesized intermediate image) instead of returning a 429 to the user. Previously this fallback only fired for image uploads. Club-payout cron warnings for dancers with no registered wallet are now emitted at most once per 24 hours instead of every 5-minute tick. `[fix, infra]`+- **Free text-to-3D over MCP — no payment, no key** — The three.ws MCP server now ships a free tool: forge_free turns a text prompt into a textured, downloadable 3D model with zero cost — no x402 payment, no wallet, no API key. It runs on the same free NVIDIA NIM (Microsoft TRELLIS) engine the /forge web page uses for drafts, and hands back a durable GLB plus a viewer link that renders the model in the browser. Drop your Claude/Cursor agent on it, type a prompt, get a 3D avatar. The paid tools (mesh_forge, text_to_avatar, rig_mesh) remain for image input, the Granite-directed model chain, and auto-rigging. `[sdk, feature]`- **Game-Ready export in Forge — one click to engine-ready GLB + FBX** — Any model you generate or upload in Forge can now be turned into a clean, engine-ready asset in one click. Pick Quad retopology (field-aligned QuadriFlow edge loops that rig and animate well) or Tri low-poly (silhouette-preserving, with the texture re-baked), set a poly budget with 5k / 15k / 50k presets, and export a textured GLB plus an FBX for Unity and Unreal together. You see the before→after poly count (e.g. 28,400 → 5,012) and can flip on a live wireframe to inspect the new topology right in the viewer. Files are served from our own CDN. (`/forge`) `[feature]`- **Generate a rigged 3D avatar from a text prompt in chat** — Chat can now build a full avatar from a sentence. Ask it to "make me an avatar of …" and it forges a textured 3D model, auto-rigs it into an animation-ready character, saves it to your avatar library, and shows it in an orbit viewer you can spin (press S to see the skeleton). If you're not signed in it still hands back the rigged model and tells you to sign in to save. The tool is on by default in a fresh chat. (`/chat`) `[feature]`- **iPhone now world-locks your IRL agent — it holds its real spot as you pan and walk** — iPhone Safari has no AR mode, so a placed agent used to drift with the camera. On three.ws/irl it now stays anchored to its real-world spot using the compass and GPS: pan your phone and the agent holds its real bearing instead of following the view, and walk toward it and it grows and keeps its place. Tapping Pin here saves the full placement — facing, ground height, and how good your GPS fix was — so iPhone placements match the AR-anchored version other phones see. If you pin before your location is ready, it waits for the first fix and pins precisely instead of dropping at a default spot. Permission states are designed and recoverable too: if motion or location access is off you get a clear card with the exact iOS Settings path and a Try again button, and if your phone can't read an absolute compass heading you're warned that others may see the agent rotated. (`/irl`) `[improvement]`diff --git a/api/_lib/avatar-agent.js b/api/_lib/avatar-agent.jsnew file mode 100644index 000000000..ba8d2f701--- /dev/null+++ b/api/_lib/avatar-agent.js@@ -0,0 +1,71 @@+// Provision an agent (and its custodial Solana wallet) for a newly created+// avatar. Extracted from api/avatars/index.js so every avatar-creation path —+// direct upload AND the chat/forge "text → avatar" save — yields a first-class+// agent the same way, instead of a bare library entry.++import { sql } from './db.js';+import { withDbRetry } from './db-retry.js';++// Claim an existing agent that has no avatar yet, or create a default one, then+// ensure that agent has a custodial Solana wallet. Idempotent and safe to retry+// (the claim is naturally idempotent and the insert is guarded by NOT EXISTS),+// so a transient DB blip never leaves an avatar without its agent. Never throws+// — callers run it fire-and-forget via queueMicrotask. Returns the agent id (or+// null if provisioning could not complete).+export async function provisionAvatarAgent({ userId, avatarId, avatarName }) {+ try {+ const agentId = await withDbRetry(async () => {+ const linked = await sql`+ WITH agent_to_update AS (+ SELECT id FROM agent_identities+ WHERE user_id = ${userId}+ AND avatar_id IS NULL+ AND deleted_at IS NULL+ ORDER BY created_at ASC+ LIMIT 1+ )+ UPDATE agent_identities+ SET avatar_id = ${avatarId}, updated_at = NOW()+ FROM agent_to_update+ WHERE agent_identities.id = agent_to_update.id+ RETURNING agent_identities.id+ `;+ if (linked.length) return linked[0].id;+ const [created] = await sql`+ INSERT INTO agent_identities (user_id, name, avatar_id, is_public, created_at, updated_at)+ SELECT+ ${userId},+ ${avatarName || 'My Agent'},+ ${avatarId},+ false,+ NOW(),+ NOW()+ WHERE NOT EXISTS (+ SELECT 1 FROM agent_identities+ WHERE user_id = ${userId} AND avatar_id = ${avatarId}+ )+ RETURNING id+ `;+ return created?.id ?? null;+ });++ // Every 3D avatar's agent gets a custodial Solana wallet on first save so+ // it can transact immediately. Solana-only by product decision — EVM is+ // opt-in via the wallet panel. Idempotent: an agent that already has a+ // Solana wallet is untouched.+ if (agentId) {+ const { getOrCreateAgentSolanaWallet } = await import('./agent-wallet.js');+ await getOrCreateAgentSolanaWallet(agentId).catch((e) =>+ console.warn('[avatar-agent] solana wallet provision failed', agentId, e?.message),+ );+ }+ return agentId;+ } catch (err) {+ console.error('[avatar-agent] auto-agent failed', {+ avatarId,+ userId,+ error: err?.message,+ });+ return null;+ }+}diff --git a/api/avatars/from-forge.js b/api/avatars/from-forge.jsnew file mode 100644index 000000000..c1cb34fc0--- /dev/null+++ b/api/avatars/from-forge.js@@ -0,0 +1,167 @@+// POST /api/avatars/from-forge+//+// Save a generated GLB (by URL) straight into the caller's avatar library,+// server-side. This is the durable end of the chat "text → 3D avatar" pipeline:+// the chat tool forges a mesh and auto-rigs it (both return public GLB URLs),+// then hands the final URL here. Doing the copy on the server — instead of the+// browser fetching the GLB and presigning a PUT — sidesteps cross-origin (CORS)+// reads of provider/R2 URLs, the 16 MB browser-upload cap, and the+// size-match race on /api/avatars, and it routes through the same+// createAvatar + agent-provisioning path as a normal upload so the result is a+// first-class, agent-backed avatar.+//+// Mirrors the MCP studio save_avatar tool, but session/bearer authed for the+// browser instead of x402.+//+// Request body (JSON):+// glb_url string — public https URL of the GLB to save (required)+// name string — avatar name, 1–80 chars (required)+// visibility enum? — public | unlisted | private (default unlisted)+// source_prompt string? — the prompt that generated it, kept as provenance+// rigged bool? — whether the GLB is auto-rigged (provenance only)+// tags string[]? — up to 20 organizing tags+//+// Response 201: { avatar, view_url }++import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';+import { storageKeyFor, createAvatar } from '../_lib/avatars.js';+import { putObject } from '../_lib/r2.js';+import { isValidGlbHeader, inspectGlb } from '../_lib/glb-inspect.js';+import { fetchSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';+import { provisionAvatarAgent } from '../_lib/avatar-agent.js';+import { limits } from '../_lib/rate-limit.js';+import { recordEvent } from '../_lib/usage.js';+import { env } from '../_lib/env.js';++// Match the studio/reconstruct ceiling so a runaway model can't ingest an+// unbounded blob. The avatars table allows far more, but a generated avatar is+// realistically 5–25 MB.+const MAX_GLB_BYTES = 64 * 1024 * 1024;+const VISIBILITIES = new Set(['public', 'unlisted', 'private']);++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id ?? session.userId, source: 'session' };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer && hasScope(bearer, 'avatars:write')) return bearer;+ return null;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const auth = await resolveAuth(req);+ if (!auth?.userId) {+ return error(res, 401, 'unauthorized', 'sign in (or provide an avatars:write token) to save an avatar');+ }++ const rl = await limits.upload(auth.userId);+ if (!rl.success) {+ res.setHeader('Retry-After', Math.max(1, Math.ceil((rl.reset - Date.now()) / 1000)));+ return error(res, 429, 'rate_limited', 'too many avatar saves; try again shortly');+ }++ let body;+ try {+ body = await readJson(req);+ } catch (err) {+ return error(res, 400, 'bad_request', err?.message || 'invalid JSON body');+ }++ const glbUrl = typeof body?.glb_url === 'string' ? body.glb_url.trim() : '';+ const name = typeof body?.name === 'string' ? body.name.trim().slice(0, 80) : '';+ if (!glbUrl) return error(res, 400, 'invalid_request', 'glb_url is required');+ if (!name) return error(res, 400, 'invalid_request', 'name is required (1–80 chars)');++ const visibility = VISIBILITIES.has(body?.visibility) ? body.visibility : 'unlisted';+ const sourcePrompt =+ typeof body?.source_prompt === 'string' ? body.source_prompt.slice(0, 1000) : null;+ const rigged = body?.rigged === true;+ const tags = Array.isArray(body?.tags)+ ? body.tags.map((t) => String(t).trim()).filter(Boolean).slice(0, 20)+ : [];++ // Fetch the GLB server-side through the SSRF guard (https-only, no+ // private/loopback/metadata targets) — glb_url is model-influenced, so it is+ // never trusted to point at our own network.+ let resp;+ try {+ resp = await fetchSafePublicUrl(glbUrl, {}, { allowHttp: false });+ } catch (err) {+ if (err instanceof SsrfBlockedError) {+ return error(res, 400, 'invalid_url', 'glb_url must be a public https URL');+ }+ return error(res, 502, 'fetch_failed', `could not fetch glb_url: ${err?.message || 'network error'}`);+ }+ if (!resp.ok) {+ return error(res, 502, 'fetch_failed', `glb_url returned ${resp.status}`);+ }++ const declared = Number(resp.headers.get('content-length') || 0);+ if (declared && declared > MAX_GLB_BYTES) {+ return error(res, 413, 'payload_too_large', `glb is ${declared} bytes; max is ${MAX_GLB_BYTES}`);+ }+ const buf = Buffer.from(await resp.arrayBuffer());+ if (buf.length > MAX_GLB_BYTES) {+ return error(res, 413, 'payload_too_large', `glb is ${buf.length} bytes; max is ${MAX_GLB_BYTES}`);+ }+ if (!isValidGlbHeader(buf)) {+ return error(res, 422, 'invalid_glb', 'that URL did not return a valid binary glTF (.glb)');+ }+ const info = inspectGlb(buf);++ // Durable copy under the caller's own storage namespace, then register it.+ const slug = `studio-${Math.random().toString(36).slice(2, 8)}`;+ const storageKey = storageKeyFor({ userId: auth.userId, slug });+ await putObject({+ key: storageKey,+ body: buf,+ contentType: 'model/gltf-binary',+ metadata: { source: 'studio', user_id: auth.userId },+ });++ const avatar = await createAvatar({+ userId: auth.userId,+ storageKey,+ input: {+ slug,+ name,+ description: null,+ size_bytes: buf.length,+ content_type: 'model/gltf-binary',+ source: 'studio',+ source_meta: {+ source_glb_url: glbUrl,+ source_prompt: sourcePrompt,+ generator: 'chat-forge-avatar',+ is_rigged: rigged || info.isRigged || null,+ mesh_count: info.meshCount ?? null,+ animation_count: info.animationCount ?? null,+ },+ visibility,+ tags,+ checksum_sha256: null,+ parent_avatar_id: null,+ },+ });++ // First-class like a normal upload: provision the agent + custodial wallet.+ queueMicrotask(() =>+ provisionAvatarAgent({ userId: auth.userId, avatarId: avatar.id, avatarName: avatar.name }),+ );++ recordEvent({+ userId: auth.userId,+ apiKeyId: auth.apiKeyId,+ clientId: auth.clientId,+ avatarId: avatar.id,+ kind: 'upload',+ bytes: buf.length,+ meta: { source: 'chat-forge-avatar', rigged: Boolean(rigged) },+ });++ const viewUrl = `${env.APP_ORIGIN || ''}/discover/avatar/${avatar.id}`;+ return json(res, 201, { avatar, view_url: viewUrl });+});diff --git a/api/avatars/index.js b/api/avatars/index.jsindex 56eac500f..1a5c4c010 100644--- a/api/avatars/index.js+++ b/api/avatars/index.js@@ -7,7 +7,7 @@ import { headObject, r2 } from '../_lib/r2.js';import { HeadObjectCommand } from '@aws-sdk/client-s3';import { env } from '../_lib/env.js';import { sql } from '../_lib/db.js';-import { withDbRetry } from '../_lib/db-retry.js';+import { provisionAvatarAgent } from '../_lib/avatar-agent.js';import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';import { parse, createAvatarBody } from '../_lib/validate.js';import { recordEvent } from '../_lib/usage.js';@@ -121,69 +121,9 @@ async function handleCreate(req, res) {// (parent_avatar_id set) — the re-point above already handled that case.// Fire-and-forget — 201 returns regardless.if (!body.parent_avatar_id) {- queueMicrotask(async () => {- try {- // Transient Neon "fetch failed" blips must not leave a new avatar- // without its agent. The claim is naturally idempotent and the- // insert is guarded by NOT EXISTS below, so the whole sequence is- // safe to retry on a connection-level failure.- const agentId = await withDbRetry(async () => {- // First try to claim an existing agent that has no avatar yet.- const linked = await sql`- WITH agent_to_update AS (- SELECT id FROM agent_identities- WHERE user_id = ${auth.userId}- AND avatar_id IS NULL- AND deleted_at IS NULL- ORDER BY created_at ASC- LIMIT 1- )- UPDATE agent_identities- SET avatar_id = ${avatar.id}, updated_at = NOW()- FROM agent_to_update- WHERE agent_identities.id = agent_to_update.id- RETURNING agent_identities.id- `;- if (linked.length) return linked[0].id;- // No existing agent to claim — create a default one. The NOT EXISTS- // guard keeps a retried insert (after a lost response) from- // creating a second agent for the same avatar.- const [created] = await sql`- INSERT INTO agent_identities (user_id, name, avatar_id, is_public, created_at, updated_at)- SELECT- ${auth.userId},- ${avatar.name || 'My Agent'},- ${avatar.id},- false,- NOW(),- NOW()- WHERE NOT EXISTS (- SELECT 1 FROM agent_identities- WHERE user_id = ${auth.userId} AND avatar_id = ${avatar.id}- )- RETURNING id- `;- return created?.id ?? null;- });-- // Every 3D avatar's agent gets a custodial Solana wallet on first- // save so it can transact immediately. Solana-only by product- // decision — EVM is opt-in via the wallet panel, never auto-minted.- // Idempotent: an agent that already has a Solana wallet is untouched.- if (agentId) {- const { getOrCreateAgentSolanaWallet } = await import('../_lib/agent-wallet.js');- await getOrCreateAgentSolanaWallet(agentId).catch((e) =>- console.warn('[avatars] solana wallet provision failed', agentId, e?.message),- );- }- } catch (err) {- console.error('[avatars] auto-agent failed', {- avatarId: avatar.id,- userId: auth.userId,- error: err?.message,- });- }- });+ queueMicrotask(() =>+ provisionAvatarAgent({ userId: auth.userId, avatarId: avatar.id, avatarName: avatar.name }),+ );}recordEvent({diff --git a/chat/public/forge-viewer.html b/chat/public/forge-viewer.htmlnew file mode 100644index 000000000..8ec0fcc02--- /dev/null+++ b/chat/public/forge-viewer.html@@ -0,0 +1,1049 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />+ <title>three.ws Forge — 3D preview</title>+ <style>+ :root {+ --bg: #0a0c10;+ --panel: rgba(13, 16, 21, 0.72);+ --stroke: rgba(255, 255, 255, 0.12);+ --stroke-strong: rgba(255, 255, 255, 0.22);+ --text: #e8eaed;+ --muted: #9aa3ad;+ --accent: #7c5cff;+ --accent-2: #18e0c8;+ --danger: #ff6b6b;+ }+ * {+ box-sizing: border-box;+ }+ html,+ body {+ margin: 0;+ height: 100%;+ background: var(--bg);+ color: var(--text);+ font-family: ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;+ overflow: hidden;+ -webkit-font-smoothing: antialiased;+ }+ #stage {+ position: fixed;+ inset: 0;+ display: block;+ }+ canvas {+ display: block;+ width: 100%;+ height: 100%;+ outline: none;+ }++ /* ── Loading ─────────────────────────────────────────── */+ #loading {+ position: fixed;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ transition: opacity 0.5s ease;+ }+ #loading.hidden {+ opacity: 0;+ pointer-events: none;+ }+ #preview-bg {+ position: absolute;+ inset: -6%;+ background-size: cover;+ background-position: center;+ filter: blur(26px) brightness(0.42) saturate(1.1);+ transform: scale(1.12);+ opacity: 0;+ transition: opacity 0.8s ease;+ }+ #preview-bg.shown {+ opacity: 1;+ }+ .shimmer {+ position: absolute;+ inset: 0;+ background:+ radial-gradient(120% 120% at 30% 20%, rgba(124, 92, 255, 0.16), transparent 60%),+ radial-gradient(120% 120% at 75% 80%, rgba(24, 224, 200, 0.12), transparent 60%),+ var(--bg);+ }+ .shimmer::after {+ content: '';+ position: absolute;+ inset: 0;+ background: linear-gradient(110deg, transparent 30%, rgba(255, 255, 255, 0.05) 50%, transparent 70%);+ transform: translateX(-100%);+ animation: sweep 2.4s ease-in-out infinite;+ }+ @keyframes sweep {+ to {+ transform: translateX(100%);+ }+ }+ .card {+ position: relative;+ width: min(420px, 86vw);+ padding: 26px 24px 22px;+ border-radius: 18px;+ background: var(--panel);+ border: 1px solid var(--stroke);+ backdrop-filter: blur(18px);+ -webkit-backdrop-filter: blur(18px);+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.45);+ text-align: center;+ }+ .thumb {+ width: 96px;+ height: 96px;+ margin: 0 auto 16px;+ border-radius: 14px;+ border: 1px solid var(--stroke-strong);+ background-size: cover;+ background-position: center;+ position: relative;+ overflow: hidden;+ background-color: #11151b;+ }+ .thumb .ring {+ position: absolute;+ inset: -2px;+ border-radius: inherit;+ }+ .spinner {+ width: 22px;+ height: 22px;+ flex: 0 0 auto;+ }+ .spinner circle {+ fill: none;+ stroke: var(--accent-2);+ stroke-width: 4;+ stroke-linecap: round;+ stroke-dasharray: 90 150;+ transform-origin: center;+ animation: spin 1s linear infinite;+ }+ @keyframes spin {+ to {+ transform: rotate(360deg);+ }+ }+ .status-row {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 10px;+ font-size: 15px;+ font-weight: 600;+ letter-spacing: 0.01em;+ }+ .prompt {+ margin: 4px 0 16px;+ font-size: 13px;+ color: var(--muted);+ line-height: 1.45;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+ }+ .bar {+ position: relative;+ height: 5px;+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.08);+ overflow: hidden;+ }+ .bar > i {+ position: absolute;+ top: 0;+ left: 0;+ height: 100%;+ width: 40%;+ border-radius: inherit;+ background: linear-gradient(90deg, var(--accent), var(--accent-2));+ animation: indet 1.5s ease-in-out infinite;+ }+ @keyframes indet {+ 0% {+ left: -42%;+ }+ 100% {+ left: 100%;+ }+ }+ .sub {+ margin-top: 12px;+ font-size: 12px;+ color: var(--muted);+ font-variant-numeric: tabular-nums;+ }++ /* ── Viewer chrome ───────────────────────────────────── */+ #hud {+ position: fixed;+ left: 14px;+ top: 12px;+ right: 14px;+ display: flex;+ align-items: flex-start;+ gap: 10px;+ pointer-events: none;+ opacity: 0;+ transition: opacity 0.6s ease 0.2s;+ }+ #hud.shown {+ opacity: 1;+ }+ .hud-title {+ max-width: min(62%, 520px);+ padding: 7px 12px;+ font-size: 13px;+ line-height: 1.35;+ color: var(--text);+ background: var(--panel);+ border: 1px solid var(--stroke);+ border-radius: 10px;+ backdrop-filter: blur(12px);+ -webkit-backdrop-filter: blur(12px);+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+ }+ .chips {+ display: flex;+ gap: 6px;+ flex-wrap: wrap;+ }+ .chip {+ font-size: 10px;+ font-weight: 600;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--muted);+ padding: 4px 8px;+ border-radius: 999px;+ background: var(--panel);+ border: 1px solid var(--stroke);+ backdrop-filter: blur(12px);+ -webkit-backdrop-filter: blur(12px);+ }+ #toolbar {+ position: fixed;+ left: 50%;+ bottom: 14px;+ transform: translateX(-50%) translateY(8px);+ display: flex;+ gap: 6px;+ padding: 6px;+ border-radius: 14px;+ background: var(--panel);+ border: 1px solid var(--stroke);+ backdrop-filter: blur(16px);+ -webkit-backdrop-filter: blur(16px);+ box-shadow: 0 12px 32px rgba(0, 0, 0, 0.4);+ opacity: 0;+ transition: opacity 0.6s ease 0.3s, transform 0.6s ease 0.3s;+ max-width: calc(100vw - 28px);+ flex-wrap: wrap;+ justify-content: center;+ }+ #toolbar.shown {+ opacity: 1;+ transform: translateX(-50%) translateY(0);+ }+ .btn {+ appearance: none;+ border: 1px solid transparent;+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: 12.5px;+ font-weight: 600;+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 8px 12px;+ border-radius: 9px;+ cursor: pointer;+ text-decoration: none;+ transition: background 0.16s ease, border-color 0.16s ease, opacity 0.16s ease;+ white-space: nowrap;+ }+ .btn:hover {+ background: rgba(255, 255, 255, 0.08);+ }+ .btn:active {+ background: rgba(255, 255, 255, 0.14);+ }+ .btn:focus-visible {+ outline: none;+ border-color: var(--accent-2);+ box-shadow: 0 0 0 2px rgba(24, 224, 200, 0.35);+ }+ .btn[aria-pressed='true'] {+ background: rgba(124, 92, 255, 0.22);+ border-color: rgba(124, 92, 255, 0.5);+ }+ .btn.primary {+ background: linear-gradient(90deg, var(--accent), #6b8bff);+ color: #fff;+ }+ .btn.primary:hover {+ filter: brightness(1.08);+ }+ .btn[disabled] {+ opacity: 0.45;+ cursor: default;+ }+ .btn svg {+ width: 15px;+ height: 15px;+ flex: 0 0 auto;+ }+ .btn .label-sm {+ display: inline;+ }+ @media (max-width: 560px) {+ .btn .label-sm {+ display: none;+ }+ .btn {+ padding: 9px 11px;+ }+ }++ /* ── End states ──────────────────────────────────────── */+ #state {+ position: fixed;+ inset: 0;+ display: none;+ align-items: center;+ justify-content: center;+ padding: 20px;+ }+ #state.shown {+ display: flex;+ }+ .state-card {+ width: min(440px, 88vw);+ padding: 28px 26px;+ border-radius: 18px;+ background: var(--panel);+ border: 1px solid var(--stroke);+ backdrop-filter: blur(18px);+ -webkit-backdrop-filter: blur(18px);+ text-align: center;+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.45);+ }+ .state-icon {+ width: 46px;+ height: 46px;+ margin: 0 auto 14px;+ display: grid;+ place-items: center;+ border-radius: 50%;+ background: rgba(255, 107, 107, 0.14);+ color: var(--danger);+ }+ .state-title {+ font-size: 17px;+ font-weight: 700;+ margin-bottom: 8px;+ }+ .state-msg {+ font-size: 13.5px;+ color: var(--muted);+ line-height: 1.5;+ margin-bottom: 20px;+ }+ .state-actions {+ display: flex;+ gap: 8px;+ justify-content: center;+ flex-wrap: wrap;+ }+ .toast {+ position: fixed;+ left: 50%;+ bottom: 74px;+ transform: translateX(-50%) translateY(8px);+ background: var(--panel);+ border: 1px solid var(--stroke);+ color: var(--text);+ font-size: 12.5px;+ padding: 9px 14px;+ border-radius: 10px;+ backdrop-filter: blur(14px);+ -webkit-backdrop-filter: blur(14px);+ opacity: 0;+ pointer-events: none;+ transition: opacity 0.25s ease, transform 0.25s ease;+ max-width: calc(100vw - 32px);+ text-align: center;+ }+ .toast.shown {+ opacity: 1;+ transform: translateX(-50%) translateY(0);+ }+ .sr-only {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0, 0, 0, 0);+ white-space: nowrap;+ border: 0;+ }+ </style>++ <script type="importmap">+ {+ "imports": {+ "three": "https://esm.sh/[email protected]",+ "three/addons/controls/OrbitControls.js": "https://esm.sh/[email protected]/examples/jsm/controls/OrbitControls.js?external=three",+ "three/addons/loaders/GLTFLoader.js": "https://esm.sh/[email protected]/examples/jsm/loaders/GLTFLoader.js?external=three",+ "three/addons/environments/RoomEnvironment.js": "https://esm.sh/[email protected]/examples/jsm/environments/RoomEnvironment.js?external=three",+ "three/addons/libs/meshopt_decoder.module.js": "https://esm.sh/[email protected]/examples/jsm/libs/meshopt_decoder.module.js"+ }+ }+ </script>+ </head>+ <body>+ <canvas id="stage" aria-label="3D model viewer"></canvas>++ <div id="loading" role="status" aria-live="polite">+ <div id="preview-bg"></div>+ <div class="shimmer"></div>+ <div class="card">+ <div class="thumb" id="thumb">+ <svg class="ring" viewBox="0 0 100 100" aria-hidden="true">+ <circle cx="50" cy="50" r="47" fill="none" stroke="rgba(255,255,255,.08)" stroke-width="3" />+ </svg>+ </div>+ <div class="status-row">+ <svg class="spinner" viewBox="0 0 50 50" aria-hidden="true"><circle cx="25" cy="25" r="20" /></svg>+ <span id="status-label">Starting generation…</span>+ </div>+ <div class="prompt" id="prompt-text"></div>+ <div class="bar"><i></i></div>+ <div class="sub" id="sub-line">Forging a real, textured 3D model</div>+ </div>+ </div>++ <header id="hud">+ <div class="hud-title" id="hud-title"></div>+ <div class="chips" id="hud-chips"></div>+ </header>++ <nav id="toolbar" aria-label="Model controls"></nav>++ <div id="state" role="alertdialog" aria-live="assertive">+ <div class="state-card">+ <div class="state-icon" id="state-icon">+ <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" />+ </svg>+ </div>+ <div class="state-title" id="state-title">Something went wrong</div>+ <div class="state-msg" id="state-msg"></div>+ <div class="state-actions" id="state-actions"></div>+ </div>+ </div>++ <div class="toast" id="toast" role="status" aria-live="polite"></div>++ <script type="module">+ import * as THREE from 'three';+ import { OrbitControls } from 'three/addons/controls/OrbitControls.js';+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+ import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';++ // ── Payload ──────────────────────────────────────────────+ // { job, glb, preview, prompt, eta, meta:{path,tier,backend}, error }+ let data = {};+ try {+ data = JSON.parse(decodeURIComponent(location.hash.slice(1))) || {};+ } catch {+ data = {};+ }+ const FORGE = '/api/forge';+ const el = (id) => document.getElementById(id);++ const ICONS = {+ download:+ '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/>',+ external:+ '<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/>',+ expand: '<polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/>',+ reset: '<polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/>',+ rotate: '<path d="M23 4v6h-6"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>',+ rig: '<circle cx="12" cy="5" r="2"/><path d="M12 7v6"/><path d="M9 21l3-8 3 8"/><path d="M6 11l6 2 6-2"/>',+ };+ function icon(name) {+ return (+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' ++ (ICONS[name] || '') ++ '</svg>'+ );+ }++ let toastTimer;+ function toast(msg) {+ const t = el('toast');+ t.textContent = msg;+ t.classList.add('shown');+ clearTimeout(toastTimer);+ toastTimer = setTimeout(() => t.classList.remove('shown'), 3200);+ }++ const promptText = String(data.prompt || '').trim();+ if (promptText) {+ el('prompt-text').textContent = '“' + promptText + '”';+ }+ if (data.preview) {+ const bg = el('preview-bg');+ bg.style.backgroundImage = 'url("' + data.preview + '")';+ el('thumb').style.backgroundImage = 'url("' + data.preview + '")';+ const img = new Image();+ img.onload = () => bg.classList.add('shown');+ img.src = data.preview;+ }++ // ── End-state renderer ───────────────────────────────────+ function showState({ title, msg, actions, danger = true }) {+ el('loading').classList.add('hidden');+ el('state-title').textContent = title;+ el('state-msg').textContent = msg;+ const iconWrap = el('state-icon');+ iconWrap.style.background = danger ? 'rgba(255,107,107,.14)' : 'rgba(24,224,200,.14)';+ iconWrap.style.color = danger ? 'var(--danger)' : 'var(--accent-2)';+ const wrap = el('state-actions');+ wrap.innerHTML = '';+ for (const a of actions) {+ if (a.href) {+ const link = document.createElement('a');+ link.className = 'btn' + (a.primary ? ' primary' : '');+ link.href = a.href;+ link.target = '_blank';+ link.rel = 'noopener';+ link.textContent = a.label;+ wrap.appendChild(link);+ } else {+ const b = document.createElement('button');+ b.className = 'btn' + (a.primary ? ' primary' : '');+ b.textContent = a.label;+ b.addEventListener('click', a.onClick);+ wrap.appendChild(b);+ }+ }+ el('state').classList.add('shown');+ }++ const forgeLink = promptText+ ? 'https://three.ws/forge?prompt=' + encodeURIComponent(promptText)+ : 'https://three.ws/forge';++ function fail(title, msg, { retry = true } = {}) {+ const actions = [{ label: 'Open in Forge ↗', href: forgeLink, primary: !retry }];+ if (retry && promptText) {+ actions.unshift({+ label: 'Try again',+ primary: true,+ onClick: () => {+ el('state').classList.remove('shown');+ el('loading').classList.remove('hidden');+ resubmit();+ },+ });+ }+ showState({ title, msg, actions });+ }++ // ── Progress labelling (no server %, drive from elapsed) ──+ const STAGES = [+ [0, 'Generating concept image'],+ [7, 'Reconstructing geometry'],+ [22, 'Texturing surface'],+ [40, 'Finalizing mesh'],+ ];+ const started = performance.now();+ let lastStatus = '';+ function tickLabel() {+ const secs = (performance.now() - started) / 1000;+ let label = STAGES[0][1];+ for (const [t, l] of STAGES) if (secs >= t) label = l;+ if (lastStatus === 'queued' && secs < 4) label = 'Queued';+ el('status-label').textContent = label;+ const mm = Math.floor(secs / 60);+ const ss = Math.floor(secs % 60);+ const etaTxt = data.eta ? ' · ~' + Math.round(data.eta) + 's typical' : '';+ el('sub-line').textContent = (mm ? mm + 'm ' : '') + ss + 's elapsed' + etaTxt;+ }+ const labelTimer = setInterval(tickLabel, 500);+ tickLabel();++ // ── Polling ──────────────────────────────────────────────+ const MAX_MS = 6 * 60 * 1000;+ async function pollUntilDone(jobId) {+ const deadline = performance.now() + MAX_MS;+ let delay = 2500;+ while (performance.now() < deadline) {+ await new Promise((r) => setTimeout(r, delay));+ let res, body;+ try {+ res = await fetch(FORGE + '?job=' + encodeURIComponent(jobId), { credentials: 'include' });+ body = await res.json().catch(() => ({}));+ } catch {+ continue; // transient network — keep trying+ }+ if (res.status === 429) {+ const ra = Number(res.headers.get('retry-after'));+ delay = Math.min(8000, (ra ? ra * 1000 : 0) || delay + 1000);+ continue;+ }+ delay = 2500;+ lastStatus = body.status || '';+ if (body.status === 'done' && body.glb_url) return body.glb_url;+ if (body.status === 'failed') {+ return fail(+ 'Generation failed',+ body.error || 'The model couldn’t be generated. Try a clearer single-subject prompt.'+ );+ }+ }+ fail(+ 'Still working…',+ 'This is taking longer than usual. Your model may still finish in Forge — open it there to check.',+ { retry: true }+ );+ return null;+ }++ async function resubmit() {+ try {+ const res = await fetch(FORGE, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ prompt: promptText }),+ });+ const body = await res.json().catch(() => ({}));+ if (!res.ok) return fail('Couldn’t start', body.message || body.error || 'Forge rejected the request.');+ if (body.glb_url) return loadModel(body.glb_url);+ if (body.job_id) {+ const url = await pollUntilDone(body.job_id);+ if (url) loadModel(url);+ return;+ }+ fail('No model returned', 'Forge didn’t return a model. Try again or open it in Forge.');+ } catch {+ fail('Connection lost', 'Could not reach the Forge service. Check your connection and retry.');+ }+ }++ // ── Three.js viewer ──────────────────────────────────────+ let renderer, scene, camera, controls, mixer, clock, current;+ let autoRotate = true;+ let frameInfo = null;+ let loadedGlbUrl = null;++ function initThree() {+ const canvas = el('stage');+ try {+ renderer = new THREE.WebGLRenderer({ canvas, antialias: true, preserveDrawingBuffer: false });+ } catch {+ return false;+ }+ renderer.setPixelRatio(Math.min(devicePixelRatio || 1, 2));+ renderer.setSize(innerWidth, innerHeight, false);+ renderer.outputColorSpace = THREE.SRGBColorSpace;+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.05;+ renderer.shadowMap.enabled = true;+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;++ scene = new THREE.Scene();+ scene.background = new THREE.Color(0x0a0c10);++ const pmrem = new THREE.PMREMGenerator(renderer);+ scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;++ camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.01, 2000);+ camera.position.set(0, 1.1, 3.2);++ controls = new OrbitControls(camera, renderer.domElement);+ controls.enableDamping = true;+ controls.dampingFactor = 0.07;+ controls.autoRotate = true;+ controls.autoRotateSpeed = 1.4;+ controls.addEventListener('start', () => {+ autoRotate = false;+ controls.autoRotate = false;+ syncRotateBtn();+ });++ const key = new THREE.DirectionalLight(0xffffff, 2.0);+ key.position.set(4, 7, 5);+ key.castShadow = true;+ key.shadow.mapSize.set(2048, 2048);+ key.shadow.bias = -0.0004;+ key.shadow.normalBias = 0.02;+ scene.add(key);+ scene.add(new THREE.HemisphereLight(0xbfd4ff, 0x10131a, 0.35));++ clock = new THREE.Clock();+ addEventListener('resize', onResize);+ renderer.setAnimationLoop(render);+ return true;+ }++ function onResize() {+ if (!renderer) return;+ renderer.setSize(innerWidth, innerHeight, false);+ camera.aspect = innerWidth / innerHeight;+ camera.updateProjectionMatrix();+ }++ function render() {+ const dt = clock.getDelta();+ if (mixer) mixer.update(dt);+ if (controls) controls.update();+ renderer.render(scene, camera);+ }++ async function fetchGlb(url) {+ // Same-origin/CORS-friendly fetch so we can show real load errors and+ // reuse the blob for a reliable download. Falls back to direct URL.+ const res = await fetch(url, { credentials: 'include' });+ if (!res.ok) throw new Error('Model fetch failed (' + res.status + ')');+ const blob = await res.blob();+ return URL.createObjectURL(blob);+ }++ function frameObject(obj) {+ const box = new THREE.Box3().setFromObject(obj);+ const size = box.getSize(new THREE.Vector3());+ const center = box.getCenter(new THREE.Vector3());+ const maxDim = Math.max(size.x, size.y, size.z) || 1;+ obj.position.sub(center);++ const fitDist = (maxDim / 2 / Math.tan((camera.fov * Math.PI) / 360)) * 1.5;+ camera.near = maxDim / 100;+ camera.far = maxDim * 100;+ camera.updateProjectionMatrix();+ controls.minDistance = maxDim * 0.4;+ controls.maxDistance = maxDim * 6;+ controls.target.set(0, 0, 0);+ frameInfo = { dist: fitDist, height: maxDim * 0.18, maxDim };+ resetView(true);++ // Contact-shadow ground at the model's feet.+ const groundY = -size.y / 2;+ const ground = new THREE.Mesh(+ new THREE.PlaneGeometry(maxDim * 12, maxDim * 12),+ new THREE.ShadowMaterial({ opacity: 0.28 })+ );+ ground.rotation.x = -Math.PI / 2;+ ground.position.y = groundY;+ ground.receiveShadow = true;+ scene.add(ground);+ }++ function resetView(instant) {+ if (!frameInfo) return;+ const { dist, height } = frameInfo;+ const target = new THREE.Vector3(dist * 0.0, height, dist);+ if (instant) {+ camera.position.copy(target);+ } else {+ const from = camera.position.clone();+ const t0 = performance.now();+ (function ease() {+ const k = Math.min(1, (performance.now() - t0) / 450);+ const e = 1 - Math.pow(1 - k, 3);+ camera.position.lerpVectors(from, target, e);+ if (k < 1) requestAnimationFrame(ease);+ })();+ }+ controls.target.set(0, 0, 0);+ }++ function fadeIn(obj) {+ const mats = [];+ obj.traverse((n) => {+ if (n.isMesh) {+ n.castShadow = true;+ n.receiveShadow = true;+ const list = Array.isArray(n.material) ? n.material : [n.material];+ for (const m of list) {+ if (!m) continue;+ m.userData._t = m.transparent;+ m.userData._o = m.opacity;+ m.transparent = true;+ m.opacity = 0;+ mats.push(m);+ }+ }+ });+ const t0 = performance.now();+ (function step() {+ const k = Math.min(1, (performance.now() - t0) / 600);+ for (const m of mats) m.opacity = (m.userData._o ?? 1) * k;+ if (k < 1) requestAnimationFrame(step);+ else+ for (const m of mats) {+ m.transparent = m.userData._t ?? false;+ m.opacity = m.userData._o ?? 1;+ m.needsUpdate = true;+ }+ })();+ }++ const gltfLoader = new GLTFLoader();+ try {+ const { MeshoptDecoder } = await import('three/addons/libs/meshopt_decoder.module.js');+ gltfLoader.setMeshoptDecoder(MeshoptDecoder);+ } catch {+ /* meshopt optional — vanilla GLBs load without it */+ }++ async function loadModel(url) {+ loadedGlbUrl = url;+ if (!renderer && !initThree()) {+ return showState({+ title: '3D not supported here',+ msg: 'Your browser/device can’t render WebGL. Download the model or open it in Forge.',+ danger: true,+ actions: [+ { label: 'Download GLB', href: url, primary: true },+ { label: 'Open in Forge ↗', href: forgeLink },+ ],+ });+ }+ let objectUrl = url;+ try {+ objectUrl = await fetchGlb(url);+ } catch {+ /* fall back to the raw url; GLTFLoader will retry it directly */+ }+ gltfLoader.load(+ objectUrl,+ (gltf) => {+ clearInterval(labelTimer);+ if (current) {+ scene.remove(current);+ }+ current = gltf.scene;+ scene.add(current);+ frameObject(current);+ fadeIn(current);+ if (gltf.animations && gltf.animations.length) {+ mixer = new THREE.AnimationMixer(current);+ mixer.clipAction(gltf.animations[0]).play();+ }+ revealViewer();+ },+ undefined,+ () => {+ fail(+ 'Couldn’t load the model',+ 'The generated file didn’t load. It may have expired — regenerate it, or open it in Forge.'+ );+ }+ );+ }++ function revealViewer() {+ el('loading').classList.add('hidden');+ el('state').classList.remove('shown');+ buildHud();+ buildToolbar();+ requestAnimationFrame(() => {+ el('hud').classList.add('shown');+ el('toolbar').classList.add('shown');+ });+ }++ function buildHud() {+ if (promptText) el('hud-title').textContent = promptText;+ else el('hud-title').style.display = 'none';+ const chips = el('hud-chips');+ chips.innerHTML = '';+ const m = data.meta || {};+ for (const v of [m.backend, m.tier, m.path]) {+ if (!v) continue;+ const c = document.createElement('span');+ c.className = 'chip';+ c.textContent = v;+ chips.appendChild(c);+ }+ }++ let rotateBtn;+ function syncRotateBtn() {+ if (rotateBtn) rotateBtn.setAttribute('aria-pressed', String(autoRotate));+ }++ function mkBtn({ name, label, labelSm, onClick, href, primary, pressed, aria }) {+ const tag = href ? 'a' : 'button';+ const b = document.createElement(tag);+ b.className = 'btn' + (primary ? ' primary' : '');+ b.innerHTML = icon(name) + '<span class="' + (labelSm ? 'label-sm' : '') + '">' + label + '</span>';+ b.setAttribute('aria-label', aria || label);+ if (pressed !== undefined) b.setAttribute('aria-pressed', String(pressed));+ if (href) {+ b.href = href;+ b.target = '_blank';+ b.rel = 'noopener';+ } else {+ b.addEventListener('click', onClick);+ }+ return b;+ }++ async function download() {+ try {+ const blobUrl = await fetchGlb(loadedGlbUrl);+ const a = document.createElement('a');+ a.href = blobUrl;+ a.download = (promptText ? promptText.slice(0, 40).replace(/[^a-z0-9]+/gi, '-') : 'forge-model') + '.glb';+ document.body.appendChild(a);+ a.click();+ a.remove();+ setTimeout(() => URL.revokeObjectURL(blobUrl), 4000);+ } catch {+ window.open(loadedGlbUrl, '_blank', 'noopener');+ }+ }++ function buildToolbar() {+ const bar = el('toolbar');+ bar.innerHTML = '';++ bar.appendChild(mkBtn({ name: 'download', label: 'Download', labelSm: true, onClick: download, aria: 'Download GLB' }));++ rotateBtn = mkBtn({+ name: 'rotate',+ label: 'Spin',+ labelSm: true,+ pressed: autoRotate,+ onClick: () => {+ autoRotate = !autoRotate;+ controls.autoRotate = autoRotate;+ syncRotateBtn();+ },+ });+ bar.appendChild(rotateBtn);++ bar.appendChild(+ mkBtn({+ name: 'reset',+ label: 'Recenter',+ labelSm: true,+ onClick: () => resetView(false),+ aria: 'Recenter camera',+ })+ );++ if (document.fullscreenEnabled) {+ bar.appendChild(+ mkBtn({+ name: 'expand',+ label: 'Fullscreen',+ labelSm: true,+ onClick: () => {+ if (document.fullscreenElement) document.exitFullscreen();+ else document.documentElement.requestFullscreen().catch(() => {});+ },+ })+ );+ }++ // Rig & animate — backend-supported but may be disabled on a+ // deployment; self-heals on the unconfigured response.+ const rigBtn = mkBtn({+ name: 'rig',+ label: 'Rig & Animate',+ labelSm: true,+ primary: true,+ onClick: () => rigAndAnimate(rigBtn),+ });+ bar.appendChild(rigBtn);++ bar.appendChild(mkBtn({ name: 'external', label: 'Forge', labelSm: true, href: forgeLink, aria: 'Open in Forge' }));+ }++ async function rigAndAnimate(btn) {+ if (!loadedGlbUrl) return;+ btn.setAttribute('disabled', '');+ const restore = btn.innerHTML;+ btn.innerHTML = icon('rig') + '<span class="label-sm">Rigging…</span>';+ try {+ const res = await fetch(FORGE + '?action=rig', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ glb_url: loadedGlbUrl }),+ });+ const body = await res.json().catch(() => ({}));+ if (res.status === 501 || body.error === 'rig_unconfigured') {+ btn.remove();+ toast('Auto-rigging isn’t enabled on this deployment.');+ return;+ }+ if (!res.ok || !body.job_id) {+ btn.innerHTML = restore;+ btn.removeAttribute('disabled');+ toast(body.message || 'Rigging is busy — try again shortly.');+ return;+ }+ toast('Rigging your model — this adds a skeleton + idle motion.');+ const rigged = await pollUntilDone(body.job_id);+ if (rigged) {+ el('loading').classList.remove('hidden');+ el('status-label').textContent = 'Loading rigged model';+ await loadModel(rigged);+ toast('Rigged & animated.');+ } else {+ btn.innerHTML = restore;+ btn.removeAttribute('disabled');+ }+ } catch {+ btn.innerHTML = restore;+ btn.removeAttribute('disabled');+ toast('Rigging failed — try again.');+ }+ }++ // ── Boot ─────────────────────────────────────────────────+ (function boot() {+ if (data.error) {+ clearInterval(labelTimer);+ return fail('Couldn’t generate', String(data.error));+ }+ if (data.glb) return loadModel(data.glb);+ if (data.job) {+ (async () => {+ const url = await pollUntilDone(data.job);+ if (url) loadModel(url);+ })();+ return;+ }+ clearInterval(labelTimer);+ fail('Nothing to show', 'No model or job was provided. Try generating again.');+ })();+ </script>+ </body>+</html>diff --git a/chat/src/tools.js b/chat/src/tools.jsindex 86b4ed2c0..7ed9a24f2 100644--- a/chat/src/tools.js+++ b/chat/src/tools.js@@ -1126,7 +1126,7 @@ return { mint, signature, metadataUri, explorer: 'https://solscan.io/tx/' + signid: 'forge-text-to-3d',name: 'Text → 3D Forge',description:- 'Generate a real, textured 3D model from a text prompt with the three.ws Forge and render it in an orbit viewer — same engine as three.ws/forge, free, no key required.',+ 'Generate a real, textured 3D model from a text prompt with the three.ws Forge — live progress, a PBR orbit viewer with environment lighting and contact shadows, GLB download, and one-click rig & animate. Same engine as three.ws/forge, free, no key required.',schema: [{clientDefinition: {@@ -1137,66 +1137,46 @@ return { mint, signature, metadataUri, explorer: 'https://solscan.io/tx/' + sign{ name: 'prompt', type: 'string', description: 'Single-subject object description, e.g. "a brass steampunk owl, full body". 3–1000 chars.' },],body: `const prompt = String(args.prompt || '').trim();- if (prompt.length < 3) throw new Error('prompt required (3–1000 chars)');- const submit = await fetch('/api/forge', { method: 'POST', headers: {'content-type':'application/json'}, credentials: 'include', body: JSON.stringify({ prompt }) });- if (!submit.ok) throw new Error('Forge submit failed: ' + submit.status + ' ' + await submit.text());- const job = await submit.json();- if (!job.job_id) throw new Error('Forge returned no job id');- let state = null;- for (let i = 0; i < 75; i++) {- await new Promise((r) => setTimeout(r, 2500));- const poll = await fetch('/api/forge?job=' + encodeURIComponent(job.job_id), { credentials: 'include' });- if (!poll.ok) throw new Error('Forge poll failed: ' + poll.status);- state = await poll.json();- if (state.status === 'done' || state.status === 'failed') break;+ // Submit on the host page (same-origin, cookies) then hand off to the hosted+ // /chat/forge-viewer.html which streams real progress and renders the model.+ // Returning immediately keeps the chat responsive instead of blocking the+ // tool for the full ~30-90s generation behind a bare spinner.+ let payload;+ if (prompt.length < 3) {+ payload = { error: 'Describe one subject in at least 3 characters, e.g. "a brass steampunk owl, full body".', prompt };+ } else if (prompt.length > 1000) {+ payload = { error: 'Keep the prompt under 1000 characters — one clear subject works best.', prompt };+ } else {+ try {+ const res = await fetch('/api/forge', { method: 'POST', headers: {'content-type':'application/json'}, credentials: 'include', body: JSON.stringify({ prompt }) });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) {+ payload = { error: String(data.message || data.error || ('Forge request failed (' + res.status + ')')), prompt };+ } else if (data.glb_url || data.job_id) {+ payload = {+ job: data.job_id || null,+ glb: data.glb_url || null,+ preview: data.preview_image_url || null,+ prompt,+ eta: typeof data.eta_seconds === 'number' ? data.eta_seconds : null,+ meta: { path: data.path || null, tier: data.tier || null, backend: data.backend || null },+ };+ } else {+ payload = { error: 'Forge did not return a model or job. Try again, or open three.ws/forge.', prompt };+ }+ } catch (err) {+ payload = { error: 'Could not reach the Forge service. Check your connection and try again.', prompt };+ }}- if (!state || state.status === 'failed') throw new Error('Generation failed: ' + ((state && state.error) || 'unknown error'));- if (state.status !== 'done') throw new Error('Generation timed out after ~3 minutes — try again or open three.ws/forge');- const glb = state.glb_url;- if (!glb) throw new Error('Job finished without a model URL');- const html = \`<!DOCTYPE html><html><head><meta charset="utf-8"><style>- html,body{margin:0;height:100%;background:#0b0d10;color:#e5e7eb;font-family:ui-sans-serif,system-ui,sans-serif;overflow:hidden}- #hud{position:absolute;left:12px;top:10px;font-size:13px;background:rgba(0,0,0,.4);padding:6px 10px;border-radius:8px;max-width:70%}- #bar{position:absolute;left:12px;bottom:10px;display:flex;gap:8px;font-size:12px}- #bar a{color:#e5e7eb;background:rgba(0,0,0,.4);padding:6px 10px;border-radius:8px;text-decoration:none;border:1px solid rgba(255,255,255,.15)}- #bar a:hover{background:rgba(255,255,255,.12)}- </style></head><body>- <div id="hud">\${prompt.replace(/</g,'<')}</div>- <div id="bar">- <a href="\${glb}" download="forge-model.glb">Download GLB</a>- <a href="https://three.ws/forge?prompt=\${encodeURIComponent(prompt)}" target="_blank" rel="noopener">Open in Forge ↗</a>- </div>- <script type="module">- import * as THREE from 'https://esm.sh/[email protected]';- import { OrbitControls } from 'https://esm.sh/[email protected]/examples/jsm/controls/OrbitControls.js';- import { GLTFLoader } from 'https://esm.sh/[email protected]/examples/jsm/loaders/GLTFLoader.js';- const renderer = new THREE.WebGLRenderer({ antialias: true });- renderer.setPixelRatio(devicePixelRatio); renderer.setSize(innerWidth, innerHeight); renderer.setClearColor(0x0b0d10);- document.body.appendChild(renderer.domElement);- const scene = new THREE.Scene();- const cam = new THREE.PerspectiveCamera(45, innerWidth/innerHeight, 0.01, 1000); cam.position.set(0, 1.2, 3);- const ctl = new OrbitControls(cam, renderer.domElement); ctl.enableDamping = true; ctl.autoRotate = true; ctl.autoRotateSpeed = 1.6;- addEventListener('resize', () => { renderer.setSize(innerWidth, innerHeight); cam.aspect = innerWidth/innerHeight; cam.updateProjectionMatrix(); });- addEventListener('pointerdown', () => { ctl.autoRotate = false; }, { once: true });- scene.add(new THREE.AmbientLight(0xffffff, 0.7));- const k = new THREE.DirectionalLight(0xffffff, 1.1); k.position.set(3, 4, 5); scene.add(k);- const gltf = await new GLTFLoader().loadAsync(\${JSON.stringify(glb)});- const m = gltf.scene;- const box = new THREE.Box3().setFromObject(m);- const size = box.getSize(new THREE.Vector3()).length();- const center = box.getCenter(new THREE.Vector3());- m.position.sub(center); cam.position.set(0, size * 0.25, size * 1.4); ctl.target.set(0,0,0);- scene.add(m);- function tick(){ ctl.update(); renderer.render(scene, cam); requestAnimationFrame(tick); }- tick();- </script></body></html>\`;- return { contentType: 'text/html', content: html };`,+ const src = '/chat/forge-viewer.html#' + encodeURIComponent(JSON.stringify(payload));+ const html = '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style>html,body{margin:0;height:100%;background:#0a0c10;overflow:hidden}iframe{border:0;display:block;width:100%;height:100%}</style></head><body><iframe src="' + src + '" allow="fullscreen" allowfullscreen referrerpolicy="no-referrer-when-downgrade"></iframe></body></html>';+ return { contentType: 'text/html', content: html, status: payload.error ? 'error' : 'started', prompt };`,},type: 'function',function: {name: 'ForgeTextTo3D',description:- 'Generate a real 3D model (textured GLB) from a text prompt using the three.ws Forge, then render it in an interactive orbit viewer. Use whenever the user asks to make, create, generate, or forge a 3D model/object/mesh from a description. Takes ~30–90 s. The prompt should describe ONE subject with material and style details.',+ 'Generate a real 3D model (textured GLB) from a text prompt using the three.ws Forge, then render it inline with live progress and an interactive PBR orbit viewer (download, recenter, fullscreen, rig & animate). Use whenever the user asks to make, create, generate, or forge a 3D model/object/mesh from a description. Returns immediately and streams progress in-place; the model appears in ~30–90 s. The prompt should describe ONE subject with material and style details.',parameters: {type: 'object',properties: {diff --git a/data/changelog.json b/data/changelog.jsonindex dcf749781..3958b9393 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws \u2014 the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-17",+ "title": "Free text-to-3D over MCP — no payment, no key",+ "summary": "The three.ws MCP server now ships a free tool: forge_free turns a text prompt into a textured, downloadable 3D model with zero cost — no x402 payment, no wallet, no API key. It runs on the same free NVIDIA NIM (Microsoft TRELLIS) engine the /forge web page uses for drafts, and hands back a durable GLB plus a viewer link that renders the model in the browser. Drop your Claude/Cursor agent on it, type a prompt, get a 3D avatar. The paid tools (mesh_forge, text_to_avatar, rig_mesh) remain for image input, the Granite-directed model chain, and auto-rigging.",+ "tags": [+ "sdk",+ "feature"+ ]+ },{"date": "2026-06-17","title": "Generate a rigged 3D avatar from a text prompt in chat",diff --git a/mcp-server/README.md b/mcp-server/README.mdindex 1ad6a7485..e9d377dd4 100644--- a/mcp-server/README.md+++ b/mcp-server/README.md@@ -4,7 +4,7 @@<h1 align="center">@three-ws/mcp-server</h1>-<p align="center"><strong>Paid x402 MCP tools from three.ws — text/image→3D, avatars, rigging, agent reputation, and more. Settled per call in USDC.</strong></p>+<p align="center"><strong>MCP tools from three.ws — free text→3D plus paid text/image→3D, avatars, rigging, agent reputation, and more. Paid calls settled per call in USDC.</strong></p><p align="center"><a href="https://www.npmjs.com/package/@three-ws/mcp-server"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/mcp-server?logo=npm&color=cb3837"></a>@@ -26,7 +26,7 @@----> Fifteen paid MCP tools from [three.ws](https://three.ws) — text/image→3D mesh generation, 3D avatars, GLB auto-rigging, pose seeds, pump.fun snapshots, ERC-8004 agent reputation, ENS/SNS resolution, agent-to-agent delegation, token sentiment, AgenC coordination reads, aixbt market intel, and a Solana vanity grinder. Each call is settled in USDC via the [x402](https://x402.org) payment protocol on Solana mainnet (`exact` scheme). No subscription, no API key — pay per call, and failed calls never bill the caller.+> Sixteen MCP tools from [three.ws](https://three.ws) — **one free** (`forge_free`: text prompt → 3D GLB on the free NVIDIA NIM / Microsoft TRELLIS lane, no payment and no API key) and fifteen paid: text/image→3D mesh generation, 3D avatars, GLB auto-rigging, pose seeds, pump.fun snapshots, ERC-8004 agent reputation, ENS/SNS resolution, agent-to-agent delegation, token sentiment, AgenC coordination reads, aixbt market intel, and a Solana vanity grinder. Paid calls are settled in USDC via the [x402](https://x402.org) payment protocol on Solana mainnet (`exact` scheme). No subscription, no API key — pay per call, and failed calls never bill the caller.---@@ -64,12 +64,13 @@ Restart Claude Desktop. All tools appear immediately — no install step require## Tools-Every tool quotes a fixed USDC price and settles `exact` on Solana mainnet. Prices below come straight from each tool's source. Every tool also declares MCP tool annotations (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`) so clients can scope confirmation prompts correctly — none of these tools are destructive.+Most tools quote a fixed USDC price and settle `exact` on Solana mainnet (prices below come straight from each tool's source); **`forge_free` is free** — no payment, no wallet, no API key. Every tool also declares MCP tool annotations (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`) so clients can scope confirmation prompts correctly — none of these tools are destructive.### 3D generation| Tool | Price | What it returns |-| ---------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| ---------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `forge_free` | **Free** | Textured 3D GLB from a **text prompt — at zero cost**. Drives the three.ws `/api/forge` pipeline on the free NVIDIA NIM (Microsoft TRELLIS) text→3D lane — the same engine the [`/forge`](https://three.ws/forge) web page uses for prompt drafts. No x402 payment, no wallet, no API key. Pick tier `draft` (fast, default), `standard`, or `high` — all free. Returns the durable `glbUrl`, a three.ws viewer `preview` link, the `tier`, and the `backend` that actually ran. Text-only; for image/multi-view input or the Granite-directed chain use `mesh_forge`. Feed the `glbUrl` to `rig_mesh` to animate it. || `mesh_forge` | $0.25 | Textured 3D GLB from a **text prompt or a reference image**. Text mode runs a chain of specialist models — an IBM Granite "prompt director" rewrites the prompt into an optimized single-subject 3D spec, FLUX renders a reference image, and Microsoft TRELLIS / Tencent Hunyuan3D reconstruct the mesh. Image mode (`image_url`) reconstructs directly. Returns the durable `glbUrl`, a three.ws viewer `preview`, the `directedPrompt`, and timing. || `rig_mesh` | $0.20 | Auto-rig a static GLB into an animation-ready model — humanoid skeleton + per-vertex skin weights via VAST-AI UniRig. Takes a `glb_url` (e.g. `mesh_forge`'s output), returns the `riggedGlbUrl` and a three.ws pose-studio link. || `text_to_avatar` | $0.15 | Textured 3D GLB avatar from a text prompt or reference image URLs, driving Replicate (Hunyuan-3D 3.1 by default). Returns the GLB URL, model version, prediction id, and timing. |@@ -133,6 +134,9 @@ Then replace `"command": "npx", "args": ["-y", "@three-ws/mcp-server"]` with `"c| `X402_FACILITATOR_TOKEN_SOLANA` | unset | Bearer token for the Solana facilitator, if required || `X402_FEE_PAYER_SOLANA` | three.ws default | Fee payer for the settlement transaction || `MCP_VANITY_PRICE_USD` | `$0.05` | Flat price for `vanity_grinder` |+| `FORGE_FREE_API_BASE` | `https://three.ws` | three.ws origin the free `forge_free` tool calls (`/api/forge`) |+| `FORGE_FREE_TIMEOUT_MS` | `180000` | `forge_free` poll budget before it returns a resumable `timeout` |+| `FORGE_FREE_POLL_MS` | `3000` | `forge_free` poll interval while a queued job runs || `MCP_POSE_PREVIEW_BASE` | `https://three.ws/pose` | Base URL for `get_pose_seed` preview links || `MCP_AGENT_REP_RPC_<chainId>` | public RPC | Per-chain RPC override for `agent_reputation` (tried before the failover set) || `MCP_AGENT_REP_LOG_WINDOW` | `200000` | Block window for `agent_reputation` event scan |@@ -188,6 +192,15 @@ const result = await paid.callTool('get_pose_seed', { prompt: 'warrior stance' }console.log(result.structuredContent ?? JSON.parse(result.content[0].text));```+`forge_free` needs no payer — it never emits a 402 — so you can call it on the **bare** MCP client (the one before `wrapMCPClientWithPayment`):++```js+// Free text → 3D — no wallet, no payment, no API key.+const free = await mcp.callTool('forge_free', { prompt: 'a glossy white robot mascot', tier: 'draft' });+const out = free.structuredContent ?? JSON.parse(free.content[0].text);+console.log(out.glbUrl, out.preview); // durable GLB + in-browser viewer link+```+---## Cursordiff --git a/mcp-server/server.json b/mcp-server/server.jsonindex f475825d1..6586a9137 100644--- a/mcp-server/server.json+++ b/mcp-server/server.json@@ -2,7 +2,7 @@"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name": "io.github.nirholas/3d-agent-mcp","title": "three.ws 3D Agent Tools",- "description": "Paid x402 MCP tools from three.ws: text-to-3D generation, rigging, agent reputation, market intel.",+ "description": "MCP tools from three.ws: free + paid text-to-3D, rigging, agent reputation, market intel.","websiteUrl": "https://three.ws","icons": [{@@ -18,12 +18,12 @@"source": "github","subfolder": "mcp-server"},- "version": "1.1.0",+ "version": "1.2.0","packages": [{"registryType": "npm","identifier": "@three-ws/mcp-server",- "version": "1.1.0",+ "version": "1.2.0","runtimeHint": "npx","transport": {"type": "stdio"diff --git a/pages/ibm/HOSTING.md b/pages/ibm/HOSTING.mdindex 44170bc3e..66124d469 100644--- a/pages/ibm/HOSTING.md+++ b/pages/ibm/HOSTING.md@@ -13,35 +13,37 @@ host it.The page is a **live showcase of the IBM × three.ws partnership** — five real, unmocked demospresented in sequence, each running against production three.ws systems. The hero frames the-partnership and the lineup; everything below is interactive.+partnership and the lineup; everything below is interactive. The lineup leads with **Forge**+(Demo 01) because it needs no wallet — anyone can try it instantly — then moves to the x402+payment demo (Demo 02), the 3D agent (Demo 03), Play (Demo 04), and IRL (Demo 05).-**Demo 01 · x402 payments.** x402 reactivates the dormant HTTP `402 Payment Required` status as+**Demo 02 · x402 payments.** x402 reactivates the dormant HTTP `402 Payment Required` status asa payment rail. A normal request to a paid endpoint returns `402` with machine-readable terms(amount, asset, network, recipient). The visitor's wallet signs a gasless stablecoinauthorization, the request is retried with an `X-PAYMENT` header, and the call settles on-chainin about a second — no API key, no account, no invoice. The page shows the live `402`challenge, runs a real paid call, and renders the response plus the on-chain receipt.-## The 3D agent layer (Demos 02–05)+## The 3D + agent layer (Demos 01, 03–05)-Below the payment demo the page embeds four more live three.ws surfaces, all loaded at runtime+Beyond the payment demo the page embeds four more live three.ws surfaces, all loaded at runtimefrom `https://three.ws` (still no build step, still no backend):-- **Demo 02 · A 3D AI agent** — the `<agent-3d>` web component renders a WebGL avatar that runs+- **Demo 01 · Forge, and Demos 04–05 · Play / IRL** — each is its own full-size section+ (Creation, Worlds, Reality) with an explanation and the real `three.ws/forge`,+ `three.ws/play`, and `three.ws/irl` surface embedded full-width in an `<iframe>`. They+ lazy-load as each section nears the viewport (so the heavy apps never load at once), and each+ has a one-tap **Full screen** button plus a **new-tab** fallback. IRL is AR, so it's best on a+ phone and only prompts for the camera when the visitor chooses to enable it.+- **Demo 03 · A 3D AI agent** — the `<agent-3d>` web component renders a WebGL avatar that runsits own brain in the browser and **reacts to the payment**: it celebrates and announces thesettlement the moment the visitor's `402` call clears. It lazy-boots only when scrolled intoview, and degrades to a calm skeleton if its script is blocked.-- **Demos 03–05 · Forge / Play / IRL** — each is its own full-size section (Creation, Worlds,- Reality) with an explanation and the real `three.ws/forge`, `three.ws/play`, and- `three.ws/irl` surface embedded full-width in an `<iframe>`. They lazy-load as each section- nears the viewport (so three heavy apps never load at once), and each has a one-tap- **Full screen** button plus a **new-tab** fallback. IRL is AR, so it's best on a phone and- only prompts for the camera when the visitor chooses to enable it.Because these load the agent runtime, an avatar GLB, the agent's model endpoint, and framedthree.ws pages, the **Tier 2** CSP below adds `https://three.ws` to `frame-src`/`img-src` and-`blob:` to `worker-src`. If you only want Demo 01 (the payment demo) and not the agent layer,-delete the `#agent`, `#forge`, `#play`, and `#irl` `<section>`s plus the `agent-3d.js`+`blob:` to `worker-src`. If you only want the x402 payment demo and not the 3D/agent layer,+delete the `#forge`, `#agent`, `#play`, and `#irl` `<section>`s plus the `agent-3d.js``<script>` tag, and the**Tier 1** policy is all you need.diff --git a/pages/ibm/x402-demo.html b/pages/ibm/x402-demo.htmlindex 40c03bf2e..43d5e5123 100644--- a/pages/ibm/x402-demo.html+++ b/pages/ibm/x402-demo.html@@ -243,6 +243,35 @@ a:focus-visible{outline-offset:3px}.note p{font-size:13px;color:var(--ibm-muted);line-height:1.6;font-weight:300}.note p b{color:var(--ibm-ink);font-weight:600}+/* ── Forge demo (Demo 03): tier selector, model viewer, result actions ── */+.tier-row{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:18px}+.tier{flex:1 1 150px;min-width:0;text-align:left;background:var(--ibm-field);border:1px solid var(--ibm-divider);border-bottom:2px solid var(--ibm-divider);padding:12px 14px;cursor:pointer;font-family:var(--font-sans);color:var(--ibm-ink);transition:border-color .12s,background .12s,transform .04s;border-radius:2px}+.tier:hover{border-color:var(--ibm-blue);background:var(--ibm-field-focus)}+.tier:active{transform:translateY(1px)}+.tier:focus-visible{outline:2px solid var(--ibm-blue);outline-offset:2px}+.tier[aria-checked="true"]{border-color:var(--ibm-blue);border-bottom-color:var(--ibm-blue);background:var(--ibm-field-focus)}+.tier .t-name{display:flex;align-items:baseline;justify-content:space-between;gap:8px}+.tier .t-tier{font-size:14px;font-weight:600;text-transform:capitalize}+.tier .t-price{font-family:var(--font-mono);font-size:13px;color:var(--ibm-blue);font-variant-numeric:tabular-nums}+.tier .t-blurb{font-size:11px;color:var(--ibm-muted);margin-top:4px;line-height:1.45;font-weight:300}+.tier .t-eta{font-size:11px;color:var(--ibm-subtle);margin-top:6px;font-family:var(--font-mono)}++.mv-wrap{margin:12px 0 6px;border:1px solid var(--ibm-border);background:var(--ibm-field);position:relative;border-radius:2px;overflow:hidden}+.mv-wrap model-viewer{display:block;width:100%;height:min(56vh,440px);background:radial-gradient(circle at 50% 30%,#1c2530,#0c1116 70%)}+.mv-wrap .mv-progress{position:absolute;left:0;bottom:0;height:2px;background:var(--ibm-blue);width:0;transition:width .2s linear}++.r-actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:14px}+.r-btn{display:inline-flex;align-items:center;gap:7px;background:var(--ibm-blue-fill);color:#fff;border:none;cursor:pointer;font-family:var(--font-sans);font-size:13px;font-weight:500;padding:10px 16px;border-radius:2px;text-decoration:none;transition:background .12s,transform .04s}+.r-btn:hover{background:var(--ibm-blue-fill-hover)}+.r-btn:active{transform:translateY(1px)}+.r-btn.ghost{background:none;border:1px solid var(--ibm-divider);color:var(--ibm-ink)}+.r-btn.ghost:hover{border-color:var(--ibm-blue);color:var(--ibm-blue)}+.r-btn:focus-visible{outline:2px solid var(--ibm-blue);outline-offset:2px}++.forge-foot{font-size:13px;color:var(--ibm-muted);margin-top:18px;font-weight:300}+.forge-foot a{font-weight:500}+@media(pointer:coarse){.tier,.r-btn{min-height:44px}}+/* embed snippet */.embed-block{background:#161616;color:#e0e0e0;border:1px solid #393939;padding:18px 20px;overflow:auto;margin-top:24px;font-family:var(--font-mono);font-size:13px;line-height:1.6;white-space:pre}.embed-block .c-tag{color:#82cfff}@@ -368,10 +397,12 @@ agent-3d:defined ~ .agent-skel{display:none}<meta name="twitter:description" content="A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership."><meta name="twitter:image" content="https://three.ws/og-image.png"><script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"x402 Live Demo (IBM × three.ws)","description":"A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.","url":"https://three.ws/ibm/x402-demo","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>+ <!-- model-viewer renders the GLB returned by the paid Forge demo (Demo 03) -->+ <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script></head><body>-<a href="#demo" class="skip-link">Skip to the demo</a>+<a href="#forge" class="skip-link">Skip to the demos</a><div class="err-banner" id="errBanner" role="alert"><span id="errBannerText">Something went wrong.</span>@@ -391,11 +422,11 @@ agent-3d:defined ~ .agent-skel{display:none}</div><h1>A live showcase of agentic commerce, built with <strong>IBM</strong></h1><p class="hero-sub">IBM has shaped computing for over a century — and it stays at the frontier by backing what comes next. three.ws is one of those bets: a platform for on-chain micropayments and embodied AI agents. As an IBM Business Partner, we built this page to demonstrate that partnership in the open — every demo below runs against real, production three.ws systems. Nothing is mocked, nothing is a slide.</p>- <p class="hero-sub" style="margin-top:14px">Five things we want to show you: pay-per-call micropayments over <span class="mono">x402</span>, an autonomous 3D agent that buys its own data, text turned into a 3D model, a shared 3D world, and an agent placed in augmented reality. Try each one yourself.</p>+ <p class="hero-sub" style="margin-top:14px">Five things we want to show you: pay a few cents to turn text into a 3D model, pay-per-call micropayments over <span class="mono">x402</span>, an autonomous 3D agent that buys its own data, a shared 3D world, and an agent placed in augmented reality. Try each one yourself — both demos settle real USDC from your own wallet.</p><nav class="demo-nav" aria-label="The demos on this page">- <a href="#demo"><span class="n">01</span>x402 payments</a>- <a href="#agent"><span class="n">02</span>3D agent</a>- <a href="#forge"><span class="n">03</span>Forge</a>+ <a href="#forge"><span class="n">01</span>Forge</a>+ <a href="#demo"><span class="n">02</span>x402 payments</a>+ <a href="#agent"><span class="n">03</span>3D agent</a><a href="#play"><span class="n">04</span>Play</a><a href="#irl"><span class="n">05</span>IRL</a></nav>@@ -403,6 +434,85 @@ agent-3d:defined ~ .agent-skel{display:none}</header><main>+<!-- ══ DEMO 01 · FORGE (paid x402 prompt→3D) ══ -->+<section class="section" id="forge" aria-labelledby="forge-h">+ <div class="inner">+ <div class="section-tag">Demo 01 · Creation</div>+ <h2 id="forge-h">Forge a <strong>3D model</strong> from a sentence</h2>+ <p class="section-lead">This pays the same x402 rail as the demo below — one USDC micropayment runs a real text→3D pipeline (FLUX→TRELLIS) and hands back a textured GLB you can orbit and download. The price below is read live from the server's own 402 response.</p>++ <div class="demo">+ <div class="demo-head">+ <div>+ <h3 class="demo-title">three<span>.ws</span> Forge</h3>+ <div class="demo-desc">Describe one object; pay; get back a textured, downloadable 3D model. Runs FLUX→TRELLIS (text→image→mesh) — the same pipeline that builds the bodies our agents wear.</div>+ </div>+ <div class="price-tag">+ <div class="amt" id="fgPriceAmt" aria-hidden="true">$<strong>0.05</strong></div>+ <div class="net" aria-hidden="true">USDC · per model</div>+ <span class="sr-only" id="fgPriceSr">Price: five cents in USDC per generation.</span>+ </div>+ </div>++ <div class="demo-body">+ <!-- live 402 preview -->+ <div class="preview" id="fgPreview" role="region" aria-label="Live HTTP 402 payment challenge" aria-live="polite" aria-busy="true">+ <div class="preview-label" id="fgPvLabel"><span class="dot" aria-hidden="true"></span><span id="fgPvLabelText">Reading the server's 402 challenge…</span></div>+ <div id="fgPvRows">+ <div class="preview-row"><span class="sk" style="width:38%"></span></div>+ <div class="preview-row"><span class="sk" style="width:54%"></span></div>+ <div class="preview-row"><span class="sk" style="width:46%"></span></div>+ </div>+ </div>++ <!-- quality tier -->+ <div class="tier-row" id="fgTiers" role="radiogroup" aria-label="Generation quality tier">+ <button class="tier" type="button" role="radio" aria-checked="true" data-tier="draft">+ <span class="t-name"><span class="t-tier">Draft</span><span class="t-price" data-price>$0.05</span></span>+ <span class="t-blurb">Fast preview geometry. Best to try the flow.</span>+ <span class="t-eta" data-eta>~40s</span>+ </button>+ <button class="tier" type="button" role="radio" aria-checked="false" data-tier="standard">+ <span class="t-name"><span class="t-tier">Standard</span><span class="t-price" data-price>$0.15</span></span>+ <span class="t-blurb">Balanced detail. The default for most assets.</span>+ <span class="t-eta" data-eta>~60s</span>+ </button>+ <button class="tier" type="button" role="radio" aria-checked="false" data-tier="high">+ <span class="t-name"><span class="t-tier">High</span><span class="t-price" data-price>$0.50</span></span>+ <span class="t-blurb">Maximum geometry + PBR textures. Slower.</span>+ <span class="t-eta" data-eta>~130s</span>+ </button>+ </div>++ <!-- input -->+ <div class="field-row">+ <div class="field-wrap">+ <label for="fgPrompt">Describe the object</label>+ <input id="fgPrompt" class="field" value="a brass steampunk owl, full body" maxlength="1000" autocomplete="off" spellcheck="true" inputmode="text" aria-describedby="fgPromptHint">+ <div class="field-hint" id="fgPromptHint">One subject works best — describe it in a sentence.</div>+ </div>+ <button id="fgBtn" class="btn" type="button"><span class="spin" aria-hidden="true"></span><span class="label">Pay $0.05 & forge</span> <span class="arrow" aria-hidden="true">→</span></button>+ </div>+ <div class="wallet-hint" id="fgWalletHint">On a phone? Open this page inside your <b>MetaMask</b> or <b>Phantom</b> in-app browser to pay.</div>++ <!-- result. Not a live region (its success state holds a raw-JSON block);+ concise spoken updates go to #fgAnnouncer instead. -->+ <div id="fgResult" class="result is-empty">+ Forge a model to see it appear here — orbit it, then download the GLB.+ </div>+ <p id="fgAnnouncer" class="sr-only" role="status" aria-live="polite"></p>++ <!-- requirements -->+ <div class="note">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>+ <p>You'll need a browser wallet — <b>MetaMask</b> or <b>Phantom</b> (for Solana) — holding the model's price in <b>USDC</b> on mainnet. Payment is a gasless signature; the network fee is sponsored by the facilitator. Generation runs after the payment verifies and takes roughly a minute. No wallet? Use the <a href="https://three.ws/forge" target="_blank" rel="noopener">free Forge tool</a> instead.</p>+ </div>+ </div>+ </div>+ <p class="forge-foot">Want image→3D, auto-rigging, AR preview and the full gallery? <a href="https://three.ws/forge" target="_blank" rel="noopener">Open the full Forge tool ↗</a></p>+ </div>+</section>+<!-- ══ HOW IT WORKS ══ --><section class="section" aria-labelledby="how-h"><div class="inner">@@ -431,7 +541,7 @@ agent-3d:defined ~ .agent-skel{display:none}<!-- ══ LIVE DEMO ══ --><section class="section" id="demo" aria-labelledby="demo-h"><div class="inner">- <div class="section-tag">Demo 01 · Payments</div>+ <div class="section-tag">Demo 02 · Payments</div><h2 id="demo-h">Buy a <strong>data call</strong> for $0.001</h2><p class="section-lead">This calls a real three.ws API — a token-symbol availability check — for one tenth of a cent in USDC, settled on Solana mainnet. The price below is read live from the server's own 402 response.</p>@@ -491,7 +601,7 @@ agent-3d:defined ~ .agent-skel{display:none}<!-- ══ THE AGENT ══ --><section class="section" id="agent" aria-labelledby="agent-h"><div class="inner">- <div class="section-tag">Demo 02 · Embodiment</div>+ <div class="section-tag">Demo 03 · Embodiment</div><h2 id="agent-h">An <strong>agent</strong> that pays for its own data</h2><p class="section-lead">Everything you just did by hand — read the price, sign, settle — an autonomous agent can do on its own. This is one of them: a 3D agent from three.ws, running its own brain in your browser. It watches the call above and reacts the moment your payment settles. Ask it how x402 works.</p>@@ -530,28 +640,6 @@ agent-3d:defined ~ .agent-skel{display:none}</div></section>-<!-- ══ DEMO 03 · FORGE ══ -->-<section class="section" id="forge" aria-labelledby="forge-h">- <div class="inner">- <div class="section-tag">Demo 03 · Creation</div>- <h2 id="forge-h">Forge — describe it, get a <strong>3D model</strong></h2>- <p class="section-lead">Type a sentence and Forge runs a real generation pipeline that returns a textured, downloadable GLB — one you can orbit, rig, inspect in AR, and drop onto any agent. The bodies our agents wear start here. The live tool is below; describe something and watch it build.</p>- <div class="live-embed" data-src="https://three.ws/forge" data-allow="clipboard-write; xr-spatial-tracking; fullscreen; accelerometer; gyroscope" data-label="Forge — three.ws">- <div class="embed-bar">- <span class="bar-url"><span class="dot" aria-hidden="true"></span>three.ws/forge</span>- <span class="bar-actions">- <button type="button" data-fs>⤢ Full screen</button>- <a href="https://three.ws/forge" target="_blank" rel="noopener">New tab ↗</a>- </span>- </div>- <div class="embed-frame">- <div class="embed-load embed-state"><span class="spin" aria-hidden="true"></span><span>Loading the live Forge tool…</span></div>- <div class="embed-err embed-state">Forge couldn't load inline here. <span class="es-hint"><a href="https://three.ws/forge" target="_blank" rel="noopener">Open it in a new tab ↗</a></span></div>- </div>- </div>- </div>-</section>-<!-- ══ DEMO 04 · PLAY ══ --><section class="section" id="play" aria-labelledby="play-h"><div class="inner">@@ -1099,5 +1187,332 @@ agent-3d:defined ~ .agent-skel{display:none}loadChallengePreview();})();</script>++<!-- Demo 01 · Forge — paid x402 prompt→3D. Pays POST /api/x402/forge, then polls+ the free GET /api/forge?job=<id> for the finished GLB and orbits it inline. -->+<script type="module">+(function () {+ 'use strict';++ var FORGE_ENDPOINT = 'https://three.ws/api/x402/forge';+ var POLL_ENDPOINT = 'https://three.ws/api/forge';+ // Per-tier atomic USDC prices (6 decimals) — refreshed live from the 402+ // challenge, but seeded so the UI is correct before the first fetch resolves.+ var TIER_ATOMIC = { draft: 50000, standard: 150000, high: 500000 };+ var TIER_ETA = { draft: 40, standard: 60, high: 130 };++ var $ = function (id) { return document.getElementById(id); };+ if (!$('fgBtn')) return; // section not present — nothing to wire++ var selectedTier = 'draft';+ var inFlight = false;+ var pollTimer = null;+ var genTimer = null;++ function escapeHtml(s) {+ return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {+ return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c];+ });+ }+ function prefersReducedMotion() {+ return !!(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches);+ }+ function flashPrice(el) {+ if (!el || prefersReducedMotion()) return;+ el.classList.remove('flash'); void el.offsetWidth; el.classList.add('flash');+ el.addEventListener('animationend', function once() { el.classList.remove('flash'); el.removeEventListener('animationend', once); });+ }+ function shortAddr(a) {+ if (!a) return '—'; a = String(a);+ return a.length > 16 ? a.slice(0, 6) + '…' + a.slice(-4) : a;+ }+ function networkLabel(net) {+ if (!net) return '—';+ if (net.indexOf('solana') === 0) return 'Solana';+ if (net === 'eip155:8453') return 'Base';+ if (net.indexOf('eip155:') === 0) return 'EVM ' + net.split(':')[1];+ return net;+ }+ function explorerUrl(net, tx) {+ if (!tx || !net) return null;+ if (net.indexOf('solana') === 0) return 'https://solscan.io/tx/' + tx;+ if (net === 'eip155:8453') return 'https://basescan.org/tx/' + tx;+ return null;+ }+ function fmtUsd(atomics, decimals) {+ var n = Number(atomics) / Math.pow(10, decimals || 6);+ if (!isFinite(n)) return '$0';+ if (n < 0.01) return '$' + n.toFixed(6).replace(/0+$/, '').replace(/\.$/, '');+ return '$' + n.toFixed(2);+ }+ function priceLabel(tier) { return fmtUsd(TIER_ATOMIC[tier] || 50000, 6); }+ function announce(msg) {+ var a = $('fgAnnouncer'); if (!a) return;+ a.textContent = '';+ window.requestAnimationFrame(function () { a.textContent = msg || ''; });+ }++ function sanitizePrompt(raw) { return String(raw || '').replace(/\s+/g, ' ').trim().slice(0, 1000); }+ function setPromptError(msg) {+ var f = $('fgPrompt'), h = $('fgPromptHint');+ if (msg) { f.setAttribute('aria-invalid', 'true'); h.className = 'field-hint err'; h.textContent = msg; }+ else { f.removeAttribute('aria-invalid'); h.className = 'field-hint'; h.textContent = 'One subject works best — describe it in a sentence.'; }+ }+ function setBusy(b, label) {+ inFlight = b;+ var btn = $('fgBtn');+ btn.disabled = b || !navigator.onLine;+ btn.classList.toggle('loading', b);+ btn.querySelector('.label').textContent = b ? (label || 'Working…') : ('Pay ' + priceLabel(selectedTier) + ' & forge');+ }++ // ── price tag + button reflect the selected tier ─────────────────────────+ function syncTierUi() {+ var amt = $('fgPriceAmt');+ var html = escapeHtml(priceLabel(selectedTier)).replace(/^\$/, '$<strong>') + '</strong>';+ if (amt.innerHTML !== html) { amt.innerHTML = html; flashPrice(amt); }+ var sr = $('fgPriceSr'); if (sr) sr.textContent = 'Price: ' + priceLabel(selectedTier) + ' USDC per generation.';+ if (!inFlight) $('fgBtn').querySelector('.label').textContent = 'Pay ' + priceLabel(selectedTier) + ' & forge';+ }++ // ── tier prices from the public catalog (authoritative) ──────────────────+ function loadCatalog() {+ fetch(FORGE_ENDPOINT, { method: 'GET' })+ .then(function (r) { return r.ok ? r.json() : null; })+ .then(function (d) {+ var list = d && d.pricing_usdc;+ if (!Array.isArray(list)) return;+ list.forEach(function (t) {+ var atomic = Math.round(Number(t.price_usdc) * 1e6);+ if (t.tier && isFinite(atomic) && atomic > 0) TIER_ATOMIC[t.tier] = atomic;+ });+ document.querySelectorAll('#fgTiers .tier').forEach(function (btn) {+ var tier = btn.getAttribute('data-tier');+ var el = btn.querySelector('[data-price]');+ if (el && TIER_ATOMIC[tier]) el.textContent = fmtUsd(TIER_ATOMIC[tier], 6);+ });+ syncTierUi();+ })+ .catch(function () {});+ }++ // ── live 402 challenge preview for the selected tier ─────────────────────+ function loadChallengePreview() {+ var preview = $('fgPreview');+ if (preview) preview.setAttribute('aria-busy', 'true');+ var prompt = sanitizePrompt($('fgPrompt').value) || 'a brass steampunk owl, full body';+ fetch(FORGE_ENDPOINT, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ prompt: prompt, tier: selectedTier, aspect_ratio: '1:1' })+ })+ .then(function (res) {+ if (res.status !== 402 && res.status !== 401) throw new Error('expected 402, got ' + res.status);+ return res.json().catch(function () { return null; });+ })+ .then(function (body) {+ var accepts = (body && body.accepts) || [];+ if (!accepts.length) throw new Error('no payment terms in challenge');+ renderChallengePreview(accepts);+ })+ .catch(function (err) {+ var label = $('fgPvLabel'); label.className = 'preview-label err';+ $('fgPvLabelText').textContent = 'Could not reach the endpoint (' + err.message + ').';+ $('fgPvRows').innerHTML = '<button class="pv-retry" type="button" id="fgPvRetry">Retry</button>';+ var r = $('fgPvRetry'); if (r) r.addEventListener('click', loadChallengePreview);+ })+ .then(function () { if (preview) preview.setAttribute('aria-busy', 'false'); });+ }++ function renderChallengePreview(accepts) {+ var byNet = {};+ accepts.forEach(function (a) { if (a && a.network && !byNet[a.network]) byNet[a.network] = a; });+ var nets = Object.keys(byNet).map(function (k) { return byNet[k]; });+ var first = nets[0];+ var decimals = (first.extra && first.extra.decimals) || 6;++ var atomic = Number(first.amount);+ if (isFinite(atomic) && atomic > 0) { TIER_ATOMIC[selectedTier] = atomic; syncTierUi(); }++ var label = $('fgPvLabel'); label.className = 'preview-label ok fresh';+ $('fgPvLabelText').innerHTML = '<span class="mono">HTTP 402 Payment Required</span> — the server is quoting these terms right now';++ var rows = '';+ rows += '<div class="preview-row"><span class="k">price</span><span class="v">' + escapeHtml(fmtUsd(first.amount, decimals)) + ' USDC · ' + escapeHtml(selectedTier) + '</span></div>';+ var badges = nets.map(function (a) { return '<span class="badge">' + escapeHtml(networkLabel(a.network)) + '</span>'; }).join('');+ rows += '<div class="preview-row"><span class="k">networks</span><span class="v">' + badges + '</span></div>';+ nets.forEach(function (a) {+ rows += '<div class="preview-row"><span class="k">pay to</span><span class="v">' + escapeHtml(shortAddr(a.payTo)) + ' <span style="color:var(--ibm-subtle)">(' + escapeHtml(networkLabel(a.network)) + ')</span></span></div>';+ });+ rows += '<div class="preview-row"><span class="k">returns</span><span class="v">a job token → poll for the finished GLB</span></div>';+ $('fgPvRows').innerHTML = rows;+ }++ // ── result states ─────────────────────────────────────────────────────────+ function setResultEmpty() {+ var el = $('fgResult'); el.className = 'result is-empty';+ el.innerHTML = 'Forge a model to see it appear here — orbit it, then download the GLB.';+ announce('');+ }+ function setResultLoading(msg) {+ var el = $('fgResult'); el.className = 'result is-loading';+ el.innerHTML = '<div class="r-status"><span class="spin" aria-hidden="true"></span><span>' + escapeHtml(msg) + '</span></div>';+ announce(msg);+ }+ function setResultError(msg) {+ var text = msg || 'Something went wrong.';+ var el = $('fgResult'); el.className = 'result is-error';+ el.innerHTML = '<div class="r-status err"><span aria-hidden="true">✕</span> <span>' + escapeHtml(text) + '</span></div><button class="retry" type="button" id="fgRetry">Try again</button>';+ var rb = $('fgRetry'); if (rb) rb.addEventListener('click', runForge);+ announce('Error: ' + text);+ }+ function setResultGenerating(payment, etaSec, startTs) {+ var el = $('fgResult'); el.className = 'result is-loading';+ el.innerHTML =+ '<div class="r-status"><span class="spin" aria-hidden="true"></span><span id="fgGenText">Payment settled — forging your model…</span></div>' ++ '<div class="mv-wrap"><div style="height:min(56vh,440px);display:flex;align-items:center;justify-content:center;color:var(--ibm-subtle);font-size:13px">Generating geometry…</div><div class="mv-progress" id="fgProg"></div></div>';+ announce('Payment settled. Forging your 3D model — about ' + etaSec + ' seconds.');+ clearInterval(genTimer);+ genTimer = setInterval(function () {+ var elapsed = Math.round((Date.now() - startTs) / 1000);+ var prog = Math.min(0.95, elapsed / (etaSec * 1.4));+ var bar = $('fgProg'); if (bar) bar.style.width = (prog * 100).toFixed(1) + '%';+ var t = $('fgGenText'); if (t) t.textContent = 'Payment settled — forging your model… ' + elapsed + 's';+ }, 1000);+ }+ function setResultDone(glbUrl, payment, meta) {+ clearInterval(genTimer);+ var el = $('fgResult'); el.className = 'result is-done';+ var explorer = explorerUrl(payment.network, payment.transaction);+ var safeGlb = escapeHtml(glbUrl);++ var html = '';+ html += '<div class="r-status ok"><span class="r-check" aria-hidden="true">✓</span><span>Payment settled — model forged</span></div>';+ html += '<div class="mv-wrap"><model-viewer src="' + safeGlb + '" alt="The 3D model you just forged" camera-controls auto-rotate rotation-per-second="18deg" interaction-prompt="none" shadow-intensity="0.7" shadow-softness="0.8" environment-image="neutral" exposure="1" camera-orbit="0deg 80deg auto" loading="eager"></model-viewer></div>';+ html += '<div class="r-actions">' ++ '<a class="r-btn" href="' + safeGlb + '" download target="_blank" rel="noopener">Download GLB</a>' ++ '<a class="r-btn ghost" href="https://three.ws/forge" target="_blank" rel="noopener">Rig & refine in Forge ↗</a>' ++ '</div>';++ html += '<dl class="receipt">';+ html += '<div class="receipt-pair"><dt class="rk">Tier</dt><dd class="rv">' + escapeHtml((meta && meta.tier) || selectedTier) + '</dd></div>';+ html += '<div class="receipt-pair"><dt class="rk">Network</dt><dd class="rv">' + escapeHtml(networkLabel(payment.network)) + '</dd></div>';+ html += '<div class="receipt-pair"><dt class="rk">Payer</dt><dd class="rv">' + escapeHtml(shortAddr(payment.payer)) + '</dd></div>';+ html += '<div class="receipt-pair"><dt class="rk">Transaction</dt><dd class="rv">' ++ (payment.transaction+ ? (explorer ? '<a href="' + explorer + '" target="_blank" rel="noopener">' + escapeHtml(shortAddr(payment.transaction)) + ' <span aria-hidden="true">↗</span></a>' : escapeHtml(shortAddr(payment.transaction)))+ : '—') + '</dd></div>';+ html += '</dl>';++ html += '<details class="raw"><summary>View raw response & settlement</summary><pre>' ++ escapeHtml(JSON.stringify({ glb_url: glbUrl, job: meta, payment: payment }, null, 2)).slice(0, 6000) + '</pre></details>';++ el.innerHTML = html;+ announce('Your 3D model is ready. Orbit it above or download the GLB.');+ }++ // ── poll the free status endpoint until the GLB is ready ─────────────────+ function pollForge(jobId, payment, etaSec) {+ var startTs = Date.now();+ var tries = 0;+ var maxTries = 150; // ~6.5 min at 2.6s+ setResultGenerating(payment, etaSec, startTs);+ (function tick() {+ fetch(POLL_ENDPOINT + '?job=' + encodeURIComponent(jobId), { method: 'GET' })+ .then(function (r) { return r.json().catch(function () { return null; }); })+ .then(function (d) {+ if (!d) throw new Error('empty');+ if (d.status === 'done' && d.glb_url) { setResultDone(d.glb_url, payment, d); return; }+ if (d.status === 'failed') { clearInterval(genTimer); setResultError(d.error || 'Generation failed. Your payment settled — try the full Forge tool.'); return; }+ tries++;+ if (tries >= maxTries) { clearInterval(genTimer); setResultError('Still working after several minutes — your payment settled. Track it in the full Forge tool.'); return; }+ pollTimer = setTimeout(tick, 2600);+ })+ .catch(function () {+ tries++;+ if (tries >= maxTries) { clearInterval(genTimer); setResultError('Lost contact while generating — your payment settled. Track it in the full Forge tool.'); return; }+ pollTimer = setTimeout(tick, 2600);+ });+ })();+ }++ // ── pay → generate ───────────────────────────────────────────────────────+ function runForge() {+ if (inFlight) return;+ if (!navigator.onLine) { setResultError('You appear to be offline. Reconnect and try again.'); return; }++ var prompt = sanitizePrompt($('fgPrompt').value);+ if (prompt.length < 3) { setPromptError('Describe an object — at least a few characters.'); $('fgPrompt').focus(); return; }+ setPromptError(null);+ $('fgPrompt').value = prompt;++ if (!window.X402 || typeof window.X402.pay !== 'function') {+ setResultError('Payment widget is still loading — give it a second and try again.');+ return;+ }++ var tier = selectedTier;+ var trigger = document.activeElement;+ setBusy(true, 'Waiting for wallet…');+ setResultLoading('Waiting for your wallet… approve the ' + priceLabel(tier) + ' USDC payment to start the generation.');++ window.X402.pay({+ endpoint: FORGE_ENDPOINT,+ method: 'POST',+ body: { prompt: prompt, tier: tier, aspect_ratio: '1:1' },+ merchant: 'three.ws',+ action: 'Forge: ' + prompt.slice(0, 48),+ caps: { maxPerCall: (TIER_ATOMIC[tier] || 500000) }+ }).then(function (out) {+ if (!out || !out.ok) { setResultError('The payment did not complete. Please try again.'); return; }+ var job = out.result || {};+ var payment = out.payment || {};+ // The paid route may finish synchronously on some backends.+ if (job.status === 'done' && job.glb_url) { setResultDone(job.glb_url, payment, job); return; }+ var jobId = job.job_id;+ if (!jobId) { setResultError('Payment settled, but no job token came back. Try the full Forge tool.'); return; }+ var eta = Number(job.eta_seconds) || TIER_ETA[tier] || 60;+ pollForge(jobId, payment, eta);+ }).catch(function (err) {+ if (err && err.code === 'cancelled') { setResultEmpty(); return; }+ setResultError((err && err.message) || 'Payment failed. Please try again.');+ }).then(function () {+ setBusy(false);+ var t = (trigger && trigger.focus && document.body.contains(trigger)) ? trigger : $('fgBtn');+ try { t.focus(); } catch (_) { try { $('fgBtn').focus(); } catch (_2) {} }+ });+ }++ // ── tier selection ─────────────────────────────────────────────────────────+ function selectTier(tier) {+ if (tier === selectedTier || !TIER_ATOMIC[tier]) return;+ selectedTier = tier;+ document.querySelectorAll('#fgTiers .tier').forEach(function (btn) {+ btn.setAttribute('aria-checked', btn.getAttribute('data-tier') === tier ? 'true' : 'false');+ });+ syncTierUi();+ loadChallengePreview();+ }++ // ── wiring ──────────────────────────────────────────────────────────────────+ document.querySelectorAll('#fgTiers .tier').forEach(function (btn) {+ btn.addEventListener('click', function () { selectTier(btn.getAttribute('data-tier')); });+ });+ $('fgBtn').addEventListener('click', runForge);+ $('fgPrompt').addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); runForge(); } });+ var pvTimer;+ $('fgPrompt').addEventListener('input', function () {+ setPromptError(null);+ clearTimeout(pvTimer);+ pvTimer = setTimeout(loadChallengePreview, 600);+ });+ window.addEventListener('online', function () { setBusy(inFlight); loadChallengePreview(); });+ window.addEventListener('offline', function () { setBusy(inFlight); });++ syncTierUi();+ loadCatalog();+ loadChallengePreview();+})();+</script></body></html>diff --git a/public/changelog.json b/public/changelog.jsonindex 306054bf2..499a1fcb1 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-17T22:34:21.137Z",+ "generated_at": "2026-06-17T22:39:17.539Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -375,6 +375,17 @@"infra"]},+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "Free text-to-3D over MCP — no payment, no key",+ "summary": "The three.ws MCP server now ships a free tool: forge_free turns a text prompt into a textured, downloadable 3D model with zero cost — no x402 payment, no wallet, no API key. It runs on the same free NVIDIA NIM (Microsoft TRELLIS) engine the /forge web page uses for drafts, and hands back a durable GLB plus a viewer link that renders the model in the browser. Drop your Claude/Cursor agent on it, type a prompt, get a 3D avatar. The paid tools (mesh_forge, text_to_avatar, rig_mesh) remain for image input, the Granite-directed model chain, and auto-rigging.",+ "link": null,+ "tags": [+ "sdk",+ "feature"+ ]+ },{"date": "2026-06-17","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 63ef2ff69..f0e093027 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -294,6 +294,14 @@<category>fix</category><description>When the NVIDIA NIM free lane returns a 5xx and the Replicate TRELLIS lane is also unavailable, the forge now falls through to the HuggingFace Spaces fallback for text→3D requests (using the FLUX-synthesized intermediate image) instead of returning a 429 to the user. Previously this fallback only fired for image uploads. Club-payout cron warnings for dancers with no registered wallet are now emitted at most once per 24 hours instead of every 5-minute tick.</description></item>+ <item>+ <title>Free text-to-3D over MCP — no payment, no key</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-17:Free text-to-3D over MCP — no payment, no key</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>sdk</category>+ <description>The three.ws MCP server now ships a free tool: forge_free turns a text prompt into a textured, downloadable 3D model with zero cost — no x402 payment, no wallet, no API key. It runs on the same free NVIDIA NIM (Microsoft TRELLIS) engine the /forge web page uses for drafts, and hands back a durable GLB plus a viewer link that renders the model in the browser. Drop your Claude/Cursor agent on it, type a prompt, get a 3D avatar. The paid tools (mesh_forge, text_to_avatar, rig_mesh) remain for image input, the Granite-directed model chain, and auto-rigging.</description>+ </item><item><title>Game-Ready export in Forge — one click to engine-ready GLB + FBX</title><link>https://three.ws/forge</link>diff --git a/public/chat/forge-viewer.html b/public/chat/forge-viewer.htmlnew file mode 100644index 000000000..8ec0fcc02--- /dev/null+++ b/public/chat/forge-viewer.html@@ -0,0 +1,1049 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />+ <title>three.ws Forge — 3D preview</title>+ <style>+ :root {+ --bg: #0a0c10;+ --panel: rgba(13, 16, 21, 0.72);+ --stroke: rgba(255, 255, 255, 0.12);+ --stroke-strong: rgba(255, 255, 255, 0.22);+ --text: #e8eaed;+ --muted: #9aa3ad;+ --accent: #7c5cff;+ --accent-2: #18e0c8;+ --danger: #ff6b6b;+ }+ * {+ box-sizing: border-box;+ }+ html,+ body {+ margin: 0;+ height: 100%;+ background: var(--bg);+ color: var(--text);+ font-family: ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;+ overflow: hidden;+ -webkit-font-smoothing: antialiased;+ }+ #stage {+ position: fixed;+ inset: 0;+ display: block;+ }+ canvas {+ display: block;+ width: 100%;+ height: 100%;+ outline: none;+ }++ /* ── Loading ─────────────────────────────────────────── */+ #loading {+ position: fixed;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ transition: opacity 0.5s ease;+ }+ #loading.hidden {+ opacity: 0;+ pointer-events: none;+ }+ #preview-bg {+ position: absolute;+ inset: -6%;+ background-size: cover;+ background-position: center;+ filter: blur(26px) brightness(0.42) saturate(1.1);+ transform: scale(1.12);+ opacity: 0;+ transition: opacity 0.8s ease;+ }+ #preview-bg.shown {+ opacity: 1;+ }+ .shimmer {+ position: absolute;+ inset: 0;+ background:+ radial-gradient(120% 120% at 30% 20%, rgba(124, 92, 255, 0.16), transparent 60%),+ radial-gradient(120% 120% at 75% 80%, rgba(24, 224, 200, 0.12), transparent 60%),+ var(--bg);+ }+ .shimmer::after {+ content: '';+ position: absolute;+ inset: 0;+ background: linear-gradient(110deg, transparent 30%, rgba(255, 255, 255, 0.05) 50%, transparent 70%);+ transform: translateX(-100%);+ animation: sweep 2.4s ease-in-out infinite;+ }+ @keyframes sweep {+ to {+ transform: translateX(100%);+ }+ }+ .card {+ position: relative;+ width: min(420px, 86vw);+ padding: 26px 24px 22px;+ border-radius: 18px;+ background: var(--panel);+ border: 1px solid var(--stroke);+ backdrop-filter: blur(18px);+ -webkit-backdrop-filter: blur(18px);+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.45);+ text-align: center;+ }+ .thumb {+ width: 96px;+ height: 96px;+ margin: 0 auto 16px;+ border-radius: 14px;+ border: 1px solid var(--stroke-strong);+ background-size: cover;+ background-position: center;+ position: relative;+ overflow: hidden;+ background-color: #11151b;+ }+ .thumb .ring {+ position: absolute;+ inset: -2px;+ border-radius: inherit;+ }+ .spinner {+ width: 22px;+ height: 22px;+ flex: 0 0 auto;+ }+ .spinner circle {+ fill: none;+ stroke: var(--accent-2);+ stroke-width: 4;+ stroke-linecap: round;+ stroke-dasharray: 90 150;+ transform-origin: center;+ animation: spin 1s linear infinite;+ }+ @keyframes spin {+ to {+ transform: rotate(360deg);+ }+ }+ .status-row {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 10px;+ font-size: 15px;+ font-weight: 600;+ letter-spacing: 0.01em;+ }+ .prompt {+ margin: 4px 0 16px;+ font-size: 13px;+ color: var(--muted);+ line-height: 1.45;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+ }+ .bar {+ position: relative;+ height: 5px;+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.08);+ overflow: hidden;+ }+ .bar > i {+ position: absolute;+ top: 0;+ left: 0;+ height: 100%;+ width: 40%;+ border-radius: inherit;+ background: linear-gradient(90deg, var(--accent), var(--accent-2));+ animation: indet 1.5s ease-in-out infinite;+ }+ @keyframes indet {+ 0% {+ left: -42%;+ }+ 100% {+ left: 100%;+ }+ }+ .sub {+ margin-top: 12px;+ font-size: 12px;+ color: var(--muted);+ font-variant-numeric: tabular-nums;+ }++ /* ── Viewer chrome ───────────────────────────────────── */+ #hud {+ position: fixed;+ left: 14px;+ top: 12px;+ right: 14px;+ display: flex;+ align-items: flex-start;+ gap: 10px;+ pointer-events: none;+ opacity: 0;+ transition: opacity 0.6s ease 0.2s;+ }+ #hud.shown {+ opacity: 1;+ }+ .hud-title {+ max-width: min(62%, 520px);+ padding: 7px 12px;+ font-size: 13px;+ line-height: 1.35;+ color: var(--text);+ background: var(--panel);+ border: 1px solid var(--stroke);+ border-radius: 10px;+ backdrop-filter: blur(12px);+ -webkit-backdrop-filter: blur(12px);+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+ }+ .chips {+ display: flex;+ gap: 6px;+ flex-wrap: wrap;+ }+ .chip {+ font-size: 10px;+ font-weight: 600;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--muted);+ padding: 4px 8px;+ border-radius: 999px;+ background: var(--panel);+ border: 1px solid var(--stroke);+ backdrop-filter: blur(12px);+ -webkit-backdrop-filter: blur(12px);+ }+ #toolbar {+ position: fixed;+ left: 50%;+ bottom: 14px;+ transform: translateX(-50%) translateY(8px);+ display: flex;+ gap: 6px;+ padding: 6px;+ border-radius: 14px;+ background: var(--panel);+ border: 1px solid var(--stroke);+ backdrop-filter: blur(16px);+ -webkit-backdrop-filter: blur(16px);+ box-shadow: 0 12px 32px rgba(0, 0, 0, 0.4);+ opacity: 0;+ transition: opacity 0.6s ease 0.3s, transform 0.6s ease 0.3s;+ max-width: calc(100vw - 28px);+ flex-wrap: wrap;+ justify-content: center;+ }+ #toolbar.shown {+ opacity: 1;+ transform: translateX(-50%) translateY(0);+ }+ .btn {+ appearance: none;+ border: 1px solid transparent;+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: 12.5px;+ font-weight: 600;+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 8px 12px;+ border-radius: 9px;+ cursor: pointer;+ text-decoration: none;+ transition: background 0.16s ease, border-color 0.16s ease, opacity 0.16s ease;+ white-space: nowrap;+ }+ .btn:hover {+ background: rgba(255, 255, 255, 0.08);+ }+ .btn:active {+ background: rgba(255, 255, 255, 0.14);+ }+ .btn:focus-visible {+ outline: none;+ border-color: var(--accent-2);+ box-shadow: 0 0 0 2px rgba(24, 224, 200, 0.35);+ }+ .btn[aria-pressed='true'] {+ background: rgba(124, 92, 255, 0.22);+ border-color: rgba(124, 92, 255, 0.5);+ }+ .btn.primary {+ background: linear-gradient(90deg, var(--accent), #6b8bff);+ color: #fff;+ }+ .btn.primary:hover {+ filter: brightness(1.08);+ }+ .btn[disabled] {+ opacity: 0.45;+ cursor: default;+ }+ .btn svg {+ width: 15px;+ height: 15px;+ flex: 0 0 auto;+ }+ .btn .label-sm {+ display: inline;+ }+ @media (max-width: 560px) {+ .btn .label-sm {+ display: none;+ }+ .btn {+ padding: 9px 11px;+ }+ }++ /* ── End states ──────────────────────────────────────── */+ #state {+ position: fixed;+ inset: 0;+ display: none;+ align-items: center;+ justify-content: center;+ padding: 20px;+ }+ #state.shown {+ display: flex;+ }+ .state-card {+ width: min(440px, 88vw);+ padding: 28px 26px;+ border-radius: 18px;+ background: var(--panel);+ border: 1px solid var(--stroke);+ backdrop-filter: blur(18px);+ -webkit-backdrop-filter: blur(18px);+ text-align: center;+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.45);+ }+ .state-icon {+ width: 46px;+ height: 46px;+ margin: 0 auto 14px;+ display: grid;+ place-items: center;+ border-radius: 50%;+ background: rgba(255, 107, 107, 0.14);+ color: var(--danger);+ }+ .state-title {+ font-size: 17px;+ font-weight: 700;+ margin-bottom: 8px;+ }+ .state-msg {+ font-size: 13.5px;+ color: var(--muted);+ line-height: 1.5;+ margin-bottom: 20px;+ }+ .state-actions {+ display: flex;+ gap: 8px;+ justify-content: center;+ flex-wrap: wrap;+ }+ .toast {+ position: fixed;+ left: 50%;+ bottom: 74px;+ transform: translateX(-50%) translateY(8px);+ background: var(--panel);+ border: 1px solid var(--stroke);+ color: var(--text);+ font-size: 12.5px;+ padding: 9px 14px;+ border-radius: 10px;+ backdrop-filter: blur(14px);+ -webkit-backdrop-filter: blur(14px);+ opacity: 0;+ pointer-events: none;+ transition: opacity 0.25s ease, transform 0.25s ease;+ max-width: calc(100vw - 32px);+ text-align: center;+ }+ .toast.shown {+ opacity: 1;+ transform: translateX(-50%) translateY(0);+ }+ .sr-only {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0, 0, 0, 0);+ white-space: nowrap;+ border: 0;+ }+ </style>++ <script type="importmap">+ {+ "imports": {+ "three": "https://esm.sh/[email protected]",+ "three/addons/controls/OrbitControls.js": "https://esm.sh/[email protected]/examples/jsm/controls/OrbitControls.js?external=three",+ "three/addons/loaders/GLTFLoader.js": "https://esm.sh/[email protected]/examples/jsm/loaders/GLTFLoader.js?external=three",+ "three/addons/environments/RoomEnvironment.js": "https://esm.sh/[email protected]/examples/jsm/environments/RoomEnvironment.js?external=three",+ "three/addons/libs/meshopt_decoder.module.js": "https://esm.sh/[email protected]/examples/jsm/libs/meshopt_decoder.module.js"+ }+ }+ </script>+ </head>+ <body>+ <canvas id="stage" aria-label="3D model viewer"></canvas>++ <div id="loading" role="status" aria-live="polite">+ <div id="preview-bg"></div>+ <div class="shimmer"></div>+ <div class="card">+ <div class="thumb" id="thumb">+ <svg class="ring" viewBox="0 0 100 100" aria-hidden="true">+ <circle cx="50" cy="50" r="47" fill="none" stroke="rgba(255,255,255,.08)" stroke-width="3" />+ </svg>+ </div>+ <div class="status-row">+ <svg class="spinner" viewBox="0 0 50 50" aria-hidden="true"><circle cx="25" cy="25" r="20" /></svg>+ <span id="status-label">Starting generation…</span>+ </div>+ <div class="prompt" id="prompt-text"></div>+ <div class="bar"><i></i></div>+ <div class="sub" id="sub-line">Forging a real, textured 3D model</div>+ </div>+ </div>++ <header id="hud">+ <div class="hud-title" id="hud-title"></div>+ <div class="chips" id="hud-chips"></div>+ </header>++ <nav id="toolbar" aria-label="Model controls"></nav>++ <div id="state" role="alertdialog" aria-live="assertive">+ <div class="state-card">+ <div class="state-icon" id="state-icon">+ <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" />+ </svg>+ </div>+ <div class="state-title" id="state-title">Something went wrong</div>+ <div class="state-msg" id="state-msg"></div>+ <div class="state-actions" id="state-actions"></div>+ </div>+ </div>++ <div class="toast" id="toast" role="status" aria-live="polite"></div>++ <script type="module">+ import * as THREE from 'three';+ import { OrbitControls } from 'three/addons/controls/OrbitControls.js';+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+ import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';++ // ── Payload ──────────────────────────────────────────────+ // { job, glb, preview, prompt, eta, meta:{path,tier,backend}, error }+ let data = {};+ try {+ data = JSON.parse(decodeURIComponent(location.hash.slice(1))) || {};+ } catch {+ data = {};+ }+ const FORGE = '/api/forge';+ const el = (id) => document.getElementById(id);++ const ICONS = {+ download:+ '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/>',+ external:+ '<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/>',+ expand: '<polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/>',+ reset: '<polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/>',+ rotate: '<path d="M23 4v6h-6"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>',+ rig: '<circle cx="12" cy="5" r="2"/><path d="M12 7v6"/><path d="M9 21l3-8 3 8"/><path d="M6 11l6 2 6-2"/>',+ };+ function icon(name) {+ return (+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' ++ (ICONS[name] || '') ++ '</svg>'+ );+ }++ let toastTimer;+ function toast(msg) {+ const t = el('toast');+ t.textContent = msg;+ t.classList.add('shown');+ clearTimeout(toastTimer);+ toastTimer = setTimeout(() => t.classList.remove('shown'), 3200);+ }++ const promptText = String(data.prompt || '').trim();+ if (promptText) {+ el('prompt-text').textContent = '“' + promptText + '”';+ }+ if (data.preview) {+ const bg = el('preview-bg');+ bg.style.backgroundImage = 'url("' + data.preview + '")';+ el('thumb').style.backgroundImage = 'url("' + data.preview + '")';+ const img = new Image();+ img.onload = () => bg.classList.add('shown');+ img.src = data.preview;+ }++ // ── End-state renderer ───────────────────────────────────+ function showState({ title, msg, actions, danger = true }) {+ el('loading').classList.add('hidden');+ el('state-title').textContent = title;+ el('state-msg').textContent = msg;+ const iconWrap = el('state-icon');+ iconWrap.style.background = danger ? 'rgba(255,107,107,.14)' : 'rgba(24,224,200,.14)';+ iconWrap.style.color = danger ? 'var(--danger)' : 'var(--accent-2)';+ const wrap = el('state-actions');+ wrap.innerHTML = '';+ for (const a of actions) {+ if (a.href) {+ const link = document.createElement('a');+ link.className = 'btn' + (a.primary ? ' primary' : '');+ link.href = a.href;+ link.target = '_blank';+ link.rel = 'noopener';+ link.textContent = a.label;+ wrap.appendChild(link);+ } else {+ const b = document.createElement('button');+ b.className = 'btn' + (a.primary ? ' primary' : '');+ b.textContent = a.label;+ b.addEventListener('click', a.onClick);+ wrap.appendChild(b);+ }+ }+ el('state').classList.add('shown');+ }++ const forgeLink = promptText+ ? 'https://three.ws/forge?prompt=' + encodeURIComponent(promptText)+ : 'https://three.ws/forge';++ function fail(title, msg, { retry = true } = {}) {+ const actions = [{ label: 'Open in Forge ↗', href: forgeLink, primary: !retry }];+ if (retry && promptText) {+ actions.unshift({+ label: 'Try again',+ primary: true,+ onClick: () => {+ el('state').classList.remove('shown');+ el('loading').classList.remove('hidden');+ resubmit();+ },+ });+ }+ showState({ title, msg, actions });+ }++ // ── Progress labelling (no server %, drive from elapsed) ──+ const STAGES = [+ [0, 'Generating concept image'],+ [7, 'Reconstructing geometry'],+ [22, 'Texturing surface'],+ [40, 'Finalizing mesh'],+ ];+ const started = performance.now();+ let lastStatus = '';+ function tickLabel() {+ const secs = (performance.now() - started) / 1000;+ let label = STAGES[0][1];+ for (const [t, l] of STAGES) if (secs >= t) label = l;+ if (lastStatus === 'queued' && secs < 4) label = 'Queued';+ el('status-label').textContent = label;+ const mm = Math.floor(secs / 60);+ const ss = Math.floor(secs % 60);+ const etaTxt = data.eta ? ' · ~' + Math.round(data.eta) + 's typical' : '';+ el('sub-line').textContent = (mm ? mm + 'm ' : '') + ss + 's elapsed' + etaTxt;+ }+ const labelTimer = setInterval(tickLabel, 500);+ tickLabel();++ // ── Polling ──────────────────────────────────────────────+ const MAX_MS = 6 * 60 * 1000;+ async function pollUntilDone(jobId) {+ const deadline = performance.now() + MAX_MS;+ let delay = 2500;+ while (performance.now() < deadline) {+ await new Promise((r) => setTimeout(r, delay));+ let res, body;+ try {+ res = await fetch(FORGE + '?job=' + encodeURIComponent(jobId), { credentials: 'include' });+ body = await res.json().catch(() => ({}));+ } catch {+ continue; // transient network — keep trying+ }+ if (res.status === 429) {+ const ra = Number(res.headers.get('retry-after'));+ delay = Math.min(8000, (ra ? ra * 1000 : 0) || delay + 1000);+ continue;+ }+ delay = 2500;+ lastStatus = body.status || '';+ if (body.status === 'done' && body.glb_url) return body.glb_url;+ if (body.status === 'failed') {+ return fail(+ 'Generation failed',+ body.error || 'The model couldn’t be generated. Try a clearer single-subject prompt.'+ );+ }+ }+ fail(+ 'Still working…',+ 'This is taking longer than usual. Your model may still finish in Forge — open it there to check.',+ { retry: true }+ );+ return null;+ }++ async function resubmit() {+ try {+ const res = await fetch(FORGE, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ prompt: promptText }),+ });+ const body = await res.json().catch(() => ({}));+ if (!res.ok) return fail('Couldn’t start', body.message || body.error || 'Forge rejected the request.');+ if (body.glb_url) return loadModel(body.glb_url);+ if (body.job_id) {+ const url = await pollUntilDone(body.job_id);+ if (url) loadModel(url);+ return;+ }+ fail('No model returned', 'Forge didn’t return a model. Try again or open it in Forge.');+ } catch {+ fail('Connection lost', 'Could not reach the Forge service. Check your connection and retry.');+ }+ }++ // ── Three.js viewer ──────────────────────────────────────+ let renderer, scene, camera, controls, mixer, clock, current;+ let autoRotate = true;+ let frameInfo = null;+ let loadedGlbUrl = null;++ function initThree() {+ const canvas = el('stage');+ try {+ renderer = new THREE.WebGLRenderer({ canvas, antialias: true, preserveDrawingBuffer: false });+ } catch {+ return false;+ }+ renderer.setPixelRatio(Math.min(devicePixelRatio || 1, 2));+ renderer.setSize(innerWidth, innerHeight, false);+ renderer.outputColorSpace = THREE.SRGBColorSpace;+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.05;+ renderer.shadowMap.enabled = true;+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;++ scene = new THREE.Scene();+ scene.background = new THREE.Color(0x0a0c10);++ const pmrem = new THREE.PMREMGenerator(renderer);+ scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;++ camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.01, 2000);+ camera.position.set(0, 1.1, 3.2);++ controls = new OrbitControls(camera, renderer.domElement);+ controls.enableDamping = true;+ controls.dampingFactor = 0.07;+ controls.autoRotate = true;+ controls.autoRotateSpeed = 1.4;+ controls.addEventListener('start', () => {+ autoRotate = false;+ controls.autoRotate = false;+ syncRotateBtn();+ });++ const key = new THREE.DirectionalLight(0xffffff, 2.0);+ key.position.set(4, 7, 5);+ key.castShadow = true;+ key.shadow.mapSize.set(2048, 2048);+ key.shadow.bias = -0.0004;+ key.shadow.normalBias = 0.02;+ scene.add(key);+ scene.add(new THREE.HemisphereLight(0xbfd4ff, 0x10131a, 0.35));++ clock = new THREE.Clock();+ addEventListener('resize', onResize);+ renderer.setAnimationLoop(render);+ return true;+ }++ function onResize() {+ if (!renderer) return;+ renderer.setSize(innerWidth, innerHeight, false);+ camera.aspect = innerWidth / innerHeight;+ camera.updateProjectionMatrix();+ }++ function render() {+ const dt = clock.getDelta();+ if (mixer) mixer.update(dt);+ if (controls) controls.update();+ renderer.render(scene, camera);+ }++ async function fetchGlb(url) {+ // Same-origin/CORS-friendly fetch so we can show real load errors and+ // reuse the blob for a reliable download. Falls back to direct URL.+ const res = await fetch(url, { credentials: 'include' });+ if (!res.ok) throw new Error('Model fetch failed (' + res.status + ')');+ const blob = await res.blob();+ return URL.createObjectURL(blob);+ }++ function frameObject(obj) {+ const box = new THREE.Box3().setFromObject(obj);+ const size = box.getSize(new THREE.Vector3());+ const center = box.getCenter(new THREE.Vector3());+ const maxDim = Math.max(size.x, size.y, size.z) || 1;+ obj.position.sub(center);++ const fitDist = (maxDim / 2 / Math.tan((camera.fov * Math.PI) / 360)) * 1.5;+ camera.near = maxDim / 100;+ camera.far = maxDim * 100;+ camera.updateProjectionMatrix();+ controls.minDistance = maxDim * 0.4;+ controls.maxDistance = maxDim * 6;+ controls.target.set(0, 0, 0);+ frameInfo = { dist: fitDist, height: maxDim * 0.18, maxDim };+ resetView(true);++ // Contact-shadow ground at the model's feet.+ const groundY = -size.y / 2;+ const ground = new THREE.Mesh(+ new THREE.PlaneGeometry(maxDim * 12, maxDim * 12),+ new THREE.ShadowMaterial({ opacity: 0.28 })+ );+ ground.rotation.x = -Math.PI / 2;+ ground.position.y = groundY;+ ground.receiveShadow = true;+ scene.add(ground);+ }++ function resetView(instant) {+ if (!frameInfo) return;+ const { dist, height } = frameInfo;+ const target = new THREE.Vector3(dist * 0.0, height, dist);+ if (instant) {+ camera.position.copy(target);+ } else {+ const from = camera.position.clone();+ const t0 = performance.now();+ (function ease() {+ const k = Math.min(1, (performance.now() - t0) / 450);+ const e = 1 - Math.pow(1 - k, 3);+ camera.position.lerpVectors(from, target, e);+ if (k < 1) requestAnimationFrame(ease);+ })();+ }+ controls.target.set(0, 0, 0);+ }++ function fadeIn(obj) {+ const mats = [];+ obj.traverse((n) => {+ if (n.isMesh) {+ n.castShadow = true;+ n.receiveShadow = true;+ const list = Array.isArray(n.material) ? n.material : [n.material];+ for (const m of list) {+ if (!m) continue;+ m.userData._t = m.transparent;+ m.userData._o = m.opacity;+ m.transparent = true;+ m.opacity = 0;+ mats.push(m);+ }+ }+ });+ const t0 = performance.now();+ (function step() {+ const k = Math.min(1, (performance.now() - t0) / 600);+ for (const m of mats) m.opacity = (m.userData._o ?? 1) * k;+ if (k < 1) requestAnimationFrame(step);+ else+ for (const m of mats) {+ m.transparent = m.userData._t ?? false;+ m.opacity = m.userData._o ?? 1;+ m.needsUpdate = true;+ }+ })();+ }++ const gltfLoader = new GLTFLoader();+ try {+ const { MeshoptDecoder } = await import('three/addons/libs/meshopt_decoder.module.js');+ gltfLoader.setMeshoptDecoder(MeshoptDecoder);+ } catch {+ /* meshopt optional — vanilla GLBs load without it */+ }++ async function loadModel(url) {+ loadedGlbUrl = url;+ if (!renderer && !initThree()) {+ return showState({+ title: '3D not supported here',+ msg: 'Your browser/device can’t render WebGL. Download the model or open it in Forge.',+ danger: true,+ actions: [+ { label: 'Download GLB', href: url, primary: true },+ { label: 'Open in Forge ↗', href: forgeLink },+ ],+ });+ }+ let objectUrl = url;+ try {+ objectUrl = await fetchGlb(url);+ } catch {+ /* fall back to the raw url; GLTFLoader will retry it directly */+ }+ gltfLoader.load(+ objectUrl,+ (gltf) => {+ clearInterval(labelTimer);+ if (current) {+ scene.remove(current);+ }+ current = gltf.scene;+ scene.add(current);+ frameObject(current);+ fadeIn(current);+ if (gltf.animations && gltf.animations.length) {+ mixer = new THREE.AnimationMixer(current);+ mixer.clipAction(gltf.animations[0]).play();+ }+ revealViewer();+ },+ undefined,+ () => {+ fail(+ 'Couldn’t load the model',+ 'The generated file didn’t load. It may have expired — regenerate it, or open it in Forge.'+ );+ }+ );+ }++ function revealViewer() {+ el('loading').classList.add('hidden');+ el('state').classList.remove('shown');+ buildHud();+ buildToolbar();+ requestAnimationFrame(() => {+ el('hud').classList.add('shown');+ el('toolbar').classList.add('shown');+ });+ }++ function buildHud() {+ if (promptText) el('hud-title').textContent = promptText;+ else el('hud-title').style.display = 'none';+ const chips = el('hud-chips');+ chips.innerHTML = '';+ const m = data.meta || {};+ for (const v of [m.backend, m.tier, m.path]) {+ if (!v) continue;+ const c = document.createElement('span');+ c.className = 'chip';+ c.textContent = v;+ chips.appendChild(c);+ }+ }++ let rotateBtn;+ function syncRotateBtn() {+ if (rotateBtn) rotateBtn.setAttribute('aria-pressed', String(autoRotate));+ }++ function mkBtn({ name, label, labelSm, onClick, href, primary, pressed, aria }) {+ const tag = href ? 'a' : 'button';+ const b = document.createElement(tag);+ b.className = 'btn' + (primary ? ' primary' : '');+ b.innerHTML = icon(name) + '<span class="' + (labelSm ? 'label-sm' : '') + '">' + label + '</span>';+ b.setAttribute('aria-label', aria || label);+ if (pressed !== undefined) b.setAttribute('aria-pressed', String(pressed));+ if (href) {+ b.href = href;+ b.target = '_blank';+ b.rel = 'noopener';+ } else {+ b.addEventListener('click', onClick);+ }+ return b;+ }++ async function download() {+ try {+ const blobUrl = await fetchGlb(loadedGlbUrl);+ const a = document.createElement('a');+ a.href = blobUrl;+ a.download = (promptText ? promptText.slice(0, 40).replace(/[^a-z0-9]+/gi, '-') : 'forge-model') + '.glb';+ document.body.appendChild(a);+ a.click();+ a.remove();+ setTimeout(() => URL.revokeObjectURL(blobUrl), 4000);+ } catch {+ window.open(loadedGlbUrl, '_blank', 'noopener');+ }+ }++ function buildToolbar() {+ const bar = el('toolbar');+ bar.innerHTML = '';++ bar.appendChild(mkBtn({ name: 'download', label: 'Download', labelSm: true, onClick: download, aria: 'Download GLB' }));++ rotateBtn = mkBtn({+ name: 'rotate',+ label: 'Spin',+ labelSm: true,+ pressed: autoRotate,+ onClick: () => {+ autoRotate = !autoRotate;+ controls.autoRotate = autoRotate;+ syncRotateBtn();+ },+ });+ bar.appendChild(rotateBtn);++ bar.appendChild(+ mkBtn({+ name: 'reset',+ label: 'Recenter',+ labelSm: true,+ onClick: () => resetView(false),+ aria: 'Recenter camera',+ })+ );++ if (document.fullscreenEnabled) {+ bar.appendChild(+ mkBtn({+ name: 'expand',+ label: 'Fullscreen',+ labelSm: true,+ onClick: () => {+ if (document.fullscreenElement) document.exitFullscreen();+ else document.documentElement.requestFullscreen().catch(() => {});+ },+ })+ );+ }++ // Rig & animate — backend-supported but may be disabled on a+ // deployment; self-heals on the unconfigured response.+ const rigBtn = mkBtn({+ name: 'rig',+ label: 'Rig & Animate',+ labelSm: true,+ primary: true,+ onClick: () => rigAndAnimate(rigBtn),+ });+ bar.appendChild(rigBtn);++ bar.appendChild(mkBtn({ name: 'external', label: 'Forge', labelSm: true, href: forgeLink, aria: 'Open in Forge' }));+ }++ async function rigAndAnimate(btn) {+ if (!loadedGlbUrl) return;+ btn.setAttribute('disabled', '');+ const restore = btn.innerHTML;+ btn.innerHTML = icon('rig') + '<span class="label-sm">Rigging…</span>';+ try {+ const res = await fetch(FORGE + '?action=rig', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ glb_url: loadedGlbUrl }),+ });+ const body = await res.json().catch(() => ({}));+ if (res.status === 501 || body.error === 'rig_unconfigured') {+ btn.remove();+ toast('Auto-rigging isn’t enabled on this deployment.');+ return;+ }+ if (!res.ok || !body.job_id) {+ btn.innerHTML = restore;+ btn.removeAttribute('disabled');+ toast(body.message || 'Rigging is busy — try again shortly.');+ return;+ }+ toast('Rigging your model — this adds a skeleton + idle motion.');+ const rigged = await pollUntilDone(body.job_id);+ if (rigged) {+ el('loading').classList.remove('hidden');+ el('status-label').textContent = 'Loading rigged model';+ await loadModel(rigged);+ toast('Rigged & animated.');+ } else {+ btn.innerHTML = restore;+ btn.removeAttribute('disabled');+ }+ } catch {+ btn.innerHTML = restore;+ btn.removeAttribute('disabled');+ toast('Rigging failed — try again.');+ }+ }++ // ── Boot ─────────────────────────────────────────────────+ (function boot() {+ if (data.error) {+ clearInterval(labelTimer);+ return fail('Couldn’t generate', String(data.error));+ }+ if (data.glb) return loadModel(data.glb);+ if (data.job) {+ (async () => {+ const url = await pollUntilDone(data.job);+ if (url) loadModel(url);+ })();+ return;+ }+ clearInterval(labelTimer);+ fail('Nothing to show', 'No model or job was provided. Try generating again.');+ })();+ </script>+ </body>+</html>diff --git a/public/features.json b/public/features.jsonindex 104ec54b6..b5784893b 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-17T22:34:21.122Z",+ "generated_at": "2026-06-17T22:39:17.520Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/mcp-forge-free.test.js b/tests/mcp-forge-free.test.jsnew file mode 100644index 000000000..c38a78c2c--- /dev/null+++ b/tests/mcp-forge-free.test.js@@ -0,0 +1,177 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++import { buildForgeFreeTool } from '../mcp-server/src/tools/forge-free.js';++// `forge_free` is the ONE free MCP tool — text prompt → 3D GLB on the free+// NVIDIA NIM (TRELLIS) lane, no x402 payment and no API key. These tests guard:+// - the descriptor advertises free-ness and is a write (mints an artifact),+// - input is validated before any network call,+// - the synchronous-done forge response is shaped into a free result,+// - a queued job is polled to completion,+// - the request pins backend:"nvidia" so the happy path is never the paid lane,+// - upstream states (not_configured / busy / failed) become designed toolErrors+// (ok:false → isError, which on a paid tool cancels billing; here it just+// gives the caller a stable error contract).++// A Response stub good enough for the tool's fetch usage (status, ok, json).+function res(status, body = {}) {+ return {+ status,+ ok: status >= 200 && status < 300,+ json: async () => body,+ };+}++// Pull the tool's structured return out of the MCP CallToolResult envelope.+function structured(envelope) {+ return envelope.structuredContent;+}++describe('forge_free — descriptor', () => {+ it('is free, a write, open-world, and never quotes a USDC price', () => {+ const tool = buildForgeFreeTool();+ expect(tool.name).toBe('forge_free');+ expect(tool.title).toMatch(/free/i);+ expect(tool.description.toLowerCase()).toContain('free');+ // A free tool must NOT advertise a USDC price in its description.+ expect(tool.description).not.toMatch(/\$[0-9]/);+ // Mentions the free engine so an LLM picks it for zero-cost text→3D.+ expect(tool.description).toMatch(/TRELLIS|NVIDIA/i);++ expect(tool.annotations).toEqual({+ readOnlyHint: false,+ destructiveHint: false,+ idempotentHint: false,+ openWorldHint: true,+ });+ expect(tool.inputSchema.prompt).toBeTruthy();+ expect(tool.inputSchema.tier).toBeTruthy();+ expect(tool.handler).toBeTypeOf('function');+ });+});++describe('forge_free — handler', () => {+ let fetchMock;+ let tool;+ beforeEach(() => {+ fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ // Tighten the poll cadence so the queued-job test doesn't wait seconds.+ process.env.FORGE_FREE_POLL_MS = '1';+ tool = buildForgeFreeTool();+ });+ afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ delete process.env.FORGE_FREE_POLL_MS;+ });++ it('rejects a too-short prompt without hitting the network', async () => {+ const out = structured(await tool.handler({ prompt: 'no' }, {}));+ expect(out.ok).toBe(false);+ expect(out.error).toBe('invalid_input');+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('pins the free NVIDIA lane and shapes a synchronous completion', async () => {+ fetchMock.mockResolvedValueOnce(+ res(200, {+ job_id: null,+ creation_id: 'abc123',+ status: 'done',+ glb_url: 'https://three.ws/cdn/forge/nvidia/x.glb',+ backend: 'nvidia',+ durable: true,+ }),+ );++ const out = structured(await tool.handler({ prompt: 'a glossy white robot mascot' }, {}));++ // Exactly one call — the synchronous done path skips polling entirely.+ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [url, opts] = fetchMock.mock.calls[0];+ expect(url).toMatch(/\/api\/forge$/);+ const body = JSON.parse(opts.body);+ // The free lane must be pinned so the happy path is never the paid Replicate lane.+ expect(body).toMatchObject({ backend: 'nvidia', path: 'image', prompt: 'a glossy white robot mascot' });+ // Tier defaults to draft (fast, free).+ expect(body.tier).toBe('draft');++ expect(out).toMatchObject({+ ok: true,+ free: true,+ cost: '$0.00',+ mode: 'text_to_3d',+ glbUrl: 'https://three.ws/cdn/forge/nvidia/x.glb',+ backend: 'nvidia',+ tier: 'draft',+ creationId: 'abc123',+ durable: true,+ jobId: null,+ });+ // The viewer link renders the model in-browser.+ expect(out.preview).toBe(+ 'https://three.ws/viewer?src=' + encodeURIComponent('https://three.ws/cdn/forge/nvidia/x.glb'),+ );+ expect(typeof out.durationMs).toBe('number');+ });++ it('honors a requested tier and polls a queued job to done', async () => {+ fetchMock+ .mockResolvedValueOnce(+ res(200, { job_id: 'tok_abc', creation_id: 'c1', status: 'queued', backend: 'nvidia' }),+ )+ .mockResolvedValueOnce(res(200, { job_id: 'tok_abc', status: 'running' }))+ .mockResolvedValueOnce(+ res(200, {+ job_id: 'tok_abc',+ status: 'done',+ glb_url: 'https://three.ws/cdn/forge/nvidia/y.glb',+ backend: 'nvidia',+ creation_id: 'c1',+ durable: true,+ }),+ );++ const out = structured(await tool.handler({ prompt: 'a carved oak chair', tier: 'standard' }, {}));++ expect(JSON.parse(fetchMock.mock.calls[0][1].body).tier).toBe('standard');+ // Submit + two polls.+ expect(fetchMock).toHaveBeenCalledTimes(3);+ expect(fetchMock.mock.calls[1][0]).toContain('?job=tok_abc');+ expect(out).toMatchObject({+ ok: true,+ free: true,+ tier: 'standard',+ jobId: 'tok_abc',+ glbUrl: 'https://three.ws/cdn/forge/nvidia/y.glb',+ backend: 'nvidia',+ });+ });++ it('surfaces a not-configured deployment as a designed error', async () => {+ fetchMock.mockResolvedValueOnce(res(503, { message: 'free text→3D is not configured' }));+ const envelope = await tool.handler({ prompt: 'a brass telescope' }, {});+ expect(envelope.isError).toBe(true);+ const out = structured(envelope);+ expect(out.ok).toBe(false);+ expect(out.error).toBe('not_configured');+ });++ it('surfaces a busy lane as a rate_limited error with retry hint', async () => {+ fetchMock.mockResolvedValueOnce(res(429, { message: 'busy', retry_after: 8 }));+ const out = structured(await tool.handler({ prompt: 'a ceramic teapot' }, {}));+ expect(out.ok).toBe(false);+ expect(out.error).toBe('rate_limited');+ expect(out.retryAfter).toBe(8);+ });++ it('reports a terminal generation failure from the poll loop', async () => {+ fetchMock+ .mockResolvedValueOnce(res(200, { job_id: 'tok_fail', status: 'queued', backend: 'nvidia' }))+ .mockResolvedValueOnce(res(200, { job_id: 'tok_fail', status: 'failed', error: 'NVCF dropped the job' }));+ const out = structured(await tool.handler({ prompt: 'a marble bust' }, {}));+ expect(out.ok).toBe(false);+ expect(out.error).toBe('generation_failed');+ });+});