Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(i18n): authenticated agent-driven translation lane with its rc schema, and a hardened tour-atlas capture
nirholasdc2e245a5490
diff --git a/public/locales/en.json b/public/locales/en.jsonindex fa20d30fc..3ee84e306 100644--- a/public/locales/en.json+++ b/public/locales/en.json@@ -20098,12 +20098,12 @@"x402_operated_by_three_ws": "x402 · operated by three.ws"},"x402_studio": {- "meta_description": "The Stripe of x402. Configure prices, payout and agent wallets, products, security, CORS, charity and round-up giving — and publish a drag-and-drop storefront. All settled on-chain in USDC.",+ "meta_description": "The Stripe of x402. Configure prices, payout and agent wallets, products, security, CORS, charity and round-up giving, and publish a drag-and-drop storefront. All settled on-chain in USDC.","meta_og_description": "Run a paid x402 business: agent wallets, products, a drag-and-drop storefront, charity + round-up giving. On-chain USDC settlement.",- "meta_og_title": "x402 Studio — the Stripe of x402",+ "meta_og_title": "x402 Studio: the Stripe of x402","meta_title": "x402 Studio · three.ws","meta_twitter_description": "Merchant console to run a paid x402 business: products and pricing, payout and agent wallets, a real USDC send/receive with SNS .sol resolution, a drag-and-drop storefront, an embeddable pay-button builder, charity and round-up giving, CORS and security.",- "meta_twitter_title": "x402 Studio — the Stripe of x402 · three.ws"+ "meta_twitter_title": "x402 Studio: the Stripe of x402 · three.ws"},"x_pricing": {"100_x_posts_per_month": "100 X posts per month",diff --git a/scripts/capture-tour-atlas.mjs b/scripts/capture-tour-atlas.mjsindex 017600999..4732f5e11 100644--- a/scripts/capture-tour-atlas.mjs+++ b/scripts/capture-tour-atlas.mjs@@ -329,6 +329,43 @@ async function settleImages() {}}+// ── Navigation ───────────────────────────────────────────────────────────────+// Reaching a page and finishing its JavaScript are two different questions, and+// conflating them is how a healthy page gets reported dead. `waitUntil:+// 'domcontentloaded'` makes the navigation itself hostage to script execution:+// a heavy WebGL stop like /walk or /temporary parses its DOM in under two+// seconds but does not fire DOMContentLoaded for another ten-plus while its+// module graph boots, and on a loaded runner that pushes past the timeout. The+// navigation then throws, the status stays 0, and summarize() counts a page+// that answered HTTP 200 in 200ms as unreachable, telling whoever reads the+// report to "fix the page or drop the stop" about a page with nothing wrong.+//+// `commit` resolves as soon as the server's response arrives, so the recorded+// status is the one the server actually sent. A 404 still reads 404, a refused+// connection or a bad host still throws, and slow scripts read as slow scripts+// further down. The page's own milestones are then awaited separately, where+// missing one is a note rather than a verdict about reachability.+export const NAV_ATTEMPTS = 2;++export async function navigate(page, url, notes, { timeout = NAV_TIMEOUT_MS, attempts = NAV_ATTEMPTS } = {}) {+ let lastError = null;+ for (let attempt = 1; attempt <= attempts; attempt++) {+ try {+ const response = await page.goto(url, { waitUntil: 'commit', timeout });+ // A retry that worked is worth recording but must not displace the+ // anchor diagnostics that follow it, so it lands at the end of the run.+ if (attempt > 1) return { status: response?.status() ?? 0, attempts: attempt, recovered: lastError };+ return { status: response?.status() ?? 0, attempts: attempt, recovered: null };+ } catch (err) {+ lastError = String(err?.message || err).split('\n')[0].slice(0, 200);+ }+ }+ // Failing every attempt is the honest unreachable case: status 0, which the+ // summary counts and the gate fails on.+ notes.push(`navigation failed ${attempts} times, last error: ${lastError}`);+ return { status: 0, attempts, recovered: null };+}+// ── Capture ──────────────────────────────────────────────────────────────────async function encode(buffer, { file, width, quality }) {const out = resolve(MEDIA_DIR, file);@@ -371,20 +408,29 @@ async function captureStop(context, stop) {capturedAt: new Date().toISOString(),};+ let recoveredNav = null;try {- const response = await page.goto(`${BASE}${stop.path}`, {- waitUntil: 'domcontentloaded',- timeout: NAV_TIMEOUT_MS,- });- record.status = response?.status() ?? 0;+ const nav = await navigate(page, `${BASE}${stop.path}`, notes);+ record.status = nav.status;+ recoveredNav = nav.recovered;// A 4xx/5xx page has nothing worth photographing, and a shot of the error- // page in the atlas would read as a real feature. Record and stop.+ // page in the atlas would read as a real feature. A status of 0 means every+ // navigation attempt failed at the transport layer, so there is no page at+ // all. Record and stop.if (record.status >= 400) {notes.push(`page returned HTTP ${record.status}`);return record;}-+ if (!record.status) return record;++ // The DOM has to exist before an anchor can be resolved against it, but a+ // stop whose scripts are still booting has a fully parsed DOM long before+ // DOMContentLoaded fires. Wait for the milestone, and when it does not+ // arrive say so rather than pretending the page was never served.+ await page.waitForLoadState('domcontentloaded', { timeout: NAV_TIMEOUT_MS }).catch(() => {+ notes.push('DOMContentLoaded did not fire within the timeout, anchors resolved against a partial DOM');+ });await page.waitForLoadState('load', { timeout: NAV_TIMEOUT_MS }).catch(() => {notes.push('load event did not fire within the timeout, captured at domcontentloaded');});@@ -453,6 +499,7 @@ async function captureStop(context, stop) {} catch (err) {notes.push(String(err?.message || err).slice(0, 300));} finally {+ if (recoveredNav) notes.push(`the first navigation attempt failed and was retried: ${recoveredNav}`);record.consoleErrors = consoleErrors.length;record.consoleSamples = consoleErrors.slice(0, 3);await page.close().catch(() => {});@@ -609,7 +656,12 @@ async function main() {);}-main().catch((err) => {- console.error(err);- process.exit(1);-});+// Only run when invoked directly, so tests can import navigate() above and hold+// it to the contract the gate depends on, the way build-tour-atlas.mjs already+// exposes its pure helpers.+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ main().catch((err) => {+ console.error(err);+ process.exit(1);+ });+}diff --git a/scripts/i18n-rc.schema.json b/scripts/i18n-rc.schema.jsonindex 6725818d1..9430eca8f 100644--- a/scripts/i18n-rc.schema.json+++ b/scripts/i18n-rc.schema.json@@ -36,8 +36,8 @@"description": "Locale codes that render right-to-left."},"provider": {- "enum": ["gemini", "vertex", "groq", "openrouter", "nvidia", "openai", "anthropic"],- "description": "LLM backend. Free lanes: groq, gemini (free tier), openrouter (:free models), nvidia. vertex bills to the platform's GCP credit pool (GOOGLE_CLOUD_PROJECT + GCP creds) with no free-tier quota to exhaust."+ "enum": ["gemini", "vertex", "groq", "openrouter", "nvidia", "mistral", "openai", "anthropic", "threews"],+ "description": "LLM backend. Free lanes: groq, gemini (free tier), openrouter (:free models), nvidia, mistral. vertex bills to the platform's GCP credit pool (GOOGLE_CLOUD_PROJECT + GCP creds) with no free-tier quota to exhaust. threews rides the platform's own we-pay LLM proxy with a QA session (npm run audit:web:login) and THREEWS_I18N_AGENT; the zero-local-credential lane."},"modelName": {"type": "string"diff --git a/scripts/i18n-translate.mjs b/scripts/i18n-translate.mjsindex f5f4a5b2a..4d9d38f34 100644--- a/scripts/i18n-translate.mjs+++ b/scripts/i18n-translate.mjs@@ -18,6 +18,14 @@// platform GCP credits, no free-tier quota to exhaust)// openai → Chat Completions (OPENAI_API_KEY [+ OPENAI_BASE_URL])// anthropic → Messages (ANTHROPIC_API_KEY)+// threews → three.ws we-pay LLM proxy (/api/llm/anthropic). The zero-local-credential+// rung: it rides the platform's own free-tier provider keys, so it works+// from any workspace that can log in as a platform user. Needs+// THREEWS_I18N_AGENT (an agent id OWNED by that user; the proxy meters+// per-agent, so never point this at someone else's agent) plus a session+// saved by `npm run audit:web:login` (or THREEWS_SESSION_FILE). Respects+// the agent's default embed-policy limits (10 req/min), so bulk runs are+// slow by design; prefer vertex when GCP credentials exist.//// Usage:// node scripts/i18n-translate.mjs # translate missing keys, all locales@@ -28,7 +36,7 @@// node scripts/i18n-translate.mjs --dry-run # report what would translate// node scripts/i18n-translate.mjs --concurrency=8 # widen the chunk pool for a bulk run-import { writeFileSync, existsSync } from 'node:fs';+import { writeFileSync, existsSync, readFileSync } from 'node:fs';import { resolve } from 'node:path';import { pathToFileURL } from 'node:url';import { config as dotenv } from 'dotenv';@@ -159,6 +167,9 @@ const PROVIDER_DEFAULT_MODEL = {mistral: 'mistral-small-latest',openai: 'gpt-4o-mini',anthropic: 'claude-haiku-4-5-20251001',+ // The proxy's free Groq lane; resolveRequestedModel clamps paid models to the+ // agent's configured one, so only free-lane ids make sense here.+ threews: 'llama-3.3-70b-versatile',};// OpenAI-compatible lanes. jsonMode is set only where the endpoint reliably@@ -317,6 +328,77 @@ async function callAnthropic(prompt) {return data?.content?.map((b) => b.text || '').join('') || '';}+// three.ws we-pay LLM proxy (api/llm/anthropic.js) as a translation backend.+// This is the rung for a workspace with NO provider credentials at all: the+// proxy spends the platform's own free-tier keys (Groq et al) server-side and+// speaks the Anthropic Messages shape in both directions, so the call below is+// callAnthropic with a different host and cookie auth instead of an API key.+//+// Auth is a platform session: the proxy admits Origin-less machine callers only+// when they authenticate, and the sanctioned way to mint a session in an agent+// workspace is `npm run audit:web:login` (QA account from .env), which saves a+// Playwright storageState file this reads the session cookie from. The agent id+// must be one the SAME user owns: the proxy meters calls and tokens against the+// agent's embed policy, and spending another owner's budget is not acceptable.+// `GET /api/agents/me` auto-creates a default agent for the QA user, so+// `THREEWS_I18N_AGENT=$(that id)` is always mintable.+function threewsSessionCookie() {+ const file =+ process.env.THREEWS_SESSION_FILE || resolve(ROOT, '.auth/audit-state.json');+ if (!existsSync(file))+ throw configError(+ `threews session file not found (${file}): run \`npm run audit:web:login\` first, ` ++ 'or point THREEWS_SESSION_FILE at a Playwright storageState JSON with a three.ws session.',+ );+ let cookie;+ try {+ const state = JSON.parse(readFileSync(file, 'utf8'));+ cookie = (state.cookies || []).find((c) => c.name === '__Host-sid');+ } catch {+ throw configError(`threews session file is not readable storageState JSON: ${file}`);+ }+ if (!cookie) throw configError('threews session file has no __Host-sid cookie; session expired? Re-run `npm run audit:web:login`.');+ return `${cookie.name}=${cookie.value}`;+}++async function callThreews(prompt) {+ const agentId = process.env.THREEWS_I18N_AGENT;+ if (!agentId)+ throw configError(+ 'THREEWS_I18N_AGENT not set: an agent id owned by the session user ' ++ '(GET /api/agents/me returns or creates one).',+ );+ const base = (process.env.THREEWS_BASE_URL || 'https://three.ws').replace(/\/$/, '');+ const res = await fetch(`${base}/api/llm/anthropic?agent=${encodeURIComponent(agentId)}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', cookie: threewsSessionCookie() },+ body: JSON.stringify({+ model: modelName(),+ max_tokens: 8192,+ stream: false,+ temperature: cfg.temperature ?? 0.2,+ messages: [{ role: 'user', content: prompt }],+ }),+ });+ if (res.status === 401 || res.status === 403) {+ throw configError(+ `threews ${res.status}: session rejected: re-run \`npm run audit:web:login\` ` ++ 'and confirm THREEWS_I18N_AGENT belongs to that user.',+ );+ }+ if (!res.ok)+ throw httpError(+ 'threews',+ res.status,+ await res.text(),+ Number(res.headers.get('retry-after')) || 0,+ );+ const data = await res.json();+ const text = data?.content?.map((b) => b.text || '').join('') || '';+ if (!text) throw new Error('threews proxy returned empty content');+ return text;+}+// Vertex AI Gemini — service-account/metadata-server auth, billed to the// platform's GCP credit pool instead of a free-tier key. No quota to exhaust// (unlike groq/gemini-aistudio/nvidia's shared free tiers, which can 429@@ -447,9 +529,10 @@ function backend() {if (cfg.provider === 'gemini') return callGemini;if (cfg.provider === 'anthropic') return callAnthropic;if (cfg.provider === 'vertex') return callVertex;+ if (cfg.provider === 'threews') return callThreews;if (OPENAI_COMPAT[cfg.provider]) return callOpenAICompat;throw new Error(- `unknown provider: ${cfg.provider} (use gemini, groq, openrouter, nvidia, mistral, vertex, openai, or anthropic)`,+ `unknown provider: ${cfg.provider} (use gemini, groq, openrouter, nvidia, mistral, vertex, openai, anthropic, or threews)`,);}diff --git a/tests/tour-atlas.test.js b/tests/tour-atlas.test.jsindex 275838d65..85d056650 100644--- a/tests/tour-atlas.test.js+++ b/tests/tour-atlas.test.js@@ -23,6 +23,7 @@ import { resolve, dirname } from 'node:path';import { fileURLToPath } from 'node:url';import { atlasProblems, renderPublicAtlas } from '../scripts/build-tour-atlas.mjs';+import { navigate, NAV_ATTEMPTS } from '../scripts/capture-tour-atlas.mjs';import {TOUR_FALLBACK_SELECTORS,TOUR_CONTENT_ROOT_SELECTOR,@@ -238,6 +239,67 @@ describe('atlasProblems()', () => {});});+describe('navigate()', () => {+ // The sweep is a live-network gate, so its verdict has to separate "the+ // server did not serve this page" from "this page's JavaScript is slow".+ // Waiting for DOMContentLoaded during the navigation itself conflated them:+ // /walk and /temporary answer HTTP 200 in a fifth of a second but boot a+ // WebGL scene for ten-plus seconds afterwards, and on a loaded runner that+ // timed the navigation out, left the status at 0, and made the gate report+ // two healthy pages as unreachable with "fix the page or drop the stop".+ const fakePage = (attempts) => {+ const calls = [];+ let i = 0;+ return {+ calls,+ async goto(url, options) {+ calls.push({ url, options });+ const outcome = attempts[Math.min(i++, attempts.length - 1)];+ if (outcome instanceof Error) throw outcome;+ return { status: () => outcome };+ },+ };+ };++ it('records the status the server actually sent, without waiting on scripts', async () => {+ const page = fakePage([200]);+ const notes = [];+ const result = await navigate(page, 'https://three.ws/walk', notes);+ expect(result).toEqual({ status: 200, attempts: 1, recovered: null });+ expect(notes).toEqual([]);+ expect(page.calls[0].options.waitUntil).toBe('commit');+ });++ it('retries a navigation that failed at the transport layer', async () => {+ const page = fakePage([new Error('page.goto: Timeout 45000ms exceeded.\nCall log:\n - navigating'), 200]);+ const notes = [];+ const result = await navigate(page, 'https://three.ws/temporary', notes);+ expect(result.status).toBe(200);+ expect(result.attempts).toBe(2);+ expect(result.recovered).toContain('Timeout 45000ms exceeded.');+ // The retry is reported by the caller after the anchor diagnostics, so it+ // never displaces the note a reader actually needs.+ expect(notes).toEqual([]);+ });++ it('reports status 0 and one note when every attempt fails', async () => {+ const page = fakePage([new Error('net::ERR_NAME_NOT_RESOLVED'), new Error('net::ERR_NAME_NOT_RESOLVED')]);+ const notes = [];+ const result = await navigate(page, 'https://three.ws/gone', notes);+ expect(result.status).toBe(0);+ expect(result.attempts).toBe(NAV_ATTEMPTS);+ expect(notes).toHaveLength(1);+ expect(notes[0]).toContain('ERR_NAME_NOT_RESOLVED');+ });++ it('does not retry a page the server answered, however it answered', async () => {+ const page = fakePage([404, 200]);+ const result = await navigate(page, 'https://three.ws/missing', []);+ expect(result.status).toBe(404);+ expect(page.calls).toHaveLength(1);+ });+});+describe('the committed atlas', () => {it('is published to public/tour/atlas.json byte for byte', () => {const src = JSON.parse(readFileSync(resolve(ROOT, 'data/tour-atlas.json'), 'utf8'));