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
Add adversarial input generation script and sample images
nirholas65deea4ca817
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 846a02086..b2537e88b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,9 +10,12 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **The Story So Far** (`/timeline`) — three.ws's history as an explorable 3D scene: every launch, partnership, listing, and milestone laid out along a path you can orbit in 360° or walk end to end, with a synced scrubber and source links.- **three.ws is an OpenAI Select Partner** (`/openai`) — three.ws is an OpenAI Select Partner in the OpenAI Partner Network. Connect the free three.ws 3D Studio MCP server to ChatGPT and turn a prompt into an interactive, riggable, AR-ready 3D model inline in the conversation.- **three.ws Named an OpenAI Select Partner** (`/blog/three-ws-openai-select-partner`) — three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.+- **Crypto API: automatic upstream failover ends most rate-limit errors** — The unified crypto API (/api/v1/x) no longer fails your call just because one upstream host had a bad moment. When a provider is backed by a pool of interchangeable hosts (the Solana read endpoints front the platform's full RPC pool), a rate-limited, unreachable, or erroring host now fails over to a healthy alternate within the same request. The API also remembers which host just failed for a short window, so during an outage only the first request pays the discovery cost and everything after routes straight to a working host. Rate-limit passthrough was the second-largest error class on the aggregator; this removes it for pooled providers. (`/crypto-api`) `[improvement, infra]`- **Dress any avatar: the wardrobe now adds clothes, not just recolours them** — Until now the wardrobe could only recolour or hide the clothes an avatar was generated with. It can now put NEW clothes on: the avatar editor's Wardrobe tab gained a Closet with racks of catalog pieces (tops, bottoms, footwear, outerwear, hair, headwear, glasses, accessories). Click a piece and it binds to your avatar's skeleton and moves with every animation, whatever generator the avatar came from: forge characters, selfie reconstructions and uploaded models all work, because garments are fitted to the skeleton at wear-time instead of being authored for one specific body. The body is masked under whatever you wear so skin never pokes through the cloth, a piece that cannot fit a particular skeleton politely refuses instead of deforming into spaghetti, and every download is integrity-checked against the catalog before it touches your avatar. Saved outfits persist: the downloadable and embedded versions of your avatar come out dressed too. (`/avatar-edit`) `[feature]`- **Our crypto API no longer reports itself as broken to the directories that rate it** — Agent directories and uptime monitors discover an x402 API by calling every endpoint it advertises with no arguments, to check the endpoint is alive and knows its own price. Our paid-only endpoints answered that correctly with a payment challenge, but the free-tier ones ran argument validation first and answered with an error, so about two dozen perfectly healthy endpoints were being graded as failing by a public trust monitor, roughly 14,000 times a month. A parameterless call now returns the standard 402 challenge on every endpoint, with the argument you would need named in an X-Param-Error header. Nothing changes for real callers: send any argument, even an empty one, and you get the specific validation error as before. The same probes were also the single biggest source of noise in our own error metrics, so a genuine outage in the crypto API is now visible instead of buried. (`/crypto-api`) `[fix, improvement]`+- **Our x402 facilitator now publishes a standard discovery catalog** — The three.ws self-hosted x402 facilitator serves a new public endpoint, GET /api/x402-facilitator/discovery/resources, listing every paid endpoint on the platform in the standard facilitator catalog format that x402 explorers and aggregators (like x402scan) crawl. It is the same catalog as /.well-known/x402.json, so listings on third-party explorers always match what the platform actually charges. This is groundwork for three.ws payments showing up on ecosystem explorers without routing settlement through any third party. (`/docs/x402-ring-economy`) `[feature, infra]`- **Selfie avatars now match the shape of your face, not just the colour of it** — The selfie-to-avatar engine used to do one thing: take the face from your photo and paint it onto a standard head. From straight on it looked convincing, but the skull underneath was the same for everyone, so the moment the avatar turned it stopped being you. It now reshapes the head itself to your face: width, jaw, chin, cheekbones, brow, and how far the nose projects. That step had been written and tested for a while but had never actually reached the servers, so every avatar made until today was built the old way. Making it live also turned up a flaw in how the photo was read. Face measurements arrived scaled to the picture's width and height separately, which means a tall photo stretched the face before anything else happened, and that stretch was then treated as part of your bone structure. In practice the shape of your avatar's head partly depended on whether you shot the photo tall or square, which is not something anyone would expect. Measurements are now taken in true proportions, so the same face gives the same head regardless of how the photo was framed. Finally, the limits controlling how far the head is allowed to move toward your real shape were set before there was any way to measure the result. They were far too cautious, holding the head back to about two centimetres of change and quietly discarding real differences between faces. Measured across a forty-face test set covering a wide range of ages, complexions, beards, glasses and head coverings, retuning them cut the remaining shape error by 46 percent, and no face in the set came out worse. Choosing that limit needed a second measurement, because a test set of clean, well-lit photos will always argue for removing the limit entirely: it contains nothing for the limit to catch. So each test face was also degraded the way real photos are, with camera shake, a turned head, hair across the face, a dim room and a heavily shrunk upload, and checked for whether the same person still came out with the same head. The setting we shipped is the point where matching your face stops improving but sensitivity to photo quality keeps rising. In total, avatars now capture about 60 percent of the difference between a generic head and your real one, up from 26 percent. Rebuild your avatar at /create/selfie to get one made the new way. (`/create/selfie`) `[improvement, fix]`+- **Solana reads on the crypto API stop failing when one RPC host throttles us** — The Solana endpoints on the public crypto API (balance, token holdings, token supply, largest holders, transaction, account, priority fees) were pointed at a single RPC host. Whenever that host rate-limited us, the caller got the rate-limit error even though the platform keeps a priority-ordered pool of other RPC endpoints for exactly this situation. Those calls now move to the next healthy host automatically, up to three per request, and a host that has just failed is skipped for the next 30 seconds so one bad host does not slow down every request behind it. A genuinely bad request, like a malformed address, still returns its error immediately instead of being retried. This was the second-largest error class on the API. (`/crypto-api`) `[fix, improvement]`- **The KOL Tracker is now reachable, and its numbers are real** — The KOL Tracker page shipped listed in the sitemap but with no route behind it, so three.ws/tracker returned a 404 for everyone who followed the link, and the API behind it was answering with three placeholder rows left over from a test fixture. Both are fixed. The page is served, and it now ranks real Solana traders from the live kolscan board: realized profit, win rate and trade count for the 24h, 7d and 30d windows, enriched with our own on-chain FIFO profit calculation wherever we have the trades for a wallet. Every row states where its number came from, and when a source is unreachable the board shows an honest empty state instead of inventing traders. A new test blocks the whole class of mistake: any page advertised in the site index that has no route, or that never gets built, now fails the suite before it can reach production. (`/tracker`) `[fix, feature]`- **The signing avatar's arm now sits where a signer's arm sits, and it signs real words** — The signing avatar had a broken arm. Its handshapes were right, but the arm carrying them swung out to the side and behind the body, and the clip also dragged the avatar about a metre down through the floor, so you were watching correct fingerspelling performed somewhere over the avatar's shoulder. The cause was that the arm was posed with rotations written against a skeleton convention our reference avatar does not use. Arms are now solved instead of guessed: the code measures the actual skeleton (which way each bone points, how long it is, which way each palm faces) and then runs real inverse kinematics to put the wrist at a specific point in front of the body, with the elbow hanging where an elbow hangs. Fingerspelling now happens where signers do it, in front of the dominant shoulder at jaw height with the palm facing you, and the letters themselves are unchanged, to the digit. Because a hand can now be sent to a place on the body, the avatar also has a real sign vocabulary for the first time: thirty-two everyday words including hello, thank you, please, sorry, yes, no, happy, help, love, want, welcome, name, y'all and finish, two-handed where the sign is two-handed. Type a sentence and the words with signs are signed while the rest is fingerspelled, in one continuous motion, and the page tells you which was which. There is a new section on the sign-language page listing every word it can sign, each one playable. Both arms are now posed throughout, the idle hand rests at the side instead of hanging oddly, the avatar breathes during long holds, and the camera crops closer so you can actually see the hands. (`/sign-language`) `[improvement, fix]`- **The Spatial MCP reference renderer actually renders again** — Spatial MCP is our open, public-domain shape for handing back a live 3D scene as an AI tool result instead of a link, and three.ws/spatial-mcp is the page that proves it works. It has been showing two empty frames. The demo code asked for its renderer with a path relative to the page, and because the page is served both with and without a trailing slash, that path pointed at the site root on one of them and came back as a 404, so the renderer never loaded and neither scene appeared. The demo now loads as its own module file, which resolves correctly on either address and in local development, where the same page had been failing to build at all. Both frames are live again: you can orbit and zoom a real model on the left and, on the right, the same viewer displaying a model that arrived from a completely different server in a completely different format, converted by a six-line adapter shown as JSON underneath. That side-by-side is the whole argument for the standard, so it is worth having it work. The left frame is now a genuine model from our free text-to-3D lane rather than a borrowed sample, and the sample the page used to point at had itself gone dead upstream, which is why it also stayed blank once the renderer was fixed. (`/spatial-mcp`) `[fix]`diff --git a/CLAUDE.md b/CLAUDE.mdindex 40bcf8479..c585ea74f 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -33,7 +33,7 @@ Agents stopping mid-task to ask a question is a failure mode the owner explicitl| Whether tests pass | `npm test`; do NOT pipe through `tail` (masks exit codes); a vitest failure gates the whole Playwright stage. || Model weights / assets missing | Stage them from `gs://three-ws-model-weights` or the worker README's source. Staging weights is part of deploying a worker, not a reason to stop. || Where a feature lives | `STRUCTURE.md` maps every surface to its directory. |-| How to deploy | API/frontend, from a CLEAN worktree (`git worktree add --detach /workspaces/.deploy-wt HEAD`, hardlink node_modules with `cp -al` on the same filesystem): run `npm run build:gcp` then `gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5`, then `npm run deploy:gcp:purge-cdn` (or the whole build+submit+purge in one: `npm run deploy:gcp:full`). ORDER IS LOAD-BEARING and `build:gcp` encodes it: the frontend `vite build` WIPES `dist/`, so it must run FIRST, then the UMD lib build, then `publish:lib` (which mirrors the lib into `dist/`), then `build:info`, then `check:dist`. Do NOT hand-run `build:vercel` as the frontend build — it builds the SDK/lib sub-artifacts, NOT the static HTML pages, so `dist/` ends up without `/`, `/create`, etc. and `check:dist` fails. `check:dist` needs the UMD bundle (publish:lib) present. GPU workers: their own `workers/<name>/cloudbuild.yaml`. EVERY cloudbuild config must pin `serviceAccount: …/three-ws-build@…` (default compute SA was deleted) and manual submits need `--substitutions=SHORT_SHA=manual$(date +%s)` when the config tags images with `$SHORT_SHA`. Verify the deploy landed: `curl -s https://three.ws/api/version` returns the live commit SHA + Cloud Run revision. |+| How to deploy | API/frontend, from a CLEAN worktree (`git worktree add --detach /workspaces/.deploy-wt HEAD`, hardlink node_modules with `cp -al` on the same filesystem): run `npm run build:gcp` then `gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5`, then `npm run deploy:gcp:purge-cdn` (or the whole build+submit+purge in one: `npm run deploy:gcp:full`). ORDER IS LOAD-BEARING and `build:gcp` encodes it: the frontend `vite build` WIPES `dist/`, so it must run FIRST, then the UMD lib build, then `publish:lib` (which mirrors the lib into `dist/`), then `build:info`, then `check:dist`, then `check:pages`. Do NOT hand-run `build:vercel` as the frontend build — it builds the SDK/lib sub-artifacts, NOT the static HTML pages, so `dist/` ends up without `/`, `/create`, etc. and `check:dist` fails. `check:dist` needs the UMD bundle (publish:lib) present. GPU workers: their own `workers/<name>/cloudbuild.yaml`. EVERY cloudbuild config must pin `serviceAccount: …/three-ws-build@…` (default compute SA was deleted) and manual submits need `--substitutions=SHORT_SHA=manual$(date +%s)` when the config tags images with `$SHORT_SHA`. Verify the deploy landed: `curl -s https://three.ws/api/version` returns the live commit SHA + Cloud Run revision, and `npm run smoke:prod` sweeps every page declared in `data/pages.json` against the live site (`deploy:gcp` runs it automatically after the purge). The CDN purge is synchronous on purpose — do not re-add `--async`, or post-deploy checks read stale edge content and report phantom failures. |The ONLY standing stop-and-ask gates (everything else: proceed, then report):1. Irreversible on-chain / spend actions (the gate below).diff --git a/api/_lib/aggregator.js b/api/_lib/aggregator.jsindex ccdab11a6..c6d20f110 100644--- a/api/_lib/aggregator.js+++ b/api/_lib/aggregator.js@@ -26,6 +26,24 @@ const MAX_UPSTREAM_ATTEMPTS = 3;const RETRYABLE_CODES = new Set(['upstream_rate_limited', 'upstream_unreachable']);const isRetryable = (err) => RETRYABLE_CODES.has(err?.code) || err?.status === 502;+// Short per-host memory of retryable failures. Without it, every request+// re-discovers a dead primary the hard way (worst case the full 20s timeout)+// before failing over; with it, only the first request of an outage pays that+// cost and the rest go straight to a healthy alternate. State is per-instance+// (each Cloud Run instance learns on its own), which is fine: the window is+// short and a wrong guess only reorders attempts, never removes them.+const HOST_COOLDOWN_MS = 30_000;+const _hostCooldowns = new Map(); // base URL -> epoch ms until the host is trusted again++const coolingDown = (base) => (_hostCooldowns.get(base) ?? 0) > Date.now();+const markBad = (base) => _hostCooldowns.set(base, Date.now() + HOST_COOLDOWN_MS);+const markGood = (base) => _hostCooldowns.delete(base);++/** Clear per-host failure memory. Exported for tests, which share module state. */+export function resetUpstreamHealth() {+ _hostCooldowns.clear();+}+// Alternate hosts for a provider, primary first, resolved lazily and only when// the primary has already failed — a provider like `solana` fronts a pool of// interchangeable RPC endpoints, and resolving that pool can be expensive@@ -86,62 +104,126 @@ export async function executeUpstream({ provider, endpoint, query = {}, body, ap// caller's query params. See the `solana` provider in api/v1/_providers.js.const upstreamMethod = endpoint.upstreamMethod || endpoint.method;- if (endpoint.method === 'GET' && endpoint.query) {- for (const [k, v] of Object.entries(endpoint.query(query))) {- if (v != null && v !== '') url.searchParams.set(k, String(v));+ // One attempt against one upstream host. Everything host-independent (the+ // query builder, the body builder) is re-run per attempt because applyKey may+ // write the key into the URL, which differs per host.+ const attempt = async (base) => {+ const url = new URL(base + path);++ if (endpoint.method === 'GET' && endpoint.query) {+ for (const [k, v] of Object.entries(endpoint.query(query))) {+ if (v != null && v !== '') url.searchParams.set(k, String(v));+ }}- }- const headers = { accept: 'application/json' };- let outBody;- if (upstreamMethod === 'POST') {- // A GET-caller/POST-upstream endpoint has no caller body to forward — its- // `body()` builder consumes the caller's query params instead.- outBody = endpoint.body ? endpoint.body(endpoint.method === 'GET' ? query : body) : body;- headers['content-type'] = 'application/json';- }- provider.applyKey(headers, url, apiKey);+ const headers = { accept: 'application/json' };+ let outBody;+ if (upstreamMethod === 'POST') {+ // A GET-caller/POST-upstream endpoint has no caller body to forward — its+ // `body()` builder consumes the caller's query params instead.+ outBody = endpoint.body ? endpoint.body(endpoint.method === 'GET' ? query : body) : body;+ headers['content-type'] = 'application/json';+ }+ provider.applyKey(headers, url, apiKey);- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), UPSTREAM_TIMEOUT_MS);- let res;- try {- res = await fetch(url, {- method: upstreamMethod,- headers,- body: outBody != null ? JSON.stringify(outBody) : undefined,- signal: controller.signal,- });- } catch (err) {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), UPSTREAM_TIMEOUT_MS);+ let res;+ try {+ res = await fetch(url, {+ method: upstreamMethod,+ headers,+ body: outBody != null ? JSON.stringify(outBody) : undefined,+ signal: controller.signal,+ });+ } catch (err) {+ clearTimeout(timer);+ const e = new Error(`${provider.name} is unreachable`);+ e.status = 504;+ e.code = 'upstream_unreachable';+ e.cause = err;+ throw e;+ }clearTimeout(timer);- const e = new Error(`${provider.name} is unreachable`);- e.status = 504;- e.code = 'upstream_unreachable';- e.cause = err;- throw e;- }- clearTimeout(timer);- const text = await res.text();- let data;- try {- data = text ? JSON.parse(text) : null;- } catch {- data = text;+ const text = await res.text();+ let data;+ try {+ data = text ? JSON.parse(text) : null;+ } catch {+ data = text;+ }++ if (!res.ok) {+ const e = new Error(+ `${provider.name} returned ${res.status} for ${endpoint.id}`,+ );+ // Map upstream 5xx to 502 (we're the proxy); pass client-fault 4xx through.+ e.status = res.status >= 500 ? 502 : res.status;+ e.code = res.status === 429 ? 'upstream_rate_limited' : 'upstream_error';+ e.detail = typeof data === 'object' ? data : { message: String(data).slice(0, 300) };+ throw e;+ }++ return endpoint.transform ? endpoint.transform(data) : data;+ };++ // A provider whose upstream is a pool of interchangeable hosts (Solana RPC)+ // should not hand the caller a 429 while a healthy alternate sits unused:+ // the free lane's rate-limit passthrough was the second-largest error class+ // on the aggregator. Providers with no alternates make exactly one attempt,+ // as before, so this costs a single-host provider nothing.+ //+ // The cooldown map feeds in here: a primary that failed a retryable way in+ // the last HOST_COOLDOWN_MS is skipped up front (only when alternates exist+ // to take its place), and alternates are tried freshest-first.+ const primaryCooling = coolingDown(provider.base) && typeof provider.bases === 'function';++ let firstErr;+ if (!primaryCooling) {+ try {+ const out = await attempt(provider.base);+ markGood(provider.base);+ return out;+ } catch (err) {+ if (!isRetryable(err)) throw err;+ markBad(provider.base);+ firstErr = err;+ }}- if (!res.ok) {- const e = new Error(- `${provider.name} returned ${res.status} for ${endpoint.id}`,- );- // Map upstream 5xx to 502 (we're the proxy); pass client-fault 4xx through.- e.status = res.status >= 500 ? 502 : res.status;- e.code = res.status === 429 ? 'upstream_rate_limited' : 'upstream_error';- e.detail = typeof data === 'object' ? data : { message: String(data).slice(0, 300) };- throw e;+ const alternates = await alternateBases(provider);+ if (!alternates.length) {+ if (firstErr) throw firstErr;+ // The primary was skipped for cooldown but the pool came back empty:+ // try it anyway rather than failing without a single attempt.+ const out = await attempt(provider.base);+ markGood(provider.base);+ return out;}- return endpoint.transform ? endpoint.transform(data) : data;+ // Healthy-looking alternates first, recently-failed ones after, and a+ // skipped primary last so pool exhaustion still gives it one chance.+ const ordered = [+ ...alternates.filter((b) => !coolingDown(b)),+ ...alternates.filter((b) => coolingDown(b)),+ ...(primaryCooling ? [provider.base] : []),+ ];++ let lastErr = firstErr ?? null;+ const budget = MAX_UPSTREAM_ATTEMPTS - (firstErr ? 1 : 0);+ for (const base of ordered.slice(0, budget)) {+ try {+ const out = await attempt(base);+ markGood(base);+ return out;+ } catch (next) {+ if (!isRetryable(next)) throw next;+ markBad(base);+ lastErr = next;+ }+ }+ throw lastErr;}// ── x402 pay-per-call path ────────────────────────────────────────────────────diff --git a/api/_lib/spatial-mcp.js b/api/_lib/spatial-mcp.jsindex acacfbaed..87dcd3817 100644--- a/api/_lib/spatial-mcp.js+++ b/api/_lib/spatial-mcp.js@@ -1,270 +1,19 @@-// Spatial MCP — the open shape for 3D-native tool results, and its validator.+// Spatial MCP — server-side entry point for the open 3D-native tool-result shape.//-// MCP tool results are text/JSON today. A *spatial* MCP artifact carries a live,-// interactive 3D scene as a first-class structured-content field so a host can-// render it (orbit, animate, AR) instead of printing a URL. This module is the-// single source of truth for that shape:+// The implementation moved to public/spatial-mcp/spatial-validator.js so ONE copy+// serves every consumer: this module, the reference renderer page that imports it+// as a sibling, and any third party importing it off the published URL+// (https://three.ws/spatial-mcp/spatial-validator.js). A spec's validator is only+// useful where the mistakes happen, which is a browser, and a second copy of a+// conformance gate is a conformance gate that drifts.//-// • buildSpatialArtifact(...) — assemble a conformant artifact from the-// fields a generation tool already has (glbUrl, kind, prompt, …).-// • validateSpatialArtifact(payload) — check conformance and return ACTIONABLE-// errors ({ path, message }), not a bare boolean. Used as the gate every-// three.ws 3D tool passes its artifact through, and callable by third-party-// servers adopting the shape.-//-// It is intentionally dependency-free (no Ajv, no fetch, no DB) so it loads-// unchanged in the Vercel api/ bundle, the published npm package, the free-// OpenAI studio, and the unit tests — and carries ZERO payment, wallet, coin, or-// token surface, so the renderer and validator drop cleanly into the crypto-free-// OpenAI app. Spec: specs/SPATIAL_MCP.md.--export const SPATIAL_MCP_VERSION = '0.1';--// Versions this validator accepts. New minor versions are added here as the-// shape evolves; a host reads spatialMcpVersion to pick its renderer.-const KNOWN_VERSIONS = new Set(['0.1']);--// The subject a 3D artifact describes. Open enum — a host that doesn't know a-// kind still renders scene.glbUrl; the kind only drives labelling/affordances.-const KNOWN_KINDS = new Set(['model', 'mesh', 'avatar', 'rigged-model', 'scene']);--const TOP_LEVEL_KEYS = new Set([- 'spatialMcpVersion',- 'kind',- 'scene',- 'camera',- 'environment',- 'animation',- 'persona',- 'ar',- 'affordances',- 'meta',-]);--// A conservative https check — the renderer only ever loads assets over https,-// and rejecting other schemes at the boundary keeps data: / javascript: / http-// out of a field a host will feed to <model-viewer src>.-function isHttpsUrl(v) {- if (typeof v !== 'string' || !v) return false;- try {- return new URL(v).protocol === 'https:';- } catch {- return false;- }-}--function isPlainObject(v) {- return v != null && typeof v === 'object' && !Array.isArray(v);-}--/**- * Assemble a spec-conformant spatial artifact from the fields a generation tool- * already has. Only `glbUrl` is required; everything else is optional and only- * emitted when provided, so the output is always valid and never carries empty- * scaffolding. Pure and deterministic.- *- * @param {object} a- * @param {string} a.glbUrl the generated asset (https)- * @param {string} [a.kind] one of KNOWN_KINDS (default 'model')- * @param {string} [a.viewerUrl] three.ws viewer link (meta)- * @param {string} [a.poster] preview image (https)- * @param {string} [a.prompt] the generating prompt (meta)- * @param {string} [a.title] human title (meta)- * @param {boolean}[a.autoRotate] camera auto-rotate (default true)- * @param {string} [a.cameraOrbit] model-viewer camera-orbit string- * @param {boolean}[a.rigged] true → animation hooks enabled- * @param {string[]}[a.clips] named animation clips- * @param {string} [a.personaId] persona binding (prompt 07)- * @param {{usdzUrl?:string,glbUrl?:string,launchUrl?:string}} [a.ar] AR handoff (prompt 21)- * @returns {object} a conformant spatial artifact- */-export function buildSpatialArtifact(a = {}) {- const kind = KNOWN_KINDS.has(a.kind) ? a.kind : 'model';- const artifact = {- spatialMcpVersion: SPATIAL_MCP_VERSION,- kind,- scene: {- glbUrl: a.glbUrl,- format: 'glb',- ...(a.poster ? { poster: a.poster } : {}),- ...(a.alt ? { alt: a.alt } : {}),- },- camera: {- autoRotate: a.autoRotate !== false,- ...(a.cameraOrbit ? { orbit: a.cameraOrbit } : {}),- },- environment: {- image: a.environmentImage || 'neutral',- exposure: typeof a.exposure === 'number' ? a.exposure : 1,- shadowIntensity: typeof a.shadowIntensity === 'number' ? a.shadowIntensity : 1,- },- affordances: {- orbit: true,- zoom: true,- fullscreen: true,- download: a.download !== false,- },- };-- // Animation hooks only when the asset is actually rigged/animated.- if (a.rigged || (Array.isArray(a.clips) && a.clips.length)) {- artifact.animation = {- autoplay: a.autoplay !== false,- ...(Array.isArray(a.clips) && a.clips.length ? { clips: a.clips.slice(0, 64) } : {}),- };- }-- // Persona hook (prompt 07) — a speakable embodied body.- if (a.personaId) {- artifact.persona = { id: String(a.personaId), speakable: true };- }-- // AR handoff (prompt 21). `supported` is true when any concrete AR asset/link- // is present; a host without AR ignores this block and renders the WebGL scene.- if (a.ar && isPlainObject(a.ar)) {- const ar = {};- if (isHttpsUrl(a.ar.usdzUrl)) ar.usdzUrl = a.ar.usdzUrl;- if (isHttpsUrl(a.ar.glbUrl)) ar.glbUrl = a.ar.glbUrl;- if (isHttpsUrl(a.ar.launchUrl)) ar.launchUrl = a.ar.launchUrl;- if (Object.keys(ar).length) {- ar.supported = true;- artifact.ar = ar;- }- }-- const meta = {};- if (a.prompt) meta.prompt = String(a.prompt);- if (a.title) meta.title = String(a.title);- if (isHttpsUrl(a.viewerUrl)) meta.viewerUrl = a.viewerUrl;- if (Object.keys(meta).length) artifact.meta = meta;-- return artifact;-}--// ── Validator ────────────────────────────────────────────────────────────────--function err(errors, path, message) {- errors.push({ path, message });-}-function warn(warnings, path, message) {- warnings.push({ path, message });-}--/**- * Validate a spatial artifact against the spec. Returns actionable diagnostics —- * every problem names the offending `path` and how to fix it — so a caller (a- * third-party server adopting the shape, or a three.ws tool's self-check) can- * correct its output, not just learn that it's wrong.- *- * @param {any} payload- * @returns {{ valid:boolean, version:(string|null), errors:Array<{path,message}>,- * warnings:Array<{path,message}> }}- */-export function validateSpatialArtifact(payload) {- const errors = [];- const warnings = [];-- if (!isPlainObject(payload)) {- return {- valid: false,- version: null,- errors: [{ path: '(root)', message: 'artifact must be a JSON object' }],- warnings,- };- }-- // Version.- const version = payload.spatialMcpVersion ?? null;- if (version == null) {- err(errors, 'spatialMcpVersion', `required — set it to "${SPATIAL_MCP_VERSION}"`);- } else if (typeof version !== 'string' || !KNOWN_VERSIONS.has(version)) {- err(errors, 'spatialMcpVersion', `unknown version ${JSON.stringify(version)} — supported: ${[...KNOWN_VERSIONS].join(', ')}`);- }-- // Kind.- if (payload.kind == null) {- err(errors, 'kind', `required — one of ${[...KNOWN_KINDS].join(', ')}`);- } else if (!KNOWN_KINDS.has(payload.kind)) {- err(errors, 'kind', `unknown kind ${JSON.stringify(payload.kind)} — expected one of ${[...KNOWN_KINDS].join(', ')}`);- }-- // Scene (required, with a required https glbUrl).- if (!isPlainObject(payload.scene)) {- err(errors, 'scene', 'required object with a `glbUrl`');- } else {- if (!isHttpsUrl(payload.scene.glbUrl)) {- err(errors, 'scene.glbUrl', 'required — must be an https URL to a .glb asset');- }- if (payload.scene.format !== undefined && payload.scene.format !== 'glb') {- err(errors, 'scene.format', 'only "glb" is supported in v0.1');- } else if (payload.scene.format === undefined) {- warn(warnings, 'scene.format', 'recommended — set to "glb"');- }- if (payload.scene.poster !== undefined && !isHttpsUrl(payload.scene.poster)) {- err(errors, 'scene.poster', 'must be an https URL when present');- }- }-- // Optional blocks — validate shape/types only when present.- if (payload.camera !== undefined) {- if (!isPlainObject(payload.camera)) err(errors, 'camera', 'must be an object when present');- else if (payload.camera.autoRotate !== undefined && typeof payload.camera.autoRotate !== 'boolean')- err(errors, 'camera.autoRotate', 'must be a boolean');- } else {- warn(warnings, 'camera', 'recommended — include `{ autoRotate: true }` so hosts frame the model');- }-- if (payload.environment !== undefined && !isPlainObject(payload.environment)) {- err(errors, 'environment', 'must be an object when present');- }-- if (payload.animation !== undefined) {- if (!isPlainObject(payload.animation)) err(errors, 'animation', 'must be an object when present');- else if (payload.animation.clips !== undefined && !Array.isArray(payload.animation.clips))- err(errors, 'animation.clips', 'must be an array of clip names');- }-- if (payload.persona !== undefined && !isPlainObject(payload.persona)) {- err(errors, 'persona', 'must be an object when present');- }-- if (payload.ar !== undefined) {- if (!isPlainObject(payload.ar)) {- err(errors, 'ar', 'must be an object when present');- } else {- for (const k of ['usdzUrl', 'glbUrl', 'launchUrl']) {- if (payload.ar[k] !== undefined && !isHttpsUrl(payload.ar[k]))- err(errors, `ar.${k}`, 'must be an https URL when present');- }- const hasAsset = ['usdzUrl', 'glbUrl', 'launchUrl'].some((k) => isHttpsUrl(payload.ar[k]));- if (payload.ar.supported === true && !hasAsset)- err(errors, 'ar.supported', 'true requires at least one of ar.usdzUrl / ar.glbUrl / ar.launchUrl');- }- }-- if (payload.affordances !== undefined && !isPlainObject(payload.affordances)) {- err(errors, 'affordances', 'must be an object when present');- }-- if (payload.meta !== undefined && !isPlainObject(payload.meta)) {- err(errors, 'meta', 'must be an object when present');- }-- // Unknown top-level keys are a warning, not an error — forward-compatibility- // with hosts that carry extra fields, but flagged so typos surface.- for (const key of Object.keys(payload)) {- if (!TOP_LEVEL_KEYS.has(key)) warn(warnings, key, 'unknown top-level field — ignored by conformant renderers');- }-- return {- valid: errors.length === 0,- version: typeof version === 'string' ? version : null,- errors,- warnings,- };-}--/** Convenience: true iff `payload` is a conformant artifact. */-export function isConformantSpatialArtifact(payload) {- return validateSpatialArtifact(payload).valid;-}+// This file stays the server-side import path because every three.ws 3D tool+// already uses it (api/_mcp3d/tools/{spatial,studio,ar}.js, api/_mcp-studio/tools.js).+// Nothing else changes: same named exports, same behavior. Spec: specs/SPATIAL_MCP.md.++export {+ SPATIAL_MCP_VERSION,+ buildSpatialArtifact,+ validateSpatialArtifact,+ isConformantSpatialArtifact,+} from '../../public/spatial-mcp/spatial-validator.js';diff --git a/api/_lib/x402/discovery-resources.js b/api/_lib/x402/discovery-resources.jsnew file mode 100644index 000000000..99a54aba3--- /dev/null+++ b/api/_lib/x402/discovery-resources.js@@ -0,0 +1,167 @@+// Facilitator-standard discovery catalog — the v1 wire format behind+// GET /api/x402-facilitator/discovery/resources.+//+// x402scan (and every crawler built on the x402 npm package) lists a+// facilitator's resources via useFacilitator(config).list(), which fetches+// `${facilitatorUrl}/discovery/resources?limit=&offset=` and expects the+// LEGACY v1 ListDiscoveryResourcesResponse:+//+// {+// x402Version: 1,+// items: [{ resource, type: 'http', x402Version: 1,+// accepts: [v1 PaymentRequirements], lastUpdated, metadata? }],+// pagination: { limit, offset, total }+// }+//+// v1 PaymentRequirements differ from the v2 accepts we serve everywhere else:+// the amount field is `maxAmountRequired` (not `amount`), and `network` is a+// friendly name from the legacy enum ('solana', 'base', …), not a CAIP-2 id.+// Reference: coinbase/x402 typescript/packages/legacy/x402/src/types/verify/+// x402Specs.ts (DiscoveredResourceSchema, PaymentRequirementsSchema) and+// shared/network.ts (NetworkSchema).+//+// The catalog itself comes from buildX402DiscoveryDoc() in api/wk.js — the+// same builder that renders /.well-known/x402.json — so the facilitator's+// discovery list can never drift from the platform's canonical catalog.++import { buildX402DiscoveryDoc } from '../../wk.js';+import {+ NETWORK_SOLANA_MAINNET,+ NETWORK_SOLANA_DEVNET,+ NETWORK_BASE_MAINNET,+ NETWORK_BASE_SEPOLIA,+} from '../x402-spec.js';++// CAIP-2 → legacy v1 network name. Only networks present in the legacy+// NetworkSchema enum may appear in a v1 accept; anything else (Arbitrum, BSC,+// X Layer) is dropped from this projection — those rails stay fully+// advertised in the v2 catalog and the live 402 challenge.+const V1_NETWORK_BY_CAIP2 = {+ [NETWORK_SOLANA_MAINNET]: 'solana',+ [NETWORK_SOLANA_DEVNET]: 'solana-devnet',+ [NETWORK_BASE_MAINNET]: 'base',+ [NETWORK_BASE_SEPOLIA]: 'base-sepolia',+ 'eip155:137': 'polygon',+ 'eip155:43114': 'avalanche',+};++export const DISCOVERY_DEFAULT_LIMIT = 100;+export const DISCOVERY_MAX_LIMIT = 500;++// One v2 catalog accept → one v1 PaymentRequirements, or null when the accept+// cannot be expressed in the legacy schema (non-exact scheme, unmapped+// network, missing money fields).+export function toV1Accept(accept, item) {+ if (!accept || accept.scheme !== 'exact') return null;+ const network = V1_NETWORK_BY_CAIP2[accept.network];+ if (!network) return null;+ const amount = accept.amount ?? accept.maxAmountRequired;+ if (amount == null || !/^\d+$/.test(String(amount))) return null;+ if (!accept.payTo || !accept.asset) return null;+ const out = {+ scheme: 'exact',+ network,+ maxAmountRequired: String(amount),+ resource: accept.resource || item.url,+ description: item.description || '',+ mimeType: item.mimeType || 'application/json',+ payTo: accept.payTo,+ maxTimeoutSeconds: Number.isInteger(accept.maxTimeoutSeconds)+ ? accept.maxTimeoutSeconds+ : 60,+ asset: accept.asset,+ };+ if (accept.extra && typeof accept.extra === 'object') out.extra = accept.extra;+ if (item.outputSchema && typeof item.outputSchema === 'object') {+ out.outputSchema = item.outputSchema;+ }+ return out;+}++// One catalog resource entry → one v1 DiscoveredResource, or null when no+// accept survives the projection (e.g. an EVM-only entry on a rail the legacy+// schema doesn't name).+export function toV1Item(item, lastUpdated) {+ if (!item || !item.url) return null;+ const accepts = (Array.isArray(item.accepts) ? item.accepts : [])+ .map((a) => toV1Accept(a, item))+ .filter(Boolean);+ if (accepts.length === 0) return null;+ const metadata = {};+ for (const key of ['serviceName', 'tags', 'iconUrl', 'method', 'path', 'toolName']) {+ if (item[key] != null) metadata[key] = item[key];+ }+ return {+ resource: item.url,+ type: 'http',+ x402Version: 1,+ accepts,+ lastUpdated,+ ...(Object.keys(metadata).length > 0 ? { metadata } : {}),+ };+}++// Full catalog → one v1 response page. `lastUpdated` defaults to now; the+// cached path passes the catalog build time so a pagination sweep sees one+// consistent timestamp.+export function projectDiscoveryResources(doc, { type, limit, offset, lastUpdated } = {}) {+ if (!lastUpdated) lastUpdated = new Date().toISOString();+ const wantLimit = Math.min(+ Math.max(1, Number.parseInt(limit, 10) || DISCOVERY_DEFAULT_LIMIT),+ DISCOVERY_MAX_LIMIT,+ );+ const wantOffset = Math.max(0, Number.parseInt(offset, 10) || 0);+ // Every resource we publish is HTTP; a filter for anything else is an+ // honest empty page, not an error.+ const items =+ type && type !== 'http'+ ? []+ : (Array.isArray(doc?.resources) ? doc.resources : [])+ .map((r) => toV1Item(r, lastUpdated))+ .filter(Boolean);+ return {+ x402Version: 1,+ items: items.slice(wantOffset, wantOffset + wantLimit),+ pagination: { limit: wantLimit, offset: wantOffset, total: items.length },+ };+}++// The full catalog build walks the DB and several cached feeds, and a crawler+// pages through it ~50 requests at a time — memoize the built doc briefly+// (same 300 s freshness as the /.well-known/x402.json CDN TTL) so a+// pagination sweep costs one build. A failed rebuild serves the last good doc+// rather than 500ing the crawler mid-sweep.+const DOC_TTL_MS = 300_000;+let docCache = { at: 0, doc: null, inflight: null };++async function getDiscoveryDoc() {+ const now = Date.now();+ if (docCache.doc && now - docCache.at < DOC_TTL_MS) return docCache.doc;+ if (!docCache.inflight) {+ docCache.inflight = buildX402DiscoveryDoc()+ .then((doc) => {+ docCache = { at: Date.now(), doc, inflight: null };+ return doc;+ })+ .catch((err) => {+ docCache.inflight = null;+ if (docCache.doc) {+ console.error(+ '[x402-discovery] catalog rebuild failed, serving stale doc',+ err?.message || err,+ );+ return docCache.doc;+ }+ throw err;+ });+ }+ return docCache.inflight;+}++export async function listDiscoveryResources(query = {}) {+ const doc = await getDiscoveryDoc();+ return projectDiscoveryResources(doc, {+ ...query,+ lastUpdated: docCache.at ? new Date(docCache.at).toISOString() : undefined,+ });+}diff --git a/api/v1/README.md b/api/v1/README.mdindex 8f4ffd0e1..69867f145 100644--- a/api/v1/README.md+++ b/api/v1/README.md@@ -65,6 +65,7 @@ zero other edits.name: 'CoinGecko', // human labelcategory: 'crypto-market-data', // grouping for discoverybase: 'https://api.coingecko.com/api/v3', // upstream base URL, no trailing slash+ bases: async () => [...], // OPTIONAL: interchangeable alternate hosts (see below)requiresKey: false, // true when the upstream needs a key to function at allenvVar: 'COINGECKO_API_KEY', // env var holding three.ws's own platform key (or null)byokHeader: 'x-provider-key', // header a caller uses to supply THEIR OWN key (or null)@@ -90,6 +91,21 @@ Full field-by-field contract, including `upstreamMethod` (for a caller-facing GEan upstream POST, e.g. Solana's single JSON-RPC endpoint) and `body`, is documented inline atthe top of [`_providers.js`](_providers.js) — read it before adding a descriptor.+### `bases` — upstream failover++Set `bases` only when the provider fronts a **pool of interchangeable hosts** that answer the+same requests, the way `solana` fronts the platform's RPC pool. It is an async function+returning a priority-ordered list of base URLs.++When it is set, a retryable failure on `base` (HTTP 429, an upstream 5xx, or an unreachable+host) moves the call to the next host instead of surfacing to the caller; a 4xx other than 429+is the caller's own mistake and is never retried. At most three hosts are tried per call, and a+host that just failed is skipped for 30 seconds so only the first request of an outage pays the+discovery cost. A provider without `bases` makes exactly one attempt, as it always did.++Do **not** use it to point at a different upstream vendor: a fallback host must return the same+response shape, because the endpoint's `transform()` runs on whatever answers.+### Adding a provider or endpoint1. Add a descriptor (or a new `endpoints` entry on an existing one) to `PROVIDERS` indiff --git a/api/v1/_providers.js b/api/v1/_providers.jsindex bd7d9e77f..20cfe712a 100644--- a/api/v1/_providers.js+++ b/api/v1/_providers.js@@ -870,6 +870,15 @@ export const PROVIDERS = [// (api/_lib/env.js) — a configured Helius/Quicknode/Triton URL, or the// public mainnet endpoint as a working fallback.base: SOLANA_RPC_BASE,+ // The platform's full priority-ordered RPC pool (operator endpoint,+ // QuickNode, Helius, Alchemy, then public hosts), used by the aggregator+ // only after the primary answers 429/5xx — a public RPC rate-limiting us+ // is not a reason to fail a caller when six healthy alternates exist.+ // Imported lazily so the happy path never loads @solana/web3.js.+ bases: async () => {+ const { solanaRpcEndpoints } = await import('../_lib/solana/connection.js');+ return solanaRpcEndpoints('mainnet');+ },requiresKey: false,envVar: null,byokHeader: null,diff --git a/api/wk.js b/api/wk.jsindex a1cf665d0..ef9556ede 100644--- a/api/wk.js+++ b/api/wk.js@@ -1512,7 +1512,12 @@ function addOutputExample(r) {return r;}-async function handleX402Discovery(req, res) {+// Builds the full x402 discovery document served at /.well-known/x402.json.+// Exported so the self-facilitator's GET /discovery/resources action+// (api/x402-facilitator/[action].js) can project the same catalog into the+// facilitator-standard ListDiscoveryResourcesResponse consumed by x402scan's+// crawler — one catalog, two wire formats, no drift.+export async function buildX402DiscoveryDoc() {const origin = env.APP_ORIGIN;const mcpUrl = `${origin}/api/mcp`;const mcp3dUrl = `${origin}/api/mcp-3d`;@@ -1709,112 +1714,113 @@ async function handleX402Discovery(req, res) {const agentServiceItems = await buildAgentServiceItems(origin);const datapointItems = await buildDatapointItems(origin);- return json(- res,- 200,- {- $schema: 'https://x402.org/schemas/discovery.json',- service: {- name: 'three.ws',- legal_name: 'three.ws',- tagline: '3D generation + crypto data + launch/trust tools for AI agents.',+ return {+ $schema: 'https://x402.org/schemas/discovery.json',+ service: {+ name: 'three.ws',+ legal_name: 'three.ws',+ tagline: '3D generation + crypto data + launch/trust tools for AI agents.',+ description:+ 'three.ws — 3D generation + crypto data + launch/trust tools for AI agents. ' ++ 'Free Crypto Data API (token snapshots, security checks, holders, whales, trending, wallets — keyless) and free text→3D generation; ' ++ 'pay-per-call for Forge Pro, rigged avatars, vanity addresses, pump.fun token launches, and cross-chain trust checks (agent reputation, on-chain identity verify). ' ++ 'Reachable as paid REST endpoints (x402 v2) and MCP tool calls. USDC on Solana, Base, and Arbitrum mainnet.',+ operator: 'three.ws',+ mission:+ 'Give autonomous agents the tools they reach for mid-task — 3D assets, crypto data, launches, and trust — machine-native over HTTP 402.',+ website: origin,+ docs: `${origin}/docs/start-here`,+ repository: 'https://github.com/nirholas/three.ws',+ contact: `${origin}/`,+ tags: [+ 'x402',+ 'x402-v2',+ 'mcp',+ 'agent-first',+ '3d',+ 'text-to-3d',+ 'crypto-data',+ 'trust',+ 'token-launch',+ 'solana',+ 'base',+ 'arbitrum',+ 'usdc',+ ],+ categories: ['3D', 'AI', 'Crypto', 'Data', 'Utility'],+ environment: 'apex',+ origin,+ },+ // `.filter(Boolean)` drops any resource whose IIFE returned null —+ // e.g. permit2-paid-demo is omitted when CDP creds are missing,+ // matching the runtime 402 behavior so we don't catalog a route that+ // would fail at first paid call. The trailing .map(addOutputExample)+ // backfills a realistic response example onto every entry so indexers+ // render and rank each one (no empty result cards, no verifier warnings).+ resources: [+ {+ path: '/api/mcp',+ url: mcpUrl,+ method: 'POST',description:- 'three.ws — 3D generation + crypto data + launch/trust tools for AI agents. ' +- 'Free Crypto Data API (token snapshots, security checks, holders, whales, trending, wallets — keyless) and free text→3D generation; ' +- 'pay-per-call for Forge Pro, rigged avatars, vanity addresses, pump.fun token launches, and cross-chain trust checks (agent reputation, on-chain identity verify). ' +- 'Reachable as paid REST endpoints (x402 v2) and MCP tool calls. USDC on Solana, Base, and Arbitrum mainnet.',- operator: 'three.ws',- mission:- 'Give autonomous agents the tools they reach for mid-task — 3D assets, crypto data, launches, and trust — machine-native over HTTP 402.',- website: origin,- docs: `${origin}/docs/start-here`,- repository: 'https://github.com/nirholas/three.ws',- contact: `${origin}/`,- tags: [- 'x402',- 'x402-v2',- 'mcp',- 'agent-first',- '3d',- 'text-to-3d',- 'crypto-data',- 'trust',- 'token-launch',- 'solana',- 'base',- 'arbitrum',- 'usdc',- ],- categories: ['3D', 'AI', 'Crypto', 'Data', 'Utility'],- environment: 'apex',- origin,- },- // `.filter(Boolean)` drops any resource whose IIFE returned null —- // e.g. permit2-paid-demo is omitted when CDP creds are missing,- // matching the runtime 402 behavior so we don't catalog a route that- // would fail at first paid call. The trailing .map(addOutputExample)- // backfills a realistic response example onto every entry so indexers- // render and rank each one (no empty result cards, no verifier warnings).- resources: [- {- path: '/api/mcp',- url: mcpUrl,- method: 'POST',- description:- 'MCP 2025-06-18 Streamable HTTP transport — 3D avatar viewer, glTF model validation/inspection/optimization, and Solana agent data exposed as MCP tools. JSON-RPC 2.0 batch-aware. Currency: USDC.',- mimeType: 'application/json',- serviceName: mcpService.serviceName,- tags: mcpService.tags,- iconUrl: mcpService.iconUrl,- accepts: mcpAccepts,- extensions: extensionsForAccepts(mcpAccepts, bazaarExtension()),- links: {- openapi: `${origin}/openapi.json`,- docs: `${origin}/docs/mcp`,- agent_card: `${origin}/.well-known/agent-card.json`,- payment_config: `${origin}/.well-known/x402`,- },+ 'MCP 2025-06-18 Streamable HTTP transport — 3D avatar viewer, glTF model validation/inspection/optimization, and Solana agent data exposed as MCP tools. JSON-RPC 2.0 batch-aware. Currency: USDC.',+ mimeType: 'application/json',+ serviceName: mcpService.serviceName,+ tags: mcpService.tags,+ iconUrl: mcpService.iconUrl,+ accepts: mcpAccepts,+ extensions: extensionsForAccepts(mcpAccepts, bazaarExtension()),+ links: {+ openapi: `${origin}/openapi.json`,+ docs: `${origin}/docs/mcp`,+ agent_card: `${origin}/.well-known/agent-card.json`,+ payment_config: `${origin}/.well-known/x402`,},- {- path: '/api/mcp-3d',- url: mcp3dUrl,- method: 'POST',- description: STUDIO_CHALLENGE.description,- mimeType: 'application/json',- serviceName: STUDIO_CHALLENGE.serviceName,- tags: STUDIO_CHALLENGE.tags,- iconUrl: STUDIO_CHALLENGE.iconUrl,- accepts: mcp3dAccepts,- extensions: extensionsForAccepts(mcp3dAccepts, STUDIO_CHALLENGE.bazaar),- links: {- docs: `${origin}/docs/mcp-3d-studio`,- payment_config: `${origin}/.well-known/x402`,- },+ },+ {+ path: '/api/mcp-3d',+ url: mcp3dUrl,+ method: 'POST',+ description: STUDIO_CHALLENGE.description,+ mimeType: 'application/json',+ serviceName: STUDIO_CHALLENGE.serviceName,+ tags: STUDIO_CHALLENGE.tags,+ iconUrl: STUDIO_CHALLENGE.iconUrl,+ accepts: mcp3dAccepts,+ extensions: extensionsForAccepts(mcp3dAccepts, STUDIO_CHALLENGE.bazaar),+ links: {+ docs: `${origin}/docs/mcp-3d-studio`,+ payment_config: `${origin}/.well-known/x402`,},- // Every static /api/x402/* entry (model-check through wallet-connect),- // generated from the unified service catalog in catalog order. Editing- // a listing = editing api/_lib/service-catalog/services/<slug>.js.- ...x402CatalogItems,- // USE-13: one Bazaar catalog row per priced MCP tool. The shared- // `/api/mcp` and `/api/mcp-3d` resources above are the transport- // entries; these are the individual paid tools facilitators- // index by toolName.- ...mcpToolItems,- ...studioToolItems,- // Agent-published paid endpoints (monetize_endpoint). Dynamic —- // one entry per active agent_paid_services listing.- ...agentServiceItems,- // Datapoint fabric (/api/x402/d/…): a curated, runtime-derived- // slice of the 400k+ addressable single-datapoint endpoints, so- // indexers surface the fabric; the full id space is enumerated- // free at /api/x402/d.- ...datapointItems,- ]- .filter(Boolean)- .map(addOutputExample),- },- { 'cache-control': 'public, max-age=300' },- );+ },+ // Every static /api/x402/* entry (model-check through wallet-connect),+ // generated from the unified service catalog in catalog order. Editing+ // a listing = editing api/_lib/service-catalog/services/<slug>.js.+ ...x402CatalogItems,+ // USE-13: one Bazaar catalog row per priced MCP tool. The shared+ // `/api/mcp` and `/api/mcp-3d` resources above are the transport+ // entries; these are the individual paid tools facilitators+ // index by toolName.+ ...mcpToolItems,+ ...studioToolItems,+ // Agent-published paid endpoints (monetize_endpoint). Dynamic —+ // one entry per active agent_paid_services listing.+ ...agentServiceItems,+ // Datapoint fabric (/api/x402/d/…): a curated, runtime-derived+ // slice of the 400k+ addressable single-datapoint endpoints, so+ // indexers surface the fabric; the full id space is enumerated+ // free at /api/x402/d.+ ...datapointItems,+ ]+ .filter(Boolean)+ .map(addOutputExample),+ };+}++async function handleX402Discovery(req, res) {+ return json(res, 200, await buildX402DiscoveryDoc(), {+ 'cache-control': 'public, max-age=300',+ });}// ── dispatcher ────────────────────────────────────────────────────────────────diff --git a/api/x402-facilitator/[action].js b/api/x402-facilitator/[action].jsindex 4f1f7e6ed..76e7275c7 100644--- a/api/x402-facilitator/[action].js+++ b/api/x402-facilitator/[action].js@@ -30,6 +30,7 @@ import {verifyRingPayment,settleRingPayment,} from '../_lib/x402/self-facilitator.js';+import { listDiscoveryResources } from '../_lib/x402/discovery-resources.js';function actionFrom(req) {const q = req.query?.action;@@ -105,11 +106,29 @@ export default wrap(async (req, res) => {supported: { method: 'GET', path: `${base}/supported` },verify: { method: 'POST', path: `${base}/verify` },settle: { method: 'POST', path: `${base}/settle` },+ discovery: { method: 'GET', path: `${base}/discovery/resources` },},docs: 'https://three.ws/docs/x402-ring-economy',});}+ // GET /discovery/resources — the facilitator-standard catalog list that+ // x402scan's crawler (useFacilitator().list()) pages through when this+ // facilitator's registry entry carries a discoveryConfig. Serves the same+ // canonical catalog as /.well-known/x402.json, projected to the legacy v1+ // wire format the crawler validates. Public read, no payment. The route+ // table maps the two-segment path to action=discovery-resources; the bare+ // last-segment fallback in actionFrom() yields 'resources'.+ if (action === 'discovery-resources' || action === 'resources') {+ if (!method(req, res, ['GET'])) return;+ const list = await listDiscoveryResources({+ type: req.query?.type,+ limit: req.query?.limit,+ offset: req.query?.offset,+ });+ return json(res, 200, list, { 'cache-control': 'public, max-age=300' });+ }+// /supported is a public capability probe (no payment, no secret needed) so// api/x402-status.js probeFacilitators() can confirm we advertise exact/solana.if (action === 'supported') {diff --git a/data/changelog.json b/data/changelog.jsonindex 64ccbdff6..18b34e512 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,26 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-07-25",+ "title": "Our x402 facilitator now publishes a standard discovery catalog",+ "summary": "The three.ws self-hosted x402 facilitator serves a new public endpoint, GET /api/x402-facilitator/discovery/resources, listing every paid endpoint on the platform in the standard facilitator catalog format that x402 explorers and aggregators (like x402scan) crawl. It is the same catalog as /.well-known/x402.json, so listings on third-party explorers always match what the platform actually charges. This is groundwork for three.ws payments showing up on ecosystem explorers without routing settlement through any third party.",+ "tags": [+ "feature",+ "infra"+ ],+ "link": "/docs/x402-ring-economy"+ },+ {+ "date": "2026-07-25",+ "title": "Solana reads on the crypto API stop failing when one RPC host throttles us",+ "summary": "The Solana endpoints on the public crypto API (balance, token holdings, token supply, largest holders, transaction, account, priority fees) were pointed at a single RPC host. Whenever that host rate-limited us, the caller got the rate-limit error even though the platform keeps a priority-ordered pool of other RPC endpoints for exactly this situation. Those calls now move to the next healthy host automatically, up to three per request, and a host that has just failed is skipped for the next 30 seconds so one bad host does not slow down every request behind it. A genuinely bad request, like a malformed address, still returns its error immediately instead of being retried. This was the second-largest error class on the API.",+ "tags": [+ "fix",+ "improvement"+ ],+ "link": "/crypto-api"+ },{"date": "2026-07-25","title": "Our crypto API no longer reports itself as broken to the directories that rate it",@@ -15758,6 +15778,16 @@"feature","infra"]+ },+ {+ "date": "2026-07-25",+ "title": "Crypto API: automatic upstream failover ends most rate-limit errors",+ "summary": "The unified crypto API (/api/v1/x) no longer fails your call just because one upstream host had a bad moment. When a provider is backed by a pool of interchangeable hosts (the Solana read endpoints front the platform's full RPC pool), a rate-limited, unreachable, or erroring host now fails over to a healthy alternate within the same request. The API also remembers which host just failed for a short window, so during an outage only the first request pays the discovery cost and everything after routes straight to a working host. Rate-limit passthrough was the second-largest error class on the aggregator; this removes it for pooled providers.",+ "tags": [+ "improvement",+ "infra"+ ],+ "link": "/crypto-api"}]}diff --git a/docs/api-reference.md b/docs/api-reference.mdindex 91750e59c..64cffaf71 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -3321,6 +3321,16 @@ Each call resolves to one of four billing lanes, in this order:| **plan** | authenticate with a three.ws API key / OAuth token / session | uses the platform's upstream key, counts against your plan || **x402** | send no credentials, no free quota left | pay per call in USDC — the standard HTTP 402 challenge |+**Upstream failover (automatic, all lanes).** A provider backed by a pool of+interchangeable hosts declares them in its descriptor (`bases`), and the+aggregator walks that pool inside a single request when a host answers 429, a+5xx, or is unreachable (up to 3 hosts per call; caller-fault 4xx never+retries). A host that just failed is skipped for a short cooldown window while+an alternate exists, so an upstream outage costs one discovery, not one per+request. The `solana` provider fronts the platform's full priority-ordered RPC+pool this way; single-host providers behave as plain pass-throughs with one+attempt.+### The free tierThis is what makes "free crypto API" true instead of marketing copy: an agentdiff --git a/docs/ops/gcp-production.md b/docs/ops/gcp-production.mdindex b3360cc8a..7119bf1a2 100644--- a/docs/ops/gcp-production.md+++ b/docs/ops/gcp-production.md@@ -116,7 +116,8 @@ deploys from a human-authed CLI (command below).```bash# Frontend changed? Build first — dist/ ships from the local build.# build:gcp = site build -> agent-3d CDN lib (build:lib:full) -> publish:lib-# -> build:info -> check:dist, IN THAT ORDER. The order is load-bearing: the+# -> build:info -> check:dist -> check:pages, IN THAT ORDER. The order is+# load-bearing: the# site `vite build` WIPES dist/, so it must run before publish:lib mirrors the# lib into dist/. Plain `npm run build` is NOT enough (skips the lib publish, so# /agent-3d/latest/agent-3d.js 404s and the hero avatar dies). Hand-running@@ -125,8 +126,9 @@ deploys from a human-authed CLI (command below).npm run build:gcp# Build image on Cloud Build (32-vCPU + BuildKit layer cache) + push + deploy.-# Gated on check:dist AND db:check so an incomplete dist/ or an out-of-date-# database can no longer ship.+# Gated on check:dist, check:pages AND db:check so an incomplete dist/, an+# unreachable page, or an out-of-date database can no longer ship. Ends with a+# CDN purge and then smoke:prod against the live site.npm run deploy:gcp# Or do build + submit + CDN purge in one (from a clean worktree):@@ -135,8 +137,18 @@ npm run deploy:gcp# Verify the deploy actually landed — /api/version reports the live commit SHA# and Cloud Run revision (stamped into dist/build-info.json by build:info):curl -s https://three.ws/api/version | jq '{commitShort, branch, builtAt, revision: .runtime.revision}'++# Sweep every page declared in data/pages.json against the live site. deploy:gcp+# runs this automatically after the purge; run it standalone any time.+npm run smoke:prod```+> **The CDN purge is synchronous on purpose.** `deploy:gcp:purge-cdn` used to+> pass `--async`, so anything verifying immediately afterwards read stale edge+> content and reported phantom failures — a cached pre-deploy 404 for a page+> that the new revision serves fine. Dropping `--async` costs ~3 s and makes+> every post-deploy check trustworthy. Do not add it back.+> **Never bypass `check:dist` by calling `gcloud builds submit` directly.** It is> the only thing standing between a half-built `dist/` and production. When it> reports `MISSING: dist/agent-3d/latest/agent-3d.js`, that is not a stale or@@ -148,6 +160,19 @@ curl -s https://three.ws/api/version | jq '{commitShort, branch, builtAt, revisi> This happened on 2026-07-09 (revision `three-ws-api-00034`), where the check> was overridden on the assumption its failure was unrelated to the change.+> **`check:pages` guards a different failure: a page that ships unreachable.**+> Every entry in `data/pages.json` feeds the sitemap, `llms.txt` and+> `features.json`, so it is advertised to crawlers the moment it lands, whether+> or not anything can serve it. `server/index.mjs`'s `resolveStatic()` has no+> `.html` extension fallback by design, so a page built to `dist/<slug>.html`+> is a hard 404 at `/<slug>` unless `vercel.json` carries a rewrite. That+> shipped twice in three days: `/timeline` (fixed by `5688277bd`, "page shipped+> without a route entry") and `/tracker` (advertised 2026-07-23, 404 until a+> route landed two days later). `check:pages` resolves all ~424 declared paths+> through the real route table and fails the build on any that dead-end. When it+> fires it tells you which of the two causes applies: a missing `vercel.json`+> rewrite, or a page that was never built (missing `vite.config.js` input entry).+**Database migrations** live in `api/_lib/migrations/*.sql` and are tracked inthe `schema_migrations` table (filename + sha256). Nothing applies themautomatically — the flow is:diff --git a/docs/x402-ring-economy.md b/docs/x402-ring-economy.mdindex f60a72daa..042f448d3 100644--- a/docs/x402-ring-economy.md+++ b/docs/x402-ring-economy.md@@ -177,6 +177,14 @@ then kept in a verified, watched, auto-fundable state:the sponsor" attack **and** enforces "only our wallets settle here".- **SOL floor.** Below `X402_SPONSOR_SOL_FLOOR_LAMPORTS` (default 0.02 SOL) thefacilitator refuses to settle, pausing the loop before it can drain your SOL.+ - **Discovery catalog.** `GET /api/x402-facilitator/discovery/resources` serves+ the facilitator-standard resource list (`?limit=&offset=`, the+ `ListDiscoveryResourcesResponse` shape crawled by x402scan and every client+ built on the x402 npm package's `useFacilitator().list()`). It projects the+ same canonical catalog as `/.well-known/x402.json` into the legacy v1 wire+ format, so explorers indexing this facilitator list our paid endpoints+ automatically. Projection lives in+ [api/_lib/x402/discovery-resources.js](../api/_lib/x402/discovery-resources.js).- **Ring settlement endpoint** — [api/x402/ring-settle.js](../api/x402/ring-settle.js).Price-configurable (`X402_PRICE_RING_SETTLE`), internal (`discoverable:false`),returns a real economic-tick receipt.diff --git a/package.json b/package.jsonindex 92890ed91..512509a1a 100644--- a/package.json+++ b/package.json@@ -219,14 +219,16 @@"lint": "eslint .","lint:fix": "eslint . --fix","check:dist": "node scripts/check-dist.mjs",+ "check:pages": "node scripts/check-pages.mjs",+ "smoke:prod": "node scripts/check-pages.mjs --base https://three.ws","deploy": "npm run build:all && npm run check:dist && vercel --local-config vercel.json --prod","build:info": "node scripts/write-build-info.mjs","build:info:snapshot": "node scripts/write-build-info.mjs --snapshot",- "build:gcp": "npm run ensure:avatar-studio && npm run build:info:snapshot && npm run build && npm run build:lib:full && npm run publish:lib && npm run build:info && npm run check:dist",+ "build:gcp": "npm run ensure:avatar-studio && npm run build:info:snapshot && npm run build && npm run build:lib:full && npm run publish:lib && npm run build:info && npm run check:dist && npm run check:pages","ensure:avatar-studio": "test -f character-studio/build/index.html || npm run build:avatar-studio",- "deploy:gcp": "npm run check:dist && npm run db:check && gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5 && npm run deploy:gcp:purge-cdn",+ "deploy:gcp": "npm run check:dist && npm run check:pages && npm run db:check && gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5 && npm run deploy:gcp:purge-cdn && npm run smoke:prod","deploy:gcp:full": "npm run build:gcp && npm run deploy:gcp",- "deploy:gcp:purge-cdn": "gcloud compute url-maps invalidate-cdn-cache three-ws-lb --path '/*' --project aerial-vehicle-466722-p5 --async",+ "deploy:gcp:purge-cdn": "gcloud compute url-maps invalidate-cdn-cache three-ws-lb --path '/*' --project aerial-vehicle-466722-p5","postversion": "git push threews HEAD && git push threews --tags","validate:cards": "node scripts/validate-agent-cards.mjs","db:bootstrap": "node scripts/db-bootstrap.mjs",diff --git a/public/agent-edit/index.html b/public/agent-edit/index.htmlindex b85e0dd35..29d60e897 100644--- a/public/agent-edit/index.html+++ b/public/agent-edit/index.html@@ -693,7 +693,9 @@<div class="toast" id="toast"></div>- <script type="module" src="./edit.js"></script>+ <!-- Absolute: this page is served at /agent-edit as well as /agent-edit/, and a+ relative src resolves against the site root on the slash-less URL (404). -->+ <script type="module" src="/agent-edit/edit.js"></script><script src="/brand.js" defer></script><!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. --><script type="module" src="/i18n.js"></script>diff --git a/public/changelog.json b/public/changelog.jsonindex b7c1ac3e0..f96d598d2 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-25T09:58:05.519Z",+ "generated_at": "2026-07-25T10:10:06.549Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -46,6 +46,17 @@"launch"]},+ {+ "date": "2026-07-25",+ "type": "update",+ "title": "Crypto API: automatic upstream failover ends most rate-limit errors",+ "summary": "The unified crypto API (/api/v1/x) no longer fails your call just because one upstream host had a bad moment. When a provider is backed by a pool of interchangeable hosts (the Solana read endpoints front the platform's full RPC pool), a rate-limited, unreachable, or erroring host now fails over to a healthy alternate within the same request. The API also remembers which host just failed for a short window, so during an outage only the first request pays the discovery cost and everything after routes straight to a working host. Rate-limit passthrough was the second-largest error class on the aggregator; this removes it for pooled providers.",+ "link": "/crypto-api",+ "tags": [+ "improvement",+ "infra"+ ]+ },{"date": "2026-07-25","type": "update",@@ -67,6 +78,17 @@"improvement"]},+ {+ "date": "2026-07-25",+ "type": "update",+ "title": "Our x402 facilitator now publishes a standard discovery catalog",+ "summary": "The three.ws self-hosted x402 facilitator serves a new public endpoint, GET /api/x402-facilitator/discovery/resources, listing every paid endpoint on the platform in the standard facilitator catalog format that x402 explorers and aggregators (like x402scan) crawl. It is the same catalog as /.well-known/x402.json, so listings on third-party explorers always match what the platform actually charges. This is groundwork for three.ws payments showing up on ecosystem explorers without routing settlement through any third party.",+ "link": "/docs/x402-ring-economy",+ "tags": [+ "feature",+ "infra"+ ]+ },{"date": "2026-07-25","type": "update",@@ -78,6 +100,17 @@"fix"]},+ {+ "date": "2026-07-25",+ "type": "update",+ "title": "Solana reads on the crypto API stop failing when one RPC host throttles us",+ "summary": "The Solana endpoints on the public crypto API (balance, token holdings, token supply, largest holders, transaction, account, priority fees) were pointed at a single RPC host. Whenever that host rate-limited us, the caller got the rate-limit error even though the platform keeps a priority-ordered pool of other RPC endpoints for exactly this situation. Those calls now move to the next healthy host automatically, up to three per request, and a host that has just failed is skipped for the next 30 seconds so one bad host does not slow down every request behind it. A genuinely bad request, like a malformed address, still returns its error immediately instead of being retried. This was the second-largest error class on the API.",+ "link": "/crypto-api",+ "tags": [+ "fix",+ "improvement"+ ]+ },{"date": "2026-07-25","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 7fd65a8bc..2753db85f 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -38,6 +38,14 @@<category>launch</category><description>three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.</description></item>+ <item>+ <title>Crypto API: automatic upstream failover ends most rate-limit errors</title>+ <link>https://three.ws/crypto-api</link>+ <guid isPermaLink="false">2026-07-25:Crypto API: automatic upstream failover ends most rate-limit errors</guid>+ <pubDate>Sat, 25 Jul 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>The unified crypto API (/api/v1/x) no longer fails your call just because one upstream host had a bad moment. When a provider is backed by a pool of interchangeable hosts (the Solana read endpoints front the platform's full RPC pool), a rate-limited, unreachable, or erroring host now fails over to a healthy alternate within the same request. The API also remembers which host just failed for a short window, so during an outage only the first request pays the discovery cost and everything after routes straight to a working host. Rate-limit passthrough was the second-largest error class on the aggregator; this removes it for pooled providers.</description>+ </item><item><title>Dress any avatar: the wardrobe now adds clothes, not just recolours them</title><link>https://three.ws/avatar-edit</link>@@ -54,6 +62,14 @@<category>fix</category><description>Agent directories and uptime monitors discover an x402 API by calling every endpoint it advertises with no arguments, to check the endpoint is alive and knows its own price. Our paid-only endpoints answered that correctly with a payment challenge, but the free-tier ones ran argument validation first and answered with an error, so about two dozen perfectly healthy endpoints were being graded as failing by a public trust monitor, roughly 14,000 times a month. A parameterless call now returns the standard 402 challenge on every endpoint, with the argument you would need named in an X-Param-Error header. Nothing changes for real callers: send any argument, even an empty one, and you get the specific validation error as before. The same probes were also the single biggest source of noise in our own error metrics, so a genuine outage in the crypto API is now visible instead of buried.</description></item>+ <item>+ <title>Our x402 facilitator now publishes a standard discovery catalog</title>+ <link>https://three.ws/docs/x402-ring-economy</link>+ <guid isPermaLink="false">2026-07-25:Our x402 facilitator now publishes a standard discovery catalog</guid>+ <pubDate>Sat, 25 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The three.ws self-hosted x402 facilitator serves a new public endpoint, GET /api/x402-facilitator/discovery/resources, listing every paid endpoint on the platform in the standard facilitator catalog format that x402 explorers and aggregators (like x402scan) crawl. It is the same catalog as /.well-known/x402.json, so listings on third-party explorers always match what the platform actually charges. This is groundwork for three.ws payments showing up on ecosystem explorers without routing settlement through any third party.</description>+ </item><item><title>Selfie avatars now match the shape of your face, not just the colour of it</title><link>https://three.ws/create/selfie</link>@@ -62,6 +78,14 @@<category>improvement</category><description>The selfie-to-avatar engine used to do one thing: take the face from your photo and paint it onto a standard head. From straight on it looked convincing, but the skull underneath was the same for everyone, so the moment the avatar turned it stopped being you. It now reshapes the head itself to your face: width, jaw, chin, cheekbones, brow, and how far the nose projects. That step had been written and tested for a while but had never actually reached the servers, so every avatar made until today was built the old way. Making it live also turned up a flaw in how the photo was read. Face measurements arrived scaled to the picture's width and height separately, which means a tall photo stretched the face before anything else happened, and that stretch was then treated as part of your bone structure. In practice the shape of your avatar's head partly depended on whether you shot the photo tall or square, which is not something anyone would expect. Measurements are now taken in true proportions, so the same face gives the same head regardless of how the photo was framed. Finally, the limits controlling how far the head is allowed to move toward your real shape were set before there was any way to measure the result. They were far too cautious, holding the head back to about two centimetres of change and quietly discarding real differences between faces. Measured across a forty-face test set covering a wide range of ages, complexions, beards, glasses and head coverings, retuning them cut the remaining shape error by 46 percent, and no face in the set came out worse. Choosing that limit needed a second measurement, because a test set of clean, well-lit photos will always argue for removing the limit entirely: it contains nothing for the limit to catch. So each test face was also degraded the way real photos are, with camera shake, a turned head, hair across the face, a dim room and a heavily shrunk upload, and checked for whether the same person still came out with the same head. The setting we shipped is the point where matching your face stops improving but sensitivity to photo quality keeps rising. In total, avatars now capture about 60 percent of the difference between a generic head and your real one, up from 26 percent. Rebuild your avatar at /create/selfie to get one made the new way.</description></item>+ <item>+ <title>Solana reads on the crypto API stop failing when one RPC host throttles us</title>+ <link>https://three.ws/crypto-api</link>+ <guid isPermaLink="false">2026-07-25:Solana reads on the crypto API stop failing when one RPC host throttles us</guid>+ <pubDate>Sat, 25 Jul 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>The Solana endpoints on the public crypto API (balance, token holdings, token supply, largest holders, transaction, account, priority fees) were pointed at a single RPC host. Whenever that host rate-limited us, the caller got the rate-limit error even though the platform keeps a priority-ordered pool of other RPC endpoints for exactly this situation. Those calls now move to the next healthy host automatically, up to three per request, and a host that has just failed is skipped for the next 30 seconds so one bad host does not slow down every request behind it. A genuinely bad request, like a malformed address, still returns its error immediately instead of being retried. This was the second-largest error class on the API.</description>+ </item><item><title>The KOL Tracker is now reachable, and its numbers are real</title><link>https://three.ws/tracker</link>diff --git a/public/cz/index.html b/public/cz/index.htmlindex feeb6123f..90b513234 100644--- a/public/cz/index.html+++ b/public/cz/index.html@@ -7,7 +7,9 @@<meta name="description" content="Connect your wallet and claim your on-chain three.ws." data-i18n-attr="content:cz_index.meta_description"/><meta name="theme-color" content="#090909" /><link rel="icon" href="/favicon.ico" />- <link rel="stylesheet" href="./cz.css" />+ <!-- Absolute: served at /cz as well as /cz/, and a relative href resolves+ against the site root on the slash-less URL (404, unstyled page). -->+ <link rel="stylesheet" href="/cz/cz.css" /><script type="module">const CDN = 'https://three.ws/agent-3d/latest/agent-3d.js';const h = location.hostname;diff --git a/public/features.json b/public/features.jsonindex fe1e2c617..8f2d6e12d 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-25T09:58:05.512Z",+ "generated_at": "2026-07-25T10:10:06.543Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/first-meet/index.html b/public/first-meet/index.htmlindex e315e8409..afff11eaf 100644--- a/public/first-meet/index.html+++ b/public/first-meet/index.html@@ -313,7 +313,9 @@</div><script src="/dist-lib/agent-3d.js" type="module"></script>- <script type="module" src="./first-meet.js"></script>+ <!-- Absolute: served at /first-meet as well as /first-meet/, and a relative src+ resolves against the site root on the slash-less URL (404). -->+ <script type="module" src="/first-meet/first-meet.js"></script><script src="/brand.js" defer></script><!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. --><script type="module" src="/i18n.js"></script>diff --git a/public/spatial-mcp/demo.js b/public/spatial-mcp/demo.jsindex 471208355..c49264715 100644--- a/public/spatial-mcp/demo.js+++ b/public/spatial-mcp/demo.js@@ -15,6 +15,7 @@// module's URL, which always carries the directory. Correct in dev and prod, on// either URL form.import { renderSpatialArtifact } from './spatial-renderer.js';+import { validateSpatialArtifact } from './spatial-validator.js';// Left stage: a real forge_free output, generated by the free text→3D lane and// served from the same durable bucket a live tool result points at. Right stage:@@ -34,7 +35,6 @@ const native = {affordances: { orbit: true, zoom: true, fullscreen: true, download: true },meta: { title: 'Brass diving helmet', prompt: 'a weathered brass diving helmet, cracked glass porthole, verdigris patina' },};-renderSpatialArtifact(document.getElementById('stage-native'), native);// 2) A FOREIGN tool result in some other server's shape…const foreignResult = { model_url: FOREIGN_GLB, thumbnail: null, name: 'A helmet from another server' };@@ -52,5 +52,148 @@ function toSpatialArtifact(foreign) {}const transformed = toSpatialArtifact(foreignResult);++// ── Conformance, on screen ───────────────────────────────────────────────────+// The page used to assert conformance in prose. Now every payload it renders is+// run through the real validator in the browser and the verdict is shown next to+// the scene, so the claim is demonstrated instead of stated.++/** A status pill. Text carries the meaning; colour only reinforces it. */+function chip(kind, label) {+ const el = document.createElement('span');+ el.className = `chip chip-${kind}`;+ el.textContent = `${kind === 'ok' ? '✓' : kind === 'err' ? '✕' : '!'} ${label}`;+ return el;+}++/** One `{ path, message }` diagnostic as a row. */+function diagnostic(kind, path, message) {+ const row = document.createElement('div');+ row.className = `diag diag-${kind}`;+ const code = document.createElement('code');+ code.textContent = path;+ const text = document.createElement('span');+ text.textContent = message;+ row.append(code, text);+ return row;+}++const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;++/**+ * Render the validator's verdict for `artifact` into `mount`.+ * @param {HTMLElement|null} mount+ * @param {any} artifact+ * @returns {{ valid:boolean, errors:Array, warnings:Array, version:(string|null) }}+ */+function renderVerdict(mount, artifact) {+ const result = validateSpatialArtifact(artifact);+ if (!mount) return result;+ mount.textContent = '';++ mount.appendChild(+ result.valid ? chip('ok', 'conformant, 0 errors') : chip('err', plural(result.errors.length, 'error', 'errors')),+ );+ if (result.warnings.length) mount.appendChild(chip('warn', plural(result.warnings.length, 'warning', 'warnings')));++ const version = document.createElement('span');+ version.textContent = `spatialMcpVersion ${result.version || 'missing'}`;+ mount.appendChild(version);+ return result;+}++renderSpatialArtifact(document.getElementById('stage-native'), native);+renderVerdict(document.getElementById('conf-native'), native);+renderSpatialArtifact(document.getElementById('stage-foreign'), transformed);+renderVerdict(document.getElementById('conf-foreign'), transformed);document.getElementById('artifact-json').textContent = JSON.stringify(transformed, null, 2);++// ── The checker ──────────────────────────────────────────────────────────────+// Paste a tool result, see the verdict as you type, render it on demand. This is+// the part an implementer actually uses: it names the field to fix while they are+// writing the adapter, instead of making them read the spec and guess.++// Deliberately wrong in six distinct ways, one per rule class the spec defines,+// so the diagnostics teach the shape rather than just rejecting the payload.+const BROKEN_EXAMPLE = {+ spatialMcpVersion: '0.2',+ kind: 'hologram',+ scene: { glbUrl: 'http://example.com/model.glb', format: 'usdz' },+ camera: { autoRotate: 'yes' },+ ar: { supported: true },+ metaa: { title: 'a typo in a top-level key' },+};++const PRESETS = { conformant: native, broken: BROKEN_EXAMPLE };++const input = document.getElementById('payload-input');+const report = document.getElementById('check-report');+const checkStage = document.getElementById('stage-check');++/** Parse the textarea. Returns the artifact, or a JSON syntax diagnostic. */+function readPayload() {+ const text = input.value.trim();+ if (!text) return { empty: true };+ try {+ return { artifact: JSON.parse(text) };+ } catch (e) {+ return { syntaxError: e.message };+ }+}++function review() {+ const parsed = readPayload();+ report.textContent = '';++ if (parsed.empty) {+ report.appendChild(diagnostic('note', '(paste a payload)', 'or load one of the examples above'));+ return null;+ }+ if (parsed.syntaxError) {+ report.appendChild(diagnostic('err', 'JSON', parsed.syntaxError));+ return null;+ }++ const result = validateSpatialArtifact(parsed.artifact);+ const pills = document.createElement('div');+ pills.className = 'report-pills';+ pills.appendChild(+ result.valid ? chip('ok', 'conformant, 0 errors') : chip('err', plural(result.errors.length, 'error', 'errors')),+ );+ if (result.warnings.length) pills.appendChild(chip('warn', plural(result.warnings.length, 'warning', 'warnings')));+ report.appendChild(pills);++ for (const e of result.errors) report.appendChild(diagnostic('err', e.path, e.message));+ for (const w of result.warnings) report.appendChild(diagnostic('warn', w.path, w.message));+ return { result, artifact: parsed.artifact };+}++// Validate as you type, cheaply. The validator is pure and synchronous, so a+// short debounce is only there to keep keystrokes from re-rendering the report.+let debounce;+input.addEventListener('input', () => {+ clearTimeout(debounce);+ debounce = setTimeout(review, 200);+});++for (const button of document.querySelectorAll('[data-preset]')) {+ button.addEventListener('click', () => {+ input.value = JSON.stringify(PRESETS[button.dataset.preset], null, 2);+ review();+ // Renders on load for the conformant preset; for the broken one the+ // renderer's fallback is exactly what a host would show, which is the point.+ renderSpatialArtifact(checkStage, PRESETS[button.dataset.preset]);+ });+}++document.getElementById('check-render').addEventListener('click', () => {+ const reviewed = review();+ renderSpatialArtifact(checkStage, reviewed ? reviewed.artifact : null);+});++// Start populated so the section is useful before a single click, and so the+// empty state is never the first thing a visitor meets.+input.value = JSON.stringify(native, null, 2);+review();+renderSpatialArtifact(checkStage, native);diff --git a/public/spatial-mcp/index.html b/public/spatial-mcp/index.htmlindex cb43419ce..7e08d0679 100644--- a/public/spatial-mcp/index.html+++ b/public/spatial-mcp/index.html@@ -25,6 +25,41 @@pre { margin:0; padding:14px; font-size:12px; line-height:1.5; overflow:auto; max-height:340px; color:#cbd3e1; }.note { margin-top:24px; font-size:13px; color:#9aa3b2; line-height:1.6; }code { color:#dbe9ff; }++ /* Conformance surface — the validator's verdict, on screen, for every payload+ the page renders. Status is carried by a glyph AND a word, never colour alone. */+ :root { --ok:#4ade80; --err:#f87171; --warn:#fbbf24; }+ .conf { display:flex; flex-wrap:wrap; align-items:center; gap:8px; padding:10px 14px; border-top:1px solid rgba(255,255,255,0.07); font-size:12px; color:#9aa3b2; }+ .chip { display:inline-flex; align-items:center; gap:6px; padding:3px 9px; border-radius:999px; border:1px solid; font-size:11px; font-weight:600; letter-spacing:.02em; }+ .chip-ok { color:var(--ok); border-color:rgba(74,222,128,0.35); background:rgba(74,222,128,0.10); }+ .chip-err { color:var(--err); border-color:rgba(248,113,113,0.35); background:rgba(248,113,113,0.10); }+ .chip-warn { color:var(--warn); border-color:rgba(251,191,36,0.32); background:rgba(251,191,36,0.10); }++ /* Payload checker */+ .checker { display:grid; gap:12px; padding:14px; }+ .checker-bar { display:flex; flex-wrap:wrap; gap:8px; align-items:center; }+ .btn { font:inherit; font-size:12px; padding:7px 12px; border-radius:8px; cursor:pointer; color:#e8eaf0;+ border:1px solid rgba(255,255,255,0.14); background:rgba(255,255,255,0.04);+ transition: background 140ms ease, border-color 140ms ease, transform 140ms ease; }+ .btn:hover { background:rgba(255,255,255,0.08); border-color:rgba(255,255,255,0.24); }+ .btn:active { transform:translateY(1px); }+ .btn:focus-visible { outline:2px solid var(--accent); outline-offset:2px; }+ .btn-primary { color:#cfe0ff; background:rgba(110,168,254,0.14); border-color:rgba(110,168,254,0.45); }+ .btn-primary:hover { background:rgba(110,168,254,0.22); border-color:rgba(110,168,254,0.65); }+ .checker textarea { width:100%; min-height:220px; resize:vertical; padding:12px; border-radius:10px;+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size:12px; line-height:1.5;+ color:#cbd3e1; background:rgba(0,0,0,0.35); border:1px solid rgba(255,255,255,0.10); }+ .checker textarea:focus-visible { outline:2px solid var(--accent); outline-offset:1px; }+ .report { display:grid; gap:6px; }+ .report-pills { display:flex; flex-wrap:wrap; align-items:center; gap:8px; }+ .diag { display:grid; grid-template-columns:auto 1fr; gap:10px; align-items:baseline;+ padding:8px 10px; border-radius:8px; background:rgba(255,255,255,0.04); font-size:12.5px; line-height:1.5; }+ .diag code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space:nowrap; }+ .diag-err { box-shadow: inset 2px 0 0 var(--err); }+ .diag-warn { box-shadow: inset 2px 0 0 var(--warn); }+ .diag-note { color:#9aa3b2; }+ .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; }+ @media (prefers-reduced-motion: reduce) { .btn { transition:none; } }</style><link rel="canonical" href="https://three.ws/spatial-mcp">@@ -61,10 +96,12 @@<div class="card"><h2 data-i18n="spatial_mcp_index.three_ws_forge_free_artifact">three.ws forge_free → artifact</h2><div id="stage-native" class="stage"></div>+ <div id="conf-native" class="conf"></div></div><div class="card"><h2 data-i18n="spatial_mcp_index.foreign_tool_result_conformant_artifact">Foreign tool result → conformant artifact</h2><div id="stage-foreign" class="stage"></div>+ <div id="conf-foreign" class="conf"></div></div></div>@@ -73,6 +110,26 @@<pre id="artifact-json"></pre></div>+ <div class="card" style="margin-top:20px;">+ <h2 data-i18n="spatial_mcp_index.check_your_own_payload">Check your own payload</h2>+ <div class="checker">+ <p class="lede" style="max-width:70ch;" data-i18n="spatial_mcp_index.checker_lede">+ Paste a tool result below. The same validator the spec ships runs on it as you type, in your+ browser, and names the field to fix rather than answering yes or no. Conformant payloads render+ underneath; unusable ones get the designed fallback, never a blank frame.+ </p>+ <div class="checker-bar">+ <button class="btn" type="button" data-preset="conformant" data-i18n="spatial_mcp_index.load_a_conformant_example">Load a conformant example</button>+ <button class="btn" type="button" data-preset="broken" data-i18n="spatial_mcp_index.load_a_broken_example">Load a broken example</button>+ <button class="btn btn-primary" type="button" id="check-render" data-i18n="spatial_mcp_index.render_this_payload">Render this payload</button>+ </div>+ <label class="sr-only" for="payload-input" data-i18n="spatial_mcp_index.spatial_mcp_artifact_json">Spatial MCP artifact JSON</label>+ <textarea id="payload-input" spellcheck="false" autocapitalize="off" autocorrect="off"></textarea>+ <div id="check-report" class="report" role="status" aria-live="polite"></div>+ <div id="stage-check" class="stage"></div>+ </div>+ </div>+<p class="note" data-i18n-html="spatial_mcp_index.a_third_party_mcp_server_that_returns">A third-party MCP server that returns <code>{ url, previewImage }</code> becomes conformant with a tiny adapter —see <a href="/docs/spatial-mcp">docs/spatial-mcp</a>. Any renderer that speaks this shape (this one included) thendiff --git a/public/spatial-mcp/spatial-validator.js b/public/spatial-mcp/spatial-validator.jsnew file mode 100644index 000000000..1160dc44f--- /dev/null+++ b/public/spatial-mcp/spatial-validator.js@@ -0,0 +1,283 @@+// Spatial MCP — the open shape for 3D-native tool results, and its validator.+//+// MCP tool results are text/JSON today. A *spatial* MCP artifact carries a live,+// interactive 3D scene as a first-class structured-content field so a host can+// render it (orbit, animate, AR) instead of printing a URL. This module is the+// single source of truth for that shape:+//+// • buildSpatialArtifact(...) — assemble a conformant artifact from the+// fields a generation tool already has (glbUrl, kind, prompt, …).+// • validateSpatialArtifact(payload) — check conformance and return ACTIONABLE+// errors ({ path, message }), not a bare boolean. Used as the gate every+// three.ws 3D tool passes its artifact through, and callable by third-party+// servers adopting the shape.+//+// WHY IT LIVES IN /public, NEXT TO THE RENDERER+// A spec's validator is only useful where the mistakes happen: in the browser of+// whoever is building an adapter. Sitting here it is loadable three ways from one+// implementation, with no copy to drift:+//+// 1. the reference renderer page (/spatial-mcp) imports it as a sibling module+// and shows live conformance for every payload on screen;+// 2. a third party imports it straight off the published URL, exactly as+// docs/spatial-mcp.md already instructs for the renderer:+// import { validateSpatialArtifact } from 'https://three.ws/spatial-mcp/spatial-validator.js';+// 3. server-side code re-exports it from api/_lib/spatial-mcp.js, which is the+// import path every three.ws tool already uses.+//+// It is intentionally dependency-free (no Ajv, no fetch, no DB) so it loads+// unchanged in the api/ bundle, a published npm package, the free OpenAI studio,+// a plain browser, and the unit tests, and carries ZERO payment, wallet, coin, or+// token surface, so the renderer and validator drop cleanly into the crypto-free+// OpenAI app. Spec: specs/SPATIAL_MCP.md.++export const SPATIAL_MCP_VERSION = '0.1';++// Versions this validator accepts. New minor versions are added here as the+// shape evolves; a host reads spatialMcpVersion to pick its renderer.+const KNOWN_VERSIONS = new Set(['0.1']);++// The subject a 3D artifact describes. Open enum — a host that doesn't know a+// kind still renders scene.glbUrl; the kind only drives labelling/affordances.+const KNOWN_KINDS = new Set(['model', 'mesh', 'avatar', 'rigged-model', 'scene']);++const TOP_LEVEL_KEYS = new Set([+ 'spatialMcpVersion',+ 'kind',+ 'scene',+ 'camera',+ 'environment',+ 'animation',+ 'persona',+ 'ar',+ 'affordances',+ 'meta',+]);++// A conservative https check — the renderer only ever loads assets over https,+// and rejecting other schemes at the boundary keeps data: / javascript: / http+// out of a field a host will feed to <model-viewer src>.+function isHttpsUrl(v) {+ if (typeof v !== 'string' || !v) return false;+ try {+ return new URL(v).protocol === 'https:';+ } catch {+ return false;+ }+}++function isPlainObject(v) {+ return v != null && typeof v === 'object' && !Array.isArray(v);+}++/**+ * Assemble a spec-conformant spatial artifact from the fields a generation tool+ * already has. Only `glbUrl` is required; everything else is optional and only+ * emitted when provided, so the output is always valid and never carries empty+ * scaffolding. Pure and deterministic.+ *+ * @param {object} a+ * @param {string} a.glbUrl the generated asset (https)+ * @param {string} [a.kind] one of KNOWN_KINDS (default 'model')+ * @param {string} [a.viewerUrl] three.ws viewer link (meta)+ * @param {string} [a.poster] preview image (https)+ * @param {string} [a.prompt] the generating prompt (meta)+ * @param {string} [a.title] human title (meta)+ * @param {boolean}[a.autoRotate] camera auto-rotate (default true)+ * @param {string} [a.cameraOrbit] model-viewer camera-orbit string+ * @param {boolean}[a.rigged] true → animation hooks enabled+ * @param {string[]}[a.clips] named animation clips+ * @param {string} [a.personaId] persona binding (prompt 07)+ * @param {{usdzUrl?:string,glbUrl?:string,launchUrl?:string}} [a.ar] AR handoff (prompt 21)+ * @returns {object} a conformant spatial artifact+ */+export function buildSpatialArtifact(a = {}) {+ const kind = KNOWN_KINDS.has(a.kind) ? a.kind : 'model';+ const artifact = {+ spatialMcpVersion: SPATIAL_MCP_VERSION,+ kind,+ scene: {+ glbUrl: a.glbUrl,+ format: 'glb',+ ...(a.poster ? { poster: a.poster } : {}),+ ...(a.alt ? { alt: a.alt } : {}),+ },+ camera: {+ autoRotate: a.autoRotate !== false,+ ...(a.cameraOrbit ? { orbit: a.cameraOrbit } : {}),+ },+ environment: {+ image: a.environmentImage || 'neutral',+ exposure: typeof a.exposure === 'number' ? a.exposure : 1,+ shadowIntensity: typeof a.shadowIntensity === 'number' ? a.shadowIntensity : 1,+ },+ affordances: {+ orbit: true,+ zoom: true,+ fullscreen: true,+ download: a.download !== false,+ },+ };++ // Animation hooks only when the asset is actually rigged/animated.+ if (a.rigged || (Array.isArray(a.clips) && a.clips.length)) {+ artifact.animation = {+ autoplay: a.autoplay !== false,+ ...(Array.isArray(a.clips) && a.clips.length ? { clips: a.clips.slice(0, 64) } : {}),+ };+ }++ // Persona hook (prompt 07) — a speakable embodied body.+ if (a.personaId) {+ artifact.persona = { id: String(a.personaId), speakable: true };+ }++ // AR handoff (prompt 21). `supported` is true when any concrete AR asset/link+ // is present; a host without AR ignores this block and renders the WebGL scene.+ if (a.ar && isPlainObject(a.ar)) {+ const ar = {};+ if (isHttpsUrl(a.ar.usdzUrl)) ar.usdzUrl = a.ar.usdzUrl;+ if (isHttpsUrl(a.ar.glbUrl)) ar.glbUrl = a.ar.glbUrl;+ if (isHttpsUrl(a.ar.launchUrl)) ar.launchUrl = a.ar.launchUrl;+ if (Object.keys(ar).length) {+ ar.supported = true;+ artifact.ar = ar;+ }+ }++ const meta = {};+ if (a.prompt) meta.prompt = String(a.prompt);+ if (a.title) meta.title = String(a.title);+ if (isHttpsUrl(a.viewerUrl)) meta.viewerUrl = a.viewerUrl;+ if (Object.keys(meta).length) artifact.meta = meta;++ return artifact;+}++// ── Validator ────────────────────────────────────────────────────────────────++function err(errors, path, message) {+ errors.push({ path, message });+}+function warn(warnings, path, message) {+ warnings.push({ path, message });+}++/**+ * Validate a spatial artifact against the spec. Returns actionable diagnostics —+ * every problem names the offending `path` and how to fix it — so a caller (a+ * third-party server adopting the shape, or a three.ws tool's self-check) can+ * correct its output, not just learn that it's wrong.+ *+ * @param {any} payload+ * @returns {{ valid:boolean, version:(string|null), errors:Array<{path,message}>,+ * warnings:Array<{path,message}> }}+ */+export function validateSpatialArtifact(payload) {+ const errors = [];+ const warnings = [];++ if (!isPlainObject(payload)) {+ return {+ valid: false,+ version: null,+ errors: [{ path: '(root)', message: 'artifact must be a JSON object' }],+ warnings,+ };+ }++ // Version.+ const version = payload.spatialMcpVersion ?? null;+ if (version == null) {+ err(errors, 'spatialMcpVersion', `required — set it to "${SPATIAL_MCP_VERSION}"`);+ } else if (typeof version !== 'string' || !KNOWN_VERSIONS.has(version)) {+ err(errors, 'spatialMcpVersion', `unknown version ${JSON.stringify(version)} — supported: ${[...KNOWN_VERSIONS].join(', ')}`);+ }++ // Kind.+ if (payload.kind == null) {+ err(errors, 'kind', `required — one of ${[...KNOWN_KINDS].join(', ')}`);+ } else if (!KNOWN_KINDS.has(payload.kind)) {+ err(errors, 'kind', `unknown kind ${JSON.stringify(payload.kind)} — expected one of ${[...KNOWN_KINDS].join(', ')}`);+ }++ // Scene (required, with a required https glbUrl).+ if (!isPlainObject(payload.scene)) {+ err(errors, 'scene', 'required object with a `glbUrl`');+ } else {+ if (!isHttpsUrl(payload.scene.glbUrl)) {+ err(errors, 'scene.glbUrl', 'required — must be an https URL to a .glb asset');+ }+ if (payload.scene.format !== undefined && payload.scene.format !== 'glb') {+ err(errors, 'scene.format', 'only "glb" is supported in v0.1');+ } else if (payload.scene.format === undefined) {+ warn(warnings, 'scene.format', 'recommended — set to "glb"');+ }+ if (payload.scene.poster !== undefined && !isHttpsUrl(payload.scene.poster)) {+ err(errors, 'scene.poster', 'must be an https URL when present');+ }+ }++ // Optional blocks — validate shape/types only when present.+ if (payload.camera !== undefined) {+ if (!isPlainObject(payload.camera)) err(errors, 'camera', 'must be an object when present');+ else if (payload.camera.autoRotate !== undefined && typeof payload.camera.autoRotate !== 'boolean')+ err(errors, 'camera.autoRotate', 'must be a boolean');+ } else {+ warn(warnings, 'camera', 'recommended — include `{ autoRotate: true }` so hosts frame the model');+ }++ if (payload.environment !== undefined && !isPlainObject(payload.environment)) {+ err(errors, 'environment', 'must be an object when present');+ }++ if (payload.animation !== undefined) {+ if (!isPlainObject(payload.animation)) err(errors, 'animation', 'must be an object when present');+ else if (payload.animation.clips !== undefined && !Array.isArray(payload.animation.clips))+ err(errors, 'animation.clips', 'must be an array of clip names');+ }++ if (payload.persona !== undefined && !isPlainObject(payload.persona)) {+ err(errors, 'persona', 'must be an object when present');+ }++ if (payload.ar !== undefined) {+ if (!isPlainObject(payload.ar)) {+ err(errors, 'ar', 'must be an object when present');+ } else {+ for (const k of ['usdzUrl', 'glbUrl', 'launchUrl']) {+ if (payload.ar[k] !== undefined && !isHttpsUrl(payload.ar[k]))+ err(errors, `ar.${k}`, 'must be an https URL when present');+ }+ const hasAsset = ['usdzUrl', 'glbUrl', 'launchUrl'].some((k) => isHttpsUrl(payload.ar[k]));+ if (payload.ar.supported === true && !hasAsset)+ err(errors, 'ar.supported', 'true requires at least one of ar.usdzUrl / ar.glbUrl / ar.launchUrl');+ }+ }++ if (payload.affordances !== undefined && !isPlainObject(payload.affordances)) {+ err(errors, 'affordances', 'must be an object when present');+ }++ if (payload.meta !== undefined && !isPlainObject(payload.meta)) {+ err(errors, 'meta', 'must be an object when present');+ }++ // Unknown top-level keys are a warning, not an error — forward-compatibility+ // with hosts that carry extra fields, but flagged so typos surface.+ for (const key of Object.keys(payload)) {+ if (!TOP_LEVEL_KEYS.has(key)) warn(warnings, key, 'unknown top-level field — ignored by conformant renderers');+ }++ return {+ valid: errors.length === 0,+ version: typeof version === 'string' ? version : null,+ errors,+ warnings,+ };+}++/** Convenience: true iff `payload` is a conformant artifact. */+export function isConformantSpatialArtifact(payload) {+ return validateSpatialArtifact(payload).valid;+}diff --git a/scripts/check-dist.mjs b/scripts/check-dist.mjsindex 7646b9f87..b55c4c989 100644--- a/scripts/check-dist.mjs+++ b/scripts/check-dist.mjs@@ -54,14 +54,16 @@ for (const { rel, min } of distLibChecks) {// `npm run build` skipped (or run from a stale checkout) ships an incomplete// dist/ with no error — that's exactly how /dashboard and /pump-dashboard// 404'd in production on 2026-07-08 while check:dist reported green, because-// this check only ever looked at the agent-3d embed bundle. Not a full sweep-// of data/pages.json's 300 entries: most of those (docs/*, tutorials/*,-// .well-known/*, sitemap.xml) are server-rendered at request time by api/**-// handlers, not static build output, so a naive "every registered path must-// have a dist/ file" check false-flags them. This list is the pages actually-// known to be pure static Vite build output — extend it when another one-// breaks the same way, rather than trying to infer static-vs-dynamic from-// data/pages.json alone.+// this check only ever looked at the agent-3d embed bundle. This list stays as+// a fast, dependency-free tripwire for "was `npm run build` skipped entirely".+//+// The full sweep of data/pages.json now lives in scripts/check-pages.mjs, which+// runs straight after this one in `build:gcp`. The reason it wasn't done here+// is that a naive "every registered path must have a dist/ file" check+// false-flags the ~200 entries served by api/** handlers at request time+// (docs/*, tutorials/*, .well-known/*). check-pages.mjs resolves each path+// through the real vercel.json route table instead, so it can tell a+// server-rendered page from an unreachable one and needs no allowlist.const criticalStaticPages = ['/', '/dashboard', '/pump-dashboard', '/dashboard-next', '/create', '/discover'];function resolvesToFile(pagePath) {diff --git a/scripts/check-pages.mjs b/scripts/check-pages.mjsnew file mode 100644index 000000000..2b3d4f323--- /dev/null+++ b/scripts/check-pages.mjs@@ -0,0 +1,124 @@+#!/usr/bin/env node+// Assert every page declared in data/pages.json is actually reachable.+//+// data/pages.json is the source of the sitemap, llms.txt and features.json, so+// anything listed there is advertised to crawlers and to users the moment it+// lands. Nothing checked that the page could actually be served, and two have+// shipped as hard 404s in three days: /timeline (fixed by 5688277bd) and+// /tracker (advertised 2026-07-23, 404 until a route landed two days later).+// Both had a built dist/<slug>.html and no vercel.json rewrite, and+// server/index.mjs deliberately has no `.html` extension fallback.+//+// Two modes:+// node scripts/check-pages.mjs resolve against the local dist/+// node scripts/check-pages.mjs --base <url> sweep a live deployment+//+// The local mode runs in `build:gcp` (before the image is built) and turns an+// unreachable page into a red build. The --base mode runs after a deploy, where+// it also catches CDN and revision problems the build cannot see.++import { existsSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { collectDeclaredPaths, loadRouteTable, resolveRequest } from './lib/page-routing.mjs';++const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');++const argv = process.argv.slice(2);+const readFlag = (name) => {+ const i = argv.indexOf(name);+ return i === -1 ? null : argv[i + 1];+};+const base = readFlag('--base');+const concurrency = Number(readFlag('--concurrency') || 12);+const timeoutMs = Number(readFlag('--timeout') || 20000);++const paths = collectDeclaredPaths(root);+if (paths.length === 0) {+ console.error('[check-pages] no paths found in data/pages.json');+ process.exit(1);+}++const failures = [];++if (base) {+ const target = base.replace(/\/$/, '');+ let done = 0;+ const queue = [...paths];++ const worker = async () => {+ for (;;) {+ const p = queue.shift();+ if (p === undefined) return;+ const url = `${target}${p}`;+ let status = 0;+ let note = '';+ try {+ const res = await fetch(url, {+ redirect: 'manual',+ signal: AbortSignal.timeout(timeoutMs),+ headers: { 'user-agent': 'three.ws-check-pages' },+ });+ status = res.status;+ if (status >= 300 && status < 400) note = `→ ${res.headers.get('location') || '(no location)'}`;+ } catch (err) {+ note = err.name === 'TimeoutError' ? 'timeout' : err.message;+ }+ // 2xx and 3xx are both reachable. A redirect that resolves is how+ // /chat (301 → /app) is meant to behave.+ if (!(status >= 200 && status < 400)) failures.push({ path: p, status, note });+ done += 1;+ if (done % 50 === 0) console.log(`[check-pages] ${done}/${paths.length}…`);+ }+ };++ console.log(`[check-pages] sweeping ${paths.length} declared pages against ${target}`);+ await Promise.all(Array.from({ length: Math.min(concurrency, paths.length) }, worker));++ if (failures.length) {+ console.error(`\n[check-pages] ${failures.length} unreachable page(s) on ${target}:`);+ for (const f of failures.sort((a, b) => a.path.localeCompare(b.path))) {+ console.error(`[check-pages] ${String(f.status || 'ERR').padEnd(4)} ${f.path} ${f.note}`);+ }+ process.exit(1);+ }+ console.log(`[check-pages] OK — all ${paths.length} declared pages reachable on ${target}`);+} else {+ const distRoot = path.join(root, 'dist');+ if (!existsSync(distRoot)) {+ console.error('[check-pages] dist/ not found — run `npm run build` first');+ process.exit(1);+ }+ const table = loadRouteTable(root);+ const counts = { static: 0, api: 0, redirect: 0, external: 0, notfound: 0 };++ for (const p of paths) {+ const r = resolveRequest(p, table, distRoot);+ counts[r.outcome] += 1;+ if (r.outcome === 'notfound') failures.push({ path: p, target: r.target });+ }++ if (failures.length) {+ console.error(+ `\n[check-pages] ${failures.length} declared page(s) resolve to a 404 in this build.`,+ );+ console.error('[check-pages] Each is advertised in the sitemap and llms.txt but cannot be served.');+ console.error(+ '[check-pages] Fix: add a vercel.json rewrite (e.g. {"src":"/slug/?","dest":"/slug.html"})',+ );+ console.error('[check-pages] and make sure the page is a vite input entry so dist/slug.html is built.\n');+ for (const f of failures.sort((a, b) => a.path.localeCompare(b.path))) {+ const built = existsSync(path.join(distRoot, `${f.path.replace(/^\//, '')}.html`));+ const why = built+ ? 'dist/*.html exists but no rewrite maps the clean URL to it'+ : 'not built into dist/ (missing vite input entry?)';+ console.error(`[check-pages] ${f.path} — ${why}`);+ }+ process.exit(1);+ }++ console.log(+ `[check-pages] OK — all ${paths.length} declared pages resolve ` ++ `(${counts.static} static, ${counts.api} api, ${counts.redirect} redirect, ${counts.external} external)`,+ );+}diff --git a/scripts/lib/page-routing.mjs b/scripts/lib/page-routing.mjsnew file mode 100644index 000000000..9fd1d8988--- /dev/null+++ b/scripts/lib/page-routing.mjs@@ -0,0 +1,153 @@+// Offline mirror of server/index.mjs's request resolution, for build-time checks.+//+// Why this exists: a page can ship to production completely unreachable and+// nothing catches it. `resolveStatic()` in server/index.mjs deliberately has no+// `.html` extension fallback — it serves an exact path or a directory's+// index.html, nothing else — so a page built to `dist/<slug>.html` is a hard+// 404 at `/<slug>` unless vercel.json carries a rewrite for it. That has now+// shipped twice in three days: `/timeline` (fixed by 5688277bd, "page shipped+// without a route entry") and `/tracker` (added to data/pages.json 2026-07-23,+// 404 in production until a route landed two days later). Both were advertised+// in the sitemap and llms.txt the whole time.+//+// This module resolves a pathname the way the running server would, against a+// built dist/, so scripts/check-pages.mjs can fail the build instead of letting+// the sitemap advertise a 404. It intentionally duplicates a small amount of+// server logic rather than importing server/index.mjs, which starts listening+// on import and cannot be loaded as a library. Keep the two in sync: the pieces+// mirrored here are the route-table split, substitute(), hasMatches() and+// resolveStatic().++import { readFileSync, statSync, existsSync } from 'node:fs';+import path from 'node:path';++const compileRoute = (r) => ({ ...r, re: new RegExp(`^${r.src}$`) });++/** Split vercel.json's route table at the {handle:"filesystem"} marker. */+export function loadRouteTable(rootDir) {+ const config = JSON.parse(readFileSync(path.join(rootDir, 'vercel.json'), 'utf8'));+ const fsIndex = config.routes.findIndex((r) => r.handle === 'filesystem');+ const end = fsIndex === -1 ? config.routes.length : fsIndex;+ return {+ phase1: config.routes.slice(0, end).filter((r) => r.src).map(compileRoute),+ postFs:+ fsIndex === -1+ ? []+ : config.routes.slice(fsIndex + 1).filter((r) => r.src).map(compileRoute),+ };+}++function substitute(template, match) {+ return template.replace(/\$(\d+)/g, (_, n) => match[Number(n)] ?? '');+}++const isExternalDest = (dest) => /^https?:\/\//.test(dest || '');++const hasValueCache = new Map();+function compileHasValue(value) {+ let re = hasValueCache.get(value);+ if (!re) {+ const caseInsensitive = value.startsWith('(?i)');+ re = new RegExp(caseInsensitive ? value.slice(4) : value, caseInsensitive ? 'i' : undefined);+ hasValueCache.set(value, re);+ }+ return re;+}++// Evaluated against a bare anonymous GET: no cookies, no query string, no+// crawler user-agent. That is deliberately the weakest possible request, so+// `has`-gated rules (the OG-preview rewrites that only fire for social bots,+// the authed-shell rules that need a session cookie) correctly do NOT match.+// A page that only resolves for a logged-in user or a scraper is still a 404+// for the visitor arriving from the sitemap, which is the case we're policing.+function hasMatches(route, host) {+ if (!route.has) return true;+ for (const cond of route.has) {+ let val;+ if (cond.type === 'host') val = host;+ else if (cond.type === 'query' || cond.type === 'header' || cond.type === 'cookie') val = undefined;+ else continue;+ if (val == null) return false;+ if (cond.value !== undefined && !compileHasValue(cond.value).test(val)) return false;+ }+ return true;+}++/** Mirror of server/index.mjs resolveStatic(): exact file, or directory/index.html. */+export function resolveStatic(distRoot, pathname) {+ let rel;+ try {+ rel = decodeURIComponent(pathname);+ } catch {+ return null;+ }+ const abs = path.normalize(path.join(distRoot, rel));+ if (!abs.startsWith(distRoot + path.sep) && abs !== distRoot) return null; // traversal guard+ try {+ let st = statSync(abs);+ let target = abs;+ if (st.isDirectory()) {+ target = path.join(abs, 'index.html');+ st = statSync(target);+ }+ return st.isFile() ? target : null;+ } catch {+ return null;+ }+}++/**+ * Resolve a pathname the way the server would for an anonymous GET.+ *+ * @returns {{outcome: 'redirect'|'external'|'api'|'static'|'notfound', status?: number, target?: string}}+ * `notfound` means the request fell through to the 404 fallback — the page is+ * unreachable in this build.+ */+export function resolveRequest(pathname, table, distRoot, { host = 'three.ws' } = {}) {+ let currentPath = pathname;++ for (const route of table.phase1) {+ const m = route.re.exec(currentPath);+ if (!m) continue;+ if (!hasMatches(route, host)) continue;+ if (route.continue) continue;+ if (route.status && !route.dest) return { outcome: 'redirect', status: route.status };+ if (route.dest) {+ const dest = substitute(route.dest, m);+ if (isExternalDest(dest)) return { outcome: 'external', target: dest };+ const qIdx = dest.indexOf('?');+ const next = qIdx === -1 ? dest : dest.slice(0, qIdx);+ // An identity passthrough (`/(.*)` → `/$1`) is not progress; treating it+ // as a rewrite would end phase-1 matching one rule early.+ if (next === currentPath) continue;+ currentPath = next;+ if (route.status && route.status >= 300 && route.status < 400) {+ return { outcome: 'redirect', status: route.status, target: currentPath };+ }+ break;+ }+ }++ if (currentPath.startsWith('/api/')) return { outcome: 'api', target: currentPath };++ const file = resolveStatic(distRoot, currentPath);+ if (file) return { outcome: 'static', target: file };++ return { outcome: 'notfound', target: currentPath };+}++/** Every `path` declared anywhere in data/pages.json, deduped, in document order. */+export function collectDeclaredPaths(rootDir) {+ const pagesFile = path.join(rootDir, 'data', 'pages.json');+ if (!existsSync(pagesFile)) return [];+ const doc = JSON.parse(readFileSync(pagesFile, 'utf8'));+ const found = [];+ (function walk(node) {+ if (Array.isArray(node)) return node.forEach(walk);+ if (node && typeof node === 'object') {+ if (typeof node.path === 'string' && node.path.startsWith('/')) found.push(node.path);+ for (const v of Object.values(node)) walk(v);+ }+ })(doc);+ return [...new Set(found)];+}diff --git a/src/fingerspelling.js b/src/fingerspelling.jsindex e760ba304..2cdc83131 100644--- a/src/fingerspelling.js+++ b/src/fingerspelling.js@@ -25,7 +25,7 @@// prefers them, falling back here for anything with no sign of its own.import { HANDSHAPES, handshapeLocals } from './sign-handshapes.js';-import { SignTimeline, posePhase, restingPose } from './sign-clip.js';+import { SignTimeline, mirrorPhase, posePhase, restingPose } from './sign-clip.js';export { HANDSHAPES, handshapeLocals, restingPose };@@ -112,31 +112,35 @@ function letterPlace(letter, offset) {export function letterPose(letter, opts = {}, base = restingPose()) {if (!HANDSHAPES[letter]) throw new Error(`no handshape for letter "${letter}"`);const orient = LETTER_ORIENT[letter] ?? {};- return posePhase(+ return spellingPhase({- right: {- shape: letter,- at: letterPlace(letter, opts.offset),- fingers: opts.fingers ?? orient.fingers ?? 'up',- palm: opts.palm ?? orient.palm ?? 'forward',- },- // The reading eye follows the hand: a small turn and tilt toward the- // spelling hand is what a signer does and what makes this look alive.- head: { turn: -3, tilt: 1.5 },- torso: { turn: -2 },+ shape: letter,+ at: letterPlace(letter, opts.offset),+ fingers: opts.fingers ?? orient.fingers ?? 'up',+ palm: opts.palm ?? orient.palm ?? 'forward',},+ opts.dominant,base,);}+/** One spelling pose: the dominant hand does the work, the body leans into it. */+function spellingPhase(hand, dominant, base) {+ const phase = {+ right: hand,+ // The reading eye follows the hand: a small turn and tilt toward the+ // spelling hand is what a signer does and what makes this look alive.+ head: { turn: -3, tilt: 1.5 },+ torso: { turn: -2 },+ };+ return posePhase(dominant === 'Left' ? mirrorPhase(phase) : phase, base);+}+/** The neutral hand a word starts and ends from: same place, open and relaxed. */-function readyPose(base) {- return posePhase(- {- right: { shape: 'RELAXED', at: letterPlace('A', { up: -0.03, forward: -0.03 }), fingers: 'up', palm: ['forward', 'in'] },- head: { turn: -3, tilt: 1.5 },- torso: { turn: -2 },- },+function readyPose(base, dominant) {+ return spellingPhase(+ { shape: 'RELAXED', at: letterPlace('A', { up: -0.03, forward: -0.03 }), fingers: 'up', palm: ['forward', 'in'] },+ dominant,base,);}@@ -147,7 +151,16 @@ function readyPose(base) {* is dropped.** @param {string} word- * @param {Partial<typeof DEFAULT_TIMING> & { name?: string, base?: import('./sign-rig.js').Pose, settle?: boolean }} [opts]+ * @param {Partial<typeof DEFAULT_TIMING> & {+ * name?: string,+ * base?: import('./sign-rig.js').Pose,+ * lead?: boolean,+ * settle?: boolean,+ * }} [opts]+ * `dominant` picks the signing hand ('Right' by default).+ * `lead: false` starts with the hand already up in signing space and+ * `settle: false` leaves it there — what a word in the MIDDLE of a sentence+ * needs, since a signer does not lower their arm between words.* @returns {object} clip document, ready for THREE.AnimationClip.parse + retarget*/export function buildFingerspellingClip(word, opts = {}) {@@ -156,17 +169,19 @@ export function buildFingerspellingClip(word, opts = {}) {if (!letters) throw new Error('word has no spellable characters (A-Z, 0-9)');const base = opts.base ?? restingPose();- const tl = new SignTimeline({ base });- const ready = readyPose(base);+ const dominant = opts.dominant === 'Left' ? 'Left' : 'Right';+ const ready = readyPose(base, dominant);+ const lead = opts.lead !== false;+ const tl = new SignTimeline({ base, open: lead ? base : ready });- // Lift into signing space, then spell.- tl.to(ready, timing.leadSeconds, { ease: 'out' });+ // Lift into signing space, then spell. A continuing word is already there.+ if (lead) tl.to(ready, timing.leadSeconds, { ease: 'out' });let prev = null;for (const ch of letters) {if (ch === ' ') {// A word break is a small drop and re-set of the hand, not a pause.- tl.to(readyPose(base), timing.transitionSeconds, { ease: 'smooth' });+ tl.to(readyPose(base, dominant), timing.transitionSeconds, { ease: 'smooth' });tl.hold(timing.holdSeconds * 0.5);prev = null;continue;@@ -174,30 +189,30 @@ export function buildFingerspellingClip(word, opts = {}) {if (prev === ch) {// Doubled letter: bounce outward and back rather than holding one shape// twice, which would read as a single letter.- tl.to(letterPose(ch, { offset: { out: 0.045, forward: -0.01 } }, base), timing.transitionSeconds * 0.55, { ease: 'out' });+ tl.to(letterPose(ch, { offset: { out: 0.045, forward: -0.01 }, dominant }, base), timing.transitionSeconds * 0.55, { ease: 'out' });}const motion = LETTER_MOTION[ch];if (motion) {- const step = (s) => letterPose(ch, { offset: s.offset, fingers: s.fingers, palm: s.palm }, base);+ const step = (s) => letterPose(ch, { offset: s.offset, fingers: s.fingers, palm: s.palm, dominant }, base);tl.to(step(motion[0]), timing.transitionSeconds, { ease: 'smooth' });for (let i = 1; i < motion.length; i++) {const span = (motion[i].at - motion[i - 1].at) * timing.motionSeconds;tl.to(step(motion[i]), span, { ease: i === motion.length - 1 ? 'in' : 'linear' });}} else {- tl.to(letterPose(ch, {}, base), timing.transitionSeconds, { ease: 'smooth' });+ tl.to(letterPose(ch, { dominant }, base), timing.transitionSeconds, { ease: 'smooth' });tl.hold(timing.holdSeconds);}prev = ch;}- // Drop the hand back to rest unless the caller is stitching more signing on.- if (opts.settle === false) tl.hold(timing.tailSeconds);- else tl.settle(timing.tailSeconds);+ // Drop the hand back to rest unless the caller is stitching more signing on;+ // mid-sentence the hand simply stays where it is and the next word takes over.+ if (opts.settle !== false) tl.settle(timing.tailSeconds);return tl.build({name: opts.name ?? `fingerspell-${letters.toLowerCase().replace(/ /g, '-')}`,- seed: `fingerspell:${letters}:${timing.holdSeconds}:${timing.transitionSeconds}:${timing.leadSeconds}:${timing.tailSeconds}`,+ seed: `fingerspell:${letters}:${timing.holdSeconds}:${timing.transitionSeconds}:${timing.leadSeconds}:${timing.tailSeconds}:${lead}:${opts.settle !== false}:${dominant}`,});}diff --git a/src/sign-clip.js b/src/sign-clip.jsindex c15034fa4..0f0d78306 100644--- a/src/sign-clip.js+++ b/src/sign-clip.js@@ -15,16 +15,26 @@// Signs never write joint angles. They name a handshape, a place in signing// space, and which way the fingers and palm face; everything else is solved.-import { applyHandshape, fingerBones } from './sign-handshapes.js';+import { applyHandshape } from './sign-handshapes.js';import {Pose,+ anchorPoint,+ boneAxis,+ fingerBones,+ handPartOffset,+ handPoint,+ orientQuat,+ palmAxis,qAxisAngle,qMul,+ qRotate,qSlerp,signPoint,solveArm,vAdd,vNorm,+ vScale,+ vSub,} from './sign-rig.js';/**@@ -85,16 +95,42 @@ export function direction(spec, side = 'Right') {/*** Resolve a place in signing space: an anchor name with body-relative offsets,- * an explicit point, or a `[anchor, offsets]` pair.+ * an explicit point, or an explicit `[x,y,z]`. Anchors are read from the POSE,+ * so a place on the chin follows the chin when the head turns.* @param {string|object|number[]} spec* @param {'Left'|'Right'} side+ * @param {Pose} [pose]* @returns {number[]}*/-export function place(spec, side = 'Right') {+export function place(spec, side = 'Right', pose = null) {if (Array.isArray(spec) && typeof spec[0] === 'number') return spec;- if (typeof spec === 'string') return signPoint(spec, { side });- const { anchor = 'sternum', ...offsets } = spec;- return signPoint(anchor, { ...offsets, side });+ const { anchor = 'sternum', ...offsets } = typeof spec === 'string' ? { anchor: spec } : spec;+ return pose+ ? anchorPoint(pose, anchor, { ...offsets, side })+ : signPoint(anchor, { ...offsets, side });+}++/**+ * Where a `touch:` spec says the acting hand must make contact, in world space.+ * The target is either the other (already posed) hand or a place on the body.+ *+ * @param {Pose} pose+ * @param {'Left'|'Right'} side the acting hand+ * @param {object} touch+ * @returns {number[]}+ */+function contactPoint(pose, side, touch) {+ const other = side === 'Left' ? 'Right' : 'Left';+ const target = touch.to ?? 'other';+ const base =+ target === 'other' || target === 'left' || target === 'right'+ ? handPoint(pose, target === 'other' ? other : target === 'left' ? 'Left' : 'Right', touch.on ?? 'palm')+ : place({ anchor: target, out: touch.out, up: touch.up, forward: touch.forward }, side, pose);+ if (target !== 'other' && target !== 'left' && target !== 'right') return base;+ // Offsets on a hand target are body-relative too, so a sign can sit a+ // fingertip slightly up the palm without naming a coordinate.+ const outward = side === 'Right' ? -1 : 1;+ return vAdd(base, [outward * (touch.out ?? 0), touch.up ?? 0, touch.forward ?? 0]);}// ── the resting signer ─────────────────────────────────────────────────────@@ -107,6 +143,30 @@ const REST_ARM = {shape: 'RELAXED',};+// Where the hands WAIT between two signs of the same utterance: low in front of+// the body, still inside signing space. A signer does not drop their arms to+// their sides between words, and an avatar that does reads as restarting the+// sentence on every word.+const NEUTRAL_ARM = {+ at: { anchor: 'belly', out: 0.15, up: 0.07, forward: 0.21 },+ fingers: ['up', 'forward', 'in'],+ palm: 'in',+ shape: 'RELAXED',+};++/**+ * The signer's hands between signs: still up, still in signing space, doing+ * nothing. Segments that continue an utterance open here instead of at+ * {@link restingPose}.+ * @param {Pose} [base]+ * @returns {Pose}+ */+export function neutralPose(base = restingPose()) {+ const pose = base.clone();+ for (const side of ['Left', 'Right']) poseHand(pose, side, NEUTRAL_ARM);+ return pose;+}+/*** A signer at rest: arms down, hands relaxed, chest open, head level. Every* utterance starts and ends here so signing has somewhere to come from and go@@ -141,15 +201,64 @@ export function restingPose() {*/export function poseHand(pose, side, spec) {if (spec.shape) applyHandshape(pose, spec.shape, side);+ const hand = `${side}Hand`;+ const fingers = direction(spec.fingers ?? 'up', side);+ const palm = direction(spec.palm ?? 'forward', side);++ let wrist;+ if (spec.touch) {+ // Solve the wrist BACKWARDS from the contact: the hand's orientation is+ // already known from `fingers`/`palm`, so the offset from the wrist to the+ // touching part is known too, and the wrist is wherever puts that part on+ // the target. This is what keeps a fingertip on the palm (and out of it)+ // when hand size or finger length changes.+ const contact = contactPoint(pose, side, spec.touch);+ const handQuat = orientQuat(boneAxis(hand), palmAxis(hand), fingers, palm);+ const offset = qRotate(handQuat, handPartOffset(pose, side, spec.touch.part ?? 'fingertips'));+ const clearance = spec.touch.gap ?? 0;+ wrist = vSub(vSub(contact, offset), vScale(vNorm(offset), clearance));+ } else {+ wrist = place(spec.at ?? REST_ARM.at, side, pose);+ }+solveArm(pose, side, {- wrist: place(spec.at ?? REST_ARM.at, side),- fingers: direction(spec.fingers ?? 'up', side),- palm: direction(spec.palm ?? 'forward', side),+ wrist,+ fingers,+ palm,pole: spec.pole ? direction(spec.pole, side) : undefined,});return pose;}+/**+ * Mirror a phase for a left-dominant signer: the hands swap roles, any contact+ * that named a hand follows them, and the head and torso turn the other way.+ * Places and directions need no mirroring at all, because they are written+ * body-relative (`out`, `in`) rather than as coordinates.+ *+ * About one signer in ten is left-dominant, and signing left-handed is not an+ * error to be corrected.+ *+ * @param {object} phase+ * @returns {object}+ */+export function mirrorPhase(phase) {+ const flipTouch = (hand) => {+ if (!hand || typeof hand !== 'object' || !hand.touch) return hand;+ const to = hand.touch.to;+ const flipped = to === 'left' ? 'right' : to === 'right' ? 'left' : to;+ return { ...hand, touch: { ...hand.touch, to: flipped } };+ };+ const out = { ...phase };+ delete out.left;+ delete out.right;+ if (phase.right !== undefined) out.left = flipTouch(phase.right);+ if (phase.left !== undefined) out.right = flipTouch(phase.left);+ if (phase.head) out.head = { ...phase.head, turn: -(phase.head.turn ?? 0), tilt: -(phase.head.tilt ?? 0) };+ if (phase.torso) out.torso = { ...phase.torso, turn: -(phase.torso.turn ?? 0) };+ return out;+}+/*** Build a whole-body pose for one phase of a sign.*@@ -167,13 +276,11 @@ export function poseHand(pose, side, spec) {*/export function posePhase(spec, base = restingPose()) {const pose = base.clone();- for (const side of ['Left', 'Right']) {- const own = spec[side.toLowerCase()];- const hand = own === 'rest' ? REST_ARM : spec.both ? { ...spec.both, ...(own ?? {}) } : own;- if (!hand) continue;- poseHand(pose, side, hand);- }const { head, torso } = spec;++ // Body first, arms second. The spine and neck carry the shoulders, so solving+ // the arms afterwards puts the hands where the sign says regardless of how the+ // torso leans — and lets a hand touch the chin AFTER the head has turned.if (torso) {// Spread the lean across the spine so the torso curves instead of hinging.for (const [bone, share] of [['Spine', 0.4], ['Spine1', 0.35], ['Spine2', 0.25]]) {@@ -195,6 +302,19 @@ export function posePhase(spec, base = restingPose()) {pose.setLocal('Neck', qMul(pose.getLocal('Neck'), qSlerp([0, 0, 0, 1], q, 0.45)));pose.setLocal('Head', qMul(pose.getLocal('Head'), qSlerp([0, 0, 0, 1], q, 0.55)));}++ // The hand being touched has to exist before the hand touching it, so a hand+ // whose spec has no `touch` is posed first.+ const hands = ['Left', 'Right']+ .map((side) => {+ const own = spec[side.toLowerCase()];+ const hand = own === 'rest' ? REST_ARM : spec.both ? { ...spec.both, ...(own ?? {}) } : own;+ return hand ? { side, hand } : null;+ })+ .filter(Boolean)+ .sort((a, b) => (a.hand.touch ? 1 : 0) - (b.hand.touch ? 1 : 0));+ for (const { side, hand } of hands) poseHand(pose, side, hand);+return pose;}@@ -247,12 +367,18 @@ function stableUuid(seed) {* const clip = tl.build({ name: 'sign-hello' });*/export class SignTimeline {- /** @param {{ base?: Pose, breathe?: boolean }} [opts] */- constructor({ base = restingPose(), breathe = true } = {}) {+ /**+ * @param {{ base?: Pose, open?: Pose, breathe?: boolean }} [opts]+ * `base` is where `settle()` returns to. `open` is the pose at t=0, which+ * differs from `base` for a segment continuing mid-utterance: the hands are+ * already up in signing space, so the segment must not start from the arms+ * hanging at the hips.+ */+ constructor({ base = restingPose(), open = null, breathe = true } = {}) {this.base = base;this.breathe = breathe;/** @type {{time:number, pose:Pose}[]} */- this.keys = [{ time: 0, pose: base }];+ this.keys = [{ time: 0, pose: open ?? base }];this.time = 0;}diff --git a/src/sign-dictionary.js b/src/sign-dictionary.jsindex 250fb24ec..e7e636d98 100644--- a/src/sign-dictionary.js+++ b/src/sign-dictionary.js@@ -23,7 +23,7 @@// verbs spatially, and carries meaning in the face). The page says so plainly —// we are not pretending otherwise.-import { SignTimeline, posePhase, restingPose } from './sign-clip.js';+import { SignTimeline, mirrorPhase, neutralPose, posePhase, restingPose } from './sign-clip.js';// Where the non-dominant hand waits when it is a surface for the other hand to// act on (FALL, HELP, GOOD, STOP): flat, palm up, in front of the chest.@@ -55,7 +55,7 @@ export const SIGNS = Object.freeze({THANK: {gloss: 'Flat hand moves out and down from the chin.',phases: [- { t: 0.3, right: { shape: 'FLAT', at: { anchor: 'chin', out: 0.03, up: -0.03, forward: 0.12 }, fingers: ['up', 'in'], palm: 'back' }, head: { nod: 3 }, hold: 0.12 },+ { t: 0.3, right: { shape: 'FLAT', touch: { to: 'chin', part: 'fingertips', out: 0.02, forward: 0.01 }, fingers: ['up', 'in'], palm: 'back' }, head: { nod: 3 }, hold: 0.12 },{ t: 0.34, right: { shape: 'FLAT', at: { anchor: 'chin', out: 0.08, up: -0.16, forward: 0.28 }, fingers: ['forward', 'up'], palm: 'up' }, head: { nod: 6 }, hold: 0.16 },],},@@ -106,8 +106,8 @@ export const SIGNS = Object.freeze({FALL: {gloss: 'Two legs stand on the flat palm, then tip over onto their back.',phases: [- { t: 0.32, left: BASE_PALM, right: { shape: 'V', at: { anchor: 'sternum', out: 0.02, up: 0.0, forward: 0.26 }, fingers: 'down', palm: 'back' }, hold: 0.16 },- { t: 0.3, left: BASE_PALM, right: { shape: 'V', at: { anchor: 'sternum', out: 0.16, up: -0.07, forward: 0.27 }, fingers: ['out', 'forward'], palm: 'up' }, head: { turn: -4, tilt: 4 }, hold: 0.2 },+ { t: 0.32, left: BASE_PALM, right: { shape: 'V', touch: { part: 'fingertips', on: 'palm' }, fingers: 'down', palm: 'back' }, hold: 0.16 },+ { t: 0.3, left: BASE_PALM, right: { shape: 'V', touch: { part: 'edge', on: 'palm', out: 0.09, up: 0.02 }, fingers: ['out', 'forward'], palm: 'up' }, head: { turn: -4, tilt: 4 }, hold: 0.2 },],},YALL: {@@ -141,21 +141,21 @@ export const SIGNS = Object.freeze({HELP: {gloss: 'A-hand rides the flat palm upward.',phases: [- { t: 0.32, left: BASE_PALM, right: { shape: 'A', at: { anchor: 'sternum', out: 0.03, up: -0.06, forward: 0.26 }, fingers: 'up', palm: 'in' } },- { t: 0.28, left: { ...BASE_PALM, at: { anchor: 'sternum', out: 0.06, up: 0.02, forward: 0.26 } }, right: { shape: 'A', at: { anchor: 'sternum', out: 0.03, up: 0.05, forward: 0.28 }, fingers: 'up', palm: 'in' }, hold: 0.16 },+ { t: 0.32, left: BASE_PALM, right: { shape: 'A', touch: { part: 'wrist', on: 'palm' }, fingers: 'up', palm: 'in' } },+ { t: 0.28, left: { ...BASE_PALM, at: { anchor: 'sternum', out: 0.06, up: 0.02, forward: 0.26 } }, right: { shape: 'A', touch: { part: 'wrist', on: 'palm' }, fingers: 'up', palm: 'in' }, hold: 0.16 },],},GOOD: {gloss: 'Flat hand comes down from the chin onto the other palm.',phases: [- { t: 0.3, right: { shape: 'FLAT', at: { anchor: 'chin', out: 0.03, up: -0.02, forward: 0.13 }, fingers: ['up', 'in'], palm: 'back' }, left: BASE_PALM, head: { nod: 3 } },- { t: 0.3, right: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.05, up: -0.02, forward: 0.25 }, fingers: ['forward', 'in'], palm: 'up' }, left: BASE_PALM, head: { nod: 5 }, hold: 0.18 },+ { t: 0.3, right: { shape: 'FLAT', touch: { to: 'chin', part: 'fingertips', out: 0.02, forward: 0.02 }, fingers: ['up', 'in'], palm: 'back' }, left: BASE_PALM, head: { nod: 3 } },+ { t: 0.3, right: { shape: 'FLAT', touch: { part: 'palm', on: 'palm' }, fingers: ['forward', 'in'], palm: 'up' }, left: BASE_PALM, head: { nod: 5 }, hold: 0.18 },],},BAD: {gloss: 'Flat hand leaves the chin and turns palm-down.',phases: [- { t: 0.3, right: { shape: 'FLAT', at: { anchor: 'chin', out: 0.03, up: -0.02, forward: 0.13 }, fingers: ['up', 'in'], palm: 'back' }, head: { nod: 2 } },+ { t: 0.3, right: { shape: 'FLAT', touch: { to: 'chin', part: 'fingertips', out: 0.02, forward: 0.02 }, fingers: ['up', 'in'], palm: 'back' }, head: { nod: 2 } },{ t: 0.3, right: { shape: 'FLAT', at: { anchor: 'chin', out: 0.14, up: -0.2, forward: 0.24 }, fingers: ['forward', 'out'], palm: 'down' }, head: { nod: -3, turn: -5 }, hold: 0.16 },],},@@ -168,28 +168,28 @@ export const SIGNS = Object.freeze({LEARN: {gloss: 'Fingers lift knowledge off the palm to the forehead.',phases: [- { t: 0.32, left: BASE_PALM, right: { shape: 'CLAW', at: { anchor: 'sternum', out: 0.04, up: -0.04, forward: 0.27 }, fingers: 'down', palm: 'down' } },+ { t: 0.32, left: BASE_PALM, right: { shape: 'CLAW', touch: { part: 'fingertips', on: 'palm' }, fingers: 'down', palm: 'down' } },{ t: 0.2, left: BASE_PALM, right: { shape: 'FLAT_O', at: { anchor: 'sternum', out: 0.04, up: 0.02, forward: 0.26 }, fingers: 'down', palm: 'back' } },- { t: 0.32, left: BASE_PALM, right: { shape: 'FLAT_O', at: { anchor: 'forehead', out: 0.05, up: -0.05, forward: 0.1 }, fingers: ['up', 'back'], palm: 'down' }, hold: 0.16 },+ { t: 0.32, left: BASE_PALM, right: { shape: 'FLAT_O', touch: { to: 'forehead', part: 'fingertips', out: 0.04, up: -0.04, gap: 0.02 }, fingers: ['up', 'back'], palm: 'down' }, hold: 0.16 },],},KNOW: {gloss: 'Fingertips tap the forehead.',phases: [- { t: 0.3, right: { shape: 'BENT_B', at: { anchor: 'forehead', out: 0.1, up: -0.06, forward: 0.07 }, fingers: ['up', 'in'], palm: 'back' } },- { t: 0.16, right: { shape: 'BENT_B', at: { anchor: 'forehead', out: 0.08, up: -0.06, forward: 0.04 }, fingers: ['up', 'in'], palm: 'back' }, hold: 0.14 },+ { t: 0.3, right: { shape: 'BENT_B', touch: { to: 'forehead', part: 'fingertips', out: 0.07, up: -0.05, gap: 0.03 }, fingers: ['up', 'in'], palm: 'back' } },+ { t: 0.16, right: { shape: 'BENT_B', touch: { to: 'forehead', part: 'fingertips', out: 0.07, up: -0.05 }, fingers: ['up', 'in'], palm: 'back' }, hold: 0.14 },],},THINK: {gloss: 'Index finger touches the temple.',phases: [- { t: 0.3, right: { shape: '1', at: { anchor: 'forehead', out: 0.09, up: -0.06, forward: 0.06 }, fingers: ['in', 'up'], palm: 'down' }, head: { tilt: 3 }, hold: 0.24 },+ { t: 0.3, right: { shape: '1', touch: { to: 'forehead', part: 'indextip', out: 0.08, up: -0.04 }, fingers: ['in', 'up'], palm: 'down' }, head: { tilt: 3 }, hold: 0.24 },],},SEE: {gloss: 'V-hand moves out from the eyes.',phases: [- { t: 0.3, right: { shape: 'V', at: { anchor: 'nose', out: 0.08, up: 0.02, forward: 0.1 }, fingers: ['up', 'forward'], palm: 'back' } },+ { t: 0.3, right: { shape: 'V', touch: { to: 'nose', part: 'fingertips', out: 0.05, up: -0.02, forward: 0.05, gap: 0.02 }, fingers: 'up', palm: 'back' } },{ t: 0.3, right: { shape: 'V', at: { anchor: 'nose', out: 0.11, up: -0.02, forward: 0.26 }, fingers: 'forward', palm: 'down' }, hold: 0.16 },],},@@ -204,23 +204,23 @@ export const SIGNS = Object.freeze({gloss: 'Both flat-O hands tap fingertips together.',phases: [{ t: 0.3, both: { shape: 'FLAT_O', at: { anchor: 'sternum', out: 0.11, up: 0.0, forward: 0.26 }, fingers: 'in', palm: 'down' } },- { t: 0.18, both: { shape: 'FLAT_O', at: { anchor: 'sternum', out: 0.05, up: 0.0, forward: 0.26 }, fingers: 'in', palm: 'down' } },+ { t: 0.18, both: { shape: 'FLAT_O', fingers: 'in', palm: 'down' }, left: { at: { anchor: 'sternum', out: 0.05, up: 0.0, forward: 0.26 } }, right: { touch: { part: 'fingertips', on: 'fingertips' } } },{ t: 0.18, both: { shape: 'FLAT_O', at: { anchor: 'sternum', out: 0.11, up: 0.0, forward: 0.26 }, fingers: 'in', palm: 'down' } },- { t: 0.18, both: { shape: 'FLAT_O', at: { anchor: 'sternum', out: 0.05, up: 0.0, forward: 0.26 }, fingers: 'in', palm: 'down' }, hold: 0.14 },+ { t: 0.18, both: { shape: 'FLAT_O', fingers: 'in', palm: 'down' }, left: { at: { anchor: 'sternum', out: 0.05, up: 0.0, forward: 0.26 } }, right: { touch: { part: 'fingertips', on: 'fingertips' } }, hold: 0.14 },],},STOP: {gloss: 'Flat hand chops down onto the other palm.',phases: [{ t: 0.3, left: { ...BASE_PALM, at: { anchor: 'sternum', out: 0.04, up: -0.06, forward: 0.26 } }, right: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.04, up: 0.09, forward: 0.26 }, fingers: ['forward', 'up'], palm: 'in' } },- { t: 0.2, left: { ...BASE_PALM, at: { anchor: 'sternum', out: 0.04, up: -0.06, forward: 0.26 } }, right: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.04, up: -0.03, forward: 0.26 }, fingers: 'forward', palm: 'in' }, head: { nod: 3 }, hold: 0.2 },+ { t: 0.2, left: { ...BASE_PALM, at: { anchor: 'sternum', out: 0.04, up: -0.06, forward: 0.26 } }, right: { shape: 'FLAT', touch: { part: 'edge', on: 'palm' }, fingers: 'forward', palm: 'in' }, head: { nod: 3 }, hold: 0.2 },],},WORK: {gloss: 'One fist taps the back of the other wrist twice.',phases: [{ t: 0.32, left: { shape: 'S', at: { anchor: 'sternum', out: 0.02, up: -0.08, forward: 0.26 }, fingers: ['forward', 'in'], palm: 'down' }, right: { shape: 'S', at: { anchor: 'sternum', out: 0.03, up: 0.02, forward: 0.24 }, fingers: ['forward', 'in'], palm: 'down' } },- { t: 0.16, left: { shape: 'S', at: { anchor: 'sternum', out: 0.02, up: -0.08, forward: 0.26 }, fingers: ['forward', 'in'], palm: 'down' }, right: { shape: 'S', at: { anchor: 'sternum', out: 0.03, up: -0.03, forward: 0.24 }, fingers: ['forward', 'in'], palm: 'down' } },+ { t: 0.16, left: { shape: 'S', at: { anchor: 'sternum', out: 0.02, up: -0.08, forward: 0.26 }, fingers: ['forward', 'in'], palm: 'down' }, right: { shape: 'S', touch: { part: 'palm', on: 'back' }, fingers: ['forward', 'in'], palm: 'down' } },{ t: 0.16, left: { shape: 'S', at: { anchor: 'sternum', out: 0.02, up: -0.08, forward: 0.26 }, fingers: ['forward', 'in'], palm: 'down' }, right: { shape: 'S', at: { anchor: 'sternum', out: 0.03, up: 0.02, forward: 0.24 }, fingers: ['forward', 'in'], palm: 'down' } },{ t: 0.16, left: { shape: 'S', at: { anchor: 'sternum', out: 0.02, up: -0.08, forward: 0.26 }, fingers: ['forward', 'in'], palm: 'down' }, right: { shape: 'S', at: { anchor: 'sternum', out: 0.03, up: -0.03, forward: 0.24 }, fingers: ['forward', 'in'], palm: 'down' }, hold: 0.14 },],@@ -242,8 +242,8 @@ export const SIGNS = Object.freeze({NICE: {gloss: 'Flat hand slides cleanly across the other palm.',phases: [- { t: 0.32, left: { ...BASE_PALM, fingers: ['forward', 'out'] }, right: { shape: 'FLAT', at: { anchor: 'sternum', out: -0.04, up: -0.05, forward: 0.24 }, fingers: ['forward', 'out'], palm: 'down' } },- { t: 0.32, left: { ...BASE_PALM, fingers: ['forward', 'out'] }, right: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.19, up: -0.05, forward: 0.26 }, fingers: ['forward', 'out'], palm: 'down' }, hold: 0.16 },+ { t: 0.32, left: { ...BASE_PALM, fingers: ['forward', 'out'] }, right: { shape: 'FLAT', touch: { part: 'palm', on: 'palm', out: -0.08 }, fingers: ['forward', 'out'], palm: 'down' } },+ { t: 0.32, left: { ...BASE_PALM, fingers: ['forward', 'out'] }, right: { shape: 'FLAT', touch: { part: 'palm', on: 'palm', out: 0.15 }, fingers: ['forward', 'out'], palm: 'down' }, hold: 0.16 },],},WELCOME: {@@ -272,7 +272,7 @@ export const SIGNS = Object.freeze({gloss: 'Bent hand arcs over and taps into the flat palm.',phases: [{ t: 0.32, left: BASE_PALM, right: { shape: 'BENT_B', at: { anchor: 'sternum', out: 0.2, up: 0.02, forward: 0.24 }, fingers: ['up', 'out'], palm: 'up' } },- { t: 0.3, left: BASE_PALM, right: { shape: 'BENT_B', at: { anchor: 'sternum', out: 0.06, up: -0.05, forward: 0.26 }, fingers: ['down', 'in'], palm: 'down' }, hold: 0.16 },+ { t: 0.3, left: BASE_PALM, right: { shape: 'BENT_B', touch: { part: 'fingertips', on: 'palm' }, fingers: ['down', 'in'], palm: 'down' }, hold: 0.16 },],},THREE: {@@ -363,20 +363,24 @@ export function buildSignClip(word, opts = {}) {const timing = { ...DEFAULT_SIGN_TIMING, ...opts };const rate = timing.rate > 0 ? timing.rate : 1;const base = opts.base ?? restingPose();- const tl = new SignTimeline({ base });+ const lead = opts.lead !== false;+ // Mid-utterance the hands are already up, so the sign opens from the neutral+ // signing stance rather than from the arms hanging at the sides.+ const tl = new SignTimeline({ base, open: lead ? base : neutralPose(base) });+ const dominant = opts.dominant === 'Left' ? 'Left' : 'Right';found.sign.phases.forEach((phase, i) => {- const seconds = ((phase.t ?? 0.3) + (i === 0 ? timing.leadSeconds : 0)) / rate;- tl.to(posePhase(phase, base), seconds, { ease: phase.ease ?? (i === 0 ? 'out' : 'smooth') });+ const seconds = ((phase.t ?? 0.3) + (i === 0 && lead ? timing.leadSeconds : 0)) / rate;+ const shaped = dominant === 'Left' ? mirrorPhase(phase) : phase;+ tl.to(posePhase(shaped, base), seconds, { ease: phase.ease ?? (i === 0 ? 'out' : 'smooth') });if (phase.hold) tl.hold(phase.hold / rate);});- if (opts.settle === false) tl.hold(timing.tailSeconds / rate);- else tl.settle(timing.tailSeconds / rate);+ if (opts.settle !== false) tl.settle(timing.tailSeconds / rate);return tl.build({name: opts.name ?? `sign-${found.name.toLowerCase()}`,- seed: `sign:${found.name}:${rate}`,+ seed: `sign:${found.name}:${rate}:${lead}:${opts.settle !== false}:${dominant}`,});}@@ -389,9 +393,12 @@ export function buildSignClip(word, opts = {}) {*/export function signLookup(opts = {}) {const cache = new Map();- return (word) => {- if (!cache.has(word)) cache.set(word, buildSignClip(word, { ...opts, settle: false }));- return cache.get(word);+ return (word, position = {}) => {+ const lead = position.first !== false;+ const settle = position.last !== false;+ const key = `${word}|${lead}|${settle}|${opts.dominant ?? 'Right'}`;+ if (!cache.has(key)) cache.set(key, buildSignClip(word, { ...opts, lead, settle }));+ return cache.get(key);};}diff --git a/src/sign-handshapes.js b/src/sign-handshapes.jsindex f41d01cb2..a191d547b 100644--- a/src/sign-handshapes.js+++ b/src/sign-handshapes.js@@ -15,15 +15,11 @@// `FLAT_O`, `BENT_B`, `OPEN_8`), which the lexical signs need and the alphabet// never used.-import { qAxisAngle, qMul, qNorm, vNorm } from './sign-rig.js';+import { FINGERS, FINGER_JOINTS, fingerBones, qAxisAngle, qMul, qNorm, vNorm } from './sign-rig.js';-export const FINGERS = ['Index', 'Middle', 'Ring', 'Pinky'];-export const FINGER_JOINTS = [1, 2, 3];--/** Every finger bone of one hand, in the order the clip tracks are emitted. */-export function fingerBones(side) {- return [...FINGERS, 'Thumb'].flatMap((f) => FINGER_JOINTS.map((j) => `${side}Hand${f}${j}`));-}+// The skeleton's own structure lives in sign-rig.js; re-exported here so callers+// that think in handshapes have one import.+export { FINGERS, FINGER_JOINTS, fingerBones };// Per-joint shares of a full curl (proximal knuckles carry most of it).const CURL_WEIGHTS = [85, 100, 65];diff --git a/src/sign-rig.js b/src/sign-rig.jsindex f8013d550..c56c6b091 100644--- a/src/sign-rig.js+++ b/src/sign-rig.js@@ -347,6 +347,144 @@ export function adductAxis(bone) {return vNorm(vCross(boneAxis(bone), qRotate(qConj(restWorld(bone)), handDir)));}+/** The five digits, and every finger bone of one hand in track order. */+export const FINGERS = Object.freeze(['Index', 'Middle', 'Ring', 'Pinky']);+export const FINGER_JOINTS = Object.freeze([1, 2, 3]);++export function fingerBones(side) {+ return [...FINGERS, 'Thumb'].flatMap((f) => FINGER_JOINTS.map((j) => `${side}Hand${f}${j}`));+}++// ── touchable parts of a hand ──────────────────────────────────────────────+//+// Signs are described by CONTACT ("two fingers stand on the flat palm", "the+// fingertips touch the forehead"), not by where the wrist happens to be. Solving+// that needs the geometry of the posed hand: where its fingertips are, where its+// palm faces. Reading it off the skeleton is what makes contact survive a+// different avatar — hand size and finger length change, and the contact still+// lands, where a hardcoded wrist position would drift off the palm.++// Skin sits outside the bone: contact points on a surface are offset off the+// bone plane by roughly half a hand's thickness so two hands meet instead of+// interpenetrating. Scaled from the rig's own hand length, not a magic number.+const SURFACE = 0.14; // fraction of hand length++/** Length past the last knuckle to the fingertip, estimated from the rig. */+function tipExtension(side, finger) {+ return boneLength(`${side}Hand${finger}2`) * 0.85;+}++/** World position of a fingertip under `pose` (past the final joint). */+export function fingerTip(pose, side, finger) {+ const distal = `${side}Hand${finger}3`;+ return vAdd(pose.worldPos(distal), vScale(pose.worldDir(distal), tipExtension(side, finger)));+}++const mean = (points) => vScale(points.reduce(vAdd, [0, 0, 0]), 1 / points.length);++/**+ * World position of a named part of a posed hand.+ *+ * `palm`/`back` are surface points, offset off the bone plane so a hand resting+ * on the palm sits ON it. `fingertips` is the pad of the index and middle+ * fingers, which is what most contacting signs actually use.+ *+ * @param {Pose} pose+ * @param {'Left'|'Right'} side+ * @param {'wrist'|'palm'|'back'|'fingertips'|'indextip'|'middletip'|'thumbtip'|'knuckles'|'fingers'|'edge'} part+ * @returns {number[]}+ */+export function handPoint(pose, side, part = 'fingertips') {+ const hand = `${side}Hand`;+ const q = pose.worldQuat(hand);+ const normal = vNorm(qRotate(q, palmAxis(hand)));+ const radial = vNorm(qRotate(q, radialAxis(hand)));+ const thickness = boneLength(hand) * SURFACE;+ const knuckles = () => FINGERS.map((f) => pose.worldPos(`${side}Hand${f}1`));+ switch (part) {+ case 'wrist':+ return pose.worldPos(hand);+ case 'palm':+ return vAdd(mean([pose.worldPos(hand), ...knuckles()]), vScale(normal, thickness));+ case 'back':+ return vAdd(mean([pose.worldPos(hand), ...knuckles()]), vScale(normal, -thickness));+ case 'knuckles':+ return vAdd(mean(knuckles()), vScale(normal, thickness));+ case 'fingers':+ return vAdd(+ mean([pose.worldPos(`${side}HandIndex2`), pose.worldPos(`${side}HandMiddle2`)]),+ vScale(normal, thickness),+ );+ case 'edge':+ return vAdd(pose.worldPos(`${side}HandPinky1`), vScale(radial, -thickness));+ case 'indextip':+ return fingerTip(pose, side, 'Index');+ case 'middletip':+ return fingerTip(pose, side, 'Middle');+ case 'thumbtip':+ return fingerTip(pose, side, 'Thumb');+ case 'fingertips':+ return mean([fingerTip(pose, side, 'Index'), fingerTip(pose, side, 'Middle')]);+ default:+ throw new Error(`unknown hand part "${part}"`);+ }+}++/**+ * The offset from the wrist to one of its own parts, expressed in the HAND's+ * local frame — so it depends only on the handshape, not on where the arm is.+ * That is what lets the solver work backwards: given where a fingertip must+ * END UP and which way the hand faces, this says where the wrist has to go.+ *+ * @param {Pose} pose supplies this hand's finger rotations+ * @param {'Left'|'Right'} side+ * @param {string} part+ * @returns {number[]}+ */+export function handPartOffset(pose, side, part = 'fingertips') {+ // Measure on a scratch pose whose arm is at rest, so the answer is purely the+ // hand's own shape.+ const scratch = new Pose();+ for (const bone of fingerBones(side)) scratch.setLocal(bone, pose.getLocal(bone));+ const hand = `${side}Hand`;+ const point = handPoint(scratch, side, part);+ return qRotate(qConj(scratch.worldQuat(hand)), vSub(point, scratch.worldPos(hand)));+}++// Anchors ride a bone, so a turned head carries the chin with it. Anything not+// listed is fixed in model space.+const ANCHOR_BONE = {+ forehead: 'Head',+ nose: 'Head',+ chin: 'Head',+ mouth: 'Head',+ head: 'Head',+ neck: 'Neck',+ sternum: 'Spine2',+ chest: 'Spine2',+ belly: 'Spine1',+ shoulder: 'Spine2',+ hip: 'Hips',+};++/**+ * An anchor's position under a POSE rather than at rest: the rest point is+ * carried by whichever bone owns it, so a sign that touches the chin still+ * touches the chin when the head has turned.+ *+ * @param {Pose} pose+ * @param {string} name ANCHORS key+ * @param {{ out?: number, up?: number, forward?: number, side?: 'Left'|'Right' }} [offset]+ * @returns {number[]}+ */+export function anchorPoint(pose, name, offset = {}) {+ const rest = signPoint(name, offset);+ const bone = ANCHOR_BONE[name];+ if (!bone || !hasBone(bone)) return rest;+ const local = qRotate(qConj(restWorld(bone)), vSub(rest, restPos(bone)));+ return vAdd(pose.worldPos(bone), qRotate(pose.worldQuat(bone), local));+}+// ── the signing body: anchors and workspace ────────────────────────────────/**diff --git a/src/sign-speech.js b/src/sign-speech.jsindex 88fafd3c8..7c6281932 100644--- a/src/sign-speech.js+++ b/src/sign-speech.js@@ -121,23 +121,51 @@ export function compileUtterance(text, opts = {}) {const words = utteranceWords(text);if (!words.length) throw new Error('text has no signable characters (A-Z, 0-9)');- const merged = new Map();- let cursor = 0;- const signed = [];- const spelled = [];- let truncated = false;+ // A signer raises their hands once for a sentence and lowers them once at the+ // end. Only the first word leads in from rest and only the last settles back+ // to it; every word between keeps the hands up in signing space, which is what+ // makes a sentence read as one utterance instead of as a list of words.+ const build = (word, position) =>+ lookup(word, position) ??+ buildFingerspellingClip(word, {+ ...timing,+ name: `fs-${word.toLowerCase()}`,+ lead: position.first,+ settle: position.last,+ dominant: opts.dominant,+ });- for (const word of words) {- const sign = lookup(word);- const segment = sign ?? buildFingerspellingClip(word, { ...timing, name: `fs-${word.toLowerCase()}` });- const segmentEnd = cursor + segment.duration + (cursor > 0 ? WORD_GAP_SECONDS : 0);- if (cursor > 0 && segmentEnd > maxSeconds) {+ const chosen = [];+ let planned = 0;+ let truncated = false;+ for (let i = 0; i < words.length; i++) {+ const position = { first: i === 0, last: false };+ const segment = build(words[i], position);+ const gap = chosen.length ? WORD_GAP_SECONDS : 0;+ // Reserve room for the closing settle so the cap still holds once the last+ // word is rebuilt with it.+ if (chosen.length && planned + gap + segment.duration + timing.tailSeconds > maxSeconds) {truncated = true;break;}+ planned += gap + segment.duration;+ chosen.push({ word: words[i], position, segment, signed: lookup(words[i], position) != null });+ }++ // Whichever word ended up last (the real last, or the one truncation stopped+ // at) is the one that lowers the hands.+ const closing = chosen[chosen.length - 1];+ closing.position = { ...closing.position, last: true };+ closing.segment = build(closing.word, closing.position);++ const merged = new Map();+ let cursor = 0;+ const signed = [];+ const spelled = [];+ for (const entry of chosen) {if (cursor > 0) cursor += WORD_GAP_SECONDS;- cursor = appendSegment(merged, segment, cursor);- (sign ? signed : spelled).push(word);+ cursor = appendSegment(merged, entry.segment, cursor);+ (entry.signed ? signed : spelled).push(entry.word);}// Rotation lanes only. A signed utterance is upper-body: it must never write@@ -175,13 +203,15 @@ export function compileUtterance(text, opts = {}) {* `signs` (optional) is the lexical dictionary passed through to the compiler.*/export class SignSpeaker {- constructor({ manager, signs = undefined, timing = null, maxSeconds = 45 } = {}) {+ constructor({ manager, signs = undefined, timing = null, maxSeconds = 45, dominant = 'Right' } = {}) {if (!manager) throw new Error('SignSpeaker needs a manager');this.manager = manager;+ /** Which hand leads. About one signer in ten signs left-dominant. */+ this.dominant = dominant === 'Left' ? 'Left' : 'Right';// Default to the built-in vocabulary: a signer signs the words they have// signs for and only spells the rest. Pass `signs: null` for spelling-only,// or your own lookup to override.- this.signs = signs === undefined ? signLookup() : signs;+ this.signs = signs === undefined ? signLookup({ dominant: this.dominant }) : signs;this.timing = timing;this.maxSeconds = maxSeconds;this._counter = 0;@@ -199,6 +229,7 @@ export class SignSpeaker {signs: this.signs,timing: this.timing ?? undefined,maxSeconds: this.maxSeconds,+ dominant: this.dominant,...opts,});const name = `sign-speech-${++this._counter}`;diff --git a/tests/aggregator-upstream-failover.test.js b/tests/aggregator-upstream-failover.test.jsnew file mode 100644index 000000000..ad56c5d08--- /dev/null+++ b/tests/aggregator-upstream-failover.test.js@@ -0,0 +1,236 @@+// The aggregator must not hand a caller a 429 while a healthy alternate+// upstream sits unused.+//+// `upstream_rate_limited` was the second-largest error class on /api/v1/x+// (881 in 30 days): the Solana provider pointed at a single RPC host, so every+// time that host throttled us the free lane passed the 429 straight through,+// even though the platform keeps a priority-ordered pool of six more endpoints+// for exactly this case (api/_lib/solana/connection.js).+//+// The rule under test: a retryable failure (429, unreachable, 5xx) walks the+// provider's alternate hosts; a caller-fault failure (4xx) never does; and a+// provider that declares no alternates behaves exactly as before, with one+// attempt and no extra cost.+//+// On top of that, a short per-host cooldown makes the failover sticky: a host+// that just failed is skipped while an alternate exists, so during an outage+// only the first request pays the discovery cost (worst case a full upstream+// timeout) instead of every request paying it.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { executeUpstream, resetUpstreamHealth } from '../api/_lib/aggregator.js';++const endpoint = {+ id: 'ping',+ method: 'GET',+ path: '/ping',+ query: () => ({}),+};++const providerWithPool = (bases) => ({+ id: 'test',+ name: 'Test provider',+ base: 'https://primary.invalid',+ bases: async () => bases,+ requiresKey: false,+ applyKey: () => {},+});++const reply = (status, body = {}) =>+ new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });++// executeUpstream calls fetch with a URL instance; tests may also see a string.+const hostOf = (input) => (input instanceof URL ? input : new URL(String(input.url || input))).host;++// Host health is module state shared by every test in this file.+beforeEach(() => resetUpstreamHealth());+afterEach(() => vi.unstubAllGlobals());++describe('aggregator upstream failover', () => {+ it('falls over to an alternate host on a 429', async () => {+ const seen = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input) => {+ seen.push(hostOf(input));+ return seen.length === 1 ? reply(429, { error: 'slow down' }) : reply(200, { ok: true });+ }),+ );++ const out = await executeUpstream({+ provider: providerWithPool(['https://backup-a.invalid', 'https://backup-b.invalid']),+ endpoint,+ query: {},+ apiKey: null,+ });++ expect(out).toEqual({ ok: true });+ expect(seen).toEqual(['primary.invalid', 'backup-a.invalid']);+ });++ it('falls over when the primary is unreachable', async () => {+ const seen = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input) => {+ seen.push(hostOf(input));+ if (seen.length === 1) throw new Error('ECONNREFUSED');+ return reply(200, { ok: true });+ }),+ );++ const out = await executeUpstream({+ provider: providerWithPool(['https://backup-a.invalid']),+ endpoint,+ query: {},+ apiKey: null,+ });++ expect(out).toEqual({ ok: true });+ expect(seen).toEqual(['primary.invalid', 'backup-a.invalid']);+ });++ it('never retries a caller-fault 4xx', async () => {+ const seen = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input) => {+ seen.push(hostOf(input));+ return reply(400, { error: 'bad address' });+ }),+ );++ await expect(+ executeUpstream({+ provider: providerWithPool(['https://backup-a.invalid']),+ endpoint,+ query: {},+ apiKey: null,+ }),+ ).rejects.toMatchObject({ status: 400, code: 'upstream_error' });+ expect(seen).toEqual(['primary.invalid']);+ });++ it('surfaces the failure once the whole pool is exhausted', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => reply(429, { error: 'slow down' })));++ await expect(+ executeUpstream({+ provider: providerWithPool(['https://backup-a.invalid', 'https://backup-b.invalid']),+ endpoint,+ query: {},+ apiKey: null,+ }),+ ).rejects.toMatchObject({ code: 'upstream_rate_limited' });+ });++ it('caps attempts so one call cannot walk an unbounded pool', async () => {+ const seen = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input) => {+ seen.push(hostOf(input));+ return reply(429, {});+ }),+ );++ const pool = Array.from({ length: 10 }, (_, i) => `https://backup-${i}.invalid`);+ await expect(+ executeUpstream({ provider: providerWithPool(pool), endpoint, query: {}, apiKey: null }),+ ).rejects.toMatchObject({ code: 'upstream_rate_limited' });+ expect(seen).toHaveLength(3);+ });++ it('makes exactly one attempt for a provider with no alternates', async () => {+ const seen = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input) => {+ seen.push(hostOf(input));+ return reply(429, {});+ }),+ );++ const provider = {+ id: 'single',+ name: 'Single host',+ base: 'https://primary.invalid',+ requiresKey: false,+ applyKey: () => {},+ };++ await expect(executeUpstream({ provider, endpoint, query: {}, apiKey: null })).rejects.toMatchObject({+ code: 'upstream_rate_limited',+ });+ expect(seen).toEqual(['primary.invalid']);+ });++ it('skips a primary that just failed, so only the first request pays for the outage', async () => {+ const seen = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input) => {+ const host = hostOf(input);+ seen.push(host);+ return host === 'primary.invalid' ? reply(429, {}) : reply(200, { ok: true });+ }),+ );++ const provider = providerWithPool(['https://backup-a.invalid']);+ await executeUpstream({ provider, endpoint, query: {}, apiKey: null });+ expect(seen).toEqual(['primary.invalid', 'backup-a.invalid']);++ // Second call within the cooldown window goes straight to the alternate.+ const out = await executeUpstream({ provider, endpoint, query: {}, apiKey: null });+ expect(out).toEqual({ ok: true });+ expect(seen).toEqual(['primary.invalid', 'backup-a.invalid', 'backup-a.invalid']);+ });++ it('still tries a cooled-down primary when the pool resolves empty', async () => {+ const seen = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input) => {+ seen.push(hostOf(input));+ return seen.length === 1 ? reply(429, {}) : reply(200, { ok: true });+ }),+ );++ // First call marks the primary bad; the second resolves an empty pool, so+ // the primary must be tried anyway rather than failing with no attempt.+ await executeUpstream({+ provider: providerWithPool(['https://backup-a.invalid']),+ endpoint,+ query: {},+ apiKey: null,+ });+ const out = await executeUpstream({ provider: providerWithPool([]), endpoint, query: {}, apiKey: null });+ expect(out).toEqual({ ok: true });+ expect(seen[seen.length - 1]).toBe('primary.invalid');+ });++ it('gives a skipped primary a last chance when every alternate fails', async () => {+ const seen = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input) => {+ seen.push(hostOf(input));+ // Primary recovers; the backup stays rate-limited throughout.+ return hostOf(input) === 'backup-a.invalid' || seen.length === 1+ ? reply(429, {})+ : reply(200, { ok: true });+ }),+ );++ const provider = providerWithPool(['https://backup-a.invalid']);+ await expect(executeUpstream({ provider, endpoint, query: {}, apiKey: null })).rejects.toMatchObject({+ code: 'upstream_rate_limited',+ });++ // Second call: primary is cooling, backup is tried first and fails, and+ // the primary (now recovered) is reached as the final candidate.+ const out = await executeUpstream({ provider, endpoint, query: {}, apiKey: null });+ expect(out).toEqual({ ok: true });+ expect(seen).toEqual(['primary.invalid', 'backup-a.invalid', 'backup-a.invalid', 'primary.invalid']);+ });+});diff --git a/tests/directory-page-refs.test.js b/tests/directory-page-refs.test.jsnew file mode 100644index 000000000..7def390d2--- /dev/null+++ b/tests/directory-page-refs.test.js@@ -0,0 +1,124 @@+// A page that routes is not a page that renders.+//+// Every public/<dir>/index.html is served at a CLEAN URL by a vercel.json route+// written `"/<dir>/?"`, which matches both `/<dir>` and `/<dir>/`. That single+// regex is the trap: on the slash-less URL the browser's base directory is the+// SITE ROOT, so a relative reference points somewhere the file isn't.+//+// /spatial-mcp + './spatial-renderer.js' → GET /spatial-renderer.js → 404+// /agent-edit + './edit.js' → GET /edit.js → 404+// /cz + './cz.css' → GET /cz.css → 404+//+// All three shipped that way. tests/pages-routes.test.js already proves a page is+// routed and built, and it passed for every one of them, because the route was+// never the problem: the page answered 200 and then loaded nothing. /spatial-mcp+// rendered two empty frames for its entire life. This test closes that gap+// statically, over every directory-served page, in milliseconds and with no+// browser (tests/e2e/spatial-mcp-render.spec.js covers the runtime half).+//+// Two rules, and the second one is why "just use an absolute path" is not the+// whole answer:+//+// A. No relative src/href in the markup. Use '/<dir>/file.js'.+// B. An INLINE module script must not import a file that lives inside public/.+// Relative fails per rule A, and absolute fails in Vite dev, which refuses+// it outright: "Cannot import non-asset file /spatial-mcp/spatial-renderer.js+// which is inside /public. JS/CSS files inside /public are copied as-is on+// build and can only be referenced via <script src>." Both doors are shut,+// so the fix is a sibling module: <script type="module" src="/<dir>/x.js">.+// A module's own relative imports resolve against the MODULE's URL, which+// always carries the directory, so they are correct on either URL form.+//+// Imports that resolve OUTSIDE public/ (the common `/src/…` pattern on Vite-input+// pages) are fine and deliberately not flagged: Vite transforms and bundles those.++import { describe, it, expect } from 'vitest';+import { readdirSync, readFileSync, existsSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const PUBLIC = path.join(ROOT, 'public');++/** Directory-served pages: public/<dir>/index.html. */+const pages = readdirSync(PUBLIC, { withFileTypes: true })+ .filter((d) => d.isDirectory() && existsSync(path.join(PUBLIC, d.name, 'index.html')))+ .map((dir) => ({ dir, file: path.join(PUBLIC, dir.name, 'index.html') }))+ .map(({ dir, file }) => ({ name: dir.name, rel: `public/${dir.name}/index.html`, html: readFileSync(file, 'utf8') }));++/**+ * A reference is relative when it has no scheme, no protocol-relative prefix and+ * no leading slash. Fragments and bare queries stay on the current document, so+ * they are unaffected by the base directory.+ */+const isRelativeRef = (value) => !!value && !/^([a-z][a-z0-9+.-]*:|\/\/|\/|#|\?)/i.test(value.trim());++/** Strip inline <script> and <style> BODIES, keeping their open tags so a real+ * `src`/`href` attribute is still checked. Without this, URLs built inside+ * JavaScript template literals (`${origin}/x.js`) read as page markup. */+function markupOnly(html) {+ return html+ .replace(/(<script\b[^>]*>)[\s\S]*?(<\/script>)/gi, '$1$2')+ .replace(/(<style\b[^>]*>)[\s\S]*?(<\/style>)/gi, '$1$2');+}++/** Every src/href on an element that fetches a subresource. */+function subresourceRefs(html) {+ const refs = [];+ const pattern = /<(script|link|img|source|iframe)\b[^>]*?\b(src|href)\s*=\s*["']([^"']+)["']/gi;+ for (const m of markupOnly(html).matchAll(pattern)) {+ refs.push({ tag: m[1].toLowerCase(), attr: m[2].toLowerCase(), value: m[3] });+ }+ return refs;+}++/** Import specifiers inside inline <script type="module"> bodies. */+function inlineModuleImports(html) {+ const specifiers = [];+ for (const block of html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)) {+ const [, attrs = '', body = ''] = block;+ if (!/type\s*=\s*["']module["']/i.test(attrs)) continue;+ if (/\bsrc\s*=/i.test(attrs)) continue; // external module: has no inline body+ const patterns = [+ /\bimport\s+[^;'"]*?\bfrom\s*["']([^"']+)["']/g, // import x from '…'+ /\bimport\s*\(\s*["']([^"']+)["']\s*\)/g, // import('…')+ /\bimport\s*["']([^"']+)["']/g, // import '…'+ ];+ for (const pattern of patterns) for (const m of body.matchAll(pattern)) specifiers.push(m[1]);+ }+ return specifiers;+}++/** Resolve an import specifier to a repo path, or null when it is not local. */+function resolveLocal(specifier, pageDir) {+ if (/^([a-z][a-z0-9+.-]*:|\/\/)/i.test(specifier)) return null; // bare/CDN/npm+ if (specifier.startsWith('/')) return path.join(ROOT, 'public', specifier.slice(1));+ if (specifier.startsWith('.')) return path.resolve(PUBLIC, pageDir, specifier);+ return null; // bare package specifier+}++describe('directory-served public pages', () => {+ it('has pages to check', () => {+ expect(pages.length).toBeGreaterThan(10);+ });++ describe.each(pages)('$rel', ({ name, html }) => {+ // Rule A — a relative subresource ref breaks on the slash-less clean URL.+ it('references every subresource absolutely', () => {+ const relative = subresourceRefs(html)+ .filter((r) => isRelativeRef(r.value))+ .map((r) => `<${r.tag} ${r.attr}="${r.value}"> → use "/${name}/${r.value.replace(/^\.\//, '')}"`);+ expect(relative).toEqual([]);+ });++ // Rule B — an inline module cannot import a file inside public/ by either+ // form, so it must be a sibling module referenced with <script src>.+ it('never inline-imports a module from inside public/', () => {+ const offenders = inlineModuleImports(html)+ .map((specifier) => ({ specifier, target: resolveLocal(specifier, name) }))+ .filter(({ target }) => target && target.startsWith(PUBLIC + path.sep) && existsSync(target))+ .map(({ specifier }) => `import '${specifier}' → move this script to /${name}/<file>.js and load it with <script type="module" src>`);+ expect(offenders).toEqual([]);+ });+ });+});diff --git a/tests/e2e/spatial-mcp-render.spec.js b/tests/e2e/spatial-mcp-render.spec.jsnew file mode 100644index 000000000..bdf5e6164--- /dev/null+++ b/tests/e2e/spatial-mcp-render.spec.js@@ -0,0 +1,121 @@+/**+ * /spatial-mcp actually renders. The runtime half of the guard.+ *+ * tests/directory-page-refs.test.js catches a page that ASKS for the wrong path.+ * It cannot catch a page that asks correctly and still shows nothing, which is how+ * this one failed twice over:+ *+ * 1. the demo imported './spatial-renderer.js', which resolves against the site+ * root on the slash-less clean URL, so the renderer 404'd and both frames+ * fell through to the fallback;+ * 2. once that was fixed, the demo GLB (a three.js npm sample path) had gone+ * 404 upstream, so the frames stayed empty anyway.+ *+ * A dead asset is invisible to any static check and to any test that only asserts+ * a 200 on the page. So this spec loads the real page and demands evidence: a+ * <model-viewer> per stage, its GLB actually loaded, the designed fallback absent,+ * the validator reporting conformance on screen, and no request on the page ending+ * >= 400. Both URL forms are exercised, because the two differ only in the base+ * directory the browser resolves against, which is the entire bug class.+ *+ * Fidelity: nothing is stubbed. The page fetches its real GLBs from their real+ * hosts, exactly as a visitor would. That is deliberate. A stubbed asset cannot+ * tell us the asset is gone, and being told is the point of the spec.+ */++import { test, expect } from '@playwright/test';++// The route is `"/spatial-mcp/?"`, so both of these serve the same file with a+// DIFFERENT base directory. Any relative reference works on one and breaks on the+// other, which is why both are non-negotiable here.+const URL_FORMS = ['/spatial-mcp', '/spatial-mcp/'];++const STAGES = [+ { id: 'stage-native', conf: 'conf-native', label: 'three.ws forge_free artifact' },+ { id: 'stage-foreign', conf: 'conf-foreign', label: 'foreign tool result, transformed' },+];++// Vite's HMR socket cannot reach the dev server through a proxied port (Codespaces,+// any remote container), which surfaces as a failed ws request and an uncaught+// "WebSocket closed without opened." Both are dev-server plumbing that does not+// exist in the built page, so they are the only ignored signals here. Anything a+// visitor's browser could hit counts as a failure.+const DEV_SERVER_NOISE = /^ws|\/@vite\//;+const DEV_SERVER_ERROR = /WebSocket closed without opened/;++/** Collect every response that failed, plus uncaught page errors. */+function watchFailures(page) {+ const failures = [];+ page.on('response', (r) => {+ if (r.status() >= 400) failures.push(`HTTP ${r.status()} ${r.url()}`);+ });+ page.on('pageerror', (e) => {+ if (DEV_SERVER_ERROR.test(e.message)) return;+ failures.push(`pageerror: ${e.message}`);+ });+ page.on('requestfailed', (r) => {+ if (DEV_SERVER_NOISE.test(r.url())) return;+ failures.push(`requestfailed: ${r.url()} ${r.failure()?.errorText || ''}`);+ });+ return failures;+}++for (const urlForm of URL_FORMS) {+ test(`spatial-mcp renders every stage at ${urlForm}`, async ({ page }) => {+ test.setTimeout(180_000);+ const failures = watchFailures(page);++ await page.goto(urlForm, { waitUntil: 'load' });++ for (const stage of STAGES) {+ const viewer = page.locator(`#${stage.id} model-viewer`);+ await expect(viewer, `${stage.label}: no <model-viewer> was created`).toHaveCount(1);++ // The renderer's designed fallback. Its presence means the payload was+ // unusable, which is precisely the state that shipped.+ await expect(+ page.locator(`#${stage.id} .spatial-empty`),+ `${stage.label}: fell back instead of rendering`,+ ).toHaveCount(0);++ // A viewer element proves the artifact was accepted. Only `loaded` proves+ // the GLB behind it exists and decoded.+ await expect+ .poll(() => viewer.evaluate((el) => el.loaded === true), {+ message: `${stage.label}: GLB never finished loading`,+ timeout: 120_000,+ })+ .toBe(true);++ await expect(viewer).toHaveAttribute('camera-controls', '');++ // The page's conformance claim, as rendered by the real validator.+ await expect(page.locator(`#${stage.conf}`)).toContainText('conformant, 0 errors');+ }++ // The checker starts populated and self-validating, so it is load-bearing UI.+ await expect(page.locator('#check-report')).toContainText('conformant, 0 errors');+ await expect(page.locator('#stage-check model-viewer')).toHaveCount(1);++ expect(failures, `failed requests on ${urlForm}`).toEqual([]);+ });+}++test('the checker names the offending field on a broken payload', async ({ page }) => {+ test.setTimeout(180_000);+ await page.goto('/spatial-mcp', { waitUntil: 'load' });++ await page.locator('[data-preset="broken"]').click();++ const report = page.locator('#check-report');+ // Actionable diagnostics, not a boolean: every rule class names its own path.+ await expect(report).toContainText('scene.glbUrl');+ await expect(report).toContainText('spatialMcpVersion');+ await expect(report).toContainText('kind');+ await expect(report).toContainText('camera.autoRotate');+ await expect(report).toContainText('ar.supported');+ await expect(report).not.toContainText('conformant, 0 errors');++ // An unusable payload gets the designed fallback, never a blank frame.+ await expect(page.locator('#stage-check .spatial-empty')).toHaveCount(1);+});diff --git a/tests/page-routing.test.js b/tests/page-routing.test.jsnew file mode 100644index 000000000..208d08e5b--- /dev/null+++ b/tests/page-routing.test.js@@ -0,0 +1,164 @@+/**+ * Page reachability guard — unit tests.+ *+ * scripts/check-pages.mjs gates `build:gcp` on "every path in data/pages.json+ * can actually be served". These tests cover the resolver behind it against a+ * synthetic dist/ built in a temp dir, so they assert the exact regression that+ * shipped twice in production:+ *+ * /timeline fixed by 5688277bd ("page shipped without a route entry")+ * /tracker advertised in data/pages.json 2026-07-23, 404 for two days+ *+ * Both had a built dist/<slug>.html and no vercel.json rewrite. server's+ * resolveStatic() has no `.html` extension fallback, so the clean URL 404s.+ * The `notfound` assertions below are the ones that matter — if someone adds an+ * extension fallback to the resolver, these fail loudly rather than silently+ * making the guard useless.+ */++import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import {+ loadRouteTable,+ resolveRequest,+ resolveStatic,+ collectDeclaredPaths,+} from '../scripts/lib/page-routing.mjs';++let root;+let distRoot;+let table;++const writeVercel = (routes) =>+ writeFileSync(path.join(root, 'vercel.json'), JSON.stringify({ routes }));++beforeAll(() => {+ root = mkdtempSync(path.join(tmpdir(), 'page-routing-'));+ distRoot = path.join(root, 'dist');+ mkdirSync(distRoot, { recursive: true });++ // A built page (no rewrite yet) — the /tracker and /timeline shape.+ writeFileSync(path.join(distRoot, 'tracker.html'), '<html>tracker</html>');+ // A page reachable as a directory index.+ mkdirSync(path.join(distRoot, 'changelog'), { recursive: true });+ writeFileSync(path.join(distRoot, 'changelog', 'index.html'), '<html>changelog</html>');+ writeFileSync(path.join(distRoot, 'home.html'), '<html>home</html>');+ writeFileSync(path.join(distRoot, '404.html'), '<html>404</html>');++ mkdirSync(path.join(root, 'data'), { recursive: true });+ writeFileSync(+ path.join(root, 'data', 'pages.json'),+ JSON.stringify({+ groups: [+ { pages: [{ path: '/tracker' }, { path: '/changelog' }] },+ { nested: { deeper: [{ path: '/tracker' }, { path: '/api/thing' }] } },+ ],+ }),+ );++ writeVercel([+ { src: '/', dest: '/home.html' },+ { src: '/changelog', dest: '/changelog/index.html' },+ { src: '/chat', status: 301 },+ { src: '/api/(.*)', dest: '/api/$1' },+ { src: '/ingest/(.*)', dest: 'https://example.com/$1' },+ { src: '/og/(.*)', dest: '/og.html', has: [{ type: 'header', key: 'user-agent', value: 'bot' }] },+ { handle: 'filesystem' },+ { src: '/(?!_vercel/).*', status: 404, dest: '/404.html' },+ ]);+ table = loadRouteTable(root);+});++afterAll(() => rmSync(root, { recursive: true, force: true }));++describe('loadRouteTable', () => {+ it('splits the table at the filesystem marker', () => {+ expect(table.phase1).toHaveLength(6);+ expect(table.postFs).toHaveLength(1);+ });+});++describe('resolveStatic', () => {+ it('serves an exact file', () => {+ expect(resolveStatic(distRoot, '/tracker.html')).toContain('tracker.html');+ });++ it('falls back to index.html for a directory', () => {+ expect(resolveStatic(distRoot, '/changelog')).toContain(path.join('changelog', 'index.html'));+ });++ it('does NOT append .html to a bare path (the bug that shipped twice)', () => {+ expect(resolveStatic(distRoot, '/tracker')).toBeNull();+ });++ it('refuses traversal outside dist', () => {+ expect(resolveStatic(distRoot, '/../vercel.json')).toBeNull();+ });+});++describe('resolveRequest', () => {+ it('flags a built page with no rewrite as unreachable', () => {+ // Exactly the /timeline and /tracker production regression.+ expect(resolveRequest('/tracker', table, distRoot).outcome).toBe('notfound');+ });++ it('resolves the page once a rewrite is added', () => {+ writeVercel([+ { src: '/tracker/?', dest: '/tracker.html' },+ { handle: 'filesystem' },+ { src: '/(?!_vercel/).*', status: 404, dest: '/404.html' },+ ]);+ const fixed = loadRouteTable(root);+ const r = resolveRequest('/tracker', fixed, distRoot);+ expect(r.outcome).toBe('static');+ expect(r.target).toContain('tracker.html');+ writeVercel([+ { src: '/', dest: '/home.html' },+ { src: '/changelog', dest: '/changelog/index.html' },+ { src: '/chat', status: 301 },+ { src: '/api/(.*)', dest: '/api/$1' },+ { src: '/ingest/(.*)', dest: 'https://example.com/$1' },+ { src: '/og/(.*)', dest: '/og.html', has: [{ type: 'header', key: 'user-agent', value: 'bot' }] },+ { handle: 'filesystem' },+ { src: '/(?!_vercel/).*', status: 404, dest: '/404.html' },+ ]);+ });++ it('classifies a rewrite to /api/ as server-rendered, not a 404', () => {+ expect(resolveRequest('/api/thing', table, distRoot).outcome).toBe('api');+ });++ it('classifies a status-only rule as a redirect', () => {+ expect(resolveRequest('/chat', table, distRoot)).toMatchObject({+ outcome: 'redirect',+ status: 301,+ });+ });++ it('classifies an external dest as a proxy, not a 404', () => {+ expect(resolveRequest('/ingest/e', table, distRoot).outcome).toBe('external');+ });++ it('resolves a directory index through a rewrite', () => {+ expect(resolveRequest('/changelog', table, distRoot).outcome).toBe('static');+ });++ it('serves / from the home.html rewrite', () => {+ expect(resolveRequest('/', table, distRoot).outcome).toBe('static');+ });++ it('ignores has[]-gated rules, which do not fire for an anonymous visitor', () => {+ // The OG rewrite only fires for social bots; a real visitor still 404s,+ // so the guard must not count it as reachable.+ expect(resolveRequest('/og/x', table, distRoot).outcome).toBe('notfound');+ });+});++describe('collectDeclaredPaths', () => {+ it('walks nested structures and dedupes', () => {+ const paths = collectDeclaredPaths(root);+ expect(paths).toEqual(['/tracker', '/changelog', '/api/thing']);+ });+});diff --git a/tests/sign-dictionary.test.js b/tests/sign-dictionary.test.jsindex 4c9990a93..390056eca 100644--- a/tests/sign-dictionary.test.js+++ b/tests/sign-dictionary.test.js@@ -17,7 +17,7 @@ import {signGloss,signLookup,} from '../src/sign-dictionary.js';-import { ANCHORS, Pose } from '../src/sign-rig.js';+import { ANCHORS, Pose, handPoint } from '../src/sign-rig.js';import { compileUtterance } from '../src/sign-speech.js';function poseAtTime(clip, time) {@@ -106,15 +106,17 @@ describe('compiled clips', () => {describe('where the hands actually go', () => {it('keeps every hand in front of the body for the whole sign', () => {+ // Measured against the body part the hand is level with, because the head+ // sits back from the chest: a hand correctly in front of the FACE can still+ // be behind the chest's depth.for (const word of WORDS) {const clip = buildSignClip(word);for (let t = 0.35; t < clip.duration - 0.35; t += 0.12) {const pose = poseAtTime(clip, t);for (const side of ['Left', 'Right']) {const hand = pose.worldPos(`${side}Hand`);- // −0.05 allows a hand resting beside the hip; the failure this- // guards is a hand swung round BEHIND the torso.- expect(hand[2], `${word} ${side} @${t.toFixed(2)}`).toBeGreaterThan(-0.06);+ const torso = hand[1] > ANCHORS.chin[1] ? pose.worldPos('Head') : pose.worldPos('Spine2');+ expect(hand[2] - torso[2], `${word} ${side} @${t.toFixed(2)}`).toBeGreaterThan(-0.05);}}}@@ -161,9 +163,11 @@ describe('where the hands actually go', () => {it('places the signs that are defined by their location', () => {const at = (word) => peakPose(buildSignClip(word)).worldPos('RightHand');- // KNOW and THINK are head signs; HAPPY and LOVE are chest signs.- expect(at('KNOW')[1]).toBeGreaterThan(ANCHORS.chin[1]);- expect(at('THINK')[1]).toBeGreaterThan(ANCHORS.chin[1]);+ // KNOW and THINK are head signs, and it is the FINGERTIPS that go to the+ // head: the wrist correctly sits a hand's length below, near the chin.+ const tip = (word, part) => handPoint(peakPose(buildSignClip(word)), 'Right', part);+ expect(tip('KNOW', 'fingertips')[1]).toBeGreaterThan(ANCHORS.chin[1]);+ expect(tip('THINK', 'indextip')[1]).toBeGreaterThan(ANCHORS.chin[1]);expect(at('HAPPY')[1]).toBeLessThan(ANCHORS.chin[1]);expect(at('HAPPY')[1]).toBeGreaterThan(ANCHORS.belly[1]);// LOVE crosses the arms, so the right hand ends up on the LEFT of centre.@@ -212,3 +216,51 @@ describe('signLookup', () => {expect(lookup('HAPPY')).toBe(lookup('HAPPY'));});});++describe('contact', () => {+ // Signs that are DEFINED by touch. Each entry says which part of the acting+ // hand must meet what, at the moment the contact phase lands.+ const CONTACTS = [+ { word: 'FALL', at: 0.7, part: 'fingertips', target: ['Left', 'palm'] },+ { word: 'GOOD', at: 'peak', part: 'palm', target: ['Left', 'palm'] },+ { word: 'STOP', at: 'peak', part: 'edge', target: ['Left', 'palm'] },+ { word: 'AGAIN', at: 'peak', part: 'fingertips', target: ['Left', 'palm'] },+ { word: 'HELP', at: 'peak', part: 'wrist', target: ['Left', 'palm'] },+ { word: 'WORK', at: 0.78, part: 'palm', target: ['Left', 'back'] },+ ];++ it('actually makes contact, within a finger’s width', () => {+ for (const { word, at, part, target } of CONTACTS) {+ const clip = buildSignClip(word);+ const pose = at === 'peak' ? peakPose(clip) : poseAtTime(clip, at);+ const acting = handPoint(pose, 'Right', part);+ const passive = handPoint(pose, target[0], target[1]);+ const gap = Math.hypot(...acting.map((v, i) => v - passive[i]));+ expect(gap, `${word}: ${part} to ${target.join(' ')}`).toBeLessThan(0.035);+ }+ });++ it('touches the body where the sign says, not a fixed coordinate', () => {+ // KNOW and THINK are forehead signs; the FINGERTIPS must reach the head,+ // which a wrist-placed hand never did (it buried the fingers in the skull).+ for (const [word, part] of [['KNOW', 'fingertips'], ['THINK', 'indextip']]) {+ const pose = peakPose(buildSignClip(word));+ const tip = handPoint(pose, 'Right', part);+ const head = pose.worldPos('Head');+ expect(Math.hypot(...tip.map((v, i) => v - head[i])), word).toBeLessThan(0.16);+ // And the fingertip is in FRONT of the head centre, not inside it.+ expect(tip[2], `${word} depth`).toBeGreaterThan(head[2]);+ }+ });++ it('re-solves contact when the hands are a different size', () => {+ // The whole point of solving from geometry: a longer finger moves the wrist+ // back, it does not push the fingertip through the palm. Compare the wrist+ // offset for a flat hand against a fist at the same contact.+ const flat = poseAtTime(buildSignClip('GOOD'), buildSignClip('GOOD').duration - 0.4);+ const wristToTip = Math.hypot(+ ...handPoint(flat, 'Right', 'fingertips').map((v, i) => v - flat.worldPos('RightHand')[i]),+ );+ expect(wristToTip).toBeGreaterThan(0.1); // a real hand length, read off the rig+ });+});diff --git a/tests/sign-linguistics.test.js b/tests/sign-linguistics.test.jsnew file mode 100644index 000000000..1646b4c70--- /dev/null+++ b/tests/sign-linguistics.test.js@@ -0,0 +1,137 @@+/**+ * ASL phonological constraints — a lint over the sign vocabulary.+ *+ * Two-handed signs are not free-form. Battison (1978) described two constraints+ * that hold across the whole language, and a sign that breaks one is almost+ * always an authoring mistake rather than a real exception:+ *+ * Symmetry Condition — if BOTH hands move, they use the same handshape and+ * their movement is symmetrical.+ * Dominance Condition — if the two hands take DIFFERENT handshapes, only the+ * dominant hand may move and the passive hand is limited to a small set of+ * unmarked handshapes. Two hands sharing one handshape are unrestricted,+ * which is why NAME (both hands in H, only the dominant one taps) is fine.+ *+ * Encoding them here means a new entry in src/sign-dictionary.js is checked+ * against the language, not just against whether it renders. That matters more+ * as the vocabulary grows and as signs arrive from people who did not write the+ * solver.+ */++import { describe, expect, it } from 'vitest';++import { SIGNS } from '../src/sign-dictionary.js';+import { HANDSHAPES } from '../src/sign-handshapes.js';++// The unmarked handshapes: the ones a passive hand is allowed to take. These are+// the maximally distinct, easiest-to-produce shapes of the language.+const UNMARKED = new Set(['A', 'S', 'B', 'FLAT', '5', 'C', 'O', '0', '1', 'BENT_B', 'FLAT_O', 'CLAW']);++/** Resolve each phase into what each hand is doing. */+function handTrack(sign, side) {+ return sign.phases.map((phase) => {+ const own = phase[side];+ if (own === 'rest') return null;+ const merged = phase.both ? { ...phase.both, ...(own ?? {}) } : own;+ if (!merged) return null;+ return {+ shape: merged.shape ?? null,+ // Everything that determines WHERE the hand is. Two phases that differ+ // in any of these mean the hand moved.+ place: JSON.stringify([merged.at ?? null, merged.touch ?? null, merged.fingers ?? null, merged.palm ?? null]),+ };+ });+}++function moves(track) {+ const active = track.filter(Boolean);+ if (active.length < 2) return false;+ return active.some((p) => p.place !== active[0].place);+}++/** The last handshape a hand is given (shapes carry forward between phases). */+function shapeOf(track) {+ let shape = null;+ for (const phase of track) if (phase?.shape) shape = phase.shape;+ return shape;+}++const ENTRIES = Object.entries(SIGNS).map(([word, sign]) => ({+ word,+ sign,+ right: handTrack(sign, 'right'),+ left: handTrack(sign, 'left'),+}));++const twoHanded = ENTRIES.filter((e) => e.right.some(Boolean) && e.left.some(Boolean));++describe('handshapes referenced by the vocabulary', () => {+ it('every shape a sign names actually exists', () => {+ for (const { word, sign } of ENTRIES) {+ for (const phase of sign.phases) {+ for (const hand of [phase.both, phase.left, phase.right]) {+ if (!hand || hand === 'rest' || !hand.shape) continue;+ expect(HANDSHAPES[hand.shape], `${word}: "${hand.shape}"`).toBeTruthy();+ }+ }+ }+ });+});++describe('Battison’s Symmetry Condition', () => {+ it('when both hands move, both use the same handshape', () => {+ for (const entry of twoHanded) {+ if (!moves(entry.right) || !moves(entry.left)) continue;+ const right = shapeOf(entry.right);+ const left = shapeOf(entry.left);+ expect(left, `${entry.word}: both hands move, so both must take one handshape`).toBe(right);+ }+ });+});++describe('Battison’s Dominance Condition', () => {+ it('a passive hand of its own handshape only ever takes an unmarked one', () => {+ for (const entry of twoHanded) {+ const rightMoves = moves(entry.right);+ const leftMoves = moves(entry.left);+ if (rightMoves === leftMoves) continue; // both move, or neither: not this rule+ const active = shapeOf(rightMoves ? entry.right : entry.left);+ const passive = shapeOf(rightMoves ? entry.left : entry.right);+ if (!passive || passive === active) continue; // one shared shape is unrestricted+ expect(+ UNMARKED.has(passive),+ `${entry.word}: the hands differ, so the passive "${passive}" must be an unmarked handshape`,+ ).toBe(true);+ }+ });+});++describe('vocabulary hygiene', () => {+ it('no sign leaves a hand with a place but no handshape', () => {+ for (const { word, sign } of ENTRIES) {+ for (const [i, phase] of sign.phases.entries()) {+ for (const side of ['left', 'right']) {+ const hand = phase.both ? { ...phase.both, ...(phase[side] ?? {}) } : phase[side];+ if (!hand || hand === 'rest') continue;+ const first = sign.phases.findIndex(+ (p) => p.both?.shape || p[side]?.shape,+ );+ expect(first >= 0 && first <= i, `${word} phase ${i} (${side})`).toBe(true);+ }+ }+ }+ });++ it('every phase moves the hands somewhere new', () => {+ // A phase identical to the one before it is dead time, not a sign.+ for (const { word, right, left } of ENTRIES) {+ for (let i = 1; i < right.length; i++) {+ const same =+ right[i]?.place === right[i - 1]?.place &&+ left[i]?.place === left[i - 1]?.place &&+ right[i]?.shape === right[i - 1]?.shape;+ expect(same, `${word}: phase ${i} repeats phase ${i - 1}`).toBe(false);+ }+ }+ });+});diff --git a/tests/x402-discovery-resources.test.js b/tests/x402-discovery-resources.test.jsnew file mode 100644index 000000000..0f6460a9b--- /dev/null+++ b/tests/x402-discovery-resources.test.js@@ -0,0 +1,185 @@+import { describe, it, expect } from 'vitest';+import {+ toV1Accept,+ toV1Item,+ projectDiscoveryResources,+ DISCOVERY_DEFAULT_LIMIT,+ DISCOVERY_MAX_LIMIT,+} from '../api/_lib/x402/discovery-resources.js';++// ── Fixtures ─────────────────────────────────────────────────────────────────++const SOLANA_CAIP2 = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';+const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+const PAY_TO = 'wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU';++const solanaAccept = (over = {}) => ({+ scheme: 'exact',+ network: SOLANA_CAIP2,+ network_label: 'solana-mainnet',+ amount: '10000',+ price: '$0.01',+ payTo: PAY_TO,+ asset: USDC_MINT,+ asset_symbol: 'USDC',+ maxTimeoutSeconds: 60,+ resource: 'https://three.ws/api/x402/three-intel',+ extra: { name: 'USDC', decimals: 6 },+ ...over,+});++const item = (over = {}) => ({+ path: '/api/x402/three-intel',+ url: 'https://three.ws/api/x402/three-intel',+ method: 'GET',+ description: 'Live $THREE market intel.',+ mimeType: 'application/json',+ serviceName: '$THREE Town Oracle',+ tags: ['three', 'market'],+ accepts: [solanaAccept()],+ ...over,+});++const doc = (resources) => ({ resources });++const ISO = '2026-07-25T00:00:00.000Z';++// ── toV1Accept ───────────────────────────────────────────────────────────────++describe('toV1Accept', () => {+ it('projects a v2 Solana accept to the legacy v1 shape', () => {+ const v1 = toV1Accept(solanaAccept(), item());+ expect(v1).toEqual({+ scheme: 'exact',+ network: 'solana',+ maxAmountRequired: '10000',+ resource: 'https://three.ws/api/x402/three-intel',+ description: 'Live $THREE market intel.',+ mimeType: 'application/json',+ payTo: PAY_TO,+ maxTimeoutSeconds: 60,+ asset: USDC_MINT,+ extra: { name: 'USDC', decimals: 6 },+ });+ });++ it('maps Base CAIP-2 to the v1 name', () => {+ const v1 = toV1Accept(+ solanaAccept({ network: 'eip155:8453', payTo: '0x4022de000000000000000000000000000000dEaD', asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' }),+ item(),+ );+ expect(v1.network).toBe('base');+ });++ it('drops networks the legacy schema cannot name (Arbitrum, BSC, X Layer)', () => {+ for (const network of ['eip155:42161', 'eip155:56', 'eip155:196']) {+ expect(toV1Accept(solanaAccept({ network }), item())).toBeNull();+ }+ });++ it('drops non-exact schemes', () => {+ expect(toV1Accept(solanaAccept({ scheme: 'direct' }), item())).toBeNull();+ });++ it('drops accepts with a missing or non-atomic amount', () => {+ expect(toV1Accept(solanaAccept({ amount: undefined }), item())).toBeNull();+ expect(toV1Accept(solanaAccept({ amount: '0.01' }), item())).toBeNull();+ });++ it('accepts v1-style maxAmountRequired as the amount source', () => {+ const v1 = toV1Accept(solanaAccept({ amount: undefined, maxAmountRequired: '500' }), item());+ expect(v1.maxAmountRequired).toBe('500');+ });++ it('falls back to the item url and defaults when accept fields are sparse', () => {+ const v1 = toV1Accept(+ solanaAccept({ resource: undefined, maxTimeoutSeconds: undefined, extra: undefined }),+ item({ mimeType: undefined }),+ );+ expect(v1.resource).toBe('https://three.ws/api/x402/three-intel');+ expect(v1.maxTimeoutSeconds).toBe(60);+ expect(v1.mimeType).toBe('application/json');+ expect(v1).not.toHaveProperty('extra');+ });+});++// ── toV1Item ─────────────────────────────────────────────────────────────────++describe('toV1Item', () => {+ it('builds a DiscoveredResource with metadata', () => {+ const v1 = toV1Item(item(), ISO);+ expect(v1.resource).toBe('https://three.ws/api/x402/three-intel');+ expect(v1.type).toBe('http');+ expect(v1.x402Version).toBe(1);+ expect(v1.lastUpdated).toBe(ISO);+ expect(v1.accepts).toHaveLength(1);+ expect(v1.metadata).toMatchObject({+ serviceName: '$THREE Town Oracle',+ method: 'GET',+ path: '/api/x402/three-intel',+ });+ });++ it('returns null when no accept survives the projection', () => {+ expect(toV1Item(item({ accepts: [solanaAccept({ network: 'eip155:42161' })] }), ISO)).toBeNull();+ expect(toV1Item(item({ accepts: [] }), ISO)).toBeNull();+ });++ it('returns null for a resource without a url', () => {+ expect(toV1Item(item({ url: undefined }), ISO)).toBeNull();+ });+});++// ── projectDiscoveryResources ────────────────────────────────────────────────++describe('projectDiscoveryResources', () => {+ const many = (n) =>+ doc(+ Array.from({ length: n }, (_, i) =>+ item({ url: `https://three.ws/api/x402/svc-${i}`, path: `/api/x402/svc-${i}` }),+ ),+ );++ it('returns the v1 envelope with pagination', () => {+ const page = projectDiscoveryResources(many(3), { lastUpdated: ISO });+ expect(page.x402Version).toBe(1);+ expect(page.items).toHaveLength(3);+ expect(page.pagination).toEqual({ limit: DISCOVERY_DEFAULT_LIMIT, offset: 0, total: 3 });+ });++ it('pages with limit and offset the way the x402scan crawler does', () => {+ const page1 = projectDiscoveryResources(many(150), { limit: 100, offset: 0 });+ const page2 = projectDiscoveryResources(many(150), { limit: 100, offset: 100 });+ expect(page1.items).toHaveLength(100);+ expect(page2.items).toHaveLength(50);+ expect(page2.pagination).toEqual({ limit: 100, offset: 100, total: 150 });+ expect(page1.items[0].resource).not.toBe(page2.items[0].resource);+ });++ it('clamps limit and floors offset', () => {+ const page = projectDiscoveryResources(many(2), { limit: 999999, offset: -5 });+ expect(page.pagination.limit).toBe(DISCOVERY_MAX_LIMIT);+ expect(page.pagination.offset).toBe(0);+ });++ it('counts only projectable resources in total', () => {+ const mixed = doc([+ item(),+ item({ url: 'https://three.ws/api/x402/arb-only', accepts: [solanaAccept({ network: 'eip155:42161' })] }),+ ]);+ const page = projectDiscoveryResources(mixed, {});+ expect(page.pagination.total).toBe(1);+ });++ it('serves an empty page for a non-http type filter', () => {+ const page = projectDiscoveryResources(many(3), { type: 'mcp' });+ expect(page.items).toEqual([]);+ expect(page.pagination.total).toBe(0);+ });++ it('handles a doc with no resources', () => {+ const page = projectDiscoveryResources({}, {});+ expect(page.items).toEqual([]);+ expect(page.pagination.total).toBe(0);+ });+});diff --git a/vercel.json b/vercel.jsonindex 1cd5d6c92..40dc044e3 100644--- a/vercel.json+++ b/vercel.json@@ -2500,6 +2500,10 @@"src": "/api/x402-facilitator/?","dest": "/api/x402-facilitator/[action]?action=index"},+ {+ "src": "/api/x402-facilitator/discovery/resources",+ "dest": "/api/x402-facilitator/[action]?action=discovery-resources"+ },{"src": "/api/x402-facilitator/([^/]+)","dest": "/api/x402-facilitator/[action]?action=$1"diff --git a/workers/avatar-reconstruction/eval/adversarial/crowd-group-photo.png b/workers/avatar-reconstruction/eval/adversarial/crowd-group-photo.pngnew file mode 100644index 000000000..365fd0411Binary files /dev/null and b/workers/avatar-reconstruction/eval/adversarial/crowd-group-photo.png differdiff --git a/workers/avatar-reconstruction/eval/adversarial/crowd-two-people.png b/workers/avatar-reconstruction/eval/adversarial/crowd-two-people.pngnew file mode 100644index 000000000..d326bad85Binary files /dev/null and b/workers/avatar-reconstruction/eval/adversarial/crowd-two-people.png differdiff --git a/workers/avatar-reconstruction/eval/adversarial/depicted-magazine-page.png b/workers/avatar-reconstruction/eval/adversarial/depicted-magazine-page.pngnew file mode 100644index 000000000..8967ad33aBinary files /dev/null and b/workers/avatar-reconstruction/eval/adversarial/depicted-magazine-page.png differdiff --git a/workers/avatar-reconstruction/eval/adversarial/depicted-oil-painting.png b/workers/avatar-reconstruction/eval/adversarial/depicted-oil-painting.pngnew file mode 100644index 000000000..e3e747b8aBinary files /dev/null and b/workers/avatar-reconstruction/eval/adversarial/depicted-oil-painting.png differdiff --git a/workers/avatar-reconstruction/eval/adversarial/depicted-phone-screen.png b/workers/avatar-reconstruction/eval/adversarial/depicted-phone-screen.pngnew file mode 100644index 000000000..a611dfdd0Binary files /dev/null and b/workers/avatar-reconstruction/eval/adversarial/depicted-phone-screen.png differdiff --git a/workers/avatar-reconstruction/eval/adversarial/depicted-wall-poster.png b/workers/avatar-reconstruction/eval/adversarial/depicted-wall-poster.pngnew file mode 100644index 000000000..d5f67d420Binary files /dev/null and b/workers/avatar-reconstruction/eval/adversarial/depicted-wall-poster.png differdiff --git a/workers/avatar-reconstruction/eval/adversarial/extreme-extreme-closeup.png b/workers/avatar-reconstruction/eval/adversarial/extreme-extreme-closeup.pngnew file mode 100644index 000000000..dcca64ab9Binary files /dev/null and b/workers/avatar-reconstruction/eval/adversarial/extreme-extreme-closeup.png differdiff --git a/workers/avatar-reconstruction/eval/adversarial/extreme-hard-backlight.png b/workers/avatar-reconstruction/eval/adversarial/extreme-hard-backlight.pngnew file mode 100644index 000000000..c445e346aBinary files /dev/null and b/workers/avatar-reconstruction/eval/adversarial/extreme-hard-backlight.png differdiff --git a/workers/avatar-reconstruction/eval/adversarial/extreme-motion-blur.png b/workers/avatar-reconstruction/eval/adversarial/extreme-motion-blur.pngnew file mode 100644index 000000000..bfad25c0fBinary files /dev/null and b/workers/avatar-reconstruction/eval/adversarial/extreme-motion-blur.png differdiff --git a/workers/avatar-reconstruction/eval/adversarial/extreme-near-profile.png b/workers/avatar-reconstruction/eval/adversarial/extreme-near-profile.pngnew file mode 100644index 000000000..4514f00acBinary files /dev/null and b/workers/avatar-reconstruction/eval/adversarial/extreme-near-profile.png differdiff --git a/workers/avatar-reconstruction/eval/adversarial/manifest.json b/workers/avatar-reconstruction/eval/adversarial/manifest.jsonnew file mode 100644index 000000000..85402171f--- /dev/null+++ b/workers/avatar-reconstruction/eval/adversarial/manifest.json@@ -0,0 +1,82 @@+[+ {+ "name": "non_face-golden-retriever",+ "category": "non_face",+ "prompt": "a close-up photograph of a golden retriever dog's face looking straight at the camera, plain grey background, sharp focus"+ },+ {+ "name": "non_face-tabby-cat",+ "category": "non_face",+ "prompt": "a close-up photograph of a tabby cat's face looking directly at the camera, plain background, sharp focus"+ },+ {+ "name": "non_face-marble-statue",+ "category": "non_face",+ "prompt": "a frontal photograph of a classical white marble bust of a human head on a plain grey background, museum lighting"+ },+ {+ "name": "non_face-porcelain-doll",+ "category": "non_face",+ "prompt": "a frontal photograph of an antique porcelain doll's head and shoulders, plain background"+ },+ {+ "name": "non_face-carnival-mask",+ "category": "non_face",+ "prompt": "a frontal photograph of a decorated venetian carnival mask hanging on a plain grey wall"+ },+ {+ "name": "non_face-shop-mannequin",+ "category": "non_face",+ "prompt": "a frontal photograph of a featureless retail shop mannequin head on a plain background"+ },+ {+ "name": "depicted-wall-poster",+ "category": "depicted",+ "prompt": "a wide photograph of a city street wall with a large advertising poster of a smiling person's face on it, seen at an angle, other buildings visible"+ },+ {+ "name": "depicted-phone-screen",+ "category": "depicted",+ "prompt": "a photograph of a hand holding a smartphone that is displaying a portrait photo of a person on its screen, indoor background"+ },+ {+ "name": "depicted-oil-painting",+ "category": "depicted",+ "prompt": "a photograph of an ornately framed renaissance oil portrait painting hanging on a gallery wall"+ },+ {+ "name": "depicted-magazine-page",+ "category": "depicted",+ "prompt": "an overhead photograph of an open glossy magazine lying on a wooden table, showing a full-page portrait photograph"+ },+ {+ "name": "crowd-group-photo",+ "category": "crowd",+ "prompt": "a photograph of six friends standing together smiling at the camera outdoors, all faces clearly visible"+ },+ {+ "name": "crowd-two-people",+ "category": "crowd",+ "prompt": "a photograph of two people standing side by side facing the camera, both faces equally visible, plain background"+ },+ {+ "name": "extreme-near-profile",+ "category": "extreme",+ "prompt": "a photograph of a person's head in near-complete side profile, ninety degrees to the camera, plain grey background"+ },+ {+ "name": "extreme-hard-backlight",+ "category": "extreme",+ "prompt": "a photograph of a person standing directly in front of a bright window, face in deep shadow and heavily backlit, silhouette-like"+ },+ {+ "name": "extreme-motion-blur",+ "category": "extreme",+ "prompt": "a photograph of a person's face with severe motion blur from fast camera movement, barely legible features"+ },+ {+ "name": "extreme-extreme-closeup",+ "category": "extreme",+ "prompt": "an extreme macro photograph showing only a person's eye and part of the nose, filling the entire frame"+ }+]\ No newline at end of filediff --git a/workers/avatar-reconstruction/eval/adversarial/non_face-carnival-mask.png b/workers/avatar-reconstruction/eval/adversarial/non_face-carnival-mask.pngnew file mode 100644index 000000000..9f11250b6Binary files /dev/null and b/workers/avatar-reconstruction/eval/adversarial/non_face-carnival-mask.png differdiff --git a/workers/avatar-reconstruction/eval/adversarial/non_face-golden-retriever.png b/workers/avatar-reconstruction/eval/adversarial/non_face-golden-retriever.pngnew file mode 100644index 000000000..1d729444eBinary files /dev/null and b/workers/avatar-reconstruction/eval/adversarial/non_face-golden-retriever.png differdiff --git a/workers/avatar-reconstruction/eval/adversarial/non_face-marble-statue.png b/workers/avatar-reconstruction/eval/adversarial/non_face-marble-statue.pngnew file mode 100644index 000000000..473c8f115Binary files /dev/null and b/workers/avatar-reconstruction/eval/adversarial/non_face-marble-statue.png differdiff --git a/workers/avatar-reconstruction/eval/adversarial/non_face-porcelain-doll.png b/workers/avatar-reconstruction/eval/adversarial/non_face-porcelain-doll.pngnew file mode 100644index 000000000..4c1c6605cBinary files /dev/null and b/workers/avatar-reconstruction/eval/adversarial/non_face-porcelain-doll.png differdiff --git a/workers/avatar-reconstruction/eval/adversarial/non_face-shop-mannequin.png b/workers/avatar-reconstruction/eval/adversarial/non_face-shop-mannequin.pngnew file mode 100644index 000000000..d6c0a5bb1Binary files /dev/null and b/workers/avatar-reconstruction/eval/adversarial/non_face-shop-mannequin.png differdiff --git a/workers/avatar-reconstruction/eval/adversarial/non_face-tabby-cat.png b/workers/avatar-reconstruction/eval/adversarial/non_face-tabby-cat.pngnew file mode 100644index 000000000..c10258a88Binary files /dev/null and b/workers/avatar-reconstruction/eval/adversarial/non_face-tabby-cat.png differdiff --git a/workers/avatar-reconstruction/eval/make_adversarial.py b/workers/avatar-reconstruction/eval/make_adversarial.pynew file mode 100644index 000000000..d24086205--- /dev/null+++ b/workers/avatar-reconstruction/eval/make_adversarial.py@@ -0,0 +1,156 @@+"""+Build the adversarial half of the benchmark — the inputs that should NOT drive a+face morph.++`make_refs.py` produces clean portraits, which measure fidelity. They cannot+measure safety, because nothing in them is wrong. This produces the opposite: a+set where the correct behaviour is either "detect nothing" or "detect something+and refuse to use it".++The distinction that matters is between two failure modes:++- **Detection fails.** Safe. `face_pipeline` falls back to texture-only and the+ user gets a template-shaped head rather than a corrupted one.+- **Detection succeeds on the wrong thing.** Dangerous, and the reason this file+ exists. MediaPipe FaceMesh is a *fitted model*: it does not answer "is this a+ face", it answers "where would a face be if there were one". Handed a pet, a+ painting, a mask or a statue it will happily return 468 confident, internally+ coherent landmarks. Every point is wrong in a *correlated* way, so the+ per-control-point clamp in `morph_head_to_landmarks` — which only bounds how+ far any single point may travel — sees nothing unusual and passes the whole+ distorted geometry through to the mesh.++Categories, chosen because each defeats a different assumption:++ non_face — a face-like thing that is not a person (pet, statue, doll, mask)+ depicted — a real face, but a picture of one inside a scene (poster, phone+ screen, painting): correct detection, wrong subject, and often a+ severe perspective skew+ crowd — several faces, so "the" face is ambiguous+ extreme — a real person past the pose/quality envelope the pipeline assumes+ (near-profile, hard backlight, heavy motion blur)++Usage+-----+ python -m eval.make_adversarial --out eval/adversarial+ python -m eval.make_adversarial --out eval/adversarial --upload++Then measure what the pipeline does with them:++ python -m eval.detection_guard --adversarial eval/adversarial --photos eval/refs+"""++from __future__ import annotations++import argparse+import base64+import json+import subprocess+import sys+from pathlib import Path++import httpx++PROJECT = "aerial-vehicle-466722-p5"+LOCATION = "us-central1"+MODEL = "gemini-2.5-flash-image"+GCS_PREFIX = "gs://three-ws-avatar-reconstructions/eval-adversarial"++SAMPLES = [+ # ── non_face: face-like, not a person ────────────────────────────────────+ ("non_face", "golden-retriever", "a close-up photograph of a golden retriever dog's face looking straight at the camera, plain grey background, sharp focus"),+ ("non_face", "tabby-cat", "a close-up photograph of a tabby cat's face looking directly at the camera, plain background, sharp focus"),+ ("non_face", "marble-statue", "a frontal photograph of a classical white marble bust of a human head on a plain grey background, museum lighting"),+ ("non_face", "porcelain-doll", "a frontal photograph of an antique porcelain doll's head and shoulders, plain background"),+ ("non_face", "carnival-mask", "a frontal photograph of a decorated venetian carnival mask hanging on a plain grey wall"),+ ("non_face", "shop-mannequin", "a frontal photograph of a featureless retail shop mannequin head on a plain background"),++ # ── depicted: a real face, but not the photographer's subject ────────────+ ("depicted", "wall-poster", "a wide photograph of a city street wall with a large advertising poster of a smiling person's face on it, seen at an angle, other buildings visible"),+ ("depicted", "phone-screen", "a photograph of a hand holding a smartphone that is displaying a portrait photo of a person on its screen, indoor background"),+ ("depicted", "oil-painting", "a photograph of an ornately framed renaissance oil portrait painting hanging on a gallery wall"),+ ("depicted", "magazine-page", "an overhead photograph of an open glossy magazine lying on a wooden table, showing a full-page portrait photograph"),++ # ── crowd: which face? ───────────────────────────────────────────────────+ ("crowd", "group-photo", "a photograph of six friends standing together smiling at the camera outdoors, all faces clearly visible"),+ ("crowd", "two-people", "a photograph of two people standing side by side facing the camera, both faces equally visible, plain background"),++ # ── extreme: a real subject, past the envelope ───────────────────────────+ ("extreme", "near-profile", "a photograph of a person's head in near-complete side profile, ninety degrees to the camera, plain grey background"),+ ("extreme", "hard-backlight", "a photograph of a person standing directly in front of a bright window, face in deep shadow and heavily backlit, silhouette-like"),+ ("extreme", "motion-blur", "a photograph of a person's face with severe motion blur from fast camera movement, barely legible features"),+ ("extreme", "extreme-closeup", "an extreme macro photograph showing only a person's eye and part of the nose, filling the entire frame"),+]+++def access_token() -> str:+ return subprocess.run(+ ["gcloud", "auth", "print-access-token"],+ capture_output=True, text=True, check=True,+ ).stdout.strip()+++def generate(client: httpx.Client, token: str, prompt: str) -> bytes:+ url = (+ f"https://{LOCATION}-aiplatform.googleapis.com/v1/projects/{PROJECT}"+ f"/locations/{LOCATION}/publishers/google/models/{MODEL}:generateContent"+ )+ response = client.post(+ url,+ headers={"Authorization": f"Bearer {token}"},+ json={+ "contents": [{"role": "user", "parts": [{"text": prompt}]}],+ "generationConfig": {+ "responseModalities": ["IMAGE"],+ "imageConfig": {"aspectRatio": "3:4"},+ },+ },+ timeout=300.0,+ )+ response.raise_for_status()+ payload = response.json()+ for part in payload.get("candidates", [{}])[0].get("content", {}).get("parts", []):+ if "inlineData" in part:+ return base64.b64decode(part["inlineData"]["data"])+ raise RuntimeError(f"no image returned: {json.dumps(payload)[:200]}")+++def main() -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--out", type=Path, default=Path("eval/adversarial"))+ ap.add_argument("--upload", action="store_true")+ ap.add_argument("--force", action="store_true")+ args = ap.parse_args()++ args.out.mkdir(parents=True, exist_ok=True)+ token = access_token()+ manifest = []++ with httpx.Client() as client:+ for i, (category, slug, prompt) in enumerate(SAMPLES, 1):+ name = f"{category}-{slug}"+ path = args.out / f"{name}.png"+ entry = {"name": name, "category": category, "prompt": prompt}+ if path.exists() and not args.force:+ print(f"[{i}/{len(SAMPLES)}] {name} — exists, skipping")+ manifest.append(entry)+ continue+ print(f"[{i}/{len(SAMPLES)}] {name} … ", end="", flush=True)+ try:+ path.write_bytes(generate(client, token, prompt))+ manifest.append(entry)+ print("ok")+ except Exception as exc:+ print(f"FAILED — {exc}")++ (args.out / "manifest.json").write_text(json.dumps(manifest, indent=2))+ print(f"\n{len(manifest)}/{len(SAMPLES)} in {args.out}")++ if args.upload:+ subprocess.run(["gcloud", "storage", "rsync", "-r", str(args.out), GCS_PREFIX], check=True)+ print(f"mirrored → {GCS_PREFIX}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())