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
x402-server SDK correctness pass and embeddable concierge widget
nirholasab0aab85a6bc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex aa40497d2..882cfc89d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -50,6 +50,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Solana price and trade reads now ride a dedicated premium connection** — Every live Solana read the platform depends on (the $THREE price and bonding-curve, wallet balances, agent trades, and on-chain activity) now goes first through a dedicated premium RPC endpoint that absorbs the load ahead of the shared public providers, then falls back automatically down the full free-provider chain if that endpoint is ever unavailable. In practice that means fewer rate-limit stalls and fewer degraded or stale reads when Solana is busy, without adding a single point of failure: if the premium lane blinks, the free chain still answers. (`/pulse`) `[infra, improvement]`- **The docs got a full accuracy pass against the live platform** — Every page under three.ws/docs was cross-checked line by line against the code that actually runs in production. Around 180 outdated or wrong statements were corrected: dead links and sample URLs, endpoints and prices that had changed, code examples that no longer worked, and descriptions of features that had since evolved. Twenty-two existing guides that were previously unreachable from the sidebar (including the 3D Viewer, Editor, Crypto Data API, Trading Copilot, and Premium pass docs) are now listed in the navigation, and every wallet ability deep-dive gained a copy-pasteable Try It section. If you read something in the docs today, it matches what the platform actually does. (`/docs`) `[docs, improvement]`- **The free 3D Studio now publishes a machine-readable API description** — The free text-to-3D generation endpoint that powers the three.ws 3D Studio in ChatGPT now ships a published OpenAPI description at /.well-known/3d-studio-openapi.yaml. Any app, custom GPT, or agent can read it to discover how to generate a model from a prompt and poll for the result, with no account, no API key, and no payment. It documents only the free generation action and is kept automatically in sync with the version used by the 3D Studio custom GPT, so the two never drift. `[docs, sdk]`+- **The x402-server SDK now attaches the payment receipt on every paid response** — Our most-installed npm package, @three-ws/x402-server (the seller side of x402), got a correctness pass. Paid endpoints built with it now guarantee the buyer never receives the result before the payment settles, and every paid response carries the on-chain settlement receipt in the X-PAYMENT-RESPONSE header, even for handlers that write their own response (the common Express case, which previously dropped the receipt). A new streaming mode settles up-front for file downloads and event streams, a handler that errors now returns a clean retryable 500 without charging, and the Base Sepolia test lane now advertises the correct testnet USDC. Ships with four runnable examples and a step-by-step tutorial you can follow offline before touching a wallet. (`/tutorials/x402-server-sdk`) `[sdk, fix]`- **Two new guides explain the Forge, inside and out** — The 3D generation pipeline now has real documentation at both depths. A plain-language guide walks through the five steps between typing a prompt and downloading a model, including how jobs quietly move to a backup engine when one goes down. A full architecture deep dive covers the engine grid, free-first routing, failover, storage, GPU workers, and payments for anyone building on or contributing to the pipeline. Also published on the blog. (`/docs/how-forge-works`) `[docs]`## 2026-07-17diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 312a5bb06..47bdd9ada 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -965,6 +965,17 @@ export const limits = {chatUser: (userId) =>getLimiter('chat:user', { limit: 40, window: '1 m', critical: true }).limit(userId),chatIp: (ip) => getLimiter('chat:ip', { limit: 60, window: '1 m', critical: true }).limit(ip),+ // Embeddable concierge widget (/api/concierge) — anonymous, any-origin+ // traffic from third-party sites, so it gets its own bucket instead of+ // sharing chat:ip: a widget-hosting page must not starve the signed-in+ // viewer chat (and vice versa). Same critical fail-closed policy: this lane+ // spends free-tier LLM quota and can fall through to funded rungs.+ conciergeIp: (ip) =>+ getLimiter('concierge:ip', { limit: 20, window: '1 m', critical: true }).limit(ip),+ // Global ceiling across every embedded widget combined — bounds the total+ // free-tier draw of the whole third-party fleet, mirroring chatHostKeyGlobal.+ conciergeGlobal: () =>+ getLimiter('concierge:global', { limit: 600, window: '1 m', critical: true }).limit('global'),// Global ceiling on inference billed to the HOST's provider keys (i.e. callers// who supplied no key of their own). Stops distributed abuse — many accounts// each under their per-user limit collectively draining the platform's quota.diff --git a/api/concierge.js b/api/concierge.jsnew file mode 100644index 000000000..616226409--- /dev/null+++ b/api/concierge.js@@ -0,0 +1,277 @@+// POST /api/concierge — the answer engine behind @three-ws/concierge.+//+// The embeddable site-concierge widget (concierge-sdk/) posts the visitor's+// question, the running conversation, and a bounded snapshot of the HOST page+// (title/description/headings/nav/main text + optional curated `knowledge`).+// This handler grounds a system prompt in that snapshot and streams the answer+// back as SSE — the same { chunk → done } event shape /api/chat uses:+//+// Body: { message, history[], site{...}, persona?, lang? }+// Response: SSE data: { type: 'chunk', text }+// data: { type: 'done', provider, model }+// data: { type: 'error', code, message }+//+// Differences from /api/chat, and why this is its own route:+// - CORS is `*`: the whole point is embedding on ANY third-party site, which+// the /api/chat allowlist forbids. No cookies/credentials cross this lane.+// - Anonymous-only, with its own IP + global rate buckets (limits.conciergeIp+// / conciergeGlobal) so widget traffic can't starve signed-in chat.+// - No tool calls, no persona store, no BYOK: one job — grounded answers.+// - Providers come from the shared free-first chain (api/_lib/llm.js+// providerChain), streamed. Anthropic-shaped rungs are skipped: their SSE+// wire format differs and every OpenAI-compatible rung (incl. the+// credits-funded vertex-gemini anchor) already covers availability.++import { cors, method, readJson, wrap, error, rateLimited } from './_lib/http.js';+import { parse } from './_lib/validate.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { providerChain, LlmUnavailableError } from './_lib/llm.js';+import { moderateAnonInput, refusalReply } from './_lib/moderation.js';+import { markProviderCooldown, providersInCooldown, AUTH_COOLDOWN_SECONDS } from './_lib/provider-health.js';+import { recordEvent } from './_lib/usage.js';+import { captureException } from './_lib/sentry.js';+import { z } from 'zod';++export const maxDuration = 60;++const MAX_ANSWER_TOKENS = 700;+const CONNECT_TIMEOUT_MS = 20_000;+const TOTAL_BUDGET_MS = 40_000;++const siteSchema = z+ .object({+ url: z.string().max(600).optional(),+ name: z.string().max(120).optional(),+ title: z.string().max(200).optional(),+ description: z.string().max(500).optional(),+ headings: z.array(z.string().max(160)).max(24).optional(),+ nav: z.array(z.string().max(60)).max(24).optional(),+ knowledge: z.string().max(8000).optional(),+ content: z.string().max(6000).optional(),+ })+ .partial()+ .default({});++const bodySchema = z.object({+ message: z.string().trim().min(1).max(2000),+ history: z+ .array(+ z.object({+ role: z.enum(['user', 'assistant']),+ content: z.string().min(1).max(4000),+ }),+ )+ .max(20)+ .default([]),+ site: siteSchema,+ persona: z.string().trim().max(200).optional(),+ lang: z.string().trim().max(20).optional(),+});++// Anthropic-shaped rungs stream a different SSE dialect than the OpenAI reader+// below understands; skip them (see header note).+const NON_OPENAI_STYLES = new Set(['anthropic', 'vertex-anthropic']);++function buildSystemPrompt({ site, persona, lang }) {+ const name = site.name || site.title || 'this website';+ const lines = [+ `You are the AI concierge for ${name}, embedded as a chat widget on the site itself.`,+ 'Answer the visitor\'s questions about the site, its product, content, and how to use it.',+ 'Be genuinely helpful, warm, and concise: two short paragraphs at most, or a compact list.',+ 'Ground every claim in the site information below. If it does not contain the answer, say so honestly and point the visitor to the closest thing that does (a nav item, a page, or contacting the team). Never invent prices, features, or policies.',+ 'You may use light markdown: **bold**, `code`, links, and bullet lists.',+ 'Only link to URLs that appear in the site information.',+ persona ? `Tone instruction from the site owner: ${persona}` : '',+ lang ? `Reply in the visitor's language (${lang}) when their message is in it.` : '',+ '',+ '--- SITE INFORMATION ---',+ site.url ? `URL: ${site.url}` : '',+ site.title ? `Page title: ${site.title}` : '',+ site.description ? `Description: ${site.description}` : '',+ site.nav?.length ? `Navigation: ${site.nav.join(' · ')}` : '',+ site.headings?.length ? `Page headings: ${site.headings.join(' · ')}` : '',+ site.knowledge ? `Curated site knowledge (authoritative):\n${site.knowledge}` : '',+ site.content ? `Current page content:\n${site.content}` : '',+ ];+ return lines.filter(Boolean).join('\n');+}++// Read one OpenAI-compatible SSE stream, forwarding text deltas. Returns the+// accumulated reply text; throws on transport failure mid-stream.+async function pumpOpenAIStream(upstream, onText) {+ const decoder = new TextDecoder();+ let buf = '';+ let reply = '';+ for await (const chunk of upstream.body) {+ buf += decoder.decode(chunk, { stream: true });+ let idx;+ while ((idx = buf.indexOf('\n')) !== -1) {+ const line = buf.slice(0, idx).trim();+ buf = buf.slice(idx + 1);+ if (!line.startsWith('data:')) continue;+ const payload = line.slice(5).trim();+ if (!payload || payload === '[DONE]') continue;+ let evt;+ try {+ evt = JSON.parse(payload);+ } catch {+ continue; // partial/malformed frame — never fatal+ }+ const delta = evt.choices?.[0]?.delta?.content;+ if (typeof delta === 'string' && delta) {+ reply += delta;+ onText(delta);+ }+ }+ }+ return reply;+}++function isBillingAuthStatus(status) {+ return status === 401 || status === 402 || status === 403;+}++// Hostname only, for usage telemetry — never the full URL (query strings from+// third-party pages are not ours to store). Malformed input → null.+function siteHostname(url) {+ if (!url) return null;+ try {+ return new URL(url, 'https://invalid.local').hostname;+ } catch {+ return null;+ }+}++export default wrap(async (req, res) => {+ if (cors(req, res, { origins: '*', methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ const body = parse(bodySchema, await readJson(req));+ const ip = clientIp(req);+ const rl = await limits.conciergeIp(ip);+ if (!rl.success) return rateLimited(res, rl, 'too many questions from this connection, try again shortly');+ const gl = await limits.conciergeGlobal();+ if (!gl.success) return rateLimited(res, gl, 'the concierge is at capacity, try again in a moment');++ const started = Date.now();++ const sseHead = () =>+ res.writeHead(200, {+ 'Content-Type': 'text/event-stream; charset=utf-8',+ 'Cache-Control': 'no-cache, no-transform',+ 'X-Accel-Buffering': 'no',+ });+ const sendSSE = (obj) => res.write(`data: ${JSON.stringify(obj)}\n\n`);++ // Anonymous pre-moderation (FAIL-OPEN, same policy as /api/chat): a flagged+ // message gets a normal in-band refusal, and a moderation outage never takes+ // the concierge down.+ const verdict = await moderateAnonInput(body.message);+ if (verdict.flagged) {+ sseHead();+ sendSSE({ type: 'chunk', text: refusalReply() });+ sendSSE({ type: 'done', moderated: true });+ res.end();+ recordEvent({+ userId: null,+ kind: 'chat',+ tool: 'concierge',+ latencyMs: Date.now() - started,+ meta: { moderated: true, anonymous: true },+ });+ return;+ }++ const system = buildSystemPrompt(body);+ const messages = [+ { role: 'system', content: system },+ ...body.history.map((m) => ({ role: m.role, content: m.content })),+ { role: 'user', content: body.message },+ ];++ const chain = providerChain().filter((p) => !NON_OPENAI_STYLES.has(p.name));+ if (!chain.length) throw new LlmUnavailableError();++ const cooled = await providersInCooldown(chain.map((p) => p.name));+ const ordered = [...chain.filter((p) => !cooled.has(p.name)), ...chain.filter((p) => cooled.has(p.name))];++ let lastFailure = null;+ const attempted = [];+ for (const provider of ordered) {+ if (Date.now() - started > TOTAL_BUDGET_MS) break;+ attempted.push(provider.name);++ let upstream;+ try {+ const headers = provider.getHeaders ? await provider.getHeaders() : provider.headers;+ const ctrl = new AbortController();+ const timer = setTimeout(() => ctrl.abort(), Math.min(provider.timeoutMs || CONNECT_TIMEOUT_MS, CONNECT_TIMEOUT_MS));+ upstream = await fetch(provider.url, {+ method: 'POST',+ headers,+ body: JSON.stringify({+ model: provider.model,+ max_tokens: MAX_ANSWER_TOKENS,+ stream: true,+ messages,+ }),+ signal: ctrl.signal,+ }).finally(() => clearTimeout(timer));+ } catch (err) {+ lastFailure = err;+ continue; // transport/timeout — next rung+ }++ if (!upstream.ok) {+ const text = await upstream.text().catch(() => '');+ lastFailure = new Error(`${provider.name} HTTP ${upstream.status}: ${text.slice(0, 200)}`);+ if (isBillingAuthStatus(upstream.status)) {+ void markProviderCooldown(provider.name, AUTH_COOLDOWN_SECONDS, 'auth');+ } else if (upstream.status === 429 || upstream.status >= 500) {+ void markProviderCooldown(provider.name);+ }+ continue;+ }++ // Connected — stream the answer through.+ sseHead();+ let reply = '';+ try {+ reply = await pumpOpenAIStream(upstream, (text) => sendSSE({ type: 'chunk', text }));+ } catch (err) {+ captureException(err, { route: 'concierge', stage: 'stream', provider: provider.name });+ sendSSE({ type: 'error', code: 'stream_error', message: 'stream interrupted' });+ res.end();+ return;+ }+ sendSSE({ type: 'done', provider: provider.name, model: provider.model });+ res.end();+ recordEvent({+ userId: null,+ kind: 'chat',+ tool: 'concierge',+ latencyMs: Date.now() - started,+ meta: {+ provider: provider.name,+ model: provider.model,+ anonymous: true,+ site: siteHostname(body.site?.url),+ reply_chars: reply.length,+ history_turns: body.history.length,+ },+ });+ return;+ }++ // Every rung failed before a byte streamed — a plain HTTP error the widget+ // renders as its friendly retry bubble.+ captureException(lastFailure || new Error('concierge: no provider reachable'), {+ route: 'concierge',+ stage: 'connect',+ });+ res.setHeader('Retry-After', '15');+ return error(res, 503, 'rate_limited', 'The concierge is at capacity right now. Please try again in a few seconds.', {+ providers_tried: attempted.length,+ retry_after: 15,+ });+});diff --git a/concierge-sdk/LICENSE b/concierge-sdk/LICENSEnew file mode 100644index 000000000..dff21b7f4--- /dev/null+++ b/concierge-sdk/LICENSE@@ -0,0 +1,20 @@+Copyright 2026 nirholas++All rights reserved.++This software is proprietary and may not be used, copied, modified, distributed,+translated, or made available to any third party without the express written+permission of the copyright owner.++No rights are granted by implication, estoppel, or otherwise. Use of this+software is subject to the terms of a separate license agreement with the+copyright owner.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.++IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE FOR ANY CLAIM, DAMAGES, OR+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE,+ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+DEALINGS IN THE SOFTWARE.diff --git a/concierge-sdk/build.mjs b/concierge-sdk/build.mjsnew file mode 100644index 000000000..2f7da1dca--- /dev/null+++ b/concierge-sdk/build.mjs@@ -0,0 +1,57 @@+#!/usr/bin/env node+/**+ * Build @three-ws/concierge.+ *+ * Three artifacts:+ * dist/concierge.mjs — ESM, `three` left external. For bundler / npm+ * consumers who already depend on three.+ * dist/concierge.global.js — self-contained ESM with three + addons inlined,+ * registers <three-concierge>, runs the+ * data-concierge auto-init, and exposes+ * window.ThreeWsConcierge. For a one-tag CDN+ * <script type="module"> embed.+ * dist/concierge.css — the injected stylesheet, materialised for the+ * "@three-ws/concierge/style.css" subpath.+ */++import { build } from 'esbuild';+import { mkdirSync, writeFileSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { CSS } from './src/styles.js';++const here = dirname(fileURLToPath(import.meta.url));+const outDir = resolve(here, 'dist');+mkdirSync(outDir, { recursive: true });++const common = {+ bundle: true,+ sourcemap: true,+ target: ['es2020'],+ logLevel: 'info',+};++// 1) ESM, three external (peer dependency).+await build({+ ...common,+ entryPoints: [resolve(here, 'src/index.js')],+ format: 'esm',+ external: ['three', 'three/addons/*'],+ outfile: resolve(outDir, 'concierge.mjs'),+});++// 2) Self-contained build for a plain CDN <script type="module"> — ESM (not+// IIFE) because the stage lazy-imports the meshopt decoder module.+await build({+ ...common,+ entryPoints: [resolve(here, 'src/global.js')],+ format: 'esm',+ minify: true,+ outfile: resolve(outDir, 'concierge.global.js'),+ banner: { js: '/* @three-ws/concierge — https://three.ws/concierge */' },+});++// 3) Stylesheet for the ./style.css subpath import.+writeFileSync(resolve(outDir, 'concierge.css'), CSS.trimStart());++console.log('[concierge] built dist/concierge.mjs, dist/concierge.global.js, dist/concierge.css');diff --git a/concierge-sdk/package.json b/concierge-sdk/package.jsonnew file mode 100644index 000000000..a77b0b0e8--- /dev/null+++ b/concierge-sdk/package.json@@ -0,0 +1,78 @@+{+ "name": "@three-ws/concierge",+ "version": "0.1.0",+ "description": "An AI concierge for any website: a floating chat widget with a rigged 3D avatar that blinks and lipsyncs, streaming answers grounded in your live page, browser-native voice in/out, and a one-tag embed. Powered by three.ws.",+ "keywords": [+ "chatbot",+ "chat-widget",+ "support-chat",+ "ai-assistant",+ "3d",+ "avatar",+ "three.js",+ "webgl",+ "lipsync",+ "text-to-speech",+ "speech-recognition",+ "web-component",+ "embeddable",+ "concierge",+ "intercom-alternative"+ ],+ "author": "three.ws <[email protected]> (https://three.ws)",+ "license": "SEE LICENSE IN LICENSE",+ "homepage": "https://three.ws/concierge",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "concierge-sdk"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "type": "module",+ "main": "./dist/concierge.mjs",+ "module": "./dist/concierge.mjs",+ "unpkg": "./dist/concierge.global.js",+ "jsdelivr": "./dist/concierge.global.js",+ "types": "./types/index.d.ts",+ "exports": {+ ".": {+ "types": "./types/index.d.ts",+ "import": "./dist/concierge.mjs",+ "default": "./dist/concierge.mjs"+ },+ "./catalog": {+ "types": "./types/index.d.ts",+ "import": "./src/catalog.js",+ "default": "./src/catalog.js"+ },+ "./global": "./dist/concierge.global.js",+ "./style.css": "./dist/concierge.css"+ },+ "files": [+ "dist/concierge.mjs",+ "dist/concierge.mjs.map",+ "dist/concierge.global.js",+ "dist/concierge.global.js.map",+ "dist/concierge.css",+ "src",+ "types",+ "README.md",+ "LICENSE"+ ],+ "scripts": {+ "build": "node build.mjs",+ "prepublishOnly": "node build.mjs",+ "test": "node --test 'test/*.test.js'"+ },+ "peerDependencies": {+ "three": ">=0.150.0"+ },+ "engines": {+ "node": ">=18"+ },+ "publishConfig": {+ "access": "public"+ }+}diff --git a/concierge-sdk/src/catalog.js b/concierge-sdk/src/catalog.jsnew file mode 100644index 000000000..875dd7745--- /dev/null+++ b/concierge-sdk/src/catalog.js@@ -0,0 +1,118 @@+/**+ * Concierge catalog — @three-ws/concierge+ * =======================================+ *+ * Every entry is a skeleton-rigged humanoid GLB with verified face morphs or a+ * talk animation, served from the three.ws origin (the repo's public/ web+ * root). The concierge frames the avatar as a bust inside the chat panel and+ * drives blink + viseme lipsync, so an unrigged mesh would read as a dead+ * statue — those are excluded by rule, same as @three-ws/page-agent.+ *+ * Override `assetBase` (or an entry's `url`) to self-host the GLBs.+ */++/** Default CDN base. Real, public three.ws assets — `public/avatars/*.glb`. */+export const DEFAULT_ASSET_BASE = 'https://three.ws/avatars/';++/**+ * @typedef {Object} ConciergeAvatar+ * @property {string} id Stable slug used in attributes / localStorage.+ * @property {string} name Display name shown in the header + picker.+ * @property {string} tagline One-line personality hook for the picker card.+ * @property {string} file GLB filename under the asset base.+ * @property {string} [url] Absolute override; wins over assetBase+file.+ * @property {'viseme'|'jaw'|'animation'} lipsync Mouth driver.+ * @property {'bust'|'upper'|'full'} framing Camera crop in the panel.+ * @property {{ lang?: string, pitch?: number, rate?: number, match?: string[] }} voice+ * @property {string} accent Default accent color for this avatar's chrome.+ */++/** @type {ConciergeAvatar[]} */+export const AVATARS = [+ {+ id: 'sol',+ name: 'Sol',+ tagline: 'Calm, clear product guide',+ file: 'realistic-halfbody.glb',+ lipsync: 'viseme',+ framing: 'bust',+ voice: { lang: 'en-US', pitch: 1.0, rate: 1.0, match: ['samantha', 'jenny', 'aria', 'google us english'] },+ accent: '#6366f1',+ },+ {+ id: 'nova',+ name: 'Nova',+ tagline: 'Upbeat, friendly host',+ file: 'selfie-girl.glb',+ lipsync: 'viseme',+ framing: 'upper',+ voice: { lang: 'en-US', pitch: 1.12, rate: 1.04, match: ['jenny', 'aria', 'samantha', 'google us english'] },+ accent: '#ec4899',+ },+ {+ id: 'vera',+ name: 'Vera',+ tagline: 'Composed, professional',+ file: 'realistic-female.glb',+ lipsync: 'viseme',+ framing: 'bust',+ voice: { lang: 'en-GB', pitch: 1.0, rate: 0.98, match: ['libby', 'sonia', 'google uk english female', 'serena'] },+ accent: '#14b8a6',+ },+ {+ id: 'atlas',+ name: 'Atlas',+ tagline: 'Confident, grounded',+ file: 'realistic-male.glb',+ lipsync: 'viseme',+ framing: 'bust',+ voice: { lang: 'en-US', pitch: 0.92, rate: 0.98, match: ['guy', 'eric', 'google us english', 'daniel'] },+ accent: '#3b82f6',+ },+ {+ id: 'echo',+ name: 'Echo',+ tagline: 'Neutral, even-keeled',+ file: 'default.glb',+ lipsync: 'viseme',+ framing: 'upper',+ voice: { lang: 'en-US', pitch: 1.0, rate: 1.0, match: ['google us english', 'samantha', 'guy'] },+ accent: '#8b5cf6',+ },+];++export const DEFAULT_AVATAR_ID = 'sol';++/** Look up a catalog entry by id; unknown ids resolve to the default. */+export function getAvatar(id) {+ return AVATARS.find((a) => a.id === id) || AVATARS.find((a) => a.id === DEFAULT_AVATAR_ID);+}++/** Resolve the GLB URL for an entry (absolute `url` wins over assetBase). */+export function avatarUrl(entry, assetBase = DEFAULT_ASSET_BASE) {+ if (!entry) return null;+ if (entry.url) return entry.url;+ const base = assetBase.endsWith('/') ? assetBase : assetBase + '/';+ return base + entry.file;+}++/**+ * Normalize a host-supplied custom avatar (a plain GLB URL or a partial entry)+ * into a full catalog-shaped entry so the runtime treats it uniformly.+ */+export function customAvatarEntry(urlOrEntry) {+ if (!urlOrEntry) return null;+ if (typeof urlOrEntry === 'string') {+ return {+ id: 'custom',+ name: 'Assistant',+ tagline: 'Custom avatar',+ url: urlOrEntry,+ lipsync: 'viseme',+ framing: 'bust',+ voice: { lang: 'en-US', pitch: 1, rate: 1, match: [] },+ accent: '#6366f1',+ };+ }+ return { ...getAvatar(DEFAULT_AVATAR_ID), id: 'custom', name: 'Assistant', ...urlOrEntry };+}diff --git a/concierge-sdk/src/client.js b/concierge-sdk/src/client.jsnew file mode 100644index 000000000..a3f498712--- /dev/null+++ b/concierge-sdk/src/client.js@@ -0,0 +1,132 @@+/**+ * Streaming answer client — @three-ws/concierge+ * =============================================+ *+ * POSTs the visitor's question + conversation history + the harvested site+ * snapshot to the answer endpoint and reads the SSE reply incrementally, so+ * tokens render (and speak) as they arrive instead of after the full answer.+ *+ * Wire format (matches /api/concierge on three.ws):+ * → POST { message, history[], site{...}, persona?, lang? }+ * ← SSE data: { type: 'chunk', text } repeated+ * data: { type: 'done', provider?, model? }+ * data: { type: 'error', error }+ *+ * Any OpenAI-compatible endpoint can be substituted by hosts that run their+ * own backend — set `endpoint` and keep the same request/SSE contract.+ */++export const DEFAULT_ENDPOINT = 'https://three.ws/api/concierge';++export const MAX_HISTORY_TURNS = 20;+export const MAX_MESSAGE_CHARS = 2000;++/**+ * Parse one SSE frame body (the text after `data: `) into an event object.+ * Returns null for keep-alives / malformed frames — the stream must survive+ * both without surfacing an error to the visitor.+ */+export function parseSseEvent(raw) {+ const s = String(raw || '').trim();+ if (!s || s === '[DONE]') return null;+ try {+ const evt = JSON.parse(s);+ return evt && typeof evt === 'object' ? evt : null;+ } catch {+ return null;+ }+}++/**+ * Incremental SSE buffer: feed it network chunks, get complete events out.+ * Split on blank lines per the SSE spec; multi-line `data:` fields join.+ */+export function createSseBuffer(onEvent) {+ let buf = '';+ return {+ push(text) {+ buf += text;+ let idx;+ while ((idx = buf.indexOf('\n\n')) !== -1) {+ const frame = buf.slice(0, idx);+ buf = buf.slice(idx + 2);+ const data = frame+ .split('\n')+ .filter((l) => l.startsWith('data:'))+ .map((l) => l.slice(5).trim())+ .join('\n');+ const evt = parseSseEvent(data);+ if (evt) onEvent(evt);+ }+ },+ };+}++/**+ * Ask the concierge a question.+ *+ * @param {{ endpoint?: string, message: string,+ * history?: {role:'user'|'assistant', content:string}[],+ * site?: object, persona?: string, lang?: string,+ * signal?: AbortSignal,+ * onChunk?: (text:string)=>void }} opts+ * @returns {Promise<{ text: string, provider?: string, model?: string }>}+ */+export async function askConcierge(opts) {+ const endpoint = opts.endpoint || DEFAULT_ENDPOINT;+ const history = (opts.history || [])+ .slice(-MAX_HISTORY_TURNS)+ .map((m) => ({ role: m.role, content: String(m.content).slice(0, 4000) }));++ const res = await fetch(endpoint, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ message: String(opts.message).slice(0, MAX_MESSAGE_CHARS),+ history,+ site: opts.site || {},+ persona: opts.persona || undefined,+ lang: opts.lang || (typeof navigator !== 'undefined' ? navigator.language : undefined),+ }),+ signal: opts.signal,+ });++ if (!res.ok) {+ let detail = '';+ try {+ const body = await res.json();+ detail = body?.error || body?.message || '';+ } catch {+ /* non-JSON error body */+ }+ const err = new Error(detail || `concierge endpoint returned HTTP ${res.status}`);+ err.status = res.status;+ throw err;+ }++ let text = '';+ let meta = {};+ let streamError = null;+ const sse = createSseBuffer((evt) => {+ if (evt.type === 'chunk' && typeof evt.text === 'string') {+ text += evt.text;+ opts.onChunk?.(evt.text);+ } else if (evt.type === 'done') {+ meta = { provider: evt.provider, model: evt.model };+ } else if (evt.type === 'error') {+ streamError = new Error(evt.error || 'concierge stream error');+ }+ });++ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ sse.push(decoder.decode(value, { stream: true }));+ }+ sse.push(decoder.decode());++ if (streamError && !text) throw streamError;+ return { text, ...meta };+}diff --git a/concierge-sdk/src/context.js b/concierge-sdk/src/context.jsnew file mode 100644index 000000000..ac6e1bb53--- /dev/null+++ b/concierge-sdk/src/context.js@@ -0,0 +1,106 @@+/**+ * Site-context harvester — @three-ws/concierge+ * ============================================+ *+ * The concierge grounds its answers in the page it is embedded on, with no+ * crawler, no index, and no server-side setup: at ask-time it reads the live+ * DOM — title, meta description, headings, nav labels, and the main content —+ * and ships a bounded snapshot to the answer endpoint. A host can top this up+ * with a `knowledge` string (FAQ, policies, product facts) that is always+ * included ahead of the harvested page text.+ *+ * Pure DOM-in / JSON-out so it is unit-testable with a fake document.+ */++export const MAX_CONTENT_CHARS = 6000;+export const MAX_KNOWLEDGE_CHARS = 8000;++const SKIP_SELECTOR =+ 'script,style,noscript,template,svg,iframe,canvas,[aria-hidden="true"],[hidden],[data-concierge-ignore]';++function cleanText(s) {+ return String(s || '')+ .replace(/\s+/g, ' ')+ .trim();+}++/** Collect visible text from a root, skipping chrome/noise elements. */+function harvestText(root, budget) {+ if (!root) return '';+ const clone = root.cloneNode(true);+ for (const el of clone.querySelectorAll(SKIP_SELECTOR)) el.remove();+ // The concierge's own UI must never feed back into its context.+ for (const el of clone.querySelectorAll('[data-three-concierge]')) el.remove();+ return cleanText(clone.textContent).slice(0, budget);+}++/**+ * Build the site snapshot for one ask.+ * @param {Document} doc+ * @param {{ knowledge?: string, siteName?: string }} [opts]+ * @returns {{ url: string, title: string, description: string, headings: string[],+ * nav: string[], content: string, name: string }}+ */+export function harvestSiteContext(doc, opts = {}) {+ if (!doc) return { url: '', title: '', description: '', headings: [], nav: [], content: '', name: '' };++ const title = cleanText(doc.title).slice(0, 200);+ const description = cleanText(+ doc.querySelector('meta[name="description"]')?.getAttribute('content') ||+ doc.querySelector('meta[property="og:description"]')?.getAttribute('content'),+ ).slice(0, 500);++ const headings = [...doc.querySelectorAll('h1, h2, h3')]+ .map((h) => cleanText(h.textContent))+ .filter((t) => t && t.length <= 120)+ .slice(0, 24);++ const nav = [...doc.querySelectorAll('nav a, header a')]+ .map((a) => cleanText(a.textContent))+ .filter((t) => t && t.length <= 40);+ const uniqueNav = [...new Set(nav)].slice(0, 24);++ const main =+ doc.querySelector('main') || doc.querySelector('[role="main"]') || doc.querySelector('article') || doc.body;+ const content = harvestText(main, MAX_CONTENT_CHARS);++ const name =+ cleanText(doc.querySelector('meta[property="og:site_name"]')?.getAttribute('content')) ||+ (opts.siteName ? cleanText(opts.siteName) : '') ||+ (typeof location !== 'undefined' ? location.hostname : '');++ return {+ url: typeof location !== 'undefined' ? location.href.split('#')[0] : '',+ title,+ description,+ headings,+ nav: uniqueNav,+ content,+ name: name.slice(0, 120),+ };+}++/**+ * Merge host knowledge + harvested page into the `site` payload the+ * /api/concierge endpoint accepts. Knowledge leads (it is curated), the live+ * page fills the remaining budget.+ */+export function buildSitePayload(doc, opts = {}) {+ const ctx = harvestSiteContext(doc, opts);+ const knowledge = cleanText(opts.knowledge).slice(0, MAX_KNOWLEDGE_CHARS);+ let content = ctx.content;+ if (knowledge) {+ const remaining = Math.max(0, MAX_CONTENT_CHARS - Math.min(knowledge.length, MAX_CONTENT_CHARS));+ content = content.slice(0, remaining);+ }+ return {+ url: ctx.url,+ name: ctx.name,+ title: ctx.title,+ description: ctx.description,+ headings: ctx.headings,+ nav: ctx.nav,+ knowledge,+ content,+ };+}diff --git a/concierge-sdk/src/element.js b/concierge-sdk/src/element.jsnew file mode 100644index 000000000..88bd9152a--- /dev/null+++ b/concierge-sdk/src/element.js@@ -0,0 +1,115 @@+/**+ * <three-concierge> custom element — @three-ws/concierge+ * ======================================================+ *+ * Declarative wrapper around Concierge. The element itself is invisible (the+ * widget docks itself to the viewport corner); it exists so a site can add an+ * AI concierge with pure HTML:+ *+ * <three-concierge name="Atelier AI" site-name="Atelier"+ * suggestions="What is Atelier?|How much does it cost?"+ * accent="#f97316"></three-concierge>+ *+ * Attributes (all optional):+ * endpoint answer API (default: https://three.ws/api/concierge)+ * avatar initial catalog avatar id (sol | nova | vera | atlas | echo)+ * avatars comma-separated allow-list of catalog ids for the picker+ * custom-avatar URL of a rigged GLB to use instead of the catalog+ * asset-base override the GLB host+ * name assistant display name (default: the avatar's name)+ * site-name product/site name used in the greeting + grounding+ * greeting first line shown in the empty state and teaser+ * suggestions pipe-separated prompt chips ("a|b|c", max 4)+ * knowledge curated facts (FAQ, policies) the answers are grounded in+ * persona one-line tone instruction, e.g. "warm, playful, concise"+ * accent CSS color for the whole widget chrome+ * position bottom-right | bottom-left+ * theme auto | dark | light+ * lang BCP-47 hint for voice in/out+ * open present → start with the panel open+ * muted present → start with voice off+ * no-picker present → hide the avatar picker+ * no-teaser present → never show the proactive teaser bubble+ * z-index stacking override+ *+ * Methods proxy the controller: ask(text), open(), close(), reset(),+ * setAvatar(id), setMuted(bool). Events re-dispatch as DOM CustomEvents:+ * three-concierge:ready | :open | :close | :message | :agentchange | :error+ */++import { Concierge } from './widget.js';++const bool = (el, name) => el.hasAttribute(name);++export class ThreeConciergeElement extends HTMLElement {+ connectedCallback() {+ if (this._widget) return;+ this.style.display = 'none';++ this._widget = new Concierge({+ endpoint: this.getAttribute('endpoint') || undefined,+ avatar: this.getAttribute('avatar') || undefined,+ avatars: this.getAttribute('avatars')?.split(',').map((s) => s.trim()).filter(Boolean),+ customAvatar: this.getAttribute('custom-avatar') || undefined,+ assetBase: this.getAttribute('asset-base') || undefined,+ name: this.getAttribute('name') || undefined,+ siteName: this.getAttribute('site-name') || undefined,+ greeting: this.getAttribute('greeting') || undefined,+ suggestions: this.getAttribute('suggestions')?.split('|').map((s) => s.trim()).filter(Boolean),+ knowledge: this.getAttribute('knowledge') || undefined,+ persona: this.getAttribute('persona') || undefined,+ accent: this.getAttribute('accent') || undefined,+ position: this.getAttribute('position') || undefined,+ theme: this.getAttribute('theme') || undefined,+ lang: this.getAttribute('lang') || undefined,+ open: bool(this, 'open'),+ muted: bool(this, 'muted'),+ picker: !bool(this, 'no-picker'),+ teaser: !bool(this, 'no-teaser'),+ zIndex: this.getAttribute('z-index') ? Number(this.getAttribute('z-index')) : undefined,+ });++ for (const ev of ['ready', 'open', 'close', 'message', 'agentchange', 'error']) {+ this._widget.on(ev, (detail) => {+ this.dispatchEvent(+ new CustomEvent(`three-concierge:${ev}`, { detail, bubbles: true, composed: true }),+ );+ });+ }+ }++ disconnectedCallback() {+ this._widget?.dispose();+ this._widget = null;+ }++ // ── Imperative API proxy ──────────────────────────────────────────────────+ ask(text) {+ return this._widget?.ask(text);+ }+ open() {+ this._widget?.setOpen(true);+ }+ close() {+ this._widget?.setOpen(false);+ }+ reset() {+ this._widget?.reset();+ }+ setAvatar(id) {+ return this._widget?.setAvatar(id);+ }+ setMuted(muted) {+ this._widget?.setMuted(muted);+ }+ get controller() {+ return this._widget;+ }+}++export function registerElement(tag = 'three-concierge') {+ if (typeof customElements !== 'undefined' && !customElements.get(tag)) {+ customElements.define(tag, ThreeConciergeElement);+ }+ return tag;+}diff --git a/concierge-sdk/src/global.js b/concierge-sdk/src/global.jsnew file mode 100644index 000000000..49e1351fe--- /dev/null+++ b/concierge-sdk/src/global.js@@ -0,0 +1,15 @@+/**+ * CDN entry — @three-ws/concierge+ * ===============================+ *+ * The one-tag build: bundles the whole widget (three inlined), registers+ * <three-concierge>, runs the `data-concierge` script auto-init, and exposes+ * the API at window.ThreeWsConcierge for script consumers.+ */++import * as api from './index.js';++if (typeof window !== 'undefined') {+ window.ThreeWsConcierge = api;+ window.Concierge = window.Concierge || api.Concierge;+}diff --git a/concierge-sdk/src/index.js b/concierge-sdk/src/index.jsnew file mode 100644index 000000000..e48ac7c9e--- /dev/null+++ b/concierge-sdk/src/index.js@@ -0,0 +1,103 @@+/**+ * @three-ws/concierge — public entry+ * ==================================+ *+ * An AI concierge for any website: floating launcher, chat panel with a+ * rigged 3D avatar that blinks and lipsyncs, streaming answers grounded in+ * the live page, voice out (Web Speech TTS) and push-to-talk voice in.+ *+ * Three ways in:+ *+ * 1. Zero-JS CDN tag:+ * <script type="module"+ * src="https://three.ws/concierge/concierge.global.js"+ * data-concierge data-site-name="Acme"></script>+ * 2. HTML tag:+ * import '@three-ws/concierge';+ * <three-concierge site-name="Acme" accent="#f97316"></three-concierge>+ * 3. Imperative:+ * import { Concierge } from '@three-ws/concierge';+ * const c = new Concierge({ siteName: 'Acme', knowledge: FAQ });+ * c.ask('What does the Pro plan cost?');+ *+ * `three` is a peer dependency for the module builds; the .global.js build+ * inlines it for script-tag use.+ */++export const VERSION = '0.1.0';++export { Concierge, drainSentences } from './widget.js';+export { ThreeConciergeElement, registerElement } from './element.js';+export { AvatarStage } from './stage.js';+export { SpeechNarrator } from './narrator.js';+export { createLipsync, buildMorphMap, estimateDurationMs } from './lipsync.js';+export {+ AVATARS, DEFAULT_AVATAR_ID, DEFAULT_ASSET_BASE,+ getAvatar, avatarUrl, customAvatarEntry,+} from './catalog.js';+export { harvestSiteContext, buildSitePayload, MAX_CONTENT_CHARS, MAX_KNOWLEDGE_CHARS } from './context.js';+export { askConcierge, parseSseEvent, createSseBuffer, DEFAULT_ENDPOINT, MAX_HISTORY_TURNS } from './client.js';+export { renderMarkdown, stripMarkdown, escapeHtml } from './markdown.js';+export { createMic, micSupported } from './mic.js';+export { CSS, ensureStyles } from './styles.js';++import { Concierge } from './widget.js';+import { registerElement } from './element.js';++// Register the <three-concierge> element on import (browser only).+if (typeof window !== 'undefined') {+ registerElement();+}++/**+ * Convenience factory — mount a concierge and return the controller.+ * @param {ConstructorParameters<typeof Concierge>[0]} [config]+ */+export function mount(config) {+ return new Concierge(config);+}++/**+ * Auto-init from a `<script data-concierge>` tag so a site can install the+ * widget with no JS at all — the script's `data-*` attributes become config.+ * Idempotent: only the first tagged script mounts an instance.+ */+function autoInit() {+ if (typeof document === 'undefined' || window.__threeWsConcierge) return;+ const tag = document.currentScript || document.querySelector('script[data-concierge]');+ if (!tag || !tag.hasAttribute('data-concierge')) return;++ const d = tag.dataset;+ window.__threeWsConcierge = new Concierge({+ endpoint: d.endpoint || undefined,+ avatar: d.avatar || undefined,+ avatars: d.avatars?.split(',').map((s) => s.trim()).filter(Boolean),+ customAvatar: d.customAvatar || undefined,+ assetBase: d.assetBase || undefined,+ name: d.name || undefined,+ siteName: d.siteName || undefined,+ greeting: d.greeting || undefined,+ suggestions: d.suggestions?.split('|').map((s) => s.trim()).filter(Boolean),+ knowledge: d.knowledge || undefined,+ persona: d.persona || undefined,+ accent: d.accent || undefined,+ position: d.position || undefined,+ theme: d.theme || undefined,+ lang: d.lang || undefined,+ open: 'open' in d,+ muted: 'muted' in d,+ picker: !('noPicker' in d),+ teaser: !('noTeaser' in d),+ zIndex: d.zIndex ? Number(d.zIndex) : undefined,+ });+}++if (typeof window !== 'undefined') {+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', autoInit, { once: true });+ } else {+ autoInit();+ }+}++export default Concierge;diff --git a/concierge-sdk/src/lipsync.js b/concierge-sdk/src/lipsync.jsnew file mode 100644index 000000000..be7c5b18e--- /dev/null+++ b/concierge-sdk/src/lipsync.js@@ -0,0 +1,170 @@+/**+ * Lipsync driver — @three-ws/concierge (shared lineage: page-agent-sdk/src/lipsync.js)+ * =====================================+ *+ * Text → viseme heuristic. No audio analysis, no microphone, no network. We+ * tokenize the spoken text into a timed viseme sequence and lerp the matching+ * morph targets each frame, so the mouth shapes track the words the speech+ * engine is saying. This is the same approach three.ws ships in production+ * (src/runtime/lipsync.js); it is reproduced here so the package stays+ * dependency-free apart from `three`.+ *+ * Three mouth drivers, chosen from the discovered morph targets:+ * - 'arkit': full Oculus/ARKit viseme set (best).+ * - 'jaw': only jawOpen/mouthOpen — amplitude-style open/close.+ * - none: no morphs → returns a no-op timeline; the stage carries the+ * talk visually through body animation instead.+ */++const ARKIT_VISEMES = [+ 'viseme_aa', 'viseme_CH', 'viseme_DD', 'viseme_E', 'viseme_FF',+ 'viseme_I', 'viseme_kk', 'viseme_nn', 'viseme_O', 'viseme_PP',+ 'viseme_RR', 'viseme_sil', 'viseme_SS', 'viseme_TH', 'viseme_U',+];+const JAW_FALLBACKS = ['jawOpen', 'mouthOpen'];++const CHAR_TO_VISEME = {+ a: 'viseme_aa', e: 'viseme_E', i: 'viseme_I', o: 'viseme_O', u: 'viseme_U',+ b: 'viseme_PP', m: 'viseme_PP', p: 'viseme_PP',+ f: 'viseme_FF', v: 'viseme_FF',+ d: 'viseme_DD', t: 'viseme_DD', n: 'viseme_DD', l: 'viseme_DD',+ k: 'viseme_kk', g: 'viseme_kk', c: 'viseme_kk', q: 'viseme_kk',+ s: 'viseme_SS', z: 'viseme_SS', x: 'viseme_SS',+ r: 'viseme_RR', w: 'viseme_U', y: 'viseme_I', h: 'viseme_E', j: 'viseme_CH',+};+const DIGRAPH_TO_VISEME = { th: 'viseme_TH', ch: 'viseme_CH', sh: 'viseme_CH' };++const MS_PER_PHONEME = 80;+const WORD_GAP_MS = 120;+const PUNCT_GAP_MS = 200;+const LERP = 0.35;++/**+ * Build a map of morph-target name → [{ mesh, index }] for the avatar root.+ * @param {import('three').Object3D} root+ * @returns {{ mode: 'arkit'|'jaw', map: Map<string, {mesh:any,index:number}[]> }|null}+ */+export function buildMorphMap(root) {+ const arkit = new Map();+ const jaw = new Map();+ root?.traverse?.((node) => {+ if (!node.isMesh || !node.morphTargetDictionary || !node.morphTargetInfluences) return;+ const dict = node.morphTargetDictionary;+ for (const name of ARKIT_VISEMES) {+ if (dict[name] === undefined) continue;+ if (!arkit.has(name)) arkit.set(name, []);+ arkit.get(name).push({ mesh: node, index: dict[name] });+ }+ for (const name of JAW_FALLBACKS) {+ if (dict[name] === undefined) continue;+ if (!jaw.has(name)) jaw.set(name, []);+ jaw.get(name).push({ mesh: node, index: dict[name] });+ }+ });+ if (arkit.size) return { mode: 'arkit', map: arkit };+ if (jaw.size) return { mode: 'jaw', map: jaw };+ return null;+}++function tokenize(text) {+ const seq = [];+ const lower = String(text || '').toLowerCase();+ let t = 0;+ for (let i = 0; i < lower.length; ) {+ const pair = i + 1 < lower.length ? lower[i] + lower[i + 1] : '';+ if (DIGRAPH_TO_VISEME[pair]) {+ seq.push({ viseme: DIGRAPH_TO_VISEME[pair], startMs: t, endMs: t + MS_PER_PHONEME * 2 });+ t += MS_PER_PHONEME * 2;+ i += 2;+ continue;+ }+ const ch = lower[i];+ if (CHAR_TO_VISEME[ch]) {+ seq.push({ viseme: CHAR_TO_VISEME[ch], startMs: t, endMs: t + MS_PER_PHONEME });+ t += MS_PER_PHONEME;+ } else if (/\s/.test(ch)) {+ t += WORD_GAP_MS;+ } else if (/[.,!?;:]/.test(ch)) {+ t += PUNCT_GAP_MS;+ }+ i++;+ }+ return seq;+}++/** Rough natural duration of `text` in ms, used to pace the no-morph case. */+export function estimateDurationMs(text) {+ const seq = tokenize(text);+ return seq.length ? seq[seq.length - 1].endMs : 0;+}++/**+ * Start a lipsync timeline. The returned object exposes:+ * - tick(nowMs): call every frame; advances + lerps morph influences.+ * - stop(): reset all influences to 0 and mark done.+ * - done: true once the sequence has fully played.+ *+ * The caller owns the clock so the timeline can be synced to the speech engine+ * (we start it on utterance `start`, advance on the render loop, stop on `end`).+ *+ * @param {string} text+ * @param {ReturnType<typeof buildMorphMap>|null} morph+ * @param {{ rate?: number }} [opts] rate>1 speeds the mouth to match faster TTS+ */+export function createLipsync(text, morph, opts = {}) {+ const rate = opts.rate && opts.rate > 0 ? opts.rate : 1;+ const seq = morph ? tokenize(text) : [];+ const totalMs = seq.length ? seq[seq.length - 1].endMs : 0;+ let startMs = -1;+ let done = false;++ // Per-morph smoothed influence so we can lerp toward targets each frame.+ const current = morph ? new Map([...morph.map.keys()].map((k) => [k, 0])) : new Map();++ function apply(name, value) {+ const entries = morph?.map.get(name);+ if (!entries) return;+ for (const { mesh, index } of entries) mesh.morphTargetInfluences[index] = value;+ }++ function tick(nowMs) {+ if (!morph || done) return;+ if (startMs < 0) startMs = nowMs;+ const elapsed = (nowMs - startMs) * rate;++ // Determine the active viseme target for this instant.+ let active = null;+ if (elapsed <= totalMs) {+ for (const ph of seq) {+ if (elapsed >= ph.startMs && elapsed < ph.endMs) { active = ph.viseme; break; }+ }+ }++ // In jaw mode there's no per-viseme shape — any active phoneme opens the+ // jaw on an envelope; silence closes it.+ for (const name of current.keys()) {+ let target = 0;+ if (morph.mode === 'arkit') {+ target = name === active ? 0.92 : 0;+ } else {+ // jaw: open while speaking, with a gentle per-phoneme pulse+ target = active ? 0.45 + 0.25 * Math.abs(Math.sin(elapsed / 70)) : 0;+ }+ const next = current.get(name) + (target - current.get(name)) * LERP;+ current.set(name, next);+ apply(name, next);+ }++ if (elapsed > totalMs + 120) done = true;+ }++ function stop() {+ done = true;+ for (const name of current.keys()) {+ current.set(name, 0);+ apply(name, 0);+ }+ }++ return { tick, stop, get done() { return done; }, get totalMs() { return totalMs; } };+}diff --git a/concierge-sdk/src/markdown.js b/concierge-sdk/src/markdown.jsnew file mode 100644index 000000000..e30883815--- /dev/null+++ b/concierge-sdk/src/markdown.js@@ -0,0 +1,114 @@+/**+ * Markdown-lite renderer — @three-ws/concierge+ * ============================================+ *+ * Answers stream back as plain text with light markdown (bold, code, links,+ * lists). This renders that subset to safe HTML: every piece of source text is+ * escaped BEFORE markup is applied, links are restricted to http(s)/mailto and+ * always open in a new tab with rel hardening. No innerHTML of raw model+ * output, ever.+ */++const ESC = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };++export function escapeHtml(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ESC[c]);+}++function safeHref(url) {+ const u = String(url || '').trim();+ if (/^(https?:\/\/|mailto:|\/)/i.test(u)) return u;+ return null;+}++function inline(md) {+ let out = escapeHtml(md);+ // `code`+ out = out.replace(/`([^`]+)`/g, '<code>$1</code>');+ // **bold** then *italic*+ out = out.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');+ out = out.replace(/(^|[\s(])\*([^*\n]+)\*(?=[\s).,!?:;]|$)/g, '$1<em>$2</em>');+ // [label](url) — href is validated; the label is already escaped+ out = out.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (m, label, url) => {+ const href = safeHref(url);+ return href+ ? `<a href="${escapeHtml(href)}" target="_blank" rel="noopener noreferrer">${label}</a>`+ : label;+ });+ return out;+}++/**+ * Render markdown-lite `text` to an HTML string (paragraphs, bullet/numbered+ * lists, fenced code blocks, inline marks). Safe against HTML injection.+ */+export function renderMarkdown(text) {+ const src = String(text ?? '').replace(/\r\n/g, '\n');+ const blocks = [];+ const lines = src.split('\n');+ let i = 0;++ while (i < lines.length) {+ const line = lines[i];++ if (/^```/.test(line)) {+ const buf = [];+ i++;+ while (i < lines.length && !/^```/.test(lines[i])) buf.push(lines[i++]);+ i++; // closing fence (or EOF)+ blocks.push(`<pre><code>${escapeHtml(buf.join('\n'))}</code></pre>`);+ continue;+ }++ if (/^\s*[-*]\s+/.test(line)) {+ const items = [];+ while (i < lines.length && /^\s*[-*]\s+/.test(lines[i])) {+ items.push(`<li>${inline(lines[i].replace(/^\s*[-*]\s+/, ''))}</li>`);+ i++;+ }+ blocks.push(`<ul>${items.join('')}</ul>`);+ continue;+ }++ if (/^\s*\d+[.)]\s+/.test(line)) {+ const items = [];+ while (i < lines.length && /^\s*\d+[.)]\s+/.test(lines[i])) {+ items.push(`<li>${inline(lines[i].replace(/^\s*\d+[.)]\s+/, ''))}</li>`);+ i++;+ }+ blocks.push(`<ol>${items.join('')}</ol>`);+ continue;+ }++ if (!line.trim()) {+ i++;+ continue;+ }++ // Paragraph: consume until a blank line or a structural line.+ const buf = [];+ while (i < lines.length && lines[i].trim() && !/^```|^\s*[-*]\s+|^\s*\d+[.)]\s+/.test(lines[i])) {+ buf.push(lines[i++]);+ }+ blocks.push(`<p>${inline(buf.join(' '))}</p>`);+ }++ return blocks.join('');+}++/**+ * Strip markdown for the voice channel — what the narrator speaks should be+ * the words, not the syntax.+ */+export function stripMarkdown(text) {+ return String(text ?? '')+ .replace(/```[\s\S]*?```/g, ' code sample. ')+ .replace(/`([^`]+)`/g, '$1')+ .replace(/\*\*([^*]+)\*\*/g, '$1')+ .replace(/\*([^*\n]+)\*/g, '$1')+ .replace(/\[([^\]]+)\]\([^)\s]+\)/g, '$1')+ .replace(/^[\s]*[-*]\s+/gm, '')+ .replace(/^[\s]*\d+[.)]\s+/gm, '')+ .replace(/\s+/g, ' ')+ .trim();+}diff --git a/concierge-sdk/src/mic.js b/concierge-sdk/src/mic.jsnew file mode 100644index 000000000..787435ad4--- /dev/null+++ b/concierge-sdk/src/mic.js@@ -0,0 +1,105 @@+/**+ * Voice input — @three-ws/concierge+ * =================================+ *+ * Thin wrapper over the Web Speech API's SpeechRecognition (webkit-prefixed on+ * Chromium). Push-to-talk: start() listens for one utterance, streams interim+ * transcripts for live feedback, and resolves the final transcript. Degrades+ * to `supported: false` where the API is absent (Firefox, most webviews) so+ * the widget can hide the mic button instead of showing a dead control.+ */++function RecognitionCtor() {+ if (typeof window === 'undefined') return null;+ return window.SpeechRecognition || window.webkitSpeechRecognition || null;+}++export function micSupported() {+ return !!RecognitionCtor();+}++/**+ * @param {{ lang?: string,+ * onInterim?: (transcript:string)=>void,+ * onState?: (s:'listening'|'idle')=>void,+ * onError?: (e:Error)=>void }} [opts]+ */+export function createMic(opts = {}) {+ const Ctor = RecognitionCtor();+ let rec = null;+ let finalText = '';+ let resolveDone = null;++ function stopInternal() {+ if (!rec) return;+ try {+ rec.stop();+ } catch {+ /* already stopped */+ }+ }++ return {+ supported: !!Ctor,+ get listening() {+ return !!rec;+ },++ /** Listen for one utterance; resolves the final transcript ('' on abort). */+ start() {+ if (!Ctor || rec) return Promise.resolve('');+ finalText = '';+ rec = new Ctor();+ rec.lang = opts.lang || (typeof navigator !== 'undefined' ? navigator.language : 'en-US');+ rec.interimResults = true;+ rec.continuous = false;+ rec.maxAlternatives = 1;++ opts.onState?.('listening');+ return new Promise((resolve) => {+ resolveDone = resolve;+ rec.onresult = (e) => {+ let interim = '';+ for (let i = e.resultIndex; i < e.results.length; i++) {+ const r = e.results[i];+ if (r.isFinal) finalText += r[0].transcript;+ else interim += r[0].transcript;+ }+ opts.onInterim?.(finalText + interim);+ };+ rec.onerror = (e) => {+ // 'no-speech'/'aborted' are normal outcomes of a quiet mic, not faults.+ if (e?.error && !/no-speech|aborted/i.test(e.error)) {+ opts.onError?.(new Error('speech-recognition: ' + e.error));+ }+ };+ rec.onend = () => {+ rec = null;+ opts.onState?.('idle');+ const out = finalText.trim();+ resolveDone?.(out);+ resolveDone = null;+ };+ try {+ rec.start();+ } catch (err) {+ rec = null;+ opts.onState?.('idle');+ opts.onError?.(err instanceof Error ? err : new Error(String(err)));+ resolve('');+ resolveDone = null;+ }+ });+ },++ /** Stop listening; the in-flight start() promise resolves with what was heard. */+ stop() {+ stopInternal();+ },++ dispose() {+ stopInternal();+ rec = null;+ },+ };+}diff --git a/concierge-sdk/src/narrator.js b/concierge-sdk/src/narrator.jsnew file mode 100644index 000000000..e8381def6--- /dev/null+++ b/concierge-sdk/src/narrator.js@@ -0,0 +1,193 @@+/**+ * SpeechNarrator — @three-ws/concierge (shared lineage: page-agent-sdk/src/narrator.js)+ * =====================================+ *+ * Speaks queued text aloud with the Web Speech API and keeps the avatar's mouth+ * in sync. There is no backend, no API key, no audio file: TTS is synthesized+ * in the browser, and the lipsync timeline is advanced on the stage's render+ * loop so visemes track the spoken words.+ *+ * Graceful by design:+ * - No speechSynthesis (or muted): we still run the lipsync timeline for the+ * text's estimated duration so the avatar visibly "talks" and captions+ * show — the page narration never silently stalls.+ * - Voice list loads async on some platforms; we wait for `voiceschanged`.+ */++import { createLipsync, estimateDurationMs } from './lipsync.js';++const hasTTS = typeof window !== 'undefined' && 'speechSynthesis' in window;++export class SpeechNarrator {+ /**+ * @param {import('./stage.js').AvatarStage} stage+ * @param {{ muted?: boolean, onState?: (s:'idle'|'speaking')=>void,+ * onCaption?: (text:string|null)=>void, onError?: (e:Error)=>void }} [opts]+ */+ constructor(stage, opts = {}) {+ this.stage = stage;+ this.muted = !!opts.muted;+ this.onState = opts.onState || (() => {});+ this.onCaption = opts.onCaption || (() => {});+ this.onError = opts.onError || (() => {});++ this.agent = null; // current RiggedAgent (for voice selection)+ this._queue = [];+ this._active = null; // { lipsync, utter, fallbackTimer, resolve }+ this._frameUnsub = stage.onFrame((dt, nowMs) => this._tick(nowMs));+ this._voices = [];++ if (hasTTS) {+ this._onVoices = this._loadVoices.bind(this);+ this._loadVoices();+ window.speechSynthesis.addEventListener?.('voiceschanged', this._onVoices);+ }+ }++ /** Switch the active agent so future utterances use its voice profile. */+ setAgent(agent) {+ this.agent = agent;+ }++ setMuted(muted) {+ this.muted = !!muted;+ if (muted && hasTTS) window.speechSynthesis.cancel();+ }++ /**+ * Queue text to speak. Returns a promise that resolves when this line ends+ * (or is skipped/cancelled). Multiple calls play in order.+ * @param {string} text+ * @param {{ interrupt?: boolean }} [opts]+ * @returns {Promise<void>}+ */+ speak(text, opts = {}) {+ const clean = String(text || '').trim();+ if (!clean) return Promise.resolve();+ if (opts.interrupt) this.cancel();+ return new Promise((resolve) => {+ this._queue.push({ text: clean, resolve });+ if (!this._active) this._next();+ });+ }++ /** Stop everything and clear the queue. */+ cancel() {+ if (hasTTS) window.speechSynthesis.cancel();+ this._finishActive(true);+ for (const item of this._queue.splice(0)) item.resolve();+ this.onCaption(null);+ this.stage.setSpeaking(false);+ this.onState('idle');+ }++ get speaking() {+ return !!this._active;+ }++ _next() {+ const item = this._queue.shift();+ if (!item) { this.onState('idle'); this.onCaption(null); this.stage.setSpeaking(false); return; }++ const rate = this.agent?.voice?.rate || 1;+ const lipsync = createLipsync(item.text, this.stage.morph, { rate });+ const active = { text: item.text, lipsync, resolve: item.resolve, utter: null, fallbackTimer: 0 };+ this._active = active;++ this.stage.setSpeaking(true);+ this.onState('speaking');+ this.onCaption(item.text);++ if (hasTTS && !this.muted) {+ const utter = new SpeechSynthesisUtterance(item.text);+ const v = this._pickVoice();+ if (v) utter.voice = v;+ utter.lang = this.agent?.voice?.lang || v?.lang || 'en-US';+ utter.pitch = clamp(this.agent?.voice?.pitch ?? 1, 0, 2);+ utter.rate = clamp(this.agent?.voice?.rate ?? 1, 0.1, 3);+ utter.onend = () => this._finishActive(false);+ utter.onerror = (e) => {+ // Some engines fire 'interrupted'/'canceled' as errors on cancel —+ // only surface genuine synthesis failures, then fall back visually.+ if (e?.error && !/interrupt|cancel/i.test(e.error)) {+ this.onError(new Error('speech-synthesis: ' + e.error));+ this._runVisualFallback(active);+ } else {+ this._finishActive(false);+ }+ };+ active.utter = utter;+ // Safety net: if neither onend nor onerror fires (known flaky on some+ // mobile engines), close out after the estimated duration + slack.+ const guardMs = estimateDurationMs(item.text) * (1 / (utter.rate || 1)) + 1500;+ active.fallbackTimer = window.setTimeout(() => this._finishActive(false), Math.max(2500, guardMs));+ try {+ window.speechSynthesis.speak(utter);+ } catch (err) {+ this.onError(err instanceof Error ? err : new Error(String(err)));+ this._runVisualFallback(active);+ }+ } else {+ this._runVisualFallback(active);+ }+ }++ /** No audio (muted / unsupported): play the lipsync visually then advance. */+ _runVisualFallback(active) {+ if (active !== this._active) return;+ // Estimate from the morph timeline when present, else from raw text so+ // no-morph (animation-lipsync) agents still hold the caption long enough.+ const ms = active.lipsync.totalMs+ ? active.lipsync.totalMs + 350+ : Math.max(1200, estimateDurationMs(active.text) + 350);+ active.fallbackTimer = window.setTimeout(() => this._finishActive(false), ms);+ }++ _tick(nowMs) {+ this._active?.lipsync?.tick(nowMs);+ }++ _finishActive(silent) {+ const active = this._active;+ if (!active) return;+ this._active = null;+ if (active.fallbackTimer) clearTimeout(active.fallbackTimer);+ active.lipsync?.stop();+ try { active.resolve(); } catch { /* consumer callback */ }+ if (!silent) this._next();+ }++ _loadVoices() {+ if (!hasTTS) return;+ this._voices = window.speechSynthesis.getVoices() || [];+ }++ _pickVoice() {+ if (!this._voices.length) this._loadVoices();+ const prof = this.agent?.voice || {};+ const voices = this._voices;+ if (!voices.length) return null;+ // 1) explicit name matches, in priority order+ for (const needle of prof.match || []) {+ const v = voices.find((x) => x.name?.toLowerCase().includes(needle.toLowerCase()));+ if (v) return v;+ }+ // 2) language match+ if (prof.lang) {+ const v = voices.find((x) => x.lang?.toLowerCase().startsWith(prof.lang.toLowerCase().slice(0, 2)));+ if (v) return v;+ }+ // 3) first local voice, else first available+ return voices.find((x) => x.localService) || voices[0];+ }++ dispose() {+ this.cancel();+ this._frameUnsub?.();+ if (hasTTS) window.speechSynthesis.removeEventListener?.('voiceschanged', this._onVoices);+ }+}++function clamp(n, lo, hi) {+ return Math.max(lo, Math.min(hi, Number(n)));+}diff --git a/concierge-sdk/src/stage.js b/concierge-sdk/src/stage.jsnew file mode 100644index 000000000..27c3e3c8c--- /dev/null+++ b/concierge-sdk/src/stage.js@@ -0,0 +1,333 @@+/**+ * AvatarStage — @three-ws/concierge (shared lineage: page-agent-sdk/src/stage.js)+ * ==================================+ *+ * The 3D surface: a transparent WebGL canvas that loads a rigged glTF agent,+ * frames it (bust / upper / full), and keeps it alive with skeletal idle motion+ * — a played idle clip when the GLB ships one, otherwise a procedural breathing+ * + sway + blink loop so the agent never looks like a frozen statue (the whole+ * reason we require rigged avatars). It exposes the morph map + a per-frame hook+ * so the lipsync driver and speech narrator can drive the mouth in sync.+ *+ * Peer-depends on `three` only. Addons resolve through the consumer's bundler+ * (or the import map / inlined build for <script> usage).+ */++import {+ Scene, PerspectiveCamera, WebGLRenderer, AmbientLight, DirectionalLight,+ Box3, Vector3, Color, Clock, PMREMGenerator, AnimationMixer, LoopRepeat,+ ACESFilmicToneMapping, SRGBColorSpace, MathUtils,+} from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';+import { buildMorphMap } from './lipsync.js';++// Catalog rigs served by three.ws (e.g. cz.glb) carry EXT_meshopt_compression;+// GLTFLoader throws "setMeshoptDecoder must be called" without a decoder.+// Lazy + memoized so pages using only uncompressed rigs skip the wasm init.+let _meshoptPromise = null;+function getMeshoptDecoder() {+ if (!_meshoptPromise) {+ _meshoptPromise = import('three/addons/libs/meshopt_decoder.module.js').then((m) => m.MeshoptDecoder);+ }+ return _meshoptPromise;+}++const FRAMING = {+ // [vertical fraction of model height to center on, distance multiplier]+ bust: { center: 0.86, dist: 0.62, fov: 28 },+ upper: { center: 0.72, dist: 1.0, fov: 30 },+ full: { center: 0.5, dist: 1.9, fov: 32 },+};++const BLINK_MORPHS = ['eyeBlinkLeft', 'eyeBlinkRight', 'eyesClosed', 'blink'];++export class AvatarStage {+ /**+ * @param {HTMLElement} container Element the canvas fills.+ * @param {{ background?: string }} [opts]+ */+ constructor(container, opts = {}) {+ this.container = container;+ this._opts = opts;++ this.scene = new Scene();+ this._applyBackground(opts.background);++ this.canvas = document.createElement('canvas');+ this.canvas.style.cssText = 'display:block;width:100%;height:100%;outline:none';+ container.appendChild(this.canvas);++ const w = container.clientWidth || 320;+ const h = container.clientHeight || 360;++ this.camera = new PerspectiveCamera(30, w / h, 0.05, 200);+ this.camera.position.set(0, 1.5, 2.2);++ this.renderer = new WebGLRenderer({+ canvas: this.canvas, antialias: true, alpha: true, powerPreference: 'high-performance',+ });+ this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ this.renderer.setSize(w, h, false);+ this.renderer.outputColorSpace = SRGBColorSpace;+ this.renderer.toneMapping = ACESFilmicToneMapping;+ this.renderer.toneMappingExposure = 1.05;++ const pmrem = new PMREMGenerator(this.renderer);+ this._envTex = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;+ this.scene.environment = this._envTex;+ pmrem.dispose();++ this.scene.add(new AmbientLight(0xffffff, 0.6));+ const key = new DirectionalLight(0xffffff, 1.4);+ key.position.set(1.5, 3, 2.5);+ this.scene.add(key);+ const rim = new DirectionalLight(0x99bbff, 0.5);+ rim.position.set(-2, 2, -2);+ this.scene.add(rim);++ this.clock = new Clock();+ this.mixer = null;+ this.model = null;+ this.morph = null;+ this._idleAction = null;+ this._talkAction = null;+ this._speaking = false;+ this._loadToken = 0;+ this._frameHooks = new Set();+ this._headBone = null;+ this._blinkTargets = [];+ this._nextBlink = 1 + Math.random() * 3;+ this._blinkT = -1;+ this._reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches || false;++ this._resizeObs = new ResizeObserver(() => this._resize());+ this._resizeObs.observe(container);++ // Pause the render loop when the tab is backgrounded or the agent scrolls+ // offscreen — a docked WebGL canvas should never burn GPU it can't be seen on.+ this._visible = !document.hidden;+ this._onscreen = true;+ this._render = this._render.bind(this);+ this._onVisibility = () => { this._visible = !document.hidden; this._kick(); };+ document.addEventListener('visibilitychange', this._onVisibility);+ this._inViewObs = new IntersectionObserver(+ (entries) => { this._onscreen = entries.some((e) => e.isIntersecting); this._kick(); },+ { threshold: 0 },+ );+ this._inViewObs.observe(container);++ this._raf = 0;+ this._raf = requestAnimationFrame(this._render);+ }++ /** (Re)start the render loop if it is paused and the stage is currently visible. */+ _kick() {+ if (this._raf || !this.renderer || !this._visible || !this._onscreen) return;+ this.clock.getDelta(); // discard the idle gap so motion resumes smoothly+ this._raf = requestAnimationFrame(this._render);+ }++ /** Register a per-frame callback `(dtSeconds, nowMs) => void`. Returns an unsubscribe. */+ onFrame(fn) {+ this._frameHooks.add(fn);+ return () => this._frameHooks.delete(fn);+ }++ /**+ * Load a rigged GLB. Replaces any current model. Resolves once framed.+ * @param {string} url+ * @param {{ framing?: 'bust'|'upper'|'full' }} [opts]+ */+ async load(url, opts = {}) {+ const token = ++this._loadToken;+ const loader = new GLTFLoader();+ loader.setMeshoptDecoder(await getMeshoptDecoder());+ const gltf = await loader.loadAsync(url);+ if (token !== this._loadToken) return null; // superseded++ if (this.model) {+ this.scene.remove(this.model);+ this._disposeObject(this.model);+ }+ if (this.mixer) { this.mixer.stopAllAction(); this.mixer.uncacheRoot(this.model); }+ this.mixer = null;+ this._idleAction = null;+ this._talkAction = null;++ this.model = gltf.scene;+ this.scene.add(this.model);+ this.morph = buildMorphMap(this.model);+ this._collectRigRefs(this.model);++ // Animation: prefer a named idle clip; keep any talk clip for speaking.+ if (gltf.animations?.length) {+ this.mixer = new AnimationMixer(this.model);+ const idle = pickClip(gltf.animations, ['idle', 'breathing', 'stand', 'rest']) || gltf.animations[0];+ const talk = pickClip(gltf.animations, ['talk', 'talking', 'speak', 'gesture', 'wave']);+ if (idle) {+ this._idleAction = this.mixer.clipAction(idle);+ this._idleAction.setLoop(LoopRepeat, Infinity).play();+ }+ if (talk && talk !== idle) {+ this._talkAction = this.mixer.clipAction(talk);+ this._talkAction.setLoop(LoopRepeat, Infinity);+ this._talkAction.enabled = true;+ this._talkAction.setEffectiveWeight(0);+ this._talkAction.play();+ }+ }++ this._frame(opts.framing || 'upper');+ return gltf;+ }++ /** Begin/halt the talking visual state (animation weight + body emphasis). */+ setSpeaking(on) {+ this._speaking = !!on;+ if (this._talkAction) {+ // Crossfade talk-clip weight; idle stays underneath.+ this._talkAction.setEffectiveWeight(on ? 0.85 : 0);+ }+ }++ _collectRigRefs(root) {+ this._headBone = null;+ this._blinkTargets = [];+ root.traverse((node) => {+ if (node.isBone && /head/i.test(node.name) && !/headtop|end/i.test(node.name) && !this._headBone) {+ this._headBone = node;+ node.userData._restQ = node.quaternion.clone();+ }+ if (node.isMesh && node.morphTargetDictionary) {+ for (const name of BLINK_MORPHS) {+ const idx = node.morphTargetDictionary[name];+ if (idx !== undefined) this._blinkTargets.push({ mesh: node, index: idx });+ }+ }+ });+ }++ _frame(framing) {+ const conf = FRAMING[framing] || FRAMING.upper;+ const box = new Box3().setFromObject(this.model);+ const size = new Vector3();+ const center = new Vector3();+ box.getSize(size);+ box.getCenter(center);+ const height = size.y || 1.7;+ const focusY = box.min.y + height * conf.center;+ const focusX = center.x;+ const maxDim = Math.max(size.x, height) || 1;++ this.camera.fov = conf.fov;+ const fov = (conf.fov * Math.PI) / 180;+ const dist = ((maxDim / 2) / Math.tan(fov / 2)) * conf.dist;+ this.camera.position.set(focusX, focusY, box.max.z + dist);+ this.camera.near = Math.max(0.01, dist / 100);+ this.camera.far = dist * 50;+ this.camera.lookAt(focusX, focusY, center.z);+ this.camera.updateProjectionMatrix();+ this._focus = new Vector3(focusX, focusY, center.z);+ }++ _proceduralIdle(t) {+ if (this.mixer || this._reduce || !this.model) return; // clip-driven or static+ // Subtle breathing on the whole model + head sway when no skeletal clip.+ const breathe = Math.sin(t * 1.6) * 0.006;+ this.model.position.y = breathe;+ if (this._headBone && this._headBone.userData._restQ) {+ const sway = Math.sin(t * 0.6) * 0.05;+ const nod = Math.sin(t * 0.9) * 0.03 + (this._speaking ? Math.sin(t * 6) * 0.04 : 0);+ this._headBone.quaternion.copy(this._headBone.userData._restQ);+ this._headBone.rotateY(sway);+ this._headBone.rotateX(nod);+ }+ }++ _blink(dt, t) {+ if (!this._blinkTargets.length || this._reduce) return;+ if (this._blinkT < 0) {+ this._nextBlink -= dt;+ if (this._nextBlink <= 0) { this._blinkT = 0; this._nextBlink = 2 + Math.random() * 4; }+ return;+ }+ this._blinkT += dt;+ const dur = 0.16;+ const v = this._blinkT < dur / 2+ ? this._blinkT / (dur / 2)+ : 1 - (this._blinkT - dur / 2) / (dur / 2);+ const w = MathUtils.clamp(v, 0, 1);+ for (const { mesh, index } of this._blinkTargets) mesh.morphTargetInfluences[index] = w;+ if (this._blinkT >= dur) this._blinkT = -1;+ }++ _render() {+ // Re-arm only while visible & onscreen; _kick() resumes when that changes.+ if (!this.renderer || !this._visible || !this._onscreen) { this._raf = 0; return; }+ this._raf = requestAnimationFrame(this._render);+ const dt = Math.min(this.clock.getDelta(), 0.05);+ const t = this.clock.elapsedTime;+ const nowMs = t * 1000;+ this.mixer?.update(dt);+ this._proceduralIdle(t);+ this._blink(dt, t);+ for (const fn of this._frameHooks) {+ try { fn(dt, nowMs); } catch { /* a misbehaving hook must not kill the loop */ }+ }+ this.renderer.render(this.scene, this.camera);+ }++ _resize() {+ if (!this.renderer || !this.camera) return;+ const w = this.container.clientWidth || 1;+ const h = this.container.clientHeight || 1;+ this.renderer.setSize(w, h, false);+ this.camera.aspect = w / h;+ this.camera.updateProjectionMatrix();+ }++ _applyBackground(value) {+ if (!value || value === 'transparent') { this.scene.background = null; return; }+ try { this.scene.background = new Color(value); } catch { this.scene.background = null; }+ }++ _disposeObject(obj) {+ obj.traverse?.((n) => {+ n.geometry?.dispose?.();+ const mats = Array.isArray(n.material) ? n.material : [n.material];+ mats.forEach((m) => {+ if (!m) return;+ for (const v of Object.values(m)) if (v?.isTexture) v.dispose();+ m.dispose?.();+ });+ });+ }++ dispose() {+ cancelAnimationFrame(this._raf);+ this._raf = 0;+ this._resizeObs?.disconnect();+ this._inViewObs?.disconnect();+ document.removeEventListener('visibilitychange', this._onVisibility);+ this._frameHooks.clear();+ if (this.model) { this.scene.remove(this.model); this._disposeObject(this.model); }+ this._envTex?.dispose();+ this._envTex = null;+ this.renderer?.dispose();+ this.renderer?.forceContextLoss?.();+ this.renderer = null;+ this.canvas?.remove();+ this.scene = null;+ this.camera = null;+ this.model = null;+ }+}++function pickClip(clips, hints) {+ for (const hint of hints) {+ const found = clips.find((c) => c.name && c.name.toLowerCase().includes(hint));+ if (found) return found;+ }+ return null;+}diff --git a/concierge-sdk/src/styles.js b/concierge-sdk/src/styles.jsnew file mode 100644index 000000000..285357ed1--- /dev/null+++ b/concierge-sdk/src/styles.js@@ -0,0 +1,198 @@+/**+ * Styles — @three-ws/concierge+ * ============================+ *+ * One injected stylesheet, scoped under .tc- prefixes and namespaced CSS+ * variables so host pages are never polluted. Themes: dark and light, chosen+ * by `data-tc-theme` on the root (the widget resolves 'auto' from+ * prefers-color-scheme and live-updates). Accent is one variable hosts set+ * from config — every tint derives via color-mix so a single hex restyles the+ * whole widget.+ */++export const CSS = `+.tc-root{+ --tc-accent:#6366f1;+ --tc-bg:#0b0c12;+ --tc-surface:#12141d;+ --tc-surface-2:#191c28;+ --tc-border:rgba(255,255,255,.09);+ --tc-text:#eceef6;+ --tc-text-dim:#8b93ab;+ --tc-user-text:#fff;+ --tc-shadow:0 24px 64px rgba(0,0,0,.5),0 4px 16px rgba(0,0,0,.35);+ --tc-radius:16px;+ position:fixed;z-index:2147482800;display:flex;flex-direction:column;align-items:flex-end;gap:12px;+ font-family:ui-sans-serif,system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;+ -webkit-font-smoothing:antialiased;line-height:1.45;+ -webkit-user-select:none;user-select:none;+}+.tc-root[data-tc-theme=light]{+ --tc-bg:#ffffff;+ --tc-surface:#f4f5f9;+ --tc-surface-2:#eceef5;+ --tc-border:rgba(15,18,32,.10);+ --tc-text:#171923;+ --tc-text-dim:#5f677e;+ --tc-shadow:0 24px 64px rgba(20,24,40,.18),0 4px 16px rgba(20,24,40,.10);+}+.tc-root[data-tc-pos=bottom-right]{right:20px;bottom:20px}+.tc-root[data-tc-pos=bottom-left]{left:20px;bottom:20px;align-items:flex-start}+.tc-root *,.tc-root *::before,.tc-root *::after{box-sizing:border-box}+.tc-root button{font:inherit;border:none;background:none;color:inherit;cursor:pointer;padding:0}+.tc-root button:focus-visible,.tc-root textarea:focus-visible,.tc-root a:focus-visible{outline:2px solid var(--tc-accent);outline-offset:2px;border-radius:6px}++/* ── Launcher ─────────────────────────────────────────────────────────── */+.tc-launcher{position:relative;width:56px;height:56px;border-radius:50%;display:grid;place-items:center;color:#fff;+ background:linear-gradient(135deg,color-mix(in srgb,var(--tc-accent) 88%,#fff 12%),color-mix(in srgb,var(--tc-accent) 82%,#000 18%));+ box-shadow:0 10px 30px color-mix(in srgb,var(--tc-accent) 45%,transparent),0 2px 8px rgba(0,0,0,.25);+ transition:transform .18s ease,box-shadow .18s ease,filter .18s ease}+.tc-launcher::before{content:'';position:absolute;inset:0;border-radius:50%;background:linear-gradient(180deg,rgba(255,255,255,.32),transparent 55%);pointer-events:none}+.tc-launcher:hover{transform:translateY(-2px) scale(1.04);filter:brightness(1.07)}+.tc-launcher:active{transform:scale(.96)}+.tc-launcher svg{width:24px;height:24px;transition:transform .25s ease}+.tc-root.is-open .tc-launcher svg{transform:rotate(90deg)}+.tc-pulse{position:absolute;inset:-4px;border-radius:50%;background:color-mix(in srgb,var(--tc-accent) 55%,transparent);animation:tc-pulse 2.6s ease-out infinite;pointer-events:none}+.tc-root.is-open .tc-pulse{display:none}+@keyframes tc-pulse{0%{transform:scale(.9);opacity:.55}70%{transform:scale(1.45);opacity:0}100%{transform:scale(1.45);opacity:0}}++/* ── Teaser bubble ────────────────────────────────────────────────────── */+.tc-teaser{max-width:240px;background:var(--tc-bg);color:var(--tc-text);border:1px solid var(--tc-border);border-radius:14px;+ padding:10px 34px 10px 14px;font-size:13.5px;box-shadow:var(--tc-shadow);position:relative;+ opacity:0;transform:translateY(8px);transition:opacity .3s ease,transform .3s ease;cursor:pointer}+.tc-teaser.is-in{opacity:1;transform:translateY(0)}+.tc-teaser-close{position:absolute;top:6px;right:6px;width:20px;height:20px;display:grid;place-items:center;color:var(--tc-text-dim);border-radius:50%}+.tc-teaser-close:hover{color:var(--tc-text);background:var(--tc-surface-2)}++/* ── Panel ────────────────────────────────────────────────────────────── */+.tc-panel{width:380px;max-width:calc(100vw - 2.5rem);max-height:min(72vh,680px);display:flex;flex-direction:column;overflow:hidden;+ background:var(--tc-bg);color:var(--tc-text);border:1px solid var(--tc-border);border-radius:var(--tc-radius);box-shadow:var(--tc-shadow);+ opacity:0;transform:translateY(14px) scale(.97);transform-origin:100% 100%;+ transition:opacity .24s ease,transform .24s cubic-bezier(.2,.9,.3,1.1)}+.tc-root[data-tc-pos=bottom-left] .tc-panel{transform-origin:0 100%}+.tc-root.is-open .tc-panel{opacity:1;transform:translateY(0) scale(1)}+.tc-panel[hidden]{display:none}++/* Header */+.tc-head{flex-shrink:0;display:flex;align-items:center;justify-content:space-between;gap:8px;padding:12px 14px;border-bottom:1px solid var(--tc-border);background:var(--tc-surface)}+.tc-head-id{display:flex;align-items:center;gap:9px;min-width:0}+.tc-head-dot{width:8px;height:8px;border-radius:50%;background:#34d399;box-shadow:0 0 0 3px color-mix(in srgb,#34d399 22%,transparent);flex-shrink:0}+.tc-head-name{font-weight:650;font-size:14px;letter-spacing:-.01em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.tc-head-sub{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:10.5px;color:var(--tc-text-dim);text-transform:lowercase}+.tc-head-actions{display:flex;align-items:center;gap:2px;flex-shrink:0}+.tc-icon-btn{width:30px;height:30px;border-radius:8px;display:grid;place-items:center;color:var(--tc-text-dim);transition:color .15s ease,background .15s ease}+.tc-icon-btn:hover{color:var(--tc-text);background:var(--tc-surface-2)}+.tc-icon-btn[aria-pressed=true]{color:var(--tc-accent)}+.tc-icon-btn svg{width:16px;height:16px}++/* Stage (3D avatar) */+.tc-stage{flex-shrink:0;position:relative;height:150px;border-bottom:1px solid var(--tc-border);+ background:+ radial-gradient(120px 90px at 50% 100%,color-mix(in srgb,var(--tc-accent) 26%,transparent),transparent 72%),+ linear-gradient(180deg,color-mix(in srgb,var(--tc-surface) 55%,transparent),var(--tc-bg));+ transition:height .25s ease}+.tc-root.is-compact .tc-stage{height:0;border-bottom:none;overflow:hidden}+.tc-stage-canvas{position:absolute;inset:0}+.tc-stage-glow{position:absolute;left:50%;bottom:8px;width:120px;height:22px;transform:translateX(-50%);border-radius:50%;+ background:color-mix(in srgb,var(--tc-accent) 30%,transparent);filter:blur(12px);opacity:.5;pointer-events:none}+.tc-stage-skel{position:absolute;left:50%;bottom:10px;width:84px;height:112px;transform:translateX(-50%);+ border-radius:44% 44% 38% 38%/56% 56% 44% 44%;overflow:hidden;opacity:0;transition:opacity .25s ease;pointer-events:none;+ background:linear-gradient(180deg,color-mix(in srgb,var(--tc-accent) 16%,transparent),transparent)}+.tc-stage.is-loading .tc-stage-skel{opacity:1}+.tc-stage-skel::after{content:'';position:absolute;inset:0;background:linear-gradient(110deg,transparent 18%,rgba(255,255,255,.2) 46%,transparent 72%);transform:translateX(-120%);animation:tc-shimmer 1.2s ease-in-out infinite}+@keyframes tc-shimmer{to{transform:translateX(120%)}}+.tc-stage-caption{position:absolute;left:10px;right:10px;bottom:8px;text-align:center;font-size:11.5px;color:var(--tc-text-dim);+ overflow:hidden;text-overflow:ellipsis;white-space:nowrap;pointer-events:none;opacity:0;transition:opacity .2s ease}+.tc-stage-caption.is-in{opacity:1}++/* Messages */+.tc-thread{flex:1;min-height:120px;overflow-y:auto;overscroll-behavior:contain;padding:14px;display:flex;flex-direction:column;gap:10px;scrollbar-width:thin;scrollbar-color:var(--tc-surface-2) transparent}+.tc-msg{max-width:86%;padding:9px 12px;border-radius:14px;font-size:13.5px;-webkit-user-select:text;user-select:text;+ overflow-wrap:anywhere;animation:tc-msg-in .22s ease both}+@keyframes tc-msg-in{from{opacity:0;transform:translateY(5px)}to{opacity:1;transform:translateY(0)}}+.tc-msg.is-user{align-self:flex-end;color:var(--tc-user-text);border-bottom-right-radius:5px;+ background:linear-gradient(135deg,color-mix(in srgb,var(--tc-accent) 90%,#fff 10%),color-mix(in srgb,var(--tc-accent) 80%,#000 20%))}+.tc-msg.is-bot{align-self:flex-start;background:var(--tc-surface);border:1px solid var(--tc-border);border-bottom-left-radius:5px}+.tc-msg.is-error{border-color:color-mix(in srgb,#f87171 45%,transparent);background:color-mix(in srgb,#f87171 9%,var(--tc-surface))}+.tc-msg p{margin:0 0 8px}.tc-msg p:last-child{margin:0}+.tc-msg ul,.tc-msg ol{margin:0 0 8px;padding-left:18px}.tc-msg ul:last-child,.tc-msg ol:last-child{margin-bottom:0}+.tc-msg li{margin:2px 0}+.tc-msg a{color:var(--tc-accent);text-decoration:underline;text-underline-offset:2px}+.tc-msg code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;background:color-mix(in srgb,var(--tc-accent) 12%,transparent);padding:1px 5px;border-radius:5px}+.tc-msg pre{margin:0 0 8px;padding:10px;border-radius:9px;background:var(--tc-surface-2);overflow-x:auto}+.tc-msg pre:last-child{margin-bottom:0}+.tc-msg pre code{background:none;padding:0}+.tc-caret{display:inline-block;width:7px;height:14px;margin-left:2px;vertical-align:-2px;background:var(--tc-accent);border-radius:2px;animation:tc-caret 1s steps(2) infinite}+@keyframes tc-caret{50%{opacity:0}}+.tc-typing{align-self:flex-start;display:inline-flex;gap:4px;padding:11px 13px;border-radius:14px;border-bottom-left-radius:5px;background:var(--tc-surface);border:1px solid var(--tc-border)}+.tc-typing i{width:6px;height:6px;border-radius:50%;background:var(--tc-text-dim);animation:tc-blink 1.2s ease-in-out infinite}+.tc-typing i:nth-child(2){animation-delay:.18s}.tc-typing i:nth-child(3){animation-delay:.36s}+@keyframes tc-blink{0%,66%,100%{opacity:.35;transform:translateY(0)}33%{opacity:1;transform:translateY(-3px)}}+.tc-retry{align-self:flex-start;margin-top:-4px;font-size:12px;color:var(--tc-accent);padding:3px 8px;border-radius:7px}+.tc-retry:hover{background:var(--tc-surface-2)}++/* Empty state + chips */+.tc-empty{margin:auto 0;text-align:center;padding:12px 6px;display:flex;flex-direction:column;gap:6px;align-items:center}+.tc-empty-title{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12.5px;color:var(--tc-text-dim)}+.tc-chips{display:flex;flex-wrap:wrap;gap:6px;justify-content:center;padding:4px 0}+.tc-chip{font-size:12px;color:var(--tc-text);background:var(--tc-surface);border:1px solid var(--tc-border);border-radius:999px;padding:6px 11px;+ transition:border-color .15s ease,background .15s ease,transform .15s ease}+.tc-chip:hover{border-color:color-mix(in srgb,var(--tc-accent) 55%,transparent);background:var(--tc-surface-2);transform:translateY(-1px)}++/* Input row */+.tc-input{flex-shrink:0;display:flex;align-items:flex-end;gap:8px;padding:10px 12px;border-top:1px solid var(--tc-border);background:var(--tc-surface)}+.tc-input textarea{flex:1;resize:none;background:transparent;border:none;color:var(--tc-text);font:inherit;font-size:13.5px;line-height:1.5;+ padding:6px 2px;max-height:110px;min-height:30px;overflow-y:auto;-webkit-user-select:text;user-select:text}+.tc-input textarea::placeholder{color:var(--tc-text-dim)}+.tc-input textarea:focus{outline:none}+.tc-input textarea:disabled{opacity:.5}+.tc-mic,.tc-send{flex-shrink:0;width:34px;height:34px;border-radius:10px;display:grid;place-items:center;transition:background .15s ease,color .15s ease,transform .12s ease}+.tc-mic{color:var(--tc-text-dim);background:var(--tc-surface-2)}+.tc-mic:hover{color:var(--tc-text)}+.tc-mic.is-live{color:#fff;background:#ef4444;animation:tc-mic 1.4s ease-in-out infinite}+@keyframes tc-mic{50%{box-shadow:0 0 0 6px color-mix(in srgb,#ef4444 25%,transparent)}}+.tc-send{color:#fff;background:linear-gradient(135deg,color-mix(in srgb,var(--tc-accent) 88%,#fff 12%),color-mix(in srgb,var(--tc-accent) 80%,#000 20%))}+.tc-send:hover{filter:brightness(1.08)}+.tc-send:active{transform:scale(.94)}+.tc-send:disabled{opacity:.4;cursor:not-allowed;filter:none}+.tc-mic svg,.tc-send svg{width:15px;height:15px}++/* Footer */+.tc-foot{flex-shrink:0;text-align:center;padding:5px 0 7px;background:var(--tc-surface)}+.tc-foot a{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:10px;color:var(--tc-text-dim);text-decoration:none;transition:color .15s ease}+.tc-foot a:hover{color:var(--tc-accent)}++/* Picker */+.tc-picker{position:absolute;inset:auto 0 0 0;top:0;z-index:5;background:color-mix(in srgb,var(--tc-bg) 88%,transparent);backdrop-filter:blur(8px);+ display:flex;flex-direction:column;padding:14px;overflow-y:auto;opacity:0;pointer-events:none;transition:opacity .2s ease}+.tc-picker.is-in{opacity:1;pointer-events:auto}+.tc-picker-title{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px;color:var(--tc-text-dim);margin:0 0 10px;text-transform:lowercase}+.tc-picker-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px}+.tc-picker-card{display:flex;flex-direction:column;gap:2px;text-align:left;padding:10px 12px;border-radius:11px;background:var(--tc-surface);border:1px solid var(--tc-border);transition:border-color .15s ease,transform .15s ease}+.tc-picker-card:hover{transform:translateY(-1px);border-color:color-mix(in srgb,var(--tc-accent) 55%,transparent)}+.tc-picker-card.is-current{border-color:var(--tc-accent);box-shadow:0 0 0 1px var(--tc-accent)}+.tc-picker-name{font-size:13px;font-weight:600}+.tc-picker-tag{font-size:11px;color:var(--tc-text-dim)}++/* Small screens: full-width sheet */+@media (max-width:480px){+ .tc-root[data-tc-pos=bottom-right],.tc-root[data-tc-pos=bottom-left]{right:12px;left:12px;bottom:12px;align-items:stretch}+ .tc-panel{width:100%;max-width:none;max-height:min(78vh,640px)}+ .tc-launcher{align-self:flex-end}+ .tc-root[data-tc-pos=bottom-left] .tc-launcher{align-self:flex-start}+}+@media (prefers-reduced-motion:reduce){+ .tc-panel,.tc-msg,.tc-teaser,.tc-launcher,.tc-stage{transition:none;animation:none}+ .tc-pulse,.tc-typing i,.tc-caret{animation:none}+}+`;++let injected = false;+export function ensureStyles(doc = typeof document !== 'undefined' ? document : null) {+ if (injected || !doc) return;+ injected = true;+ const style = doc.createElement('style');+ style.id = 'three-concierge-style';+ style.textContent = CSS;+ doc.head.appendChild(style);+}diff --git a/concierge-sdk/src/widget.js b/concierge-sdk/src/widget.jsnew file mode 100644index 000000000..6811a0a28--- /dev/null+++ b/concierge-sdk/src/widget.js@@ -0,0 +1,721 @@+/**+ * Concierge — @three-ws/concierge+ * ===============================+ *+ * The embeddable AI concierge: a floating launcher that opens a chat panel+ * with a rigged 3D avatar bust (blinks, idles, lipsyncs), streaming answers+ * grounded in the live page, browser-native voice out, and push-to-talk voice+ * in. One class owns the whole lifecycle; `<three-concierge>` and the script+ * auto-init are thin wrappers over it.+ *+ * Design decisions that matter:+ * - The WebGL stage is built lazily on FIRST OPEN. A closed widget costs the+ * host page zero GPU and no GLB download.+ * - Answers stream sentence-by-sentence into the voice channel, so the+ * avatar starts speaking while the rest of the reply is still arriving.+ * - The conversation persists in sessionStorage per origin, so a page+ * navigation does not amnesia the thread.+ */++import { AvatarStage } from './stage.js';+import { SpeechNarrator } from './narrator.js';+import { AVATARS, DEFAULT_AVATAR_ID, DEFAULT_ASSET_BASE, getAvatar, avatarUrl, customAvatarEntry } from './catalog.js';+import { buildSitePayload } from './context.js';+import { askConcierge, DEFAULT_ENDPOINT, MAX_HISTORY_TURNS } from './client.js';+import { renderMarkdown, stripMarkdown, escapeHtml } from './markdown.js';+import { createMic, micSupported } from './mic.js';+import { ensureStyles } from './styles.js';++const LS_AVATAR = 'tc:avatar';+const LS_MUTED = 'tc:muted';+const SS_THREAD = 'tc:thread';+const SS_TEASED = 'tc:teased';++const ICONS = {+ spark:+ '<svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 00-2.456 2.456z"/></svg>',+ close:+ '<svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>',+ sound:+ '<svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M19.114 5.636a9 9 0 010 12.728M16.463 8.288a5.25 5.25 0 010 7.424M6.75 8.25l4.72-4.72a.75.75 0 011.28.53v15.88a.75.75 0 01-1.28.53l-4.72-4.72H4.51c-.88 0-1.704-.507-1.938-1.354A9.01 9.01 0 012.25 12c0-.83.112-1.633.322-2.396C2.806 8.756 3.63 8.25 4.51 8.25H6.75z"/></svg>',+ soundOff:+ '<svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M17.25 9.75L19.5 12m0 0l2.25 2.25M19.5 12l2.25-2.25M19.5 12l-2.25 2.25m-10.5-6l4.72-4.72a.75.75 0 011.28.53v15.88a.75.75 0 01-1.28.53l-4.72-4.72H4.51c-.88 0-1.704-.507-1.938-1.354A9.01 9.01 0 012.25 12c0-.83.112-1.633.322-2.396C2.806 8.756 3.63 8.25 4.51 8.25H6.75z"/></svg>',+ swap:+ '<svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M7.5 21L3 16.5m0 0L7.5 12M3 16.5h13.5m0-13.5L21 7.5m0 0L16.5 12M21 7.5H7.5"/></svg>',+ collapse:+ '<svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M4.5 15.75l7.5-7.5 7.5 7.5"/></svg>',+ mic:+ '<svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M12 18.75a6 6 0 006-6v-1.5m-6 7.5a6 6 0 01-6-6v-1.5m6 7.5v3.75m-3.75 0h7.5M12 15.75a3 3 0 01-3-3V4.5a3 3 0 116 0v8.25a3 3 0 01-3 3z"/></svg>',+ send:+ '<svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.2" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5"/></svg>',+};++function storageGet(store, key) {+ try {+ return window[store].getItem(key);+ } catch {+ return null;+ }+}+function storageSet(store, key, value) {+ try {+ window[store].setItem(key, value);+ } catch {+ /* storage unavailable (private mode / blocked) — degrade to in-memory */+ }+}++/** Split streamed text into complete sentences for the voice channel. */+export function drainSentences(buffer) {+ const sentences = [];+ let rest = buffer;+ let m;+ const re = /[^.!?\n]*[.!?\n]+["')\]]?\s*/g;+ let consumed = 0;+ while ((m = re.exec(rest)) !== null) {+ const s = m[0].trim();+ if (s) sentences.push(s);+ consumed = re.lastIndex;+ }+ return { sentences, rest: rest.slice(consumed) };+}++export class Concierge {+ /**+ * @param {{+ * endpoint?: string, avatar?: string, avatars?: string[],+ * customAvatar?: string|object, assetBase?: string,+ * name?: string, siteName?: string, greeting?: string,+ * suggestions?: string[], knowledge?: string, persona?: string,+ * accent?: string, position?: 'bottom-right'|'bottom-left',+ * theme?: 'auto'|'dark'|'light', open?: boolean, muted?: boolean,+ * picker?: boolean, teaser?: boolean, zIndex?: number, lang?: string,+ * }} [config]+ */+ constructor(config = {}) {+ this.config = {+ endpoint: config.endpoint || DEFAULT_ENDPOINT,+ assetBase: config.assetBase || DEFAULT_ASSET_BASE,+ avatars: Array.isArray(config.avatars) && config.avatars.length+ ? AVATARS.filter((a) => config.avatars.includes(a.id))+ : AVATARS,+ name: config.name || '',+ siteName: config.siteName || '',+ greeting: config.greeting || '',+ suggestions: Array.isArray(config.suggestions) ? config.suggestions.slice(0, 4) : [],+ knowledge: config.knowledge || '',+ persona: config.persona || '',+ accent: config.accent || '',+ position: config.position === 'bottom-left' ? 'bottom-left' : 'bottom-right',+ theme: ['dark', 'light'].includes(config.theme) ? config.theme : 'auto',+ open: !!config.open,+ muted: !!config.muted,+ picker: config.picker !== false,+ teaser: config.teaser !== false,+ zIndex: config.zIndex,+ lang: config.lang || '',+ };++ this._custom = config.customAvatar ? customAvatarEntry(config.customAvatar) : null;+ const savedId = storageGet('localStorage', LS_AVATAR);+ this.avatar = this._custom || getAvatarFrom(this.config.avatars, config.avatar || savedId);++ this.open = false;+ this.busy = false;+ this.muted = this.config.muted || storageGet('localStorage', LS_MUTED) === '1';+ this.messages = this._restoreThread();+ this._listeners = new Map();+ this._stage = null;+ this._narrator = null;+ this._mic = null;+ this._abort = null;+ this._destroyed = false;++ if (typeof window === 'undefined' || typeof document === 'undefined') return;+ this._build();+ if (this.config.open) this.setOpen(true);+ else if (this.config.teaser) this._scheduleTeaser();+ this._emit('ready', { avatar: this.avatar.id });+ }++ // ── Events ────────────────────────────────────────────────────────────────+ on(event, fn) {+ if (!this._listeners.has(event)) this._listeners.set(event, new Set());+ this._listeners.get(event).add(fn);+ return () => this._listeners.get(event)?.delete(fn);+ }+ _emit(event, detail) {+ for (const fn of this._listeners.get(event) || []) {+ try {+ fn(detail);+ } catch {+ /* listener errors must not break the widget */+ }+ }+ }++ // ── DOM ───────────────────────────────────────────────────────────────────+ _build() {+ ensureStyles();+ const root = document.createElement('div');+ root.className = 'tc-root';+ root.setAttribute('data-three-concierge', '');+ root.setAttribute('data-tc-pos', this.config.position);+ if (this.config.zIndex) root.style.zIndex = String(this.config.zIndex);+ if (this.config.accent) root.style.setProperty('--tc-accent', this.config.accent);+ this._applyTheme(root);++ const name = this.config.name || this.avatar.name;+ root.innerHTML = `+ <section class="tc-panel" role="dialog" aria-modal="false" aria-label="${escapeHtml(name)} — site assistant" hidden>+ <header class="tc-head">+ <div class="tc-head-id">+ <span class="tc-head-dot" aria-hidden="true"></span>+ <div>+ <div class="tc-head-name"></div>+ <div class="tc-head-sub">// ai concierge</div>+ </div>+ </div>+ <div class="tc-head-actions">+ <button type="button" class="tc-icon-btn tc-btn-mute" aria-label="Toggle voice" aria-pressed="false">${ICONS.sound}</button>+ ${this.config.picker && !this._custom ? `<button type="button" class="tc-icon-btn tc-btn-swap" aria-label="Choose a different avatar">${ICONS.swap}</button>` : ''}+ <button type="button" class="tc-icon-btn tc-btn-compact" aria-label="Toggle avatar view" aria-pressed="false">${ICONS.collapse}</button>+ <button type="button" class="tc-icon-btn tc-btn-close" aria-label="Close assistant">${ICONS.close}</button>+ </div>+ </header>+ <div class="tc-stage is-loading" aria-hidden="true">+ <div class="tc-stage-glow"></div>+ <div class="tc-stage-skel"></div>+ <div class="tc-stage-canvas"></div>+ <div class="tc-stage-caption"></div>+ </div>+ <div class="tc-thread" aria-live="polite"></div>+ <div class="tc-input">+ <textarea rows="1" maxlength="2000" placeholder="Ask anything…" aria-label="Your question"></textarea>+ ${micSupported() ? `<button type="button" class="tc-mic" aria-label="Ask by voice" aria-pressed="false">${ICONS.mic}</button>` : ''}+ <button type="button" class="tc-send" aria-label="Send" disabled>${ICONS.send}</button>+ </div>+ <footer class="tc-foot"><a href="https://three.ws/concierge" target="_blank" rel="noopener noreferrer">powered by three.ws</a></footer>+ <div class="tc-picker" role="listbox" aria-label="Choose your concierge" hidden>+ <p class="tc-picker-title">// choose your concierge</p>+ <div class="tc-picker-grid"></div>+ </div>+ </section>+ <button type="button" class="tc-launcher" aria-label="Open site assistant" aria-expanded="false">+ <span class="tc-pulse" aria-hidden="true"></span>+ ${ICONS.spark}+ </button>+ `;+ document.body.appendChild(root);+ this.root = root;++ this.$ = {+ panel: root.querySelector('.tc-panel'),+ launcher: root.querySelector('.tc-launcher'),+ headName: root.querySelector('.tc-head-name'),+ mute: root.querySelector('.tc-btn-mute'),+ swap: root.querySelector('.tc-btn-swap'),+ compact: root.querySelector('.tc-btn-compact'),+ close: root.querySelector('.tc-btn-close'),+ stage: root.querySelector('.tc-stage'),+ stageCanvas: root.querySelector('.tc-stage-canvas'),+ caption: root.querySelector('.tc-stage-caption'),+ thread: root.querySelector('.tc-thread'),+ textarea: root.querySelector('textarea'),+ mic: root.querySelector('.tc-mic'),+ send: root.querySelector('.tc-send'),+ picker: root.querySelector('.tc-picker'),+ pickerGrid: root.querySelector('.tc-picker-grid'),+ };++ this.$.headName.textContent = name;+ this._syncMuteButton();+ this._renderThread();++ // Wiring+ this.$.launcher.addEventListener('click', () => this.toggle());+ this.$.close.addEventListener('click', () => this.setOpen(false));+ this.$.mute.addEventListener('click', () => this.setMuted(!this.muted));+ this.$.swap?.addEventListener('click', () => this.togglePicker());+ this.$.compact.addEventListener('click', () => this._toggleCompact());+ this.$.send.addEventListener('click', () => this._submit());+ this.$.textarea.addEventListener('input', () => this._syncInput());+ this.$.textarea.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' && !e.shiftKey) {+ e.preventDefault();+ this._submit();+ }+ });+ this._onKeydown = (e) => {+ if (e.key === 'Escape' && this.open) {+ if (!this.$.picker.hidden) this.togglePicker(false);+ else this.setOpen(false);+ }+ };+ root.addEventListener('keydown', this._onKeydown);++ if (this.$.mic) {+ this._mic = createMic({+ lang: this.config.lang || undefined,+ onInterim: (t) => {+ this.$.textarea.value = t;+ this._syncInput();+ },+ onState: (s) => {+ this.$.mic.classList.toggle('is-live', s === 'listening');+ this.$.mic.setAttribute('aria-pressed', s === 'listening' ? 'true' : 'false');+ },+ onError: (err) => this._emit('error', err),+ });+ this.$.mic.addEventListener('click', () => this._toggleMic());+ }++ if (this.config.theme === 'auto' && window.matchMedia) {+ this._mq = window.matchMedia('(prefers-color-scheme: dark)');+ this._onScheme = () => this._applyTheme(root);+ this._mq.addEventListener?.('change', this._onScheme);+ }+ }++ _applyTheme(root) {+ const theme =+ this.config.theme !== 'auto'+ ? this.config.theme+ : window.matchMedia?.('(prefers-color-scheme: dark)').matches+ ? 'dark'+ : 'light';+ root.setAttribute('data-tc-theme', theme);+ }++ // ── Open / close ──────────────────────────────────────────────────────────+ setOpen(open) {+ if (this._destroyed || open === this.open) return;+ this.open = open;+ this.root.classList.toggle('is-open', open);+ this.$.launcher.setAttribute('aria-expanded', String(open));+ this.$.launcher.setAttribute('aria-label', open ? 'Close site assistant' : 'Open site assistant');+ if (open) {+ this._killTeaser();+ this.$.panel.hidden = false;+ requestAnimationFrame(() => this.root.classList.add('is-open'));+ this._ensureStage();+ this.$.textarea.focus({ preventScroll: true });+ this._scrollThread(false);+ } else {+ this._narrator?.cancel();+ this._mic?.stop();+ // Let the close transition play before hiding.+ const panel = this.$.panel;+ setTimeout(() => {+ if (!this.open) panel.hidden = true;+ }, 240);+ this.$.launcher.focus({ preventScroll: true });+ }+ this._emit(open ? 'open' : 'close', {});+ }+ toggle() {+ this.setOpen(!this.open);+ }++ _toggleCompact() {+ const compact = this.root.classList.toggle('is-compact');+ this.$.compact.setAttribute('aria-pressed', String(compact));+ }++ // ── Teaser ────────────────────────────────────────────────────────────────+ _scheduleTeaser() {+ if (storageGet('sessionStorage', SS_TEASED) === '1' || this.messages.length) return;+ this._teaserTimer = setTimeout(() => {+ if (this.open || this._destroyed) return;+ storageSet('sessionStorage', SS_TEASED, '1');+ const teaser = document.createElement('div');+ teaser.className = 'tc-teaser';+ teaser.setAttribute('role', 'status');+ teaser.innerHTML = `<span></span><button type="button" class="tc-teaser-close" aria-label="Dismiss">${ICONS.close}</button>`;+ teaser.querySelector('span').textContent = this._greetingText();+ this.root.insertBefore(teaser, this.$.launcher);+ requestAnimationFrame(() => teaser.classList.add('is-in'));+ teaser.addEventListener('click', (e) => {+ if (e.target.closest('.tc-teaser-close')) teaser.remove();+ else {+ teaser.remove();+ this.setOpen(true);+ }+ });+ this._teaser = teaser;+ this._teaserHide = setTimeout(() => this._killTeaser(), 12000);+ }, 6000);+ }+ _killTeaser() {+ clearTimeout(this._teaserTimer);+ clearTimeout(this._teaserHide);+ this._teaser?.remove();+ this._teaser = null;+ }++ _greetingText() {+ if (this.config.greeting) return this.config.greeting;+ const site = this.config.siteName || document.querySelector('meta[property="og:site_name"]')?.content || '';+ return site ? `Hi! Ask me anything about ${site}.` : 'Hi! Ask me anything about this site.';+ }++ // ── 3D stage (lazy) ───────────────────────────────────────────────────────+ async _ensureStage() {+ if (this._stage || this._stageLoading) return;+ this._stageLoading = true;+ try {+ this._stage = new AvatarStage(this.$.stageCanvas, { background: 'transparent' });+ this._narrator = new SpeechNarrator(this._stage, {+ muted: this.muted,+ onCaption: (text) => this._setCaption(text),+ onError: () => {+ /* voice is an enhancement — a TTS engine fault must stay silent */+ },+ });+ this._narrator.setAgent(this.avatar);+ await this._stage.load(avatarUrl(this.avatar, this.config.assetBase), {+ framing: this.avatar.framing || 'bust',+ });+ this.$.stage.classList.remove('is-loading');+ } catch (err) {+ // No WebGL / GLB unreachable: hide the stage, keep the chat fully alive.+ this.root.classList.add('is-compact');+ this.$.compact.style.display = 'none';+ this._emit('error', err instanceof Error ? err : new Error(String(err)));+ } finally {+ this._stageLoading = false;+ }+ }++ _setCaption(text) {+ const el = this.$.caption;+ if (!el) return;+ if (text) {+ el.textContent = text;+ el.classList.add('is-in');+ } else {+ el.classList.remove('is-in');+ }+ }++ // ── Avatar switching ──────────────────────────────────────────────────────+ async setAvatar(id) {+ const entry = getAvatarFrom(this.config.avatars, id);+ if (!entry || entry.id === this.avatar.id) return;+ this.avatar = entry;+ storageSet('localStorage', LS_AVATAR, entry.id);+ if (!this.config.name) this.$.headName.textContent = entry.name;+ this._narrator?.cancel();+ this._narrator?.setAgent(entry);+ this._renderPicker();+ this._emit('agentchange', { avatar: entry.id });+ if (this._stage) {+ this.$.stage.classList.add('is-loading');+ try {+ await this._stage.load(avatarUrl(entry, this.config.assetBase), { framing: entry.framing || 'bust' });+ } catch (err) {+ this._emit('error', err instanceof Error ? err : new Error(String(err)));+ }+ this.$.stage.classList.remove('is-loading');+ }+ }++ togglePicker(force) {+ const show = force !== undefined ? force : this.$.picker.hidden;+ if (show) {+ this._renderPicker();+ this.$.picker.hidden = false;+ requestAnimationFrame(() => this.$.picker.classList.add('is-in'));+ } else {+ this.$.picker.classList.remove('is-in');+ setTimeout(() => {+ this.$.picker.hidden = true;+ }, 200);+ }+ }++ _renderPicker() {+ const grid = this.$.pickerGrid;+ if (!grid) return;+ grid.textContent = '';+ for (const a of this.config.avatars) {+ const card = document.createElement('button');+ card.type = 'button';+ card.className = 'tc-picker-card' + (a.id === this.avatar.id ? ' is-current' : '');+ card.setAttribute('role', 'option');+ card.setAttribute('aria-selected', String(a.id === this.avatar.id));+ card.innerHTML = `<span class="tc-picker-name"></span><span class="tc-picker-tag"></span>`;+ card.querySelector('.tc-picker-name').textContent = a.name;+ card.querySelector('.tc-picker-tag').textContent = a.tagline;+ card.addEventListener('click', () => {+ this.setAvatar(a.id);+ this.togglePicker(false);+ });+ grid.appendChild(card);+ }+ }++ // ── Voice ─────────────────────────────────────────────────────────────────+ setMuted(muted) {+ this.muted = !!muted;+ storageSet('localStorage', LS_MUTED, muted ? '1' : '0');+ this._narrator?.setMuted(this.muted);+ this._syncMuteButton();+ }+ _syncMuteButton() {+ const btn = this.$?.mute;+ if (!btn) return;+ btn.innerHTML = this.muted ? ICONS.soundOff : ICONS.sound;+ btn.setAttribute('aria-pressed', String(this.muted));+ btn.setAttribute('aria-label', this.muted ? 'Unmute voice' : 'Mute voice');+ }++ async _toggleMic() {+ if (!this._mic) return;+ if (this._mic.listening) {+ this._mic.stop();+ return;+ }+ this._narrator?.cancel();+ const transcript = await this._mic.start();+ if (transcript) {+ this.$.textarea.value = transcript;+ this._syncInput();+ this._submit();+ }+ }++ // ── Thread rendering ──────────────────────────────────────────────────────+ _restoreThread() {+ try {+ const raw = storageGet('sessionStorage', SS_THREAD);+ const arr = raw ? JSON.parse(raw) : [];+ return Array.isArray(arr)+ ? arr.filter((m) => m && (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string')+ : [];+ } catch {+ return [];+ }+ }+ _persistThread() {+ storageSet('sessionStorage', SS_THREAD, JSON.stringify(this.messages.slice(-MAX_HISTORY_TURNS * 2)));+ }++ _renderThread() {+ const thread = this.$.thread;+ thread.textContent = '';+ if (!this.messages.length) {+ const empty = document.createElement('div');+ empty.className = 'tc-empty';+ const title = document.createElement('p');+ title.className = 'tc-empty-title';+ title.textContent = this._greetingText();+ empty.appendChild(title);+ const suggestions = this.config.suggestions.length+ ? this.config.suggestions+ : defaultSuggestions(this.config.siteName);+ if (suggestions.length) {+ const chips = document.createElement('div');+ chips.className = 'tc-chips';+ for (const s of suggestions.slice(0, 4)) {+ const chip = document.createElement('button');+ chip.type = 'button';+ chip.className = 'tc-chip';+ chip.textContent = s;+ chip.addEventListener('click', () => this.ask(s));+ chips.appendChild(chip);+ }+ empty.appendChild(chips);+ }+ thread.appendChild(empty);+ return;+ }+ for (const m of this.messages) thread.appendChild(this._bubble(m.role, m.content));+ this._scrollThread(false);+ }++ _bubble(role, content, { error = false } = {}) {+ const el = document.createElement('div');+ el.className = `tc-msg is-${role === 'user' ? 'user' : 'bot'}${error ? ' is-error' : ''}`;+ if (role === 'user') el.textContent = content;+ else el.innerHTML = renderMarkdown(content);+ return el;+ }++ _scrollThread(smooth = true) {+ const t = this.$.thread;+ t.scrollTo({ top: t.scrollHeight, behavior: smooth && !matchMedia('(prefers-reduced-motion: reduce)').matches ? 'smooth' : 'auto' });+ }++ _syncInput() {+ const ta = this.$.textarea;+ ta.style.height = 'auto';+ ta.style.height = Math.min(ta.scrollHeight, 110) + 'px';+ this.$.send.disabled = this.busy || !ta.value.trim();+ }++ // ── Ask flow ──────────────────────────────────────────────────────────────+ _submit() {+ const text = this.$.textarea.value.trim();+ if (!text || this.busy) return;+ this.$.textarea.value = '';+ this._syncInput();+ this.ask(text);+ }++ /**+ * Ask the concierge a question programmatically. Renders the exchange in the+ * panel, streams the answer, speaks it, persists the thread.+ * @returns {Promise<string>} the full answer text ('' on failure)+ */+ async ask(text) {+ const question = String(text || '').trim();+ if (!question || this.busy || this._destroyed) return '';+ this.setOpen(true);+ this._narrator?.cancel();++ if (!this.messages.length) this.$.thread.textContent = '';+ this.messages.push({ role: 'user', content: question });+ this.$.thread.appendChild(this._bubble('user', question));+ this._persistThread();+ this._emit('message', { role: 'user', content: question });+ this._scrollThread();++ this.busy = true;+ this.$.send.disabled = true;++ const typing = document.createElement('div');+ typing.className = 'tc-typing';+ typing.setAttribute('aria-label', 'Assistant is thinking');+ typing.innerHTML = '<i></i><i></i><i></i>';+ this.$.thread.appendChild(typing);+ this._scrollThread();++ const streamEl = document.createElement('div');+ streamEl.className = 'tc-msg is-bot';+ let streamed = '';+ let spoken = ''; // buffer of not-yet-spoken text+ let started = false;++ this._abort = new AbortController();+ let answer = '';+ try {+ const result = await askConcierge({+ endpoint: this.config.endpoint,+ message: question,+ history: this.messages.slice(0, -1),+ site: buildSitePayload(document, {+ knowledge: this.config.knowledge,+ siteName: this.config.siteName,+ }),+ persona: this.config.persona || undefined,+ lang: this.config.lang || undefined,+ signal: this._abort.signal,+ onChunk: (chunk) => {+ if (!started) {+ started = true;+ typing.remove();+ this.$.thread.appendChild(streamEl);+ }+ streamed += chunk;+ streamEl.innerHTML = renderMarkdown(streamed) + '<span class="tc-caret" aria-hidden="true"></span>';+ this._scrollThread();+ // Speak completed sentences while the rest still streams.+ spoken += chunk;+ const { sentences, rest } = drainSentences(spoken);+ spoken = rest;+ for (const s of sentences) {+ const speakable = stripMarkdown(s);+ if (speakable) this._narrator?.speak(speakable);+ }+ },+ });+ answer = result.text.trim();+ const tail = stripMarkdown(spoken);+ if (tail) this._narrator?.speak(tail);++ typing.remove();+ if (!answer) {+ streamEl.remove();+ this._renderErrorBubble(question, 'I could not come up with an answer just now.');+ } else {+ if (!started) this.$.thread.appendChild(streamEl);+ streamEl.innerHTML = renderMarkdown(answer);+ this.messages.push({ role: 'assistant', content: answer });+ this._persistThread();+ this._emit('message', { role: 'assistant', content: answer });+ }+ } catch (err) {+ typing.remove();+ streamEl.remove();+ if (err?.name !== 'AbortError') {+ const friendly =+ err?.status === 429+ ? 'I am getting a lot of questions right now — give me a few seconds and try again.'+ : 'Something went wrong reaching my brain. Check your connection and try again.';+ this._renderErrorBubble(question, friendly);+ this._emit('error', err instanceof Error ? err : new Error(String(err)));+ }+ } finally {+ this.busy = false;+ this._abort = null;+ this._syncInput();+ this._scrollThread();+ this.$.textarea.focus({ preventScroll: true });+ }+ return answer;+ }++ _renderErrorBubble(question, message) {+ const errEl = this._bubble('assistant', message, { error: true });+ this.$.thread.appendChild(errEl);+ const retry = document.createElement('button');+ retry.type = 'button';+ retry.className = 'tc-retry';+ retry.textContent = 'Try again';+ retry.addEventListener('click', () => {+ // Rewind the failed exchange (state + DOM) so the retry doesn't double it.+ retry.remove();+ errEl.remove();+ if (this.messages[this.messages.length - 1]?.role === 'user') {+ this.messages.pop();+ this._persistThread();+ const bubbles = this.$.thread.querySelectorAll('.tc-msg.is-user');+ bubbles[bubbles.length - 1]?.remove();+ }+ this.ask(question);+ });+ this.$.thread.appendChild(retry);+ }++ /** Clear the conversation (UI + persistence). */+ reset() {+ this._abort?.abort();+ this._narrator?.cancel();+ this.messages = [];+ this._persistThread();+ this._renderThread();+ }++ dispose() {+ if (this._destroyed) return;+ this._destroyed = true;+ this._abort?.abort();+ this._killTeaser();+ this._mq?.removeEventListener?.('change', this._onScheme);+ this._mic?.dispose();+ this._narrator?.dispose();+ this._stage?.dispose();+ this.root?.remove();+ this._listeners.clear();+ }+}++function getAvatarFrom(list, id) {+ return list.find((a) => a.id === id) || list.find((a) => a.id === DEFAULT_AVATAR_ID) || list[0] || getAvatar(id);+}++function defaultSuggestions(siteName) {+ const site = siteName || 'this site';+ return [`What is ${site}?`, 'How do I get started?', 'What does it cost?'];+}diff --git a/concierge-sdk/test/catalog.test.js b/concierge-sdk/test/catalog.test.jsnew file mode 100644index 000000000..44c64fc6f--- /dev/null+++ b/concierge-sdk/test/catalog.test.js@@ -0,0 +1,54 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import {+ AVATARS,+ DEFAULT_AVATAR_ID,+ DEFAULT_ASSET_BASE,+ getAvatar,+ avatarUrl,+ customAvatarEntry,+} from '../src/catalog.js';++test('catalog entries are complete and rig-capable', () => {+ assert.ok(AVATARS.length >= 5);+ for (const a of AVATARS) {+ assert.ok(a.id && a.name && a.tagline, `${a.id}: identity fields`);+ assert.ok(a.file || a.url, `${a.id}: needs a GLB source`);+ assert.ok(['viseme', 'jaw', 'animation'].includes(a.lipsync), `${a.id}: lipsync mode`);+ assert.ok(['bust', 'upper', 'full'].includes(a.framing), `${a.id}: framing`);+ assert.ok(a.voice && typeof a.voice === 'object', `${a.id}: voice profile`);+ assert.match(a.accent, /^#[0-9a-f]{6}$/i, `${a.id}: accent color`);+ }+});++test('ids are unique and the default exists', () => {+ const ids = AVATARS.map((a) => a.id);+ assert.equal(new Set(ids).size, ids.length);+ assert.ok(ids.includes(DEFAULT_AVATAR_ID));+});++test('getAvatar falls back to the default on unknown ids', () => {+ assert.equal(getAvatar('does-not-exist').id, DEFAULT_AVATAR_ID);+ assert.equal(getAvatar('nova').id, 'nova');+ assert.equal(getAvatar(undefined).id, DEFAULT_AVATAR_ID);+});++test('avatarUrl resolves against the asset base, absolute url wins', () => {+ const sol = getAvatar('sol');+ assert.equal(avatarUrl(sol), DEFAULT_ASSET_BASE + sol.file);+ assert.equal(avatarUrl(sol, 'https://cdn.example.com/glb'), 'https://cdn.example.com/glb/' + sol.file);+ assert.equal(avatarUrl({ ...sol, url: 'https://x.test/a.glb' }), 'https://x.test/a.glb');+ assert.equal(avatarUrl(null), null);+});++test('customAvatarEntry normalizes a bare URL and a partial entry', () => {+ const fromUrl = customAvatarEntry('https://x.test/hero.glb');+ assert.equal(fromUrl.id, 'custom');+ assert.equal(fromUrl.url, 'https://x.test/hero.glb');+ assert.ok(fromUrl.voice);++ const fromEntry = customAvatarEntry({ url: 'https://x.test/b.glb', name: 'Hero' });+ assert.equal(fromEntry.id, 'custom');+ assert.equal(fromEntry.name, 'Hero');+ assert.equal(fromEntry.url, 'https://x.test/b.glb');+});diff --git a/concierge-sdk/test/client.test.js b/concierge-sdk/test/client.test.jsnew file mode 100644index 000000000..862ccc612--- /dev/null+++ b/concierge-sdk/test/client.test.js@@ -0,0 +1,52 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { parseSseEvent, createSseBuffer } from '../src/client.js';+import { drainSentences } from '../src/widget.js';++test('parseSseEvent: JSON in, object out; noise in, null out', () => {+ assert.deepEqual(parseSseEvent('{"type":"chunk","text":"hi"}'), { type: 'chunk', text: 'hi' });+ assert.equal(parseSseEvent('[DONE]'), null);+ assert.equal(parseSseEvent(''), null);+ assert.equal(parseSseEvent('not json'), null);+ assert.equal(parseSseEvent('42'), null);+});++test('createSseBuffer reassembles frames across arbitrary chunk splits', () => {+ const events = [];+ const buf = createSseBuffer((e) => events.push(e));+ const wire = 'data: {"type":"chunk","text":"Hel"}\n\ndata: {"type":"chunk","text":"lo"}\n\ndata: {"type":"done","provider":"groq"}\n\n';+ // Feed one byte at a time — worst-case network fragmentation.+ for (const ch of wire) buf.push(ch);+ assert.equal(events.length, 3);+ assert.equal(events[0].text, 'Hel');+ assert.equal(events[1].text, 'lo');+ assert.equal(events[2].type, 'done');+});++test('createSseBuffer ignores comments and keep-alives', () => {+ const events = [];+ const buf = createSseBuffer((e) => events.push(e));+ buf.push(': keep-alive\n\ndata: {"type":"chunk","text":"x"}\n\n');+ assert.equal(events.length, 1);+ assert.equal(events[0].text, 'x');+});++test('drainSentences emits complete sentences, holds the tail', () => {+ const r1 = drainSentences('Hello there. How are');+ assert.deepEqual(r1.sentences, ['Hello there.']);+ assert.equal(r1.rest, 'How are');++ const r2 = drainSentences(r1.rest + ' you today? Fine!');+ assert.deepEqual(r2.sentences, ['How are you today?', 'Fine!']);+ assert.equal(r2.rest, '');++ const r3 = drainSentences('no terminator yet');+ assert.deepEqual(r3.sentences, []);+ assert.equal(r3.rest, 'no terminator yet');+});++test('drainSentences treats newlines as sentence breaks', () => {+ const r = drainSentences('First line\nSecond');+ assert.deepEqual(r.sentences, ['First line']);+ assert.equal(r.rest, 'Second');+});diff --git a/concierge-sdk/test/context.test.js b/concierge-sdk/test/context.test.jsnew file mode 100644index 000000000..0fecd316c--- /dev/null+++ b/concierge-sdk/test/context.test.js@@ -0,0 +1,65 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { JSDOM } from 'jsdom';+import { harvestSiteContext, buildSitePayload, MAX_CONTENT_CHARS } from '../src/context.js';++const PAGE = `<!doctype html><html><head>+ <title>Acme — Rocket Skates</title>+ <meta name="description" content="Acme sells rocket skates to discerning coyotes.">+ <meta property="og:site_name" content="Acme">+</head><body>+ <header><nav><a href="/">Home</a><a href="/pricing">Pricing</a><a href="/pricing">Pricing</a></nav></header>+ <main>+ <h1>Rocket Skates</h1>+ <h2>Fast. Very fast.</h2>+ <p>Our skates reach 300 mph in under two seconds.</p>+ <script>window.secret = 'never-harvest-this';</script>+ <div aria-hidden="true">decorative noise</div>+ <div data-three-concierge><p>widget text must not feed back</p></div>+ </main>+</body></html>`;++function doc() {+ return new JSDOM(PAGE).window.document;+}++test('harvests title, description, headings, deduped nav, site name', () => {+ const ctx = harvestSiteContext(doc());+ assert.equal(ctx.title, 'Acme — Rocket Skates');+ assert.match(ctx.description, /rocket skates/i);+ assert.deepEqual(ctx.headings, ['Rocket Skates', 'Fast. Very fast.']);+ assert.deepEqual(ctx.nav, ['Home', 'Pricing']);+ assert.equal(ctx.name, 'Acme');+});++test('content excludes scripts, hidden nodes, and the widget itself', () => {+ const ctx = harvestSiteContext(doc());+ assert.match(ctx.content, /300 mph/);+ assert.ok(!ctx.content.includes('never-harvest-this'));+ assert.ok(!ctx.content.includes('decorative noise'));+ assert.ok(!ctx.content.includes('widget text'));+});++test('content is capped at the budget', () => {+ const d = doc();+ d.querySelector('main p').textContent = 'x'.repeat(MAX_CONTENT_CHARS * 2);+ const ctx = harvestSiteContext(d);+ assert.ok(ctx.content.length <= MAX_CONTENT_CHARS);+});++test('buildSitePayload lets curated knowledge lead and shrinks page content', () => {+ const knowledge = 'k'.repeat(MAX_CONTENT_CHARS);+ const payload = buildSitePayload(doc(), { knowledge });+ assert.equal(payload.knowledge.length, MAX_CONTENT_CHARS);+ assert.equal(payload.content, '');++ const light = buildSitePayload(doc(), { knowledge: 'Returns accepted within 30 days.' });+ assert.match(light.knowledge, /30 days/);+ assert.match(light.content, /300 mph/);+});++test('null document degrades to an empty snapshot', () => {+ const ctx = harvestSiteContext(null);+ assert.equal(ctx.title, '');+ assert.deepEqual(ctx.headings, []);+});diff --git a/concierge-sdk/test/markdown.test.js b/concierge-sdk/test/markdown.test.jsnew file mode 100644index 000000000..a00ee177e--- /dev/null+++ b/concierge-sdk/test/markdown.test.js@@ -0,0 +1,52 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { renderMarkdown, stripMarkdown, escapeHtml } from '../src/markdown.js';++test('escapes raw HTML — no injection from model output', () => {+ const html = renderMarkdown('<img src=x onerror=alert(1)> & <b>bold</b>');+ assert.ok(!html.includes('<img'));+ assert.ok(html.includes('<img'));+ assert.ok(html.includes('&'));+});++test('renders paragraphs, bold, italic, code', () => {+ const html = renderMarkdown('Hello **world**, try `npm i` and *relax*.\n\nSecond para.');+ assert.ok(html.includes('<strong>world</strong>'));+ assert.ok(html.includes('<code>npm i</code>'));+ assert.ok(html.includes('<em>relax</em>'));+ assert.equal((html.match(/<p>/g) || []).length, 2);+});++test('renders bullet and numbered lists', () => {+ const html = renderMarkdown('- one\n- two\n\n1. first\n2. second');+ assert.ok(html.includes('<ul><li>one</li><li>two</li></ul>'));+ assert.ok(html.includes('<ol><li>first</li><li>second</li></ol>'));+});++test('renders fenced code blocks with escaping', () => {+ const html = renderMarkdown('```\nconst a = "<script>";\n```');+ assert.ok(html.includes('<pre><code>'));+ assert.ok(html.includes('<script>'));+ assert.ok(!html.includes('<script>'));+});++test('links: http(s)/mailto/relative allowed, javascript: stripped', () => {+ const ok = renderMarkdown('[docs](https://three.ws/docs)');+ assert.ok(ok.includes('href="https://three.ws/docs"'));+ assert.ok(ok.includes('rel="noopener noreferrer"'));+ const rel = renderMarkdown('[here](/pricing)');+ assert.ok(rel.includes('href="/pricing"'));+ const evil = renderMarkdown('[click](javascript:alert(1))');+ assert.ok(!evil.includes('href'));+ assert.ok(evil.includes('click'));+});++test('stripMarkdown yields speakable text', () => {+ assert.equal(stripMarkdown('**Bold** and `code` and [link](https://x.test)'), 'Bold and code and link');+ assert.equal(stripMarkdown('- item one\n- item two'), 'item one item two');+ assert.ok(stripMarkdown('```\nlet x=1\n```').includes('code sample'));+});++test('escapeHtml covers the special five', () => {+ assert.equal(escapeHtml(`&<>"'`), '&<>"'');+});diff --git a/concierge-sdk/types/index.d.ts b/concierge-sdk/types/index.d.tsnew file mode 100644index 000000000..431ac799a--- /dev/null+++ b/concierge-sdk/types/index.d.ts@@ -0,0 +1,188 @@+// Type definitions for @three-ws/concierge++export const VERSION: string;++export interface VoiceProfile {+ lang?: string;+ pitch?: number;+ rate?: number;+ match?: string[];+}++export interface ConciergeAvatar {+ id: string;+ name: string;+ tagline: string;+ file?: string;+ url?: string;+ lipsync: 'viseme' | 'jaw' | 'animation';+ framing: 'bust' | 'upper' | 'full';+ voice: VoiceProfile;+ accent: string;+}++export const AVATARS: ConciergeAvatar[];+export const DEFAULT_AVATAR_ID: string;+export const DEFAULT_ASSET_BASE: string;+export function getAvatar(id?: string): ConciergeAvatar;+export function avatarUrl(entry: ConciergeAvatar, assetBase?: string): string | null;+export function customAvatarEntry(urlOrEntry: string | Partial<ConciergeAvatar>): ConciergeAvatar;++export interface SitePayload {+ url: string;+ name: string;+ title: string;+ description: string;+ headings: string[];+ nav: string[];+ knowledge: string;+ content: string;+}++export const MAX_CONTENT_CHARS: number;+export const MAX_KNOWLEDGE_CHARS: number;+export function harvestSiteContext(+ doc: Document,+ opts?: { knowledge?: string; siteName?: string },+): Omit<SitePayload, 'knowledge'>;+export function buildSitePayload(+ doc: Document,+ opts?: { knowledge?: string; siteName?: string },+): SitePayload;++export interface ChatTurn {+ role: 'user' | 'assistant';+ content: string;+}++export const DEFAULT_ENDPOINT: string;+export const MAX_HISTORY_TURNS: number;+export function parseSseEvent(raw: string): Record<string, unknown> | null;+export function createSseBuffer(onEvent: (evt: Record<string, unknown>) => void): {+ push(text: string): void;+};+export function askConcierge(opts: {+ endpoint?: string;+ message: string;+ history?: ChatTurn[];+ site?: Partial<SitePayload>;+ persona?: string;+ lang?: string;+ signal?: AbortSignal;+ onChunk?: (text: string) => void;+}): Promise<{ text: string; provider?: string; model?: string }>;++export function renderMarkdown(text: string): string;+export function stripMarkdown(text: string): string;+export function escapeHtml(text: string): string;++export function micSupported(): boolean;+export function createMic(opts?: {+ lang?: string;+ onInterim?: (transcript: string) => void;+ onState?: (state: 'listening' | 'idle') => void;+ onError?: (err: Error) => void;+}): {+ supported: boolean;+ readonly listening: boolean;+ start(): Promise<string>;+ stop(): void;+ dispose(): void;+};++export interface ConciergeConfig {+ endpoint?: string;+ avatar?: string;+ avatars?: string[];+ customAvatar?: string | Partial<ConciergeAvatar>;+ assetBase?: string;+ name?: string;+ siteName?: string;+ greeting?: string;+ suggestions?: string[];+ knowledge?: string;+ persona?: string;+ accent?: string;+ position?: 'bottom-right' | 'bottom-left';+ theme?: 'auto' | 'dark' | 'light';+ open?: boolean;+ muted?: boolean;+ picker?: boolean;+ teaser?: boolean;+ zIndex?: number;+ lang?: string;+}++export type ConciergeEvent = 'ready' | 'open' | 'close' | 'message' | 'agentchange' | 'error';++export class Concierge {+ constructor(config?: ConciergeConfig);+ readonly open: boolean;+ readonly busy: boolean;+ readonly muted: boolean;+ avatar: ConciergeAvatar;+ messages: ChatTurn[];+ on(event: ConciergeEvent, fn: (detail: unknown) => void): () => void;+ setOpen(open: boolean): void;+ toggle(): void;+ ask(text: string): Promise<string>;+ setAvatar(id: string): Promise<void>;+ togglePicker(force?: boolean): void;+ setMuted(muted: boolean): void;+ reset(): void;+ dispose(): void;+}++export function drainSentences(buffer: string): { sentences: string[]; rest: string };++export class ThreeConciergeElement extends HTMLElement {+ ask(text: string): Promise<string> | undefined;+ open(): void;+ close(): void;+ reset(): void;+ setAvatar(id: string): Promise<void> | undefined;+ setMuted(muted: boolean): void;+ readonly controller: Concierge | null;+}+export function registerElement(tag?: string): string;++export function mount(config?: ConciergeConfig): Concierge;++export class AvatarStage {+ constructor(container: HTMLElement, opts?: { background?: string });+ load(url: string, opts?: { framing?: 'bust' | 'upper' | 'full' }): Promise<unknown>;+ setSpeaking(on: boolean): void;+ onFrame(fn: (dt: number, nowMs: number) => void): () => void;+ dispose(): void;+}++export class SpeechNarrator {+ constructor(+ stage: AvatarStage,+ opts?: {+ muted?: boolean;+ onState?: (s: 'idle' | 'speaking') => void;+ onCaption?: (text: string | null) => void;+ onError?: (e: Error) => void;+ },+ );+ setAgent(agent: { voice?: VoiceProfile } | null): void;+ setMuted(muted: boolean): void;+ speak(text: string, opts?: { interrupt?: boolean }): Promise<void>;+ cancel(): void;+ readonly speaking: boolean;+ dispose(): void;+}++export function buildMorphMap(root: unknown): { mode: 'arkit' | 'jaw'; map: Map<string, unknown[]> } | null;+export function createLipsync(+ text: string,+ morph: ReturnType<typeof buildMorphMap>,+ opts?: { rate?: number },+): { tick(nowMs: number): void; stop(): void; readonly done: boolean; readonly totalMs: number };+export function estimateDurationMs(text: string): number;++export const CSS: string;+export function ensureStyles(doc?: Document): void;++export default Concierge;diff --git a/data/changelog.json b/data/changelog.jsonindex 697e94da9..656d762fd 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$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-18",+ "title": "The x402-server SDK now attaches the payment receipt on every paid response",+ "summary": "Our most-installed npm package, @three-ws/x402-server (the seller side of x402), got a correctness pass. Paid endpoints built with it now guarantee the buyer never receives the result before the payment settles, and every paid response carries the on-chain settlement receipt in the X-PAYMENT-RESPONSE header, even for handlers that write their own response (the common Express case, which previously dropped the receipt). A new streaming mode settles up-front for file downloads and event streams, a handler that errors now returns a clean retryable 500 without charging, and the Base Sepolia test lane now advertises the correct testnet USDC. Ships with four runnable examples and a step-by-step tutorial you can follow offline before touching a wallet.",+ "tags": [+ "sdk",+ "fix"+ ],+ "link": "/tutorials/x402-server-sdk"+ },{"date": "2026-07-18","title": "The docs got a full accuracy pass against the live platform",diff --git a/docs/tutorials/x402-server-sdk.md b/docs/tutorials/x402-server-sdk.mdnew file mode 100644index 000000000..d1eaac36d--- /dev/null+++ b/docs/tutorials/x402-server-sdk.md@@ -0,0 +1,206 @@+# Meter Any API With x402 Using @three-ws/x402-server++By the end of this tutorial you will have taken an ordinary HTTP handler and made it **charge per call** — no API keys, no Stripe, no sign-up page. A caller hits your endpoint, gets a `402 Payment Required` with a machine-readable price, pays in USDC (or `$THREE`) on Solana or Base, and retries to get the work. You will run the whole loop on your own machine first, then wire it into a real server.++This is the **seller** half of [x402](/docs/x402). The package is [`@three-ws/x402-server`](https://www.npmjs.com/package/@three-ws/x402-server) — the same merchant primitives the three.ws rails run in production, extracted as a zero-dependency SDK.++**What you'll build:**++- A paid endpoint with one wrapper: `paid({ price, payTo }, handler)`+- The full 402 handshake: challenge → verify → run the work → settle → receipt+- Solana-first pricing (USDC, optionally `$THREE`), with Base as a second lane+- A local, offline run of the entire buyer↔seller loop — no accounts needed+- The two response modes: buffered JSON (default) and streamed downloads++**Prerequisites:**++- Node.js 18+ (uses global `fetch`).+- Nothing else to start — the first run is fully offline. To take *real* payments you'll later need a Solana pay-to address and a facilitator sponsor fee-payer; both are covered at the end.++---++## 1. Install++```bash+npm install @three-ws/x402-server+```++Framework-agnostic: it works as Express/Connect middleware, a Fastify hook, a Vercel function, or a bare Node `http` handler.++## 2. The mental model: verify → work → settle++Every paid call runs three steps, always in this order:++1. **Verify** the buyer's `X-PAYMENT` header against what you advertised. No work runs unless the payment checks out.+2. **Run the work** — your actual handler.+3. **Settle** on-chain, and return the result with an `X-PAYMENT-RESPONSE` receipt.++Settlement is *last*, so a handler that throws never charges. And the buyer never receives the good before settlement — the wrapper enforces that for you (details in step 6).++## 3. Run the whole loop offline++Before wiring a real facilitator, watch the handshake end-to-end on your machine. This uses a local stub facilitator that always approves — a learning harness, not production.++Save as `demo.mjs`:++```js+import http from 'node:http';+import { createX402Server } from '@three-ws/x402-server';++const NETWORK = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';++// A local stand-in for the settlement facilitator (always approves).+const facilitator = http.createServer((req, res) => {+ let raw = ''; req.on('data', c => raw += c); req.on('end', () => {+ const body = req.url === '/verify'+ ? { isValid: true, payer: 'BuyerWallet111' }+ : { success: true, transaction: 'LOCAL_TX', network: NETWORK, payer: 'BuyerWallet111' };+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify(body));+ });+});+const facUrl = await new Promise(r => facilitator.listen(0, () => r(`http://127.0.0.1:${facilitator.address().port}`)));++// The paid resource, pointed at the local facilitator.+const server = createX402Server({ facilitator: facUrl });+const app = http.createServer(server.paid(+ {+ price: '50000', // $0.05 USDC (6-decimal atomics)+ payTo: { solana: 'THREEsynthetic1111111111111111111111111PayTo' },+ feePayer: 'THREEsynthetic1111111111111111111111FeePayer',+ description: 'Premium data',+ },+ async (_req, _res, payment) => ({ good: 'the premium data', paidBy: payment.payer }),+));+const appUrl = await new Promise(r => app.listen(0, () => r(`http://127.0.0.1:${app.address().port}`)));++// Buyer, round 1: no payment → 402 challenge.+const challenge = await (await fetch(`${appUrl}/api/premium`)).json();+console.log('402 accepts:', challenge.accepts.map(a => `${a.extra.name} on ${a.network.split(':')[0]}`));++// Buyer, round 2: attach an X-PAYMENT header and retry.+const xPayment = Buffer.from(JSON.stringify({ x402Version: 2, network: NETWORK, payload: { transaction: 'signed' } })).toString('base64');+const paid = await fetch(`${appUrl}/api/premium`, { headers: { 'x-payment': xPayment } });+console.log('200 body:', await paid.json());+const receipt = JSON.parse(Buffer.from(paid.headers.get('x-payment-response'), 'base64').toString());+console.log('receipt tx:', receipt.transaction);++facilitator.close(); app.close();+```++```bash+node demo.mjs+```++```+402 accepts: [ 'USDC on solana' ]+200 body: { good: 'the premium data', paidBy: 'BuyerWallet111' }+receipt tx: LOCAL_TX+```++That is the entire protocol. The handler just **returned a value** — the wrapper serialized it as JSON, settled, and attached the receipt header.++> This exact demo ships runnable in the package: [`examples/loopback-demo.mjs`](https://github.com/nirholas/three.ws/blob/main/packages/x402-server/examples/loopback-demo.mjs).++## 4. Price it: atomic units, lanes, and $THREE++`price` is in **atomic units** of the asset. USDC is 6-decimal, so `'10000'` = `$0.01` and `'1000000'` = `$1.00`.++Advertise both lanes by giving both a `payTo`. Solana leads (first-accept clients settle there); pass `network: ['base']` to lead with EVM.++```js+paid(+ {+ price: '50000',+ payTo: {+ solana: '<your-SPL-pay-to>',+ base: '0x<your-EVM-pay-to>',+ },+ feePayer: '<facilitator-sponsor-account>', // required for the Solana accept+ acceptThree: true, // also advertise $THREE next to USDC on Solana+ threeAmount: '10000000', // optional distinct $THREE price; omit to reuse `price`+ },+ handler,+);+```++`acceptThree: true` adds a `$THREE` Solana accept right after USDC, so a wallet's token chooser surfaces both while a first-accept client still settles USDC. `$THREE` is Solana-only.++## 5. Take a platform fee (without marking up the buyer)++A fee is carved **out** of the listed price — the buyer's total is exactly `price`; the creator nets `price − fee`.++```js+paid(+ { price: '1000000', payTo, feePayer, feeBps: 250, feeTo: '<treasury>' }, // 2.5%+ handler,+);+```++On `$1.00`: buyer pays `$1.00`, creator nets `$0.975`, treasury gets `$0.025`. The fee is clamped to 10% (`feeBps ≤ 1000`), and ships **inert** — with `feeBps: 0` or no `feeTo`, nothing is charged. You can compute a split yourself with `feeSplit(price, bps, recipient)`.++## 6. Two response modes++The wrapper guarantees the buyer never gets the good before settlement. You choose how it does that:++**Deliver-then-settle (default).** Write your response normally or return a value. The wrapper *buffers* the output, settles, then flushes the `200` with the receipt header. Best for JSON APIs.++```js+app.post('/v1/embed', paid(+ { price: '2000', payTo, feePayer },+ async (req, res, payment) => {+ res.json({ vector: await embed(req.body.text), billedTo: payment.payer });+ },+));+```++**Settle-then-stream (`streaming: true`).** For responses you can't buffer — a large file, SSE, `res.pipe`. Settlement runs first, the receipt header is set up-front, then you stream:++```js+paid(+ { price: '100000', payTo, network: ['base'], streaming: true },+ async (_req, res) => {+ res.setHeader('content-type', 'text/csv');+ res.write('id,value\n');+ for (let i = 0; i < 5; i++) res.write(`${i},${i * 1.5}\n`);+ res.end();+ },+);+```++## 7. Handle the edge cases (the SDK already does)++`verifyPayment` returns a structured result instead of throwing on a bad payment, and `paid()` maps each state to the right status:++| Situation | HTTP | Safe to retry? |+|---|---|---|+| No/!invalid `X-PAYMENT` | 402 | Yes — pay and retry |+| Facilitator `/verify` down | 502 | Yes — **no funds moved** |+| Handler threw after payment | 500 | Yes — settlement was **skipped**, no charge |+| Settlement status unknown | 502 (`settle_uncertain`) | Check on-chain first |++The two invariants that make this safe: verification runs *before* your handler, settlement runs *after* it.++## 8. Go live++To take real payments, replace the local facilitator with a live one and use real accounts:++- **`payTo`** — your Solana SPL address and/or EVM address that receives funds.+- **`feePayer`** (Solana) — the facilitator's sponsor account that co-signs the SPL transfer so the buyer pays no SOL gas. The default facilitator is `https://facilitator.payai.network`; override with the `facilitator` option.+- Deploy the handler anywhere that serves HTTPS (buyers' clients refuse non-HTTPS). Any Node host works — Vercel, Fly, Railway, a VPS.++Test it with a real buyer using the seller's twin, [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch):++```js+import { withX402 } from '@three-ws/x402-fetch';+const pay = withX402(fetch, { wallet }); // wallet signs the on-chain payment+const res = await pay('https://your.api/v1/embed', { method: 'POST', body });+// The 402 is paid and retried transparently; `res` is the paid 200.+```++## Where to go next++- [x402 overview](/docs/x402) — the protocol, the lanes, the facilitators.+- [Build a paid x402 endpoint your agent calls](/tutorials/paid-x402-endpoint) — the CDP/Base-catalog path with Bazaar discovery.+- [x402 buyer client](/docs/x402-buyer) — the paying side in depth.+- Package examples: [`packages/x402-server/examples`](https://github.com/nirholas/three.ws/tree/main/packages/x402-server/examples).diff --git a/packages/x402-server/README.md b/packages/x402-server/README.mdindex 2c2136248..0c749302d 100644--- a/packages/x402-server/README.md+++ b/packages/x402-server/README.md@@ -195,11 +195,30 @@ function — mount it as Express/Connect middleware, a Vercel function, or a Nod| `maxTimeoutSeconds` | `number` | `60` | How long the buyer has to land the signed payment. || `description` | `string` | — | Human label for the `resource` in the challenge (shown in wallets/the modal). || `serviceName` / `tags` / `iconUrl` | `string` / `string[]` / `string` | — | Bazaar discovery metadata echoed into the challenge. |+| `streaming` | `boolean` | `false` | Response ordering. `false` = deliver-then-settle (buffer the response, settle, flush with the receipt header). `true` = settle-then-stream, for self-flushing handlers (binary download, SSE, `res.pipe`). Node adapter only. || `onSettled` | `(receipt) => void` | — | Fired after a successful settlement — record the call, fire a webhook. |**Handler** — `(req, res, payment) => unknown`. `payment` is present only on a-paid call: `{ payer, network, accept, amount }`. Throwing from the handler-returns its error to the buyer and **skips settlement** — no funds move.+paid call: `{ payer, network, accept, amount }`. Write your response+(`res.json(...)`) **or** just `return` a value — either way the wrapper holds+the bytes until settlement lands (see [Response modes](#response-modes)).+Throwing from the handler **skips settlement** (no funds move) and returns a+`500` the buyer can retry with the same payment.++### Response modes++`paid()` guarantees the buyer never receives the good before settlement, two ways:++- **Deliver-then-settle (default).** The handler's response is **buffered**, the+ payment settles, then the `200` is flushed with the `X-PAYMENT-RESPONSE`+ receipt header attached. Handlers may `res.json(...)`/`res.end(...)` or return+ a value. Best for JSON APIs.+- **Settle-then-stream (`streaming: true`).** For responses you can't buffer+ (large files, SSE, `res.pipe`): settlement runs first, the receipt header is+ set up-front, then the handler writes its own body — paid by construction.++This mirrors `api/_lib/x402-paid-endpoint.js` on the platform. Runnable examples+for both modes are in [`examples/`](./examples).### `buildChallenge(options) → Body`@@ -316,6 +335,12 @@ handler never charges). A `429` from your upstream can be retried with the## Examples+Runnable versions of everything below live in [`examples/`](./examples) — start+with [`examples/loopback-demo.mjs`](./examples/loopback-demo.mjs), which runs the+whole buyer↔seller loop offline against a local stub facilitator+(`node examples/loopback-demo.mjs`). A step-by-step walkthrough is in the+[x402-server SDK tutorial](https://three.ws/tutorials/x402-server-sdk).+**Express — meter an existing API**```jsdiff --git a/packages/x402-server/examples/README.md b/packages/x402-server/examples/README.mdnew file mode 100644index 000000000..e2c7d0096--- /dev/null+++ b/packages/x402-server/examples/README.md@@ -0,0 +1,41 @@+# Examples — @three-ws/x402-server++Runnable examples for the seller half of x402. Each is a standalone `.mjs` file.++| File | What it shows | Run |+|---|---|---|+| [`loopback-demo.mjs`](loopback-demo.mjs) | The **whole loop offline** — a paid server, a buyer, and a local stub facilitator. No accounts or network needed. Start here. | `node examples/loopback-demo.mjs` |+| [`express-metered-api.mjs`](express-metered-api.mjs) | Meter an existing Express route with `paid()` (deliver-then-settle). | `node examples/express-metered-api.mjs` |+| [`raw-primitives.mjs`](raw-primitives.mjs) | Drive `buildChallenge` / `verifyPayment` / `settlePayment` / `feeSplit` directly, no middleware. | `node examples/raw-primitives.mjs` |+| [`streaming-download.mjs`](streaming-download.mjs) | A paid binary/stream download with `streaming: true` (settle-then-stream). | `node examples/streaming-download.mjs` |++## The two response modes++`paid()` guarantees the buyer never receives the good before settlement. It does+that two ways, and you pick per route:++- **Deliver-then-settle (default).** Your handler writes its response normally+ (`res.json(...)`) or just `return`s a value. The wrapper **buffers** that+ output, settles the payment, then flushes the `200` with the+ `X-PAYMENT-RESPONSE` receipt header attached. Best for JSON APIs — see+ `express-metered-api.mjs`.+- **Settle-then-stream (`streaming: true`).** For responses you can't buffer (a+ large file, SSE, `res.pipe`). Settlement runs first, the receipt header is set+ up-front, then your handler streams the body. See `streaming-download.mjs`.++Either way the order is **verify → work → settle**: a handler that throws never+charges (the failed-payment path returns `500` and skips settlement).++## Pairing with a buyer++A real buyer signs the on-chain payment. The offline demo fakes that with a stub+facilitator; against a live facilitator, use the buyer-side+[`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch) —+it pays any `402` these servers emit automatically:++```js+import { withX402 } from '@three-ws/x402-fetch';+const pay = withX402(fetch, { wallet }); // wallet signs the on-chain payment+const res = await pay('http://localhost:3000/v1/embed', { method: 'POST', body });+// The 402 is paid and retried transparently; `res` is the paid 200.+```diff --git a/packages/x402-server/examples/express-metered-api.mjs b/packages/x402-server/examples/express-metered-api.mjsnew file mode 100644index 000000000..dda13284d--- /dev/null+++ b/packages/x402-server/examples/express-metered-api.mjs@@ -0,0 +1,53 @@+// Meter an existing Express API with x402 — the one-liner path.+//+// Run: node examples/express-metered-api.mjs+// Then a buyer using @three-ws/x402-fetch calls /v1/embed with a plain fetch and+// the 402 is paid automatically. An unpaid curl shows the challenge:+//+// curl -i http://localhost:3000/v1/embed -X POST \+// -H 'content-type: application/json' -d '{"text":"hello"}'+// → HTTP/1.1 402 Payment Required (with a PAYMENT-REQUIRED header + accepts[])+//+// This points at the real platform facilitator. Swap payTo/feePayer for your own+// accounts (Solana needs a facilitator sponsor fee-payer; see the README).++import express from 'express';+import { paid } from '@three-ws/x402-server';++const app = express();+app.use(express.json());++// A synthetic pay-to + fee-payer so the example runs as-is. Replace with your+// own funded accounts before taking real payments.+const PAY_TO = { solana: 'THREEsynthetic1111111111111111111111111PayTo' };+const FEE_PAYER = 'THREEsynthetic1111111111111111111111FeePayer';++app.post(+ '/v1/embed',+ paid(+ {+ price: '2000', // $0.002 in 6-decimal USDC atomics+ asset: 'usdc',+ payTo: PAY_TO,+ feePayer: FEE_PAYER, // required for the Solana accept+ description: 'Text embedding',+ serviceName: 'Acme Embed',+ onSettled: (receipt) => console.log('settled:', receipt.transaction),+ },+ // Deliver-then-settle: write your response normally. The wrapper buffers+ // it, settles the payment, then flushes the 200 with the X-PAYMENT-RESPONSE+ // receipt attached — the buyer never gets the good before settlement.+ async (req, res, payment) => {+ const vector = await embed(req.body?.text ?? '');+ res.json({ vector, billedTo: payment.payer });+ },+ ),+);++app.listen(3000, () => console.log('paid embed API on http://localhost:3000/v1/embed'));++// Stand-in for your real model call. Replace with the actual work.+async function embed(text) {+ const seed = [...String(text)].reduce((a, c) => a + c.charCodeAt(0), 0);+ return Array.from({ length: 8 }, (_, i) => Number((Math.sin(seed + i) / 2 + 0.5).toFixed(4)));+}diff --git a/packages/x402-server/examples/loopback-demo.mjs b/packages/x402-server/examples/loopback-demo.mjsnew file mode 100644index 000000000..e9c5063e5--- /dev/null+++ b/packages/x402-server/examples/loopback-demo.mjs@@ -0,0 +1,88 @@+// End-to-end, offline: a paid server + a buyer, wired to a LOCAL stub+// facilitator so the whole 402 → verify → work → settle → receipt loop runs on+// your machine with no accounts, keys, or network. This is a learning harness+// (the package's own tests use the same local-facilitator technique), not a+// production setup — real deployments point `facilitator` at a live settlement+// service that moves real funds.+//+// Run: node examples/loopback-demo.mjs++import http from 'node:http';+import { createX402Server } from '@three-ws/x402-server';++const NETWORK = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';+const PAY_TO = 'THREEsynthetic1111111111111111111111111PayTo';+const FEE_PAYER = 'THREEsynthetic1111111111111111111111FeePayer';++// 1) A local stand-in for the settlement facilitator. It always approves; a real+// facilitator verifies the signed payment on-chain and settles it.+const facilitator = http.createServer((req, res) => {+ let raw = '';+ req.on('data', (c) => (raw += c));+ req.on('end', () => {+ const body =+ req.url === '/verify'+ ? { isValid: true, payer: 'BuyerWallet1111111111111111111111111111111' }+ : { success: true, transaction: 'LOCAL_TX_SIGNATURE', network: NETWORK, payer: 'BuyerWallet1111111111111111111111111111111' };+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify(body));+ });+});++// 2) The paid resource, pointed at the local facilitator.+async function main() {+ const facUrl = await listen(facilitator);+ const server = createX402Server({ facilitator: facUrl });++ const paidHandler = server.paid(+ {+ price: '50000', // $0.05 USDC+ asset: 'usdc',+ payTo: { solana: PAY_TO },+ feePayer: FEE_PAYER,+ description: 'Premium data',+ onSettled: (receipt) => console.log(' [server] settled tx:', receipt.transaction),+ },+ async (req, res, payment) => {+ console.log(' [server] work runs for payer:', payment.payer);+ res.json = (o) => { res.setHeader('content-type', 'application/json'); res.end(JSON.stringify(o)); };+ res.json({ good: 'the premium data', paidBy: payment.payer });+ },+ );++ const app = http.createServer(paidHandler);+ const appUrl = await listen(app);+ const resource = `${appUrl}/api/premium`;++ // 3) Buyer, round one: no payment → receives the 402 challenge.+ console.log('\n[buyer] GET with no payment…');+ const challengeRes = await fetch(resource);+ const challenge = await challengeRes.json();+ console.log(` [buyer] ${challengeRes.status} — accepts ${challenge.accepts.length} lane(s):`,+ challenge.accepts.map((a) => `${a.extra.name} on ${a.network.split(':')[0]}`).join(', '));++ // 4) Buyer, round two: attach an X-PAYMENT header and retry. (A real buyer+ // signs the on-chain payment here — e.g. via @three-ws/x402-fetch. We hand+ // the stub facilitator a placeholder payload.)+ const xPayment = Buffer.from(+ JSON.stringify({ x402Version: 2, network: NETWORK, payload: { transaction: 'signed-by-buyer-wallet' } }),+ ).toString('base64');++ console.log('\n[buyer] retrying with X-PAYMENT…');+ const paidRes = await fetch(resource, { headers: { 'x-payment': xPayment } });+ const good = await paidRes.json();+ const receipt = JSON.parse(Buffer.from(paidRes.headers.get('x-payment-response'), 'base64').toString());++ console.log(` [buyer] ${paidRes.status} — good:`, good);+ console.log(' [buyer] X-PAYMENT-RESPONSE receipt tx:', receipt.transaction);++ facilitator.close();+ app.close();+ console.log('\nDone. verify → work → settle → receipt, all local.');+}++function listen(srv) {+ return new Promise((resolve) => srv.listen(0, () => resolve(`http://127.0.0.1:${srv.address().port}`)));+}++main().catch((err) => { console.error(err); process.exit(1); });diff --git a/packages/x402-server/examples/raw-primitives.mjs b/packages/x402-server/examples/raw-primitives.mjsnew file mode 100644index 000000000..dca7ebfcb--- /dev/null+++ b/packages/x402-server/examples/raw-primitives.mjs@@ -0,0 +1,66 @@+// Drive the four primitives directly — no paid() middleware.+//+// Use this when you need full control of the request lifecycle (a custom+// framework, a queue worker, a non-HTTP transport). The order is load-bearing:+// verify → run the work → settle. Settlement is always last, so a handler that+// throws never charges.+//+// Run: node examples/raw-primitives.mjs (prints the challenge this route emits)++import {+ buildChallenge,+ verifyPayment,+ settlePayment,+ feeSplit,+} from '@three-ws/x402-server';++const PAY_TO = { solana: 'THREEsynthetic1111111111111111111111111PayTo' };+const FEE_PAYER = 'THREEsynthetic1111111111111111111111FeePayer';+const TREASURY = 'TREASURYsynthetic111111111111111111111Treasury';++// The exact 402 envelope this resource would emit on an unpaid request.+const challenge = buildChallenge({+ price: '50000', // $0.05 USDC+ asset: 'usdc',+ payTo: PAY_TO,+ feePayer: FEE_PAYER,+ feeBps: 250, // 2.5% platform fee, carved OUT of the price+ feeTo: TREASURY,+ resourceUrl: 'https://your.api/summarize',+ description: 'Document summarization',+});++console.log('402 challenge envelope:\n', JSON.stringify(challenge, null, 2));+console.log('\nfee split on this price:', feeSplit('50000', 250, TREASURY));++// The request handler you'd wire into your framework.+export async function handle(req, res) {+ const header = req.headers['x-payment'];++ // 1 — no payment yet → answer with the challenge (body + base64 header).+ if (!header) {+ res.statusCode = 402;+ res.setHeader('PAYMENT-REQUIRED', Buffer.from(JSON.stringify(challenge)).toString('base64'));+ res.setHeader('content-type', 'application/json');+ return res.end(JSON.stringify(challenge));+ }++ // 2 — verify against the same accepts we advertised. No work runs unless ok.+ const verified = await verifyPayment({ paymentHeader: header, requirements: challenge.accepts });+ if (!verified.ok) {+ res.statusCode = verified.status || 402;+ return res.end(JSON.stringify(verified.body));+ }++ // 3 — run the work, THEN settle. Never settle before the work succeeds.+ const summary = await summarize(req.body?.text ?? '');+ const receipt = await settlePayment({ verified });++ res.setHeader('X-PAYMENT-RESPONSE', Buffer.from(JSON.stringify(receipt)).toString('base64'));+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify({ summary, payer: verified.payer, tx: receipt.transaction }));+}++async function summarize(text) {+ return String(text).split(/\s+/).slice(0, 12).join(' ') + (text ? ' …' : '');+}diff --git a/packages/x402-server/examples/streaming-download.mjs b/packages/x402-server/examples/streaming-download.mjsnew file mode 100644index 000000000..825665977--- /dev/null+++ b/packages/x402-server/examples/streaming-download.mjs@@ -0,0 +1,39 @@+// A paid file download with streaming:true (settle-then-stream).+//+// Some responses can't be buffered — a large binary, an SSE stream, a res.pipe.+// For those, set `streaming: true`: the wrapper settles the payment FIRST, emits+// the X-PAYMENT-RESPONSE receipt header up-front, then hands you the raw response+// to write however you like. Your handler is paid by construction before the+// first byte ships.+//+// Run: node examples/streaming-download.mjs+// curl -i http://localhost:3001/download → 402 challenge+// (a paid retry streams the file with the receipt header already set)++import http from 'node:http';+import { paid } from '@three-ws/x402-server';++const PAY_TO = { base: '0x00000000000000000000000000000000DeaDBeef' };++const handler = paid(+ {+ price: '100000', // $0.10 USDC+ asset: 'usdc',+ payTo: PAY_TO,+ network: ['base'],+ streaming: true, // settle up-front, then stream the body+ description: 'Dataset export (CSV)',+ },+ async (_req, res) => {+ // The X-PAYMENT-RESPONSE header is already set — just stream.+ res.setHeader('content-type', 'text/csv');+ res.setHeader('content-disposition', 'attachment; filename="export.csv"');+ res.write('id,value\n');+ for (let i = 0; i < 5; i++) res.write(`${i},${(i * 1.5).toFixed(2)}\n`);+ res.end();+ },+);++http.createServer(handler).listen(3001, () =>+ console.log('paid streaming download on http://localhost:3001/download'),+);diff --git a/packages/x402-server/package.json b/packages/x402-server/package.jsonindex a4f0eb5f0..e678b0bcf 100644--- a/packages/x402-server/package.json+++ b/packages/x402-server/package.json@@ -1,6 +1,6 @@{"name": "@three-ws/x402-server",- "version": "0.1.0",+ "version": "0.1.2","description": "The merchant side of x402 — turn any HTTP endpoint into a paid one. Issue 402 challenges, price SKUs, verify and settle the X-PAYMENT header on Solana and Base, and take a platform fee. Advertise the two main assets — USDC and $THREE — in one challenge.","type": "module","main": "./src/index.js",@@ -16,6 +16,7 @@},"files": ["src",+ "examples","README.md","LICENSE"],diff --git a/packages/x402-server/src/index.d.ts b/packages/x402-server/src/index.d.tsindex 5ea1ffc41..073517dd3 100644--- a/packages/x402-server/src/index.d.ts+++ b/packages/x402-server/src/index.d.ts@@ -162,6 +162,10 @@ export interface PaidAdapter {challenge(ctx: any, body: unknown, args: any[], status?: number): any;dispatch(ctx: any, handler: Function, payment: Payment, args: any[]): Promise<{ __handled: boolean; value?: unknown }>;respond(ctx: any, dispatched: unknown, receipt: Receipt, args: any[]): any;+ /** Settle-then-stream entry point for `streaming: true` (node only). */+ stream?(ctx: any, handler: Function, payment: Payment, receipt: Receipt, args: any[]): any;+ /** Handle a handler throw AFTER a valid payment but before settlement. */+ fail(ctx: any, err: unknown, args: any[]): any;}export interface PaidOptions extends BuildChallengeOptions {@@ -169,6 +173,14 @@ export interface PaidOptions extends BuildChallengeOptions {facilitator?: string;/** Fired after a successful settlement — record the call, fire a webhook. */onSettled?: (receipt: Receipt) => void;+ /**+ * Response ordering. Default (false) is deliver-then-settle: run the work,+ * settle, then flush the response with the X-PAYMENT-RESPONSE receipt header.+ * The buyer never receives the good before settlement. Set `true` for+ * self-flushing handlers (binary download, SSE, res.pipe): settlement runs+ * first and the receipt header is emitted up-front. Node adapter only.+ */+ streaming?: boolean;/** Runtime adapter. Defaults to node (req,res); use `fetchAdapter` for fetch. */adapter?: PaidAdapter;}diff --git a/packages/x402-server/src/index.js b/packages/x402-server/src/index.jsindex ee517be5b..cd517d1d6 100644--- a/packages/x402-server/src/index.js+++ b/packages/x402-server/src/index.js@@ -45,6 +45,10 @@ export const MAX_FEE_BPS = 1000; // 10%const CANONICAL_USDC = {solana: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',base: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',+ // Circle's Base Sepolia testnet USDC — a distinct mint from Base mainnet.+ // Advertising the mainnet address on a testnet accept makes the facilitator+ // verify against a token the buyer never signed for.+ 'base-sepolia': '0x036CbD53842c5426634e7929541eC2318f3dCF7e',};// $THREE — the three.ws platform token, the second main x402 settlement asset@@ -263,13 +267,14 @@ function resolveAsset(asset, lane) {}return CANONICAL_THREE.solana;}- if (!asset || asset === 'usdc') return CANONICAL_USDC[lane === 'base-sepolia' ? 'base' : lane];+ if (!asset || asset === 'usdc') return CANONICAL_USDC[lane];if (typeof asset === 'string') return asset;if (typeof asset === 'object') {- const pinned = asset[lane] ?? asset[lane === 'base-sepolia' ? 'base' : lane];- return pinned || CANONICAL_USDC[lane === 'base-sepolia' ? 'base' : lane];+ // A pin can target the exact lane, or `base` can stand in for `base-sepolia`.+ const pinned = asset[lane] ?? (lane === 'base-sepolia' ? asset.base : undefined);+ return pinned || CANONICAL_USDC[lane];}- return CANONICAL_USDC[lane === 'base-sepolia' ? 'base' : lane];+ return CANONICAL_USDC[lane];}// Assemble the full v2 envelope. Accepts either a pre-built `accepts[]` (raw@@ -554,6 +559,14 @@ function buildPaidHandler({ buildChallenge, verifyPayment, settlePayment }, optstags,iconUrl,onSettled,+ // Response ordering. Default (false) is DELIVER-THEN-SETTLE: run the work,+ // settle, then flush the response with the X-PAYMENT-RESPONSE receipt+ // header attached — the buyer never receives the good before the payment+ // settles. Set `streaming: true` for handlers that must write their own+ // body (binary download, SSE, res.pipe): settlement runs FIRST and the+ // receipt header is emitted up-front, so a self-flushing handler is paid+ // by construction. Mirrors api/_lib/x402-paid-endpoint.js.+ streaming = false,adapter = nodeAdapter,} = opts;@@ -563,9 +576,19 @@ function buildPaidHandler({ buildChallenge, verifyPayment, settlePayment }, optsthrow new ThreeWsError('feeBps > 0 requires feeTo (the fee recipient) — no recipient, no fee.', { code: 'invalid_input' });}- // A route-scoped server when a custom facilitator is set; else the shared one.- const verify = facilitator ? createX402Server({ facilitator }).verifyPayment : verifyPayment;- const settle = facilitator ? createX402Server({ facilitator }).settlePayment : settlePayment;+ // One route-scoped server when a custom facilitator is set (reused for both+ // verify and settle); else the shared default client.+ const scoped = facilitator ? createX402Server({ facilitator }) : null;+ const verify = scoped ? scoped.verifyPayment : verifyPayment;+ const settle = scoped ? scoped.settlePayment : settlePayment;++ async function runSettle(verified) {+ const receipt = await settle({ verified });+ if (typeof onSettled === 'function') {+ try { onSettled(receipt); } catch { /* a webhook/log error must not unsettle a paid call */ }+ }+ return receipt;+ }return async function paidHandler(...args) {const ctx = adapter.read(...args);@@ -586,27 +609,47 @@ function buildPaidHandler({ buildChallenge, verifyPayment, settlePayment }, optsreturn adapter.challenge(ctx, verified.body || challengeBody, args, verified.status || 402);}- // 2 — dispatch the work. A throw here returns the error and SKIPS- // settlement — no funds move on a failed call.const payment = {payer: verified.payer,network: verified.network,amount: verified.amount,accept: verified.accept,};- const dispatched = await adapter.dispatch(ctx, handler, payment, args);- if (dispatched && dispatched.__handled) return dispatched.value;- // 3 — settle, AFTER the work succeeded. Settlement is the last step.- const receipt = await settle({ verified });- if (typeof onSettled === 'function') {- try { onSettled(receipt); } catch { /* a webhook/log error must not unsettle a paid call */ }+ // Streaming (settle-then-stream): settle up-front, emit the receipt header,+ // then let the handler own the response body. Requires an adapter that can+ // stream (node); other adapters fall back to deliver-then-settle.+ if (streaming && typeof adapter.stream === 'function') {+ const receipt = await runSettle(verified);+ return adapter.stream(ctx, handler, payment, receipt, args);}++ // 2 — dispatch the work. The adapter buffers any response the handler+ // writes so nothing reaches the buyer before settlement. A throw here+ // SKIPS settlement (no funds move on a failed call) and surfaces a 500.+ let dispatched;+ try {+ dispatched = await adapter.dispatch(ctx, handler, payment, args);+ } catch (err) {+ return adapter.fail(ctx, err, args);+ }+ if (dispatched && dispatched.__handled) return dispatched.value;++ // 3 — settle, AFTER the work succeeded. Settlement is the last step, and+ // the buffered response is flushed with the receipt header in respond().+ const receipt = await runSettle(verified);return adapter.respond(ctx, dispatched, receipt, args);};}-// Node / Express / Vercel adapter: `(req, res, next?)`.+// Node / Express / Vercel adapter: `(req, res)`.+//+// The buyer must never receive the good before settlement, and the 200 must+// carry the base64 X-PAYMENT-RESPONSE receipt. A handler that writes its own+// response (`res.json`/`res.send`/`res.end`) would flush both problems away, so+// dispatch() BUFFERS every write; respond() then settles, injects the receipt+// header, and flushes for real. Handlers may also just RETURN a value — the+// wrapper serialises it. Streaming handlers opt out via `streaming: true`.const nodeAdapter = {read(req, res) {return {@@ -627,27 +670,121 @@ const nodeAdapter = {res.end?.(JSON.stringify(body));return undefined;},- // Run the user's (req, res, payment) handler. If it writes the response- // itself (the common Express case), it returns nothing and we treat the call- // as handled after settling. We still settle by capturing completion via a- // res.end wrapper.+ // Run the (req, res, payment) handler with a buffered response so no bytes+ // reach the buyer until settlement. Captures the handler's return value too,+ // for handlers that return a value instead of writing.async dispatch(ctx, handler, payment) {- await handler(ctx.req, ctx.res, payment);- // The handler owns the response object; settlement headers are attached in- // respond() only when the response is still open. Express handlers that- // already ended the response get settled silently (receipt via onSettled).- return { __handled: false };+ ctx._buffer = bufferNodeResponse(ctx.res);+ const value = await handler(ctx.req, ctx.res, payment);+ return { __handled: false, value };},- respond(ctx, _dispatched, receipt) {+ respond(ctx, dispatched, receipt) {const { res } = ctx;- // Attach the receipt header if the response is still writable.- if (res && !res.writableEnded && typeof res.setHeader === 'function') {- try { res.setHeader('X-PAYMENT-RESPONSE', base64Encode(JSON.stringify(receipt))); } catch { /* headers already sent */ }+ const buffer = ctx._buffer;+ const receiptHeader = base64Encode(JSON.stringify(receipt));++ // Write-style handler (Express res.json/send/end): flush the buffered+ // response with the receipt header injected ahead of the real end().+ if (buffer && buffer.ended) {+ buffer.flush({ 'X-PAYMENT-RESPONSE': receiptHeader });+ return receipt;}++ // Return-value handler: the handler returned a value without writing.+ // Serialise it as JSON with the receipt header. Restore the real methods+ // first so our end() below actually flushes.+ if (buffer) buffer.restore();+ const value = dispatched?.value;+ const body = value === undefined ? { ok: true } : value;+ if (!res.statusCode || res.statusCode === 200) res.statusCode = 200;+ try { res.setHeader?.('content-type', 'application/json; charset=utf-8'); } catch { /* headers sent */ }+ try { res.setHeader?.('X-PAYMENT-RESPONSE', receiptHeader); } catch { /* headers sent */ }+ res.end?.(typeof body === 'string' ? body : JSON.stringify(body));return receipt;},+ // settle-then-stream: settlement already ran; attach the receipt header+ // up-front, then hand the raw response to the (self-flushing) handler.+ async stream(ctx, handler, payment, receipt) {+ const { res } = ctx;+ try { res.setHeader?.('X-PAYMENT-RESPONSE', base64Encode(JSON.stringify(receipt))); } catch { /* headers sent */ }+ await handler(ctx.req, ctx.res, payment);+ return receipt;+ },+ // The work threw AFTER a valid payment but BEFORE settlement — no funds+ // moved. Discard any buffered partial output and return a clean 500 so the+ // buyer can retry (their payment authorization is still spendable).+ fail(ctx, err) {+ const { res } = ctx;+ const buffer = ctx._buffer;+ if (buffer) buffer.restore();+ if (res && !res.writableEnded) {+ res.statusCode = err?.status && err.status >= 400 && err.status < 600 ? err.status : 500;+ try { res.setHeader?.('content-type', 'application/json; charset=utf-8'); } catch { /* headers sent */ }+ res.end?.(JSON.stringify({ error: err?.code || 'handler_error', message: err?.message || 'the paid work failed; payment was not settled' }));+ }+ return undefined;+ },};+// Wrap a Node ServerResponse so writes are captured instead of flushed. Returns+// a controller: `ended` reflects whether the handler called end(); `flush(extra)`+// restores the real methods, sets `extra` headers, and emits the buffered body;+// `restore()` puts the real methods back without flushing.+function bufferNodeResponse(res) {+ const orig = { write: res.write, end: res.end, writeHead: res.writeHead };+ const chunks = [];+ const state = { ended: false, pendingCb: null };++ res.write = function bufferedWrite(chunk, enc, cb) {+ if (chunk) chunks.push(toBuffer(chunk, typeof enc === 'string' ? enc : undefined));+ const done = typeof enc === 'function' ? enc : cb;+ if (typeof done === 'function') done();+ return true;+ };+ res.end = function bufferedEnd(chunk, enc, cb) {+ if (chunk && typeof chunk !== 'function') chunks.push(toBuffer(chunk, typeof enc === 'string' ? enc : undefined));+ state.ended = true;+ state.pendingCb = typeof chunk === 'function' ? chunk : typeof enc === 'function' ? enc : typeof cb === 'function' ? cb : null;+ return res;+ };+ // Capture an explicit status (and any header map) from writeHead without+ // sending it; headers flush together at real end().+ res.writeHead = function bufferedWriteHead(status, ...rest) {+ if (typeof status === 'number') res.statusCode = status;+ const headerMap = rest.find((r) => r && typeof r === 'object' && !Array.isArray(r));+ if (headerMap && typeof res.setHeader === 'function') {+ for (const [k, v] of Object.entries(headerMap)) { try { res.setHeader(k, v); } catch { /* ignore */ } }+ }+ return res;+ };++ function restore() {+ res.write = orig.write;+ res.end = orig.end;+ res.writeHead = orig.writeHead;+ }++ return {+ get ended() { return state.ended; },+ restore,+ flush(extraHeaders) {+ restore();+ if (extraHeaders && typeof res.setHeader === 'function') {+ for (const [k, v] of Object.entries(extraHeaders)) { try { res.setHeader(k, v); } catch { /* headers sent */ } }+ }+ const body = chunks.length ? Buffer.concat(chunks) : undefined;+ if (typeof orig.end === 'function') orig.end.call(res, body);+ if (state.pendingCb) { try { state.pendingCb(); } catch { /* callback error is not ours to own */ } }+ },+ };+}++function toBuffer(chunk, enc) {+ if (Buffer.isBuffer(chunk)) return chunk;+ if (chunk instanceof Uint8Array) return Buffer.from(chunk);+ return Buffer.from(String(chunk), enc || 'utf8');+}+// Fetch-style adapter: `(request) => Response`. The handler receives// `(request, payment)` and returns a `Response` (or a plain object → JSON).export const fetchAdapter = {@@ -681,6 +818,12 @@ export const fetchAdapter = {}return jsonResponse(value ?? { ok: true }, 200, headers);},+ // The work threw after a valid payment but before settlement — no funds+ // moved. Return a clean 500 so the buyer can retry.+ fail(_ctx, err) {+ const status = err?.status && err.status >= 400 && err.status < 600 ? err.status : 500;+ return jsonResponse({ error: err?.code || 'handler_error', message: err?.message || 'the paid work failed; payment was not settled' }, status);+ },};// ── small helpers ──────────────────────────────────────────────────────────diff --git a/packages/x402-server/test/x402-server.test.js b/packages/x402-server/test/x402-server.test.jsindex 6dcade319..1d61801a8 100644--- a/packages/x402-server/test/x402-server.test.js+++ b/packages/x402-server/test/x402-server.test.js@@ -42,6 +42,29 @@ function xPaymentHeader(payload) {return Buffer.from(JSON.stringify(payload)).toString('base64');}+// A Node ServerResponse double that records status, headers, and the flushed+// body — enough to assert the wrapper attaches X-PAYMENT-RESPONSE and buffers+// the handler's writes until after settlement. Header lookups are+// case-insensitive, like a real ServerResponse.+function mockRes() {+ const headers = {};+ const chunks = [];+ return {+ statusCode: 200,+ writableEnded: false,+ setHeader(k, v) { headers[String(k).toLowerCase()] = v; },+ getHeader(k) { return headers[String(k).toLowerCase()]; },+ write(chunk) { if (chunk) chunks.push(Buffer.from(chunk)); return true; },+ end(chunk) { if (chunk) chunks.push(Buffer.from(chunk)); this.writableEnded = true; return this; },+ get body() { return Buffer.concat(chunks).toString('utf8'); },+ get headers() { return headers; },+ };+}++function paidReq(header) {+ return { url: '/api/thing', headers: { host: 'three.ws', 'x-payment': header } };+}+test('buildChallenge() emits the exact v2 accepts[] envelope', () => {const challenge = buildChallenge({price: '50000',@@ -88,6 +111,18 @@ test('buildChallenge() advertises only the requested lane', () => {assert.equal(challenge.accepts[0].network, NETWORK_BASE_MAINNET);});+test('base-sepolia advertises the testnet USDC mint, not Base mainnet USDC', () => {+ const challenge = buildChallenge({+ price: '1000',+ payTo: { 'base-sepolia': SYNTH_BASE_PAYTO },+ network: ['base-sepolia'],+ });+ assert.equal(challenge.accepts.length, 1);+ // Circle's Base Sepolia USDC — distinct from Base mainnet's 0x8335… mint.+ assert.equal(challenge.accepts[0].asset, '0x036CbD53842c5426634e7929541eC2318f3dCF7e');+ assert.equal(challenge.accepts[0].extra.name, 'USD Coin');+});+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';test('acceptThree adds a $THREE Solana accept after USDC (both main assets)', () => {@@ -294,6 +329,109 @@ test('paid() verifies, runs the handler, then settles on a paid call', async ()assert.equal(settledReceipt.transaction, 'TX_PAID');});+test('paid() attaches the X-PAYMENT-RESPONSE receipt header to a write-style (Express) handler', async () => {+ const { fetch } = stubFetch([+ { body: { isValid: true, payer: SYNTH_BASE_PAYTO } },+ { body: { success: true, transaction: 'TX_RCPT', network: NETWORK_BASE_MAINNET, payer: SYNTH_BASE_PAYTO } },+ ]);+ const server = createX402Server({ fetch });+ const handler = server.paid(+ { price: '10000', payTo: { base: SYNTH_BASE_PAYTO }, network: ['base'] },+ // Express-style: the handler ends its own response. The good must NOT ship+ // before settlement, and the receipt header MUST be on the flushed 200.+ async (_req, res) => {+ res.statusCode = 201;+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify({ good: 'premium data' }));+ },+ );++ const header = xPaymentHeader({ network: NETWORK_BASE_MAINNET, payload: { authorization: { value: '10000' } } });+ const res = mockRes();+ await handler(paidReq(header), res);++ // The buffered response flushed with its own status + body preserved.+ assert.equal(res.statusCode, 201);+ assert.deepEqual(JSON.parse(res.body), { good: 'premium data' });+ // The settlement receipt rides the same 200 the buyer receives.+ const receiptHeader = res.getHeader('X-PAYMENT-RESPONSE');+ assert.ok(receiptHeader, 'X-PAYMENT-RESPONSE header is set on the response');+ const receipt = JSON.parse(Buffer.from(receiptHeader, 'base64').toString('utf8'));+ assert.equal(receipt.transaction, 'TX_RCPT');+ assert.equal(receipt.network, NETWORK_BASE_MAINNET);+});++test('paid() serialises a return-value handler with the receipt header', async () => {+ const { fetch } = stubFetch([+ { body: { isValid: true, payer: SYNTH_BASE_PAYTO } },+ { body: { success: true, transaction: 'TX_RET', network: NETWORK_BASE_MAINNET, payer: SYNTH_BASE_PAYTO } },+ ]);+ const server = createX402Server({ fetch });+ const handler = server.paid(+ { price: '10000', payTo: { base: SYNTH_BASE_PAYTO }, network: ['base'] },+ // Return-value style: no res.* calls, just return the good.+ async (_req, _res, payment) => ({ good: 'returned data', paidBy: payment.payer }),+ );++ const header = xPaymentHeader({ network: NETWORK_BASE_MAINNET, payload: { authorization: { value: '10000' } } });+ const res = mockRes();+ await handler(paidReq(header), res);++ assert.equal(res.statusCode, 200);+ assert.deepEqual(JSON.parse(res.body), { good: 'returned data', paidBy: SYNTH_BASE_PAYTO });+ assert.ok(res.getHeader('X-PAYMENT-RESPONSE'), 'return-value handlers still get the receipt header');+});++test('paid() with streaming:true settles BEFORE the handler writes, header up-front', async () => {+ const order = [];+ const { fetch, calls } = stubFetch([+ { body: { isValid: true, payer: SYNTH_BASE_PAYTO } },+ { body: { success: true, transaction: 'TX_STREAM', network: NETWORK_BASE_MAINNET, payer: SYNTH_BASE_PAYTO } },+ ]);+ const server = createX402Server({ fetch });+ const handler = server.paid(+ { price: '10000', payTo: { base: SYNTH_BASE_PAYTO }, network: ['base'], streaming: true },+ async (_req, res) => {+ // Header must already be present when a streaming handler starts writing.+ order.push('work');+ assert.ok(res.getHeader('X-PAYMENT-RESPONSE'), 'streaming handler sees the receipt header up-front');+ res.write('chunk-1;');+ res.end('chunk-2');+ },+ );++ const header = xPaymentHeader({ network: NETWORK_BASE_MAINNET, payload: { authorization: { value: '10000' } } });+ const res = mockRes();+ await handler(paidReq(header), res);++ // settle (calls[1]) ran before the work wrote its body.+ assert.equal(calls[1].url.pathname, '/settle');+ assert.deepEqual(order, ['work']);+ assert.equal(res.body, 'chunk-1;chunk-2');+});++test('paid() skips settlement and returns 500 when the handler throws (no funds move)', async () => {+ const { fetch, calls } = stubFetch([+ { body: { isValid: true, payer: SYNTH_BASE_PAYTO } },+ // No settle response queued — asserting settle is NEVER called.+ ]);+ const server = createX402Server({ fetch });+ const handler = server.paid(+ { price: '10000', payTo: { base: SYNTH_BASE_PAYTO }, network: ['base'] },+ async () => { throw new Error('work exploded'); },+ );++ const header = xPaymentHeader({ network: NETWORK_BASE_MAINNET, payload: { authorization: { value: '10000' } } });+ const res = mockRes();+ await handler(paidReq(header), res);++ assert.equal(calls.length, 1, 'only /verify ran — settlement was skipped on a failed handler');+ assert.equal(calls[0].url.pathname, '/verify');+ assert.equal(res.statusCode, 500);+ assert.ok(!res.getHeader('X-PAYMENT-RESPONSE'), 'no receipt on a failed, unsettled call');+ assert.equal(JSON.parse(res.body).error, 'handler_error');+});+test('paid() supports a fetch-style adapter (Request → Response)', async () => {const { fetch } = stubFetch([]);const server = createX402Server({ fetch });diff --git a/public/changelog.json b/public/changelog.jsonindex d4d677a8f..53d2cb71e 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-18T19:35:24.274Z",+ "generated_at": "2026-07-18T21:09:18.386Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -451,6 +451,17 @@"sdk"]},+ {+ "date": "2026-07-18",+ "type": "update",+ "title": "The x402-server SDK now attaches the payment receipt on every paid response",+ "summary": "Our most-installed npm package, @three-ws/x402-server (the seller side of x402), got a correctness pass. Paid endpoints built with it now guarantee the buyer never receives the result before the payment settles, and every paid response carries the on-chain settlement receipt in the X-PAYMENT-RESPONSE header, even for handlers that write their own response (the common Express case, which previously dropped the receipt). A new streaming mode settles up-front for file downloads and event streams, a handler that errors now returns a clean retryable 500 without charging, and the Base Sepolia test lane now advertises the correct testnet USDC. Ships with four runnable examples and a step-by-step tutorial you can follow offline before touching a wallet.",+ "link": "/tutorials/x402-server-sdk",+ "tags": [+ "sdk",+ "fix"+ ]+ },{"date": "2026-07-18","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex eef92e1a4..86c0b3b2a 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -358,6 +358,14 @@<category>docs</category><description>The free text-to-3D generation endpoint that powers the three.ws 3D Studio in ChatGPT now ships a published OpenAPI description at /.well-known/3d-studio-openapi.yaml. Any app, custom GPT, or agent can read it to discover how to generate a model from a prompt and poll for the result, with no account, no API key, and no payment. It documents only the free generation action and is kept automatically in sync with the version used by the 3D Studio custom GPT, so the two never drift.</description></item>+ <item>+ <title>The x402-server SDK now attaches the payment receipt on every paid response</title>+ <link>https://three.ws/tutorials/x402-server-sdk</link>+ <guid isPermaLink="false">2026-07-18:The x402-server SDK now attaches the payment receipt on every paid response</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>sdk</category>+ <description>Our most-installed npm package, @three-ws/x402-server (the seller side of x402), got a correctness pass. Paid endpoints built with it now guarantee the buyer never receives the result before the payment settles, and every paid response carries the on-chain settlement receipt in the X-PAYMENT-RESPONSE header, even for handlers that write their own response (the common Express case, which previously dropped the receipt). A new streaming mode settles up-front for file downloads and event streams, a handler that errors now returns a clean retryable 500 without charging, and the Base Sepolia test lane now advertises the correct testnet USDC. Ships with four runnable examples and a step-by-step tutorial you can follow offline before touching a wallet.</description>+ </item><item><title>Two new guides explain the Forge, inside and out</title><link>https://three.ws/docs/how-forge-works</link>diff --git a/public/features.json b/public/features.jsonindex 9bbc79b1c..ab74eb810 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-18T19:35:24.261Z",+ "generated_at": "2026-07-18T21:09:18.373Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/tutorials-manifest.js b/public/tutorials-manifest.jsindex 36b964a4e..5cf332444 100644--- a/public/tutorials-manifest.js+++ b/public/tutorials-manifest.js@@ -394,6 +394,16 @@previewModel: '/avatars/cz.glb',ctaPrimary: { label: 'See paid calls', href: '/pay/calls' },},+ {+ slug: 'x402-server-sdk',+ tier: 'advanced',+ title: 'Meter any API with the x402-server SDK',+ blurb: 'Turn an ordinary HTTP handler into a paid one with @three-ws/x402-server. Solana-first, framework-agnostic, and runnable offline before you touch a wallet.',+ builds: 'A paid endpoint charging USDC or $THREE, in a few lines',+ time: '30 min',+ previewModel: '/animations/soldier.glb',+ ctaPrimary: { label: 'Package on npm', href: 'https://www.npmjs.com/package/@three-ws/x402-server' },+ },{slug: 'nvidia-nim-self-host',tier: 'advanced',diff --git a/src/assistant-widget-core.js b/src/assistant-widget-core.jsnew file mode 100644index 000000000..898cdcc7e--- /dev/null+++ b/src/assistant-widget-core.js@@ -0,0 +1,169 @@+// Assistant widget — shared pure helpers.+//+// Used by the /assistant-frame runtime (src/assistant-frame.js) and the+// /assistant builder page (src/assistant-page.js). The loader+// (public/assistant/v1.js) is a standalone no-build IIFE, so it passes raw+// config through as URL params and THIS module is the authoritative validator:+// every param that ends up in CSS or a fetch URL goes through here first. A+// hostile host page can therefore never inject styles or URLs into the frame —+// anything that doesn't match the strict grammars below falls back to a safe+// default instead of being interpolated.++/** Widget interaction modes. 'both' shows the Chat|Speak segmented control. */+export const MODES = ['chat', 'speak', 'both'];++/** Launcher/panel screen positions. */+export const POSITIONS = ['right', 'left'];++/** Chat lanes: platform free chain, or the visitor's own key. */+export const LANES = ['free', 'groq', 'openrouter'];++export const DEFAULT_ACCENT = '#f97316';++/**+ * Named gradient presets — the "or a color / gradient" background option.+ * Angles in degrees. Colors are baked constants, so preset output never+ * contains caller-controlled text.+ */+export const GRADIENT_PRESETS = {+ ember: ['#1a0b05', '#7c2d12', 160],+ ocean: ['#020617', '#0c4a6e', 160],+ violet: ['#0f0518', '#5b21b6', 160],+ forest: ['#02120b', '#14532d', 160],+ dusk: ['#0b0714', '#9d174d', 200],+ slate: ['#09090b', '#27272a', 180],+};++const HEX_RE = /^#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i;++/** True when `raw` is a #rgb / #rrggbb / #rrggbbaa hex color. */+export function isHexColor(raw) {+ return typeof raw === 'string' && HEX_RE.test(raw.trim());+}++/**+ * Parse the `bg` param into a safe background descriptor.+ *+ * Grammar (anything else → transparent, never interpolated):+ * ''|'transparent' → { kind: 'transparent', css: null }+ * '#rrggbb' → { kind: 'solid', css: '#rrggbb' }+ * '<preset-name>' → { kind: 'gradient', css: 'linear-gradient(...)' }+ * 'gradient:#a,#b[,120]' → { kind: 'gradient', css: 'linear-gradient(120deg, #a, #b)' }+ *+ * @param {string|null|undefined} raw+ * @returns {{ kind: 'transparent'|'solid'|'gradient', css: string|null }}+ */+export function parseBackground(raw) {+ const value = String(raw ?? '').trim().toLowerCase();+ if (!value || value === 'transparent') return { kind: 'transparent', css: null };+ if (isHexColor(value)) return { kind: 'solid', css: value };+ if (GRADIENT_PRESETS[value]) {+ const [from, to, angle] = GRADIENT_PRESETS[value];+ return { kind: 'gradient', css: `linear-gradient(${angle}deg, ${from}, ${to})` };+ }+ if (value.startsWith('gradient:')) {+ const parts = value.slice('gradient:'.length).split(',').map((s) => s.trim());+ const [from, to, angleRaw] = parts;+ if (isHexColor(from) && isHexColor(to)) {+ const angle = clampAngle(angleRaw);+ return { kind: 'gradient', css: `linear-gradient(${angle}deg, ${from}, ${to})` };+ }+ }+ return { kind: 'transparent', css: null };+}++function clampAngle(raw) {+ const trimmed = String(raw ?? '').replace(/deg$/, '').trim();+ if (!trimmed) return 160;+ const n = Number(trimmed);+ if (!Number.isFinite(n)) return 160;+ return ((Math.round(n) % 360) + 360) % 360;+}++/** Normalize the interaction mode; unknown values → 'both'. */+export function normalizeMode(raw) {+ const value = String(raw ?? '').trim().toLowerCase();+ return MODES.includes(value) ? value : 'both';+}++/** Normalize launcher position; unknown values → 'right'. */+export function normalizePosition(raw) {+ const value = String(raw ?? '').trim().toLowerCase();+ return POSITIONS.includes(value) ? value : 'right';+}++/** Accent color for buttons/focus rings; only hex passes, else the default. */+export function sanitizeAccent(raw) {+ const value = String(raw ?? '').trim().toLowerCase();+ return isHexColor(value) ? value : DEFAULT_ACCENT;+}++/** Normalize the BYOK/free lane id; unknown values → 'free'. */+export function normalizeLane(raw) {+ const value = String(raw ?? '').trim().toLowerCase();+ return LANES.includes(value) ? value : 'free';+}++/**+ * Config keys the frame accepts, in the order the builder emits them.+ * Single source of truth for loader data-attrs, frame params, and docs.+ */+export const FRAME_PARAM_KEYS = [+ 'avatar',+ 'agent',+ 'bg',+ 'mode',+ 'accent',+ 'name',+ 'greeting',+ 'context',+ 'voice',+ 'badge',+ 'targetOrigin',+];++const TEXT_LIMITS = { name: 60, greeting: 200, context: 500 };++/**+ * Build the /assistant-frame query string from a config object. Unknown keys+ * are dropped; text fields are length-clamped so the URL stays shareable and+ * the frame never receives oversized payloads.+ *+ * @param {Record<string, string|boolean|undefined>} config+ * @returns {string} query string without the leading '?', '' when empty+ */+export function buildFrameQuery(config = {}) {+ const params = new URLSearchParams();+ for (const key of FRAME_PARAM_KEYS) {+ let value = config[key];+ if (value === undefined || value === null || value === '') continue;+ if (typeof value === 'boolean') value = value ? 'true' : 'false';+ value = String(value);+ if (TEXT_LIMITS[key]) value = value.slice(0, TEXT_LIMITS[key]);+ params.set(key, value);+ }+ return params.toString();+}++/**+ * Estimate how long spoken text stays audible — used to hold the bubble and+ * the talking animation when the platform has no TTS (or is muted). ~15 chars+ * per second of natural speech, floored so one-word lines don't blink away.+ */+export function estimateSpeechMs(text) {+ const len = String(text ?? '').trim().length;+ if (!len) return 0;+ return Math.max(1800, Math.round((len / 15) * 1000));+}++/** Default chat models per BYOK provider (OpenAI-compatible endpoints). */+export const BYOK_DEFAULT_MODELS = {+ groq: 'llama-3.3-70b-versatile',+ openrouter: 'meta-llama/llama-3.3-70b-instruct:free',+};++/** OpenAI-compatible chat-completions endpoints for BYOK lanes. */+export const BYOK_ENDPOINTS = {+ groq: 'https://api.groq.com/openai/v1/chat/completions',+ openrouter: 'https://openrouter.ai/api/v1/chat/completions',+};diff --git a/tests/assistant-widget.test.js b/tests/assistant-widget.test.jsnew file mode 100644index 000000000..6634aceda--- /dev/null+++ b/tests/assistant-widget.test.js@@ -0,0 +1,169 @@+// Assistant widget core helpers — the frame's authoritative param validator.+// Everything here guards CSS/URL injection from hostile host pages, so the+// hostile-input cases matter as much as the happy paths.++import { describe, it, expect } from 'vitest';+import {+ parseBackground,+ normalizeMode,+ normalizePosition,+ normalizeLane,+ sanitizeAccent,+ isHexColor,+ buildFrameQuery,+ estimateSpeechMs,+ GRADIENT_PRESETS,+ DEFAULT_ACCENT,+ BYOK_DEFAULT_MODELS,+ BYOK_ENDPOINTS,+ FRAME_PARAM_KEYS,+} from '../src/assistant-widget-core.js';++describe('parseBackground', () => {+ it('defaults to transparent for empty/missing values', () => {+ expect(parseBackground(undefined)).toEqual({ kind: 'transparent', css: null });+ expect(parseBackground('')).toEqual({ kind: 'transparent', css: null });+ expect(parseBackground('transparent')).toEqual({ kind: 'transparent', css: null });+ expect(parseBackground(' Transparent ')).toEqual({ kind: 'transparent', css: null });+ });++ it('accepts hex colors as solid backgrounds', () => {+ expect(parseBackground('#101820')).toEqual({ kind: 'solid', css: '#101820' });+ expect(parseBackground('#FFF')).toEqual({ kind: 'solid', css: '#fff' });+ expect(parseBackground('#11223344')).toEqual({ kind: 'solid', css: '#11223344' });+ });++ it('resolves every named gradient preset', () => {+ for (const [name, [from, to, angle]] of Object.entries(GRADIENT_PRESETS)) {+ expect(parseBackground(name)).toEqual({+ kind: 'gradient',+ css: `linear-gradient(${angle}deg, ${from}, ${to})`,+ });+ }+ });++ it('builds custom gradients from two hex stops and an optional angle', () => {+ expect(parseBackground('gradient:#0b0714,#9d174d')).toEqual({+ kind: 'gradient',+ css: 'linear-gradient(160deg, #0b0714, #9d174d)',+ });+ expect(parseBackground('gradient:#000,#fff,45')).toEqual({+ kind: 'gradient',+ css: 'linear-gradient(45deg, #000, #fff)',+ });+ expect(parseBackground('gradient:#000,#fff,45deg')).toEqual({+ kind: 'gradient',+ css: 'linear-gradient(45deg, #000, #fff)',+ });+ });++ it('normalizes out-of-range gradient angles', () => {+ expect(parseBackground('gradient:#000,#fff,-90').css).toContain('270deg');+ expect(parseBackground('gradient:#000,#fff,720').css).toContain('0deg');+ expect(parseBackground('gradient:#000,#fff,nonsense').css).toContain('160deg');+ });++ it('never interpolates hostile input into CSS', () => {+ const hostile = [+ 'url(javascript:alert(1))',+ 'red;}body{display:none',+ 'gradient:#000,url(x)',+ 'gradient:#000',+ 'gradient:red,blue',+ 'linear-gradient(#000,#fff)',+ '#12345', // wrong hex length+ 'rebeccapurple',+ ];+ for (const value of hostile) {+ expect(parseBackground(value)).toEqual({ kind: 'transparent', css: null });+ }+ });+});++describe('normalizers', () => {+ it('normalizes mode with a both default', () => {+ expect(normalizeMode('chat')).toBe('chat');+ expect(normalizeMode('SPEAK')).toBe('speak');+ expect(normalizeMode('both')).toBe('both');+ expect(normalizeMode('')).toBe('both');+ expect(normalizeMode('podcast')).toBe('both');+ });++ it('normalizes position with a right default', () => {+ expect(normalizePosition('left')).toBe('left');+ expect(normalizePosition('Right')).toBe('right');+ expect(normalizePosition('center')).toBe('right');+ });++ it('normalizes lane with a free default', () => {+ expect(normalizeLane('groq')).toBe('groq');+ expect(normalizeLane('openrouter')).toBe('openrouter');+ expect(normalizeLane('anthropic')).toBe('free');+ expect(normalizeLane(null)).toBe('free');+ });++ it('sanitizes accent to hex or the default', () => {+ expect(sanitizeAccent('#22c55e')).toBe('#22c55e');+ expect(sanitizeAccent('tomato')).toBe(DEFAULT_ACCENT);+ expect(sanitizeAccent('#22c55e;background:url(x)')).toBe(DEFAULT_ACCENT);+ });++ it('isHexColor accepts 3/6/8-digit hex only', () => {+ expect(isHexColor('#abc')).toBe(true);+ expect(isHexColor('#aabbcc')).toBe(true);+ expect(isHexColor('#aabbccdd')).toBe(true);+ expect(isHexColor('#abcd')).toBe(false);+ expect(isHexColor('abc')).toBe(false);+ });+});++describe('buildFrameQuery', () => {+ it('emits only known keys and round-trips through URLSearchParams', () => {+ const query = buildFrameQuery({+ avatar: 'selfie-girl',+ bg: 'ember',+ mode: 'chat',+ accent: '#f97316',+ name: 'Atelier AI',+ voice: true,+ badge: false,+ evil: 'dropme',+ });+ const params = new URLSearchParams(query);+ expect(params.get('avatar')).toBe('selfie-girl');+ expect(params.get('bg')).toBe('ember');+ expect(params.get('mode')).toBe('chat');+ expect(params.get('name')).toBe('Atelier AI');+ expect(params.get('voice')).toBe('true');+ expect(params.get('badge')).toBe('false');+ expect(params.get('evil')).toBeNull();+ });++ it('skips empty values and clamps long text fields', () => {+ expect(buildFrameQuery({})).toBe('');+ expect(buildFrameQuery({ name: '', greeting: undefined })).toBe('');+ const query = buildFrameQuery({ context: 'x'.repeat(2000) });+ expect(new URLSearchParams(query).get('context')).toHaveLength(500);+ });++ it('keeps FRAME_PARAM_KEYS as the single source of truth', () => {+ for (const key of ['avatar', 'agent', 'bg', 'mode', 'accent', 'name', 'greeting', 'context', 'voice', 'badge', 'targetOrigin']) {+ expect(FRAME_PARAM_KEYS).toContain(key);+ }+ });+});++describe('speech + BYOK constants', () => {+ it('estimates speech duration with a floor', () => {+ expect(estimateSpeechMs('')).toBe(0);+ expect(estimateSpeechMs('hi')).toBe(1800);+ expect(estimateSpeechMs('x'.repeat(150))).toBe(10000);+ });++ it('has a default model and endpoint for every BYOK lane', () => {+ for (const lane of ['groq', 'openrouter']) {+ expect(BYOK_DEFAULT_MODELS[lane]).toBeTruthy();+ expect(BYOK_ENDPOINTS[lane]).toMatch(/^https:\/\//);+ }+ });+});