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
selfie + widgets + r2 polish
nirholas934519186e62
diff --git a/api/webhooks/replicate.js b/api/webhooks/replicate.jsnew file mode 100644index 000000000..9b24d6d3b--- /dev/null+++ b/api/webhooks/replicate.js@@ -0,0 +1,225 @@+// Replicate webhook receiver. Replicate POSTs the full Prediction object here+// when our reconstruction job finishes (succeeded/failed/canceled). Verifying+// it lets us update the avatar_regen_jobs row immediately instead of waiting+// for the next /api/avatars/regenerate-status poll to drive the provider.+//+// Signature scheme — Standard Webhooks (https://www.standardwebhooks.com):+// webhook-id — UUID for this delivery+// webhook-timestamp — seconds since epoch+// webhook-signature — "v1,<base64-of-hmac_sha256(secret, id.timestamp.body)>+// v1,<another-sig>" (space-separated for key rotation)+//+// The secret comes from `REPLICATE_WEBHOOK_SIGNING_KEY` (set after creating a+// webhook in the Replicate dashboard). On Replicate the value is prefixed+// with `whsec_` — we strip it. The signing input is exactly `${id}.${timestamp}.${body}`+// joined with periods. Compare with timingSafeEqual.+//+// If the key isn't set the endpoint accepts the payload but does NOT mark the+// job as authenticated — useful in local dev. In production, set the env var.++import { createHmac, timingSafeEqual } from 'node:crypto';+import { sql } from '../_lib/db.js';+import { putObject } from '../_lib/r2.js';+import { storageKeyFor, createAvatar } from '../_lib/avatars.js';+import { json, method, wrap, error } from '../_lib/http.js';++const REPLAY_WINDOW_SECONDS = 5 * 60;++function stripWhsecPrefix(raw) {+ return raw.startsWith('whsec_') ? raw.slice('whsec_'.length) : raw;+}++function verifyStandardWebhook({ signingKey, id, timestamp, body, headerSig }) {+ if (!signingKey || !id || !timestamp || !headerSig) return false;++ const tsNum = Number(timestamp);+ if (!Number.isFinite(tsNum)) return false;+ const skew = Math.abs(Math.floor(Date.now() / 1000) - tsNum);+ if (skew > REPLAY_WINDOW_SECONDS) return false;++ const signed = `${id}.${timestamp}.${body}`;+ const expected = createHmac('sha256', Buffer.from(signingKey, 'base64'))+ .update(signed)+ .digest('base64');++ // Header value: "v1,<sig> v1,<sig>" — multiple sigs separated by space to+ // support rotation. Match if any v1 entry matches.+ for (const entry of String(headerSig).split(/\s+/)) {+ const [version, sig] = entry.split(',', 2);+ if (version !== 'v1' || !sig) continue;+ const a = Buffer.from(sig);+ const b = Buffer.from(expected);+ if (a.length === b.length && timingSafeEqual(a, b)) return true;+ }+ return false;+}++function extractGlbUrl(output) {+ if (!output) return null;+ if (typeof output === 'string') return output;+ if (Array.isArray(output)) {+ for (const v of output) {+ if (typeof v === 'string' && /\.glb(\?|$)/i.test(v)) return v;+ }+ for (const v of output) {+ if (typeof v === 'string' && /^https?:\/\//.test(v)) return v;+ }+ }+ if (typeof output === 'object') {+ for (const key of ['glb', 'mesh', 'mesh_url', 'output_url', 'url', 'model']) {+ if (typeof output[key] === 'string') return output[key];+ }+ }+ return null;+}++function translateStatus(s) {+ switch (s) {+ case 'starting':+ case 'queued': return 'queued';+ case 'processing': return 'running';+ case 'succeeded': return 'done';+ case 'failed':+ case 'canceled': return 'failed';+ default: return 'queued';+ }+}++async function readRaw(req, limit = 1_000_000) {+ const chunks = [];+ let total = 0;+ return new Promise((resolve, reject) => {+ req.on('data', (c) => {+ total += c.length;+ if (total > limit) {+ reject(Object.assign(new Error('payload too large'), { status: 413 }));+ req.destroy();+ return;+ }+ chunks.push(c);+ });+ req.on('end', () => resolve(Buffer.concat(chunks)));+ req.on('error', reject);+ });+}++export default wrap(async (req, res) => {+ if (!method(req, res, ['POST'])) return;++ const raw = await readRaw(req);+ const bodyText = raw.toString('utf8');++ const signingKey = process.env.REPLICATE_WEBHOOK_SIGNING_KEY+ ? stripWhsecPrefix(process.env.REPLICATE_WEBHOOK_SIGNING_KEY)+ : null;++ const id = req.headers['webhook-id'];+ const timestamp = req.headers['webhook-timestamp'];+ const headerSig = req.headers['webhook-signature'];++ let verified = false;+ if (signingKey) {+ verified = verifyStandardWebhook({ signingKey, id, timestamp, body: bodyText, headerSig });+ if (!verified) {+ return error(res, 401, 'invalid_signature', 'webhook signature mismatch');+ }+ }++ let prediction;+ try {+ prediction = JSON.parse(bodyText);+ } catch {+ return error(res, 400, 'invalid_json', 'body is not JSON');+ }++ const extJobId = prediction?.id;+ if (!extJobId) return error(res, 400, 'invalid_payload', 'missing prediction id');++ // Look up our job row keyed by the external prediction id. The regenerate+ // endpoint inserts (job_id, ext_job_id) at submission time so this is a+ // simple equality match. Skip silently if the prediction isn't ours —+ // other Replicate apps in the same account can land here harmlessly.+ const rows = await sql`+ select job_id, user_id, status, result_avatar_id, mode, params+ from avatar_regen_jobs+ where ext_job_id = ${extJobId}+ limit 1+ `;+ if (!rows[0]) return json(res, 200, { ok: true, ignored: 'no matching job' });+ const job = rows[0];++ const nextStatus = translateStatus(prediction?.status);+ const nextGlbUrl = nextStatus === 'done' ? extractGlbUrl(prediction?.output) : null;+ const nextError = nextStatus === 'failed'+ ? String(prediction?.error || 'replicate reported failure')+ : null;++ await sql`+ update avatar_regen_jobs+ set status = ${nextStatus},+ result_glb_url = ${nextGlbUrl},+ error = ${nextError},+ updated_at = now()+ where job_id = ${job.job_id}+ `;++ // Materialize the avatar inline when this is a reconstruct job that just+ // succeeded — the user's status poll will see resultAvatarId on its next+ // hit instead of waiting one more round-trip for the fetch+putObject pair.+ if (+ nextStatus === 'done' &&+ nextGlbUrl &&+ job.mode === 'reconstruct' &&+ !job.result_avatar_id+ ) {+ try {+ const params = job.params || {};+ const name = String(params.name || 'My selfie avatar').slice(0, 120);+ const description = params.description ? String(params.description).slice(0, 500) : null;+ const visibility = ['private', 'unlisted', 'public'].includes(params.visibility)+ ? params.visibility+ : 'private';++ const glbResp = await fetch(nextGlbUrl);+ if (!glbResp.ok) throw new Error(`fetch result_glb_url: ${glbResp.status}`);+ const glbBuf = Buffer.from(await glbResp.arrayBuffer());++ const slug = `selfie-${Math.random().toString(36).slice(2, 8)}`;+ const key = storageKeyFor({ userId: job.user_id, slug });+ await putObject({+ key,+ body: glbBuf,+ contentType: 'model/gltf-binary',+ metadata: { source: 'reconstruct', job_id: job.job_id },+ });+ const avatar = await createAvatar({+ userId: job.user_id,+ storageKey: key,+ input: {+ slug,+ name,+ description,+ size_bytes: glbBuf.length,+ content_type: 'model/gltf-binary',+ source: 'reconstruct',+ source_meta: { jobId: job.job_id, provider: 'replicate', replicateGlb: nextGlbUrl, via: 'webhook' },+ visibility,+ tags: ['selfie'],+ checksum_sha256: null,+ parent_avatar_id: null,+ },+ });+ await sql`+ update avatar_regen_jobs+ set result_avatar_id = ${avatar.id}, updated_at = now()+ where job_id = ${job.job_id}+ `;+ } catch (err) {+ // Materialization failure isn't fatal for the webhook ack — the+ // next /regenerate-status poll will retry the materialize path.+ console.warn('[replicate-webhook] materialize failed', { jobId: job.job_id, error: err?.message });+ }+ }++ return json(res, 200, { ok: true, verified, jobId: job.job_id, status: nextStatus });+});diff --git a/api/widgets/[id]/[action].js b/api/widgets/[id]/[action].jsindex 999e30b60..a74bf80e0 100644--- a/api/widgets/[id]/[action].js+++ b/api/widgets/[id]/[action].js@@ -1033,6 +1033,23 @@ async function handleTranscripts(req, res) {const url = new URL(req.url, 'http://x');const threadId = url.searchParams.get('thread_id');+ const format = url.searchParams.get('format');++ if (format === 'csv') {+ // Calendly/Spotify-style export — downloads the full transcript history+ // so the creator can pipe it into a spreadsheet for review.+ const csv = await exportTranscriptsCsv(id);+ res.statusCode = 200;+ res.setHeader('content-type', 'text/csv; charset=utf-8');+ res.setHeader(+ 'content-disposition',+ `attachment; filename="transcripts-${id}-${new Date().toISOString().slice(0, 10)}.csv"`,+ );+ res.setHeader('cache-control', 'no-store');+ res.end(csv);+ return;+ }+if (threadId) {const data = await getTranscript(id, threadId);if (!data) return error(res, 404, 'not_found', 'thread not found');@@ -1047,6 +1064,66 @@ async function handleTranscripts(req, res) {return json(res, 200, data);}+async function exportTranscriptsCsv(widgetId) {+ const rows = await sql`+ select t.id as thread_id, t.visitor_id, t.referer_host, t.country,+ m.role, m.content, m.provider, m.model, m.redacted, m.created_at+ from widget_chat_messages m+ join widget_chat_threads t on t.id = m.thread_id+ where m.widget_id = ${widgetId}+ order by t.last_message_at desc, m.created_at asc, m.id asc+ limit 5000+ `;+ const header = [+ 'thread_id',+ 'created_at',+ 'visitor_id',+ 'role',+ 'content',+ 'provider',+ 'model',+ 'redacted',+ 'referer_host',+ 'country',+ ];+ const lines = [header.join(',')];+ for (const r of rows) {+ lines.push(+ [+ r.thread_id,+ toIsoString(r.created_at),+ r.visitor_id,+ r.role,+ r.content,+ r.provider || '',+ r.model || '',+ r.redacted ? 'true' : 'false',+ r.referer_host || '',+ r.country || '',+ ]+ .map(csvCell)+ .join(','),+ );+ }+ return lines.join('\n') + '\n';+}++function csvCell(v) {+ const s = v == null ? '' : String(v);+ if (/[",\n\r]/.test(s)) return '"' + s.replace(/"/g, '""') + '"';+ return s;+}++function toIsoString(d) {+ if (!d) return '';+ if (d instanceof Date) return d.toISOString();+ try {+ return new Date(d).toISOString();+ } catch {+ return String(d);+ }+}+// ── knowledge (talking-agent only) ──────────────────────────────────────────async function handleKnowledge(req, res) {diff --git a/public/widgets-gallery/gallery.css b/public/widgets-gallery/gallery.cssindex a76faefdc..16a0f284a 100644--- a/public/widgets-gallery/gallery.css+++ b/public/widgets-gallery/gallery.css@@ -708,6 +708,323 @@ body.gallery-body {}}+/* ── Preview / Code tabs ─────────────────────────────────────────────────────── */++.showcase-frame-wrap {+ display: flex;+ flex-direction: column;+ gap: var(--space-xs);+ width: 100%;+ margin: 0 auto;+}++.frame-tabs {+ display: inline-flex;+ gap: 2px;+ padding: 3px;+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: var(--radius-md);+ align-self: flex-start;+}++.frame-tab {+ padding: 0.35rem 0.85rem;+ font-size: var(--text-xs);+ font-family: var(--font-body);+ color: rgba(229, 229, 229, 0.55);+ background: transparent;+ border: 0;+ border-radius: calc(var(--radius-md) - 4px);+ cursor: pointer;+ letter-spacing: 0.02em;+ transition: background 0.15s, color 0.15s;+}++.frame-tab:hover {+ color: rgba(229, 229, 229, 0.85);+}++.frame-tab[data-active='true'] {+ background: rgba(255, 255, 255, 0.1);+ color: #fff;+ box-shadow: 0 1px 0 rgba(255, 255, 255, 0.06) inset;+}++.frame-tab:focus-visible {+ outline: 2px solid rgba(255, 255, 255, 0.5);+ outline-offset: 2px;+}++/* The code panel reuses the snippet box look but takes the frame's footprint. */+.frame-code-panel {+ position: relative;+ border-radius: var(--radius-md);+ background: #050505;+ border: 1px solid rgba(255, 255, 255, 0.08);+ padding: var(--space-md);+ aspect-ratio: 1 / 1;+ overflow: auto;+ font-family: var(--font-mono);+ font-size: 12px;+ color: rgba(229, 229, 229, 0.9);+ line-height: 1.55;+}++.frame-code {+ margin: 0;+ white-space: pre-wrap;+ word-break: break-word;+}++/* ── Customize panel ─────────────────────────────────────────────────────────── */++.customize {+ margin-top: var(--space-sm);+ background: rgba(255, 255, 255, 0.02);+ border: 1px solid rgba(255, 255, 255, 0.06);+ border-radius: var(--radius-md);+ overflow: hidden;+}++.customize > summary {+ list-style: none;+ cursor: pointer;+ padding: 0.5rem 0.75rem;+ display: inline-flex;+ align-items: center;+ gap: 0.45rem;+ font-size: var(--text-xs);+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: rgba(229, 229, 229, 0.7);+ width: 100%;+ user-select: none;+}++.customize > summary::-webkit-details-marker { display: none; }+.customize > summary::marker { content: ''; }++.customize > summary:hover {+ color: #fff;+ background: rgba(255, 255, 255, 0.03);+}++.customize > summary svg {+ transition: transform 0.2s;+}++.customize[open] > summary svg {+ transform: rotate(60deg);+ color: var(--type-color, var(--accent));+}++.customize-knobs {+ display: grid;+ grid-template-columns: 1fr;+ gap: 0.5rem;+ padding: 0.25rem 0.75rem 0.75rem;+}++.knob-row {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ font-size: var(--text-xs);+}++.knob-row > label:first-child {+ flex: 0 0 4.5rem;+ color: rgba(229, 229, 229, 0.55);+ letter-spacing: 0.02em;+ text-transform: uppercase;+ font-size: 10px;+}++.knob-row input[type='text'],+.knob-row select {+ flex: 1;+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid rgba(255, 255, 255, 0.08);+ color: #e5e5e5;+ border-radius: 6px;+ padding: 0.35rem 0.55rem;+ font-family: var(--font-mono);+ font-size: 11px;+ min-width: 0;+}++.knob-row input[type='text']:focus,+.knob-row select:focus {+ outline: 1px solid var(--type-color, var(--accent));+ outline-offset: 0;+ border-color: var(--type-color, var(--accent));+}++.knob-row input[type='color'] {+ background: transparent;+ border: 1px solid rgba(255, 255, 255, 0.1);+ width: 2rem;+ height: 1.6rem;+ border-radius: 6px;+ padding: 0;+ cursor: pointer;+}++.accent-value {+ font-family: var(--font-mono);+ font-size: 11px;+ color: rgba(229, 229, 229, 0.55);+ letter-spacing: 0.02em;+}++.size-presets {+ display: inline-flex;+ gap: 2px;+ padding: 2px;+ background: rgba(255, 255, 255, 0.04);+ border-radius: 6px;+}++.size-presets button {+ min-width: 1.85rem;+ padding: 0.2rem 0.45rem;+ font-size: 10px;+ font-weight: 600;+ letter-spacing: 0.04em;+ color: rgba(229, 229, 229, 0.55);+ background: transparent;+ border: 0;+ border-radius: 4px;+ cursor: pointer;+}++.size-presets button:hover {+ color: rgba(229, 229, 229, 0.9);+}++.size-presets button[data-active='true'] {+ background: rgba(255, 255, 255, 0.1);+ color: #fff;+}++.customize-reset {+ justify-self: end;+ background: transparent;+ border: 0;+ color: rgba(229, 229, 229, 0.4);+ font-size: 10px;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ cursor: pointer;+ padding: 0.25rem 0.5rem;+}++.customize-reset:hover {+ color: rgba(229, 229, 229, 0.85);+}++/* ── Split-button copy ───────────────────────────────────────────────────────── */++.snippet-row .split-btn {+ flex: 1 1 auto;+ min-width: 140px;+ display: inline-flex;+ position: relative;+ border-radius: var(--radius-md);+ overflow: visible;+ border: 1px solid var(--type-color, var(--blue));+ background: var(--type-color, var(--blue));+ transition: filter 0.15s;+}++.snippet-row .split-btn:hover {+ filter: brightness(1.08);+}++.split-btn-main,+.split-btn-toggle {+ background: transparent;+ border: 0;+ color: #fff;+ font-family: var(--font-body);+ font-size: var(--text-sm);+ cursor: pointer;+ padding: var(--space-xs) var(--space-sm);+}++.split-btn-main {+ flex: 1;+ border-right: 1px solid rgba(0, 0, 0, 0.18);+ text-align: center;+}++.split-btn-toggle {+ padding: var(--space-xs) 0.6rem;+ display: inline-flex;+ align-items: center;+ justify-content: center;+}++.split-btn-main:focus-visible,+.split-btn-toggle:focus-visible {+ outline: 2px solid rgba(255, 255, 255, 0.6);+ outline-offset: -2px;+}++.split-btn-main.copied {+ background: rgba(0, 0, 0, 0.2);+}++.split-btn-menu {+ position: absolute;+ top: calc(100% + 4px);+ right: 0;+ min-width: 11rem;+ background: #0e0e14;+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: var(--radius-md);+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);+ padding: 4px;+ z-index: 50;+ display: flex;+ flex-direction: column;+ gap: 2px;+}++.split-btn-menu-item {+ display: flex;+ align-items: center;+ justify-content: space-between;+ background: transparent;+ border: 0;+ color: rgba(229, 229, 229, 0.85);+ font-family: var(--font-body);+ font-size: var(--text-sm);+ padding: 0.45rem 0.7rem;+ border-radius: 6px;+ cursor: pointer;+ text-align: left;+}++.split-btn-menu-item:hover {+ background: rgba(255, 255, 255, 0.06);+ color: #fff;+}++.split-btn-menu-item[aria-checked='true']::after {+ content: '✓';+ color: var(--type-color, var(--accent));+ margin-left: 0.5rem;+}++/* Studio link gets a stable secondary look (was previously the only <a>; rules+ * above still apply, but pin it to a non-flex-grow width so it doesn't fight+ * the split-btn for space). */+.snippet-row .studio-link {+ flex: 0 0 auto;+}+/* ── Reduced motion ──────────────────────────────────────────────────────────── */@media (prefers-reduced-motion: reduce) {@@ -716,7 +1033,11 @@ body.gallery-body {.snippet-row a,.filter-btn,.play-btn,- .showcase {+ .showcase,+ .frame-tab,+ .split-btn,+ .size-presets button,+ .customize > summary svg {transition: none;animation: none;}