Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: multi-provider chat with SSE streaming + model picker + dev /api proxy
nirholas83cf23267a9e
diff --git a/.env.example b/.env.exampleindex e2d92192c..3a6a97446 100644--- a/.env.example+++ b/.env.example@@ -34,21 +34,33 @@ JWT_KID=k1# Password hashing cost (bcryptjs rounds)PASSWORD_ROUNDS=11-# Anthropic API key for /api/chat (agent LLM backend). If unset, chat falls back-# to pattern matching client-side.+# /api/chat picks a provider in this order (first key found wins, unless the+# client explicitly sets `provider` in the request body):+# 1. ANTHROPIC_API_KEY → Claude Sonnet 4.6 (best tool calling)+# 2. OPENROUTER_API_KEY → free-tier models (Llama 3.3 70B, GPT-OSS, Hermes 3)+# 3. GROQ_API_KEY → Llama 3.3 70B on Groq (sub-second latency)+# 4. OPENAI_API_KEY → gpt-4o-mini++# Anthropic — get a key at https://console.anthropic.comANTHROPIC_API_KEY=# Optional overrides for chat model + output cap.CHAT_MODEL=claude-sonnet-4-6+CHAT_MAX_TOKENS=1024# Admin key for three.ws chat brand config. Set in Vercel, enter in chat settings to unlock branding panel.# Generate with: openssl rand -base64 32CHAT_ADMIN_KEY=-# OpenRouter API key — powers the built-in free model proxy (/api/chat/proxy).-# Free-tier models (e.g. google/gemini-2.0-flash-exp:free) are forwarded server-side.-# Sign up free at https://openrouter.ai+# OpenRouter — powers free-tier models in /api/chat AND the built-in proxy at+# /api/chat/proxy. Free-tier (`:free` suffix) models include Llama 3.3 70B,+# GPT-OSS 120B, Hermes 3 405B. Sign up free at https://openrouter.aiOPENROUTER_API_KEY=-CHAT_MAX_TOKENS=1024++# Groq — fastest hosted Llama (sub-second). Get a key at https://console.groq.com+GROQ_API_KEY=++# OpenAI — used for gpt-4o-mini fallback. Get a key at https://platform.openai.com+OPENAI_API_KEY=# Ready Player Me subdomain for the avatar creator iframe (client-side).# Register one at https://studio.readyplayer.me — e.g. "your-app" yieldsdiff --git a/api/chat.js b/api/chat.jsindex e6c7a7b70..7d167acce 100644--- a/api/chat.js+++ b/api/chat.js@@ -1,10 +1,18 @@-// POST /api/chat — AI-powered chat for the three.ws.+// POST /api/chat — AI-powered chat for the three.ws viewer agent.//-// Takes a user message + viewer context, forwards to Anthropic with a set of-// viewer-control tools exposed as function-calls, and returns:-// { reply: string, actions: [{ type, ...input }] }-// The client executes each action against the live viewer. The model is-// stateless here — callers pass the recent history each turn (sessionStorage).+// Body: { message, context, history, agentId?, provider?, model? }+// Response: SSE stream { type: 'chunk' | 'done' | 'error' }.+//+// Provider routing (in order):+// 1. Body.provider when present and the matching key is configured.+// 2. ANTHROPIC_API_KEY → Anthropic (default).+// 3. OPENROUTER_API_KEY → OpenRouter free tier.+// 4. GROQ_API_KEY → Groq.+// 5. OPENAI_API_KEY → OpenAI.+// Anthropic and the OpenAI-compatible providers (OpenRouter / Groq / OpenAI)+// use different request shapes, tool-call wire formats, and SSE event names —+// this file translates both directions so the client only sees the same+// { chunk → done } event stream regardless of upstream.import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';import { cors, json, method, readJson, wrap, error } from './_lib/http.js';@@ -17,10 +25,41 @@ import { z } from 'zod';export const maxDuration = 60;const ANTHROPIC_URL = 'https://api.anthropic.com/v1/messages';-const DEFAULT_MODEL = 'claude-sonnet-4-6';+const DEFAULT_ANTHROPIC_MODEL = 'claude-sonnet-4-6';+const DEFAULT_OPENROUTER_MODEL = 'meta-llama/llama-3.3-70b-instruct:free';+const DEFAULT_GROQ_MODEL = 'llama-3.3-70b-versatile';+const DEFAULT_OPENAI_MODEL = 'gpt-4o-mini';const DEFAULT_MAX_TOKENS = 1024;const HARD_MAX_TOKENS = 4096;+const PROVIDERS = {+ anthropic: {+ envKey: 'ANTHROPIC_API_KEY',+ defaultModel: DEFAULT_ANTHROPIC_MODEL,+ url: ANTHROPIC_URL,+ style: 'anthropic',+ },+ openrouter: {+ envKey: 'OPENROUTER_API_KEY',+ defaultModel: DEFAULT_OPENROUTER_MODEL,+ url: 'https://openrouter.ai/api/v1/chat/completions',+ style: 'openai',+ extraHeaders: { 'HTTP-Referer': 'https://three.ws', 'X-Title': 'three.ws agent' },+ },+ groq: {+ envKey: 'GROQ_API_KEY',+ defaultModel: DEFAULT_GROQ_MODEL,+ url: 'https://api.groq.com/openai/v1/chat/completions',+ style: 'openai',+ },+ openai: {+ envKey: 'OPENAI_API_KEY',+ defaultModel: DEFAULT_OPENAI_MODEL,+ url: 'https://api.openai.com/v1/chat/completions',+ style: 'openai',+ },+};+const contextSchema = z.object({modelName: z.string().max(200).optional(),@@ -45,6 +84,8 @@ const chatBody = z.object({message: z.string().trim().min(1).max(4000),context: contextSchema,agentId: z.string().uuid().optional(),+ provider: z.enum(['anthropic', 'openrouter', 'groq', 'openai']).optional(),+ model: z.string().min(1).max(120).optional(),history: z.array(z.object({@@ -56,6 +97,7 @@ const chatBody = z.object({.default([]),});+// Tool definitions in Anthropic shape; converted to OpenAI shape on demand.const ACTION_TOOLS = [{name: 'setWireframe',@@ -169,20 +211,28 @@ const ACTION_TOOLS = [const ACTION_NAMES = new Set(ACTION_TOOLS.map((t) => t.name));+const OPENAI_TOOLS = ACTION_TOOLS.map((t) => ({+ type: 'function',+ function: {+ name: t.name,+ description: t.description,+ parameters: t.input_schema,+ },+}));+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;- const apiKey = process.env.ANTHROPIC_API_KEY;- if (!apiKey) {- return error(res, 503, 'chat_unavailable', 'chat backend is not configured');- }-const auth = await resolveAuth(req);if (!auth) return error(res, 401, 'unauthorized', 'sign in to chat with the agent');const body = parse(chatBody, await readJson(req));- const model = process.env.CHAT_MODEL || DEFAULT_MODEL;+ const route = pickProvider(body.provider, body.model);+ if (!route) {+ return error(res, 503, 'chat_unavailable', 'no chat provider is configured');+ }+const maxTokens = clampInt(parseInt(process.env.CHAT_MAX_TOKENS || '', 10) || DEFAULT_MAX_TOKENS,128,@@ -198,47 +248,36 @@ export default wrap(async (req, res) => {if (agentRow?.persona_prompt) personaPrompt = agentRow.persona_prompt;}- const messages = [- ...body.history.map((m) => ({ role: m.role, content: m.content })),- { role: 'user', content: body.message },- ];+ const systemPrompt = buildSystemPrompt(body.context, personaPrompt);+ const history = body.history.map((m) => ({ role: m.role, content: m.content }));+ history.push({ role: 'user', content: body.message });const started = Date.now();let upstream;try {- upstream = await fetch(ANTHROPIC_URL, {+ upstream = await fetch(route.url, {method: 'POST',- headers: {- 'x-api-key': apiKey,- 'anthropic-version': '2023-06-01',- 'content-type': 'application/json',- },- body: JSON.stringify({- model,- max_tokens: maxTokens,- system: buildSystemPrompt(body.context, personaPrompt),- messages,- tools: ACTION_TOOLS,- stream: true,- }),+ headers: route.headers,+ body: JSON.stringify(route.buildPayload({ systemPrompt, history, maxTokens })),});} catch (err) {- captureException(err, { route: 'chat', stage: 'fetch' });+ captureException(err, { route: 'chat', stage: 'fetch', provider: route.name });if (process.env.DEBUG === 'true') {- console.warn('[chat] upstream fetch failed:', err.message);+ console.warn(`[chat:${route.name}] upstream fetch failed:`, err.message);}return error(res, 502, 'upstream_unavailable', 'chat backend unreachable');}if (!upstream.ok) {const text = await upstream.text().catch(() => '');- captureException(new Error(`anthropic upstream ${upstream.status}`), {+ captureException(new Error(`${route.name} upstream ${upstream.status}`), {route: 'chat',+ provider: route.name,status: upstream.status,body: text.slice(0, 400),});if (process.env.DEBUG === 'true') {- console.warn('[chat] anthropic', upstream.status, text.slice(0, 400));+ console.warn(`[chat:${route.name}]`, upstream.status, text.slice(0, 400));}return error(res, 502, 'upstream_error', `chat backend returned ${upstream.status}`);}@@ -249,6 +288,112 @@ export default wrap(async (req, res) => {'X-Accel-Buffering': 'no',});+ function sendSSE(obj) {+ res.write(`data: ${JSON.stringify(obj)}\n\n`);+ }++ const result =+ route.style === 'anthropic'+ ? await streamAnthropic(upstream, sendSSE)+ : await streamOpenAI(upstream, sendSSE);++ if (result.error) {+ captureException(result.error, { route: 'chat', stage: 'stream', provider: route.name });+ sendSSE({ type: 'error', code: 'stream_error', message: 'stream interrupted' });+ res.end();+ return;+ }++ sendSSE({+ type: 'done',+ reply: result.reply.trim(),+ actions: result.actions,+ model: route.model,+ provider: route.name,+ });+ res.end();++ const latencyMs = Date.now() - started;+ recordEvent({+ userId: auth.userId,+ apiKeyId: auth.apiKeyId,+ clientId: auth.clientId,+ kind: 'chat',+ tool: route.model,+ latencyMs,+ meta: {+ provider: route.name,+ input_tokens: result.inputTokens,+ output_tokens: result.outputTokens,+ actions: result.actions.map((a) => a.type),+ has_context: Boolean(body.context?.modelName),+ },+ });+});++// ── Provider selection ───────────────────────────────────────────────────────++function pickProvider(requested, model) {+ const order = requested+ ? [requested, ...Object.keys(PROVIDERS).filter((p) => p !== requested)]+ : ['anthropic', 'openrouter', 'groq', 'openai'];++ for (const name of order) {+ const cfg = PROVIDERS[name];+ const apiKey = process.env[cfg.envKey];+ if (!apiKey) continue;+ const chosenModel = (requested === name && model) || process.env.CHAT_MODEL || cfg.defaultModel;+ return makeRoute(name, cfg, apiKey, chosenModel);+ }+ return null;+}++function makeRoute(name, cfg, apiKey, model) {+ if (cfg.style === 'anthropic') {+ return {+ name,+ model,+ url: cfg.url,+ style: 'anthropic',+ headers: {+ 'x-api-key': apiKey,+ 'anthropic-version': '2023-06-01',+ 'content-type': 'application/json',+ },+ buildPayload: ({ systemPrompt, history, maxTokens }) => ({+ model,+ max_tokens: maxTokens,+ system: systemPrompt,+ messages: history,+ tools: ACTION_TOOLS,+ stream: true,+ }),+ };+ }+ return {+ name,+ model,+ url: cfg.url,+ style: 'openai',+ headers: {+ Authorization: `Bearer ${apiKey}`,+ 'Content-Type': 'application/json',+ ...(cfg.extraHeaders || {}),+ },+ buildPayload: ({ systemPrompt, history, maxTokens }) => ({+ model,+ max_tokens: maxTokens,+ messages: [{ role: 'system', content: systemPrompt }, ...history],+ tools: OPENAI_TOOLS,+ tool_choice: 'auto',+ stream: true,+ }),+ };+}++// ── Stream readers ───────────────────────────────────────────────────────────++async function streamAnthropic(upstream, sendSSE) {const reader = upstream.body.getReader();const decoder = new TextDecoder();let buf = '';@@ -258,10 +403,6 @@ export default wrap(async (req, res) => {let inputTokens = 0;let outputTokens = 0;- function sendSSE(obj) {- res.write(`data: ${JSON.stringify(obj)}\n\n`);- }-try {while (true) {const { value, done } = await reader.read();@@ -295,45 +436,94 @@ export default wrap(async (req, res) => {}} else if (evt.type === 'content_block_stop') {const block = blocks[evt.index];- if (block?.type === 'tool_use' && block.partialJson) {- try {- const input = JSON.parse(block.partialJson);- if (ACTION_NAMES.has(block.name)) {- actions.push({ type: block.name, ...input });- }- } catch {}+ if (block?.type === 'tool_use') {+ const action = parseToolJson(block.name, block.partialJson);+ if (action) actions.push(action);}} else if (evt.type === 'message_delta') {- outputTokens = evt.usage?.output_tokens ?? 0;+ outputTokens = evt.usage?.output_tokens ?? outputTokens;}}}} catch (err) {- captureException(err, { route: 'chat', stage: 'stream' });- sendSSE({ type: 'error', code: 'stream_error', message: 'stream interrupted' });- res.end();- return;+ return { error: err, reply, actions, inputTokens, outputTokens };}- const latencyMs = Date.now() - started;- sendSSE({ type: 'done', reply: reply.trim(), actions, model });- res.end();+ return { reply, actions, inputTokens, outputTokens };+}- recordEvent({- userId: auth.userId,- apiKeyId: auth.apiKeyId,- clientId: auth.clientId,- kind: 'chat',- tool: model,- latencyMs,- meta: {- input_tokens: inputTokens,- output_tokens: outputTokens,- actions: actions.map((a) => a.type),- has_context: Boolean(body.context?.modelName),- },- });-});+async function streamOpenAI(upstream, sendSSE) {+ const reader = upstream.body.getReader();+ const decoder = new TextDecoder();+ let buf = '';+ let reply = '';+ const actions = [];+ // OpenAI streams tool calls as deltas keyed by index. Accumulate name + arguments per index.+ const toolBuf = {};+ let inputTokens = 0;+ let outputTokens = 0;++ try {+ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ buf += decoder.decode(value, { stream: true });+ const lines = buf.split('\n');+ buf = lines.pop();+ for (const line of lines) {+ if (!line.startsWith('data: ')) continue;+ const raw = line.slice(6).trim();+ if (!raw || raw === '[DONE]') continue;+ let evt;+ try {+ evt = JSON.parse(raw);+ } catch {+ continue;+ }+ const choice = evt.choices?.[0];+ const delta = choice?.delta;+ if (delta?.content) {+ reply += delta.content;+ sendSSE({ type: 'chunk', text: delta.content });+ }+ if (Array.isArray(delta?.tool_calls)) {+ for (const tc of delta.tool_calls) {+ const idx = tc.index ?? 0;+ const slot = (toolBuf[idx] ||= { name: '', args: '' });+ if (tc.function?.name) slot.name += tc.function.name;+ if (tc.function?.arguments) slot.args += tc.function.arguments;+ }+ }+ if (evt.usage) {+ inputTokens = evt.usage.prompt_tokens ?? inputTokens;+ outputTokens = evt.usage.completion_tokens ?? outputTokens;+ }+ }+ }+ } catch (err) {+ return { error: err, reply, actions, inputTokens, outputTokens };+ }++ for (const slot of Object.values(toolBuf)) {+ const action = parseToolJson(slot.name, slot.args);+ if (action) actions.push(action);+ }++ return { reply, actions, inputTokens, outputTokens };+}++function parseToolJson(name, jsonText) {+ if (!name || !ACTION_NAMES.has(name)) return null;+ const text = jsonText && jsonText.trim() ? jsonText : '{}';+ try {+ const input = JSON.parse(text);+ return { type: name, ...input };+ } catch {+ return null;+ }+}++// ── System prompt + auth + helpers ───────────────────────────────────────────function buildSystemPrompt(ctx = {}, personaPrompt = null) {const loaded = ctx.modelName@@ -351,7 +541,7 @@ function buildSystemPrompt(ctx = {}, personaPrompt = null) {'You are the three.ws — an embodied AI assistant embedded inside a browser-native glTF/GLB viewer at three.ws.','Your job is to help the user inspect, understand, and modify the 3D scene. You have deep glTF 2.0, PBR materials, and three.js expertise.','You can also show the latest trades from pump.fun by calling the getPumpFunTrades tool.',- 'When the user asks you to change the viewer (e.g. "enable wireframe", "make the background dark blue", "turn on auto rotate"), USE the provided tools to perform the change — do not just describe it.',+ 'When the user asks you to change the viewer ("enable wireframe", "make the background dark blue", "turn on auto rotate", "load this model"), CALL the matching tool — do not just describe what would happen. Examples: user "wireframe on" → call setWireframe({value:true}). user "rotate it" → call setAutoRotate({value:true}). user "dark blue bg" → call setBgColor({value:"#0a1f44"}).','When asked about the loaded model, use the context below as ground truth. Do not invent stats.','Keep replies tight: 1–3 sentences. Plain text, no markdown headers, no emoji.','',@@ -362,7 +552,6 @@ function buildSystemPrompt(ctx = {}, personaPrompt = null) {return lines.join('\n');}-async function resolveAuth(req) {const session = await getSessionUser(req);if (session) return { userId: session.id, source: 'session' };diff --git a/chat/src/Message.svelte b/chat/src/Message.svelteindex 63fe937a0..f1cbf0771 100644--- a/chat/src/Message.svelte+++ b/chat/src/Message.svelte@@ -212,7 +212,7 @@? 'flex w-[140px] h-[280px]': 'flex h-8 w-8 md:h-9 md:w-9'} {message.role === 'system'? 'border border-teal-200 bg-teal-100'- : message.role === 'assistant' && !message.agent+ : message.role === 'assistant' && !message.agent && !(hasLogo && isLatestAssistant)? 'border border-teal-200 bg-teal-100 pb-px': ''}">@@ -221,7 +221,11 @@<!-- svelte-ignore custom-element-no-implicit-ns --><agent-3dbind:this={agentEl}- {...(message.agent?.id ? { 'agent-id': message.agent.id } : { src: '/avatars/cz.glb' })}+ {...($talkingHeadAvatarUrl+ ? { src: $talkingHeadAvatarUrl }+ : message.agent?.id+ ? { 'agent-id': message.agent.id }+ : { src: '/avatars/cz.glb' })}mode="inline"width="140"height="280"diff --git a/public/dashboard/dashboard.js b/public/dashboard/dashboard.jsindex 04aa69ab4..2546eb755 100644--- a/public/dashboard/dashboard.js+++ b/public/dashboard/dashboard.js@@ -105,47 +105,6 @@ const tabs = {account: renderAccount,};-async function renderRevenue(root) {- root.innerHTML = `- <div class="page-header">- <h1>Revenue</h1>- <p class="sub">Track your earnings from paid agent skills.</p>- </div>- <div class="stats-grid" id="revenue-stats-grid">- <div class="stat-card">Loading...</div>- </div>- <div id="revenue-events-table-container"></div>- `;-- try {- const stats = await api.getRevenueStats(); // Assumes an api helper exists- renderRevenueStats(stats);- } catch (e) {- document.getElementById('revenue-stats-grid').innerHTML = `<div class="err">Failed to load stats: ${e.message}</div>`;- }-}--function renderRevenueStats(stats) {- const grid = document.getElementById('revenue-stats-grid');-- const formatUSDC = (amount) => `$${(Number(amount) / 1e6).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;-- grid.innerHTML = `- <div class="stat-card">- <div class="label">Current Balance</div>- <div class="value green">${formatUSDC(stats.current_balance)}</div>- </div>- <div class="stat-card">- <div class="label">Net Earnings (30 Days)</div>- <div class="value">${formatUSDC(stats.earnings_last_30_days)}</div>- </div>- <div class="stat-card">- <div class="label">Lifetime Net Revenue</div>- <div class="value">${formatUSDC(stats.total_revenue_net)}</div>- </div>- `;-}-// ── Avatars ─────────────────────────────────────────────────────────────────async function renderAvatars(root) {root.innerHTML = `<h1>Your avatars</h1><p class="sub">Each avatar gets a stable URL and can be rendered in Claude or any app via MCP.</p><div id="list" class="cards"></div>`;diff --git a/public/pumpfun.html b/public/pumpfun.htmlindex 428bf55f1..f372365e1 100644--- a/public/pumpfun.html+++ b/public/pumpfun.html@@ -148,9 +148,29 @@@media (prefers-reduced-motion: reduce) {.pf-modal-backdrop, .pf-modal, .pf-skeleton, .pf-toast { animation: none; }}- main.pf-main { position: relative; flex: 1; min-height: calc(100vh - var(--header-h) - 56px); display: grid; grid-template-columns: 1fr; }+ main.pf-main { position: relative; flex: 1; min-height: calc(100vh - var(--header-h) - 56px);+ display: grid; grid-template-columns: minmax(0, 1fr) 380px; gap: 0; }+ @media (max-width: 1100px) { main.pf-main { grid-template-columns: minmax(0, 1fr) 340px; } }#stage { position: relative; display: flex; flex-direction: column; }- iframe { width: 100%; flex: 1; border: 0; display: block; background: var(--bg); }+ #stage > model-viewer#agent { width: 100%; flex: 1; min-height: 0;+ background: radial-gradient(ellipse at 50% 60%, #1a1a26 0%, #0a0a12 70%);+ --poster-color: transparent; display: block; }+ #stage-overlay { position: absolute; inset: 0; display: flex; flex-direction: column;+ justify-content: flex-end; align-items: center; padding: 0 24px 24px;+ pointer-events: none; gap: 12px; z-index: 2; }+ #stage-title { font-size: 22px; font-weight: 700; letter-spacing: 0.01em;+ color: #fff; text-shadow: 0 2px 14px rgba(0,0,0,0.7), 0 0 24px rgba(106,92,255,0.35);+ text-align: center; max-width: 720px; opacity: 0; transform: translateY(8px);+ transition: opacity 0.25s ease, transform 0.25s ease; }+ #stage-title[data-visible="true"] { opacity: 1; transform: none; }+ #stage-title .sub { display: block; font-size: 13px; font-weight: 500; color: #cbd5e1;+ text-shadow: 0 1px 8px rgba(0,0,0,0.7); margin-top: 4px; letter-spacing: 0.02em; }+ #stage-caption { font-size: 14px; font-weight: 500; color: #eee; max-width: 640px;+ background: rgba(10,10,16,0.78); border: 1px solid rgba(106,92,255,0.35);+ border-radius: 10px; padding: 8px 14px; backdrop-filter: blur(8px);+ text-align: center; opacity: 0; transform: translateY(6px);+ transition: opacity 0.2s ease, transform 0.2s ease; }+ #stage-caption[data-visible="true"] { opacity: 1; transform: none; }#anim-chips { display: flex; gap: 6px; flex-wrap: wrap; padding: 8px 12px;border-top: 1px solid var(--border); background: rgba(20,20,28,0.85);backdrop-filter: blur(6px); max-height: 96px; overflow-y: auto; }@@ -162,17 +182,15 @@.anim-chip:active { transform: scale(0.96); }.anim-chip[data-active="true"] { background: var(--accent); border-color: var(--accent); color: #fff; }.anim-chip[disabled] { opacity: 0.5; cursor: wait; }- @media (min-width: 721px) {+ @media (min-width: 721px) {#side {- position: absolute;- right: 16px;- top: 16px;- width: 360px;- max-height: 80vh;- z-index: 100;- border-radius: 8px;- box-shadow: 0 8px 24px rgba(0,0,0,0.4);- border: 1px solid var(--border);+ position: relative;+ width: auto;+ max-height: none;+ z-index: 1;+ border-radius: 0;+ box-shadow: none;+ border-left: 1px solid var(--border);background: var(--panel);display: flex;flex-direction: column;@@ -188,19 +206,7 @@overflow: hidden;}#side-header {- display: none; /* hidden on mobile by default */- }- @media (min-width: 721px) {- #side-header {- display: flex;- justify-content: space-between;- align-items: center;- padding: 6px 12px;- background: #1a1a24;- cursor: move;- border-bottom: 1px solid var(--border);- user-select: none;- }+ display: none; /* docked panel doesn't need drag/min/close affordances */}#side-header .side-title {font-weight: 600;@@ -398,7 +404,11 @@</div><main class="pf-main"><div id="stage">- <iframe id="agent" allow="autoplay" title="3D agent"></iframe>+ <model-viewer id="agent" camera-controls disable-zoom interaction-prompt="none" autoplay auto-rotate auto-rotate-delay="2000" rotation-per-second="15deg" shadow-intensity="0.6" shadow-softness="0.8" exposure="1.0" environment-image="neutral" camera-orbit="0deg 80deg 4m" field-of-view="32deg" loading="eager" aria-label="3D agent"></model-viewer>+ <div id="stage-overlay">+ <div id="stage-title" aria-live="polite"></div>+ <div id="stage-caption" aria-live="polite"></div>+ </div><div id="anim-chips" role="group" aria-label="Trigger animation"></div></div><aside id="side">@@ -1015,10 +1025,9 @@// ── Agent communication ──────────────────────────────────────────────let animations = [];- let ws = null, wsTries = 0, wsBackoff = 1000, wsClosed = false;+ let es = null, esTries = 0, esBackoff = 1000, esClosed = false;let queue = [], queueTimer = null, queuePaused = false;let replayQueue = [];- const solPrice = { val: 0, el: null };let firstClaims = { data: [], el: $('first-claims'), refreshing: false, ts: 0 };const feed = {el: $('feed'),@@ -1042,42 +1051,91 @@};const seen = new Set(); // seen mints in this session- const iframeUrl = new URL('/agent-embed.html', location.href);- function loadAgent() {- iframeUrl.searchParams.set('src', params.avatar);- // Pass some params to the agent iframe for its own analytics- iframeUrl.searchParams.set('page', 'pumpfun');- // Cursor stays a normal cursor — no avatar gaze tracking on this page- iframeUrl.searchParams.set('gaze', 'off');- if (params.asset) iframeUrl.searchParams.set('asset', params.asset);- if (params.mint) iframeUrl.searchParams.set('mint', params.mint);- iframe.src = iframeUrl.href;- }+ // ── Avatar viewer ────────────────────────────────────────────────────+ // Direct <model-viewer> (loaded from CDN at the top of the page). Replaces+ // the previous iframe-based agent embed which expected ?id=<agentId> and+ // silently rendered nothing when only ?src=<glb> was supplied.+ const viewer = iframe; // alias kept so existing variable name still reads+ function loadAgent() { viewer.src = params.avatar; }loadAgent();- window.addEventListener('message', (e) => {- if (e.source !== iframe.contentWindow) return;- const { type, payload } = e.data;- if (type === 'ready') {- iframe.contentWindow.postMessage({ type: 'getAnimations' }, '*');- } else if (type === 'animations') {- animations = payload;- const chips = $('anim-chips');- chips.innerHTML = '';- payload.forEach((anim) => {- const btn = document.createElement('button');- btn.type = 'button';- btn.className = 'anim-chip';- btn.textContent = anim;- btn.addEventListener('click', () => {- iframe.contentWindow.postMessage({ type: 'playAnimation', payload: anim }, '*');- });- chips.appendChild(btn);- });- // Repopulate animation dropdowns if the config modal is already open- if (config.modal.dataset.open === 'true') renderConfigBody();- }+ viewer.addEventListener('load', () => {+ animations = viewer.availableAnimations || [];+ const chips = $('anim-chips');+ chips.innerHTML = '';+ animations.forEach((anim) => {+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'anim-chip';+ btn.textContent = anim;+ btn.addEventListener('click', () => playAnim(anim));+ chips.appendChild(btn);+ });+ if (!animations.length) chips.innerHTML = '<span class="empty" style="padding:0">no animations on this avatar</span>';+ // Auto-play the first available animation so the avatar isn't a T-pose+ if (animations.length) { viewer.animationName = animations[0]; viewer.play({ repetitions: Infinity }); }+ if (config.modal.dataset.open === 'true') renderConfigBody();});+ viewer.addEventListener('error', (e) => {+ console.warn('[agent] model load error', e?.detail || e);+ $('anim-chips').innerHTML = '<span class="empty" style="padding:0;color:#f87171">avatar failed to load</span>';+ });++ function playAnim(name) {+ if (!viewer.availableAnimations?.includes(name)) return false;+ try {+ viewer.animationName = name;+ viewer.currentTime = 0;+ viewer.play({ repetitions: 1 });+ return true;+ } catch { return false; }+ }++ // ── Web Speech narration (replaces iframe-side TTS) ──────────────────+ const synth = window.speechSynthesis || null;+ let _voice = null;+ function pickVoice() {+ if (!synth) return null;+ if (_voice) return _voice;+ const voices = synth.getVoices();+ if (!voices.length) return null;+ _voice = voices.find(v => /en[-_]US/i.test(v.lang) && /female|samantha|zira|jenny|aria/i.test(v.name))+ || voices.find(v => /en[-_]US/i.test(v.lang))+ || voices.find(v => v.lang?.startsWith('en'))+ || voices[0];+ return _voice;+ }+ if (synth?.addEventListener) synth.addEventListener('voiceschanged', pickVoice);+ function speak(text) {+ if (!synth || !text) return 0;+ try {+ synth.cancel();+ const u = new SpeechSynthesisUtterance(text);+ const v = pickVoice();+ if (v) u.voice = v;+ u.rate = params.mood === 'hype' ? 1.15 : params.mood === 'chill' ? 0.92 : 1.0;+ u.pitch = params.mood === 'hype' ? 1.1 : 1.0;+ synth.speak(u);+ return Math.max(2000, Math.min(10000, 2200 + text.length * 55));+ } catch { return 0; }+ }++ // ── Stage overlay (caption + title) ──────────────────────────────────+ const _captionEl = $('stage-caption');+ const _titleEl = $('stage-title');+ let _captionTimer = null, _titleTimer = null;+ function showCaption(text, holdMs = 3000) {+ clearTimeout(_captionTimer);+ _captionEl.textContent = text;+ _captionEl.dataset.visible = 'true';+ _captionTimer = setTimeout(() => { _captionEl.dataset.visible = 'false'; }, holdMs);+ }+ function showTitle(title, subtitle, holdMs = 3000) {+ clearTimeout(_titleTimer);+ _titleEl.innerHTML = `${escapeHtml(title || '')}${subtitle ? `<span class="sub">${escapeHtml(subtitle)}</span>` : ''}`;+ _titleEl.dataset.visible = 'true';+ _titleTimer = setTimeout(() => { _titleEl.dataset.visible = 'false'; }, holdMs);+ }function enqueue(item, toFront = false) {if (toFront) queue.unshift(item); else queue.push(item);@@ -1099,13 +1157,14 @@let duration = 3000;if (item.type === 'say') {- iframe.contentWindow.postMessage({ type: 'say', payload: { text: item.text, mood: params.mood } }, '*');- duration = 3000 + (item.text.length * 55);+ const spokenMs = speak(item.text);+ duration = spokenMs || (3000 + (item.text.length * 55));+ showCaption(item.text, duration);} else if (item.type === 'anim') {- iframe.contentWindow.postMessage({ type: 'playAnimation', payload: item.name }, '*');+ playAnim(item.name);duration = item.duration || 2500;} else if (item.type === 'title') {- iframe.contentWindow.postMessage({ type: 'showTitle', payload: { title: item.title, subtitle: item.subtitle } }, '*');+ showTitle(item.title, item.subtitle, item.duration || 3000);duration = item.duration || 3000;}queueTimer = setTimeout(processQueue, duration);@@ -1113,51 +1172,105 @@// ── Event handlers ───────────────────────────────────────────────────+ function normalizeEvent(type, ev) {+ const tsRaw = ev.created_at ?? ev.timestamp ?? ev.ts;+ let timestamp = Date.now();+ if (typeof tsRaw === 'number') timestamp = tsRaw < 1e12 ? tsRaw * 1000 : tsRaw;+ else if (tsRaw) {+ const parsed = new Date(tsRaw).getTime();+ if (Number.isFinite(parsed)) timestamp = parsed;+ }+ const mc = Number(ev.market_cap_usd ?? ev.usd_market_cap) || 0;+ if (type === 'mint') {+ const socials = (ev.twitter || ev.telegram || ev.website)+ ? { twitter: ev.twitter, telegram: ev.telegram, website: ev.website }+ : null;+ return {+ type: 'mint',+ mint: ev.mint,+ name: ev.name || ev.symbol || 'unknown',+ ticker: ev.symbol || ev.ticker || '',+ description: ev.description || '',+ sol: Number(ev.initial_buy_sol) || 0,+ usd: Number(ev.initial_buy_usd) || 0,+ user: ev.creator || ev.user || '',+ tier: ev.tier,+ market_cap_usd: mc,+ replay: !!ev.replay,+ socials,+ timestamp,+ };+ }+ if (type === 'graduation') {+ return {+ type: 'graduation',+ mint: ev.mint,+ name: ev.name || ev.symbol || 'unknown',+ market_cap_usd: mc,+ tier: ev.tier,+ audit: ev.audit,+ replay: !!ev.replay,+ timestamp,+ };+ }+ if (type === 'claim') {+ const lamports = Number(ev.lamports ?? ev.amountLamports) || 0;+ return {+ type: 'claim',+ mint: ev.mint || ev.token_mint || '',+ user: ev.creator || ev.user || ev.claimerWallet || '',+ sol: Number(ev.sol) || (lamports ? lamports / 1e9 : 0),+ usd: Number(ev.usd) || 0,+ tier: ev.tier,+ replay: !!ev.replay,+ timestamp,+ };+ }+ return { ...ev, type, timestamp };+ }+function connect() {- wsTries++;- setStatus('connecting', `connecting (try ${wsTries})…`);- if (ws) { try { ws.close(); } catch {} ws = null; }-- const endpoint = new URL('/api/pump/feed', location.href);- endpoint.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';- if (params.asset) endpoint.searchParams.set('asset', params.asset);- if (params.network) endpoint.searchParams.set('network', params.network);-- ws = new WebSocket(endpoint.href);- ws.onopen = () => {- console.log('[ws] connected');- wsTries = 0;- wsBackoff = 1000;+ esTries++;+ setStatus('connecting', `connecting (try ${esTries})…`);+ if (es) { try { es.close(); } catch {} es = null; }++ const endpoint = new URL('/api/agents/pumpfun-feed', location.href);+ endpoint.searchParams.set('kind', params.kind || 'all');+ if (params.minTier) endpoint.searchParams.set('minTier', params.minTier);+ if (params.mcMin) endpoint.searchParams.set('mcMin', String(params.mcMin));+ if (params.mcMax) endpoint.searchParams.set('mcMax', String(params.mcMax));+ if (params.minBuy) endpoint.searchParams.set('minBuy', String(params.minBuy));+ if (params.whale) endpoint.searchParams.set('whale', String(params.whale));++ es = new EventSource(endpoint.href, { withCredentials: true });+ es.addEventListener('open', () => {+ esTries = 0;+ esBackoff = 1000;setStatus('live', 'live');- ws.send(JSON.stringify({ type: 'sol-price' }));+ });+ const ingest = (sseType) => (msg) => {+ let ev; try { ev = JSON.parse(msg.data); } catch { return; }+ handleEvent(normalizeEvent(sseType, ev));};- ws.onmessage = (e) => {- const data = JSON.parse(e.data);- if (data.type === 'sol-price') {- solPrice.val = data.price;- return;- }- if (data.type === 'events-batch') {- data.events.forEach(handleEvent);- if (data.replay) {- setTimeout(() => {- const div = document.createElement('div');- div.style = 'margin: 6px 0; text-align: center; font-size: 10px; color: #444; text-transform: uppercase; letter-spacing: 0.08em;';- div.textContent = `live events started ${new Date().toLocaleTimeString()}`;- feed.el.appendChild(div);- }, 1000);- }- return;+ es.addEventListener('mint', ingest('mint'));+ es.addEventListener('claim', ingest('claim'));+ es.addEventListener('graduation', ingest('graduation'));+ es.addEventListener('ping', () => {});+ es.addEventListener('close', () => {+ if (esClosed) return;+ try { es.close(); } catch {}+ setTimeout(connect, 250);+ });+ es.onerror = () => {+ if (esClosed || !es) return;+ if (es.readyState === EventSource.CLOSED) {+ console.log(`[sse] disconnected, reconnect in ${esBackoff/1000}s`);+ setStatus('down', 'offline');+ setTimeout(connect, esBackoff);+ esBackoff = Math.min(esBackoff * 1.5, 15000);+ } else {+ setStatus('connecting', 'reconnecting…');}- handleEvent(data);- };- ws.onerror = (err) => console.error('[ws] error', err);- ws.onclose = () => {- if (wsClosed) return;- console.log(`[ws] disconnected, reconnect in ${wsBackoff/1000}s`);- setStatus('down', 'offline');- setTimeout(connect, wsBackoff);- wsBackoff = Math.min(wsBackoff * 1.5, 15000);};}@@ -1268,9 +1381,9 @@}status.pill.addEventListener('click', () => {if (status.pill.dataset.state === 'down') {- wsClosed = false;- wsTries = 0;- wsBackoff = 1000;+ esClosed = false;+ esTries = 0;+ esBackoff = 1000;connect();}});@@ -1446,10 +1559,17 @@firstClaims.el.innerHTML = '<div class="empty">Refreshing…</div>';try {const windowMins = $('fc-window').value || 1440;- const r = await fetch(`/api/pump/first_claims?limit=100&window=${windowMins}`);+ const r = await fetch(`/api/pump/first-claims?limit=50&sinceMinutes=${windowMins}`);if (!r.ok) throw new Error('http ' + r.status);const data = await r.json();- firstClaims.data = data.claims;+ firstClaims.data = (data.items || []).map((it) => ({+ user: it.creator,+ sol: (Number(it.lamports) || 0) / 1e9,+ token_mint: it.mint || '',+ token_name: it.name || (it.mint ? it.mint.slice(0, 4) + '…' + it.mint.slice(-4) : 'unknown'),+ tx_sig: it.signature,+ timestamp: (Number(it.ts) || 0) * 1000,+ }));firstClaims.ts = now;renderFirstClaims();} catch (err) {@@ -1613,7 +1733,6 @@initSidePanel();connect();fetchFirstClaims();- setInterval(() => { if (ws?.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: 'sol-price' })); }, 15_000);</script></body></html>\ No newline at end of filediff --git a/pump-live.html b/pump-live.htmlindex bc1472671..dde6d3880 100644--- a/pump-live.html+++ b/pump-live.html@@ -151,11 +151,12 @@<div id="feed-header"><h2>New Tokens on Pump.fun</h2></div>- <div id="feed" id="log"></div>+ <div id="feed"></div></div></div><script type="module">+ import { LoopOnce, LoopRepeat } from 'three';import { Viewer } from '/src/viewer.js';// ════════════════════════════════════════════════════════════════════@@ -163,34 +164,26 @@// ════════════════════════════════════════════════════════════════════const viewerEl = document.getElementById('viewer-container');- const viewer = new Viewer(viewerEl, {- kiosk: true,- model: '/assets/models/RobotExpressive.glb',- });+ const viewer = new Viewer(viewerEl, { kiosk: true });+ window.viewer = viewer;- viewer.addEventListener('load', () => {- // Play a default animation on loop- const clips = viewer.getClips();- if (clips[5]) { // Assuming 'Idle' is a suitable default- const action = viewer.mixer.clipAction(clips[5]);- action.play();- }- });+ await viewer.load('/animations/robotexpressive.glb', '', new Map());++ const idleClip =+ viewer.clips.find((c) => /^idle$/i.test(c.name)) || viewer.clips[0];+ if (idleClip && viewer.mixer) {+ viewer.mixer.clipAction(idleClip).play();+ }function playAnimation(animationName, { loop = false } = {}) {- const clip = viewer.getClip(animationName);- if (!clip) return;+ const clip = viewer.clips.find((c) => c.name === animationName);+ if (!clip || !viewer.mixer) return;const action = viewer.mixer.clipAction(clip);action.reset();- if (!loop) {- action.loop = THREE.LoopOnce;- action.clampWhenFinished = true;- }+ action.setLoop(loop ? LoopRepeat : LoopOnce, loop ? Infinity : 1);+ action.clampWhenFinished = !loop;action.play();}-- // Expose viewer for debugging- window.viewer = viewer;// ════════════════════════════════════════════════════════════════════// PumpFun Live Token Feed Logic (adapted from original script)@@ -199,7 +192,7 @@const RPC_ENDPOINT = 'wss://pumpportal.fun/api/data';const MAX_FEED_ITEMS = 100;- const $log = document.getElementById('log');+ const $log = document.getElementById('feed');const $status = document.getElementById('status');let ws;diff --git a/src/nich-agent.js b/src/nich-agent.jsindex 6cc53c0be..31587749a 100644--- a/src/nich-agent.js+++ b/src/nich-agent.js@@ -68,7 +68,9 @@ export class NichAgent {this._hasOpened = false;this._apiDisabled = false;this._storageKey = `nich-agent:history:${this.identity?.id || 'default'}`;+ this._modelKey = `nich-agent:model:${this.identity?.id || 'default'}`;this._loadHistory();+ this._loadModelChoice();this._buildUI();if (this.voiceInput) this._initSpeechRecognition();@@ -143,6 +145,12 @@ export class NichAgent {<div class="nich-header"><span class="nich-title">${_escapeHTML(titleText)}</span><div class="nich-header-right">+ <select class="nich-model-select" aria-label="Choose model" title="Choose model">+ ${MODEL_OPTIONS.map(+ (opt) =>+ `<option value="${opt.id}"${opt.id === this._modelChoice ? ' selected' : ''}>${_escapeHTML(opt.label)}</option>`,+ ).join('')}+ </select><span class="nich-emotion-dot" id="nich-emotion-dot" title="Agent emotional state"></span>${this.layout === 'embedded' ? '' : '<button class="nich-close" aria-label="Close">×</button>'}</div>@@ -209,6 +217,13 @@ export class NichAgent {if (e.key === 'Enter') this._send();});this.panel.querySelector('.nich-mic')?.addEventListener('click', () => this._toggleMic());+ this.panel.querySelector('.nich-model-select')?.addEventListener('change', (e) => {+ this._modelChoice = e.target.value;+ try {+ localStorage.setItem(this._modelKey, this._modelChoice);+ } catch {}+ this._apiDisabled = false;+ });}// ── Panel Toggle ──────────────────────────────────────────────────────────@@ -330,6 +345,7 @@ export class NichAgent {messagesEl.appendChild(streamEl);messagesEl.scrollTop = messagesEl.scrollHeight;+ const choice = MODEL_OPTIONS.find((o) => o.id === this._modelChoice);try {const res = await fetch('/api/chat', {method: 'POST',@@ -339,6 +355,7 @@ export class NichAgent {message,context: this._buildContext(),history: this._history.slice(-10),+ ...(choice?.provider ? { provider: choice.provider, model: choice.model } : {}),}),});@@ -587,6 +604,16 @@ export class NichAgent {}}+ _loadModelChoice() {+ this._modelChoice = 'auto';+ try {+ const stored = localStorage.getItem(this._modelKey);+ if (stored && MODEL_OPTIONS.some((o) => o.id === stored)) {+ this._modelChoice = stored;+ }+ } catch {}+ }+_pushHistory(role, content) {this._history.push({ role, content });if (this._history.length > 20) this._history = this._history.slice(-20);@@ -755,3 +782,37 @@ function _escapeHTML(s) {.replace(/"/g, '"').replace(/'/g, ''');}++// Model choices surfaced in the header dropdown. `auto` lets the server pick+// based on which keys are configured (Anthropic → OpenRouter → Groq → OpenAI).+// Free OpenRouter entries are tool-call capable; Gemma/Qwen omitted because+// their tool-calling is unreliable.+const MODEL_OPTIONS = [+ { id: 'auto', label: 'Auto', provider: null, model: null },+ { id: 'anthropic:sonnet', label: 'Claude Sonnet 4.6', provider: 'anthropic', model: 'claude-sonnet-4-6' },+ {+ id: 'openrouter:llama-70b',+ label: 'Llama 3.3 70B (free)',+ provider: 'openrouter',+ model: 'meta-llama/llama-3.3-70b-instruct:free',+ },+ {+ id: 'openrouter:gpt-oss',+ label: 'GPT-OSS 120B (free)',+ provider: 'openrouter',+ model: 'openai/gpt-oss-120b:free',+ },+ {+ id: 'openrouter:hermes',+ label: 'Hermes 3 405B (free)',+ provider: 'openrouter',+ model: 'nousresearch/hermes-3-llama-3.1-405b:free',+ },+ {+ id: 'groq:llama-70b',+ label: 'Groq Llama 3.3 70B',+ provider: 'groq',+ model: 'llama-3.3-70b-versatile',+ },+ { id: 'openai:gpt-4o-mini', label: 'GPT-4o mini', provider: 'openai', model: 'gpt-4o-mini' },+];diff --git a/style.css b/style.cssindex 49f48637f..ee676e2c5 100644--- a/style.css+++ b/style.css@@ -3883,6 +3883,34 @@ body.explore-page {box-shadow 0.4s ease;}+.nich-model-select {+ background: rgba(255, 255, 255, 0.06);+ color: rgba(255, 255, 255, 0.78);+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 6px;+ padding: 2px 6px;+ font-size: 11px;+ font-family: inherit;+ max-width: 150px;+ cursor: pointer;+ outline: none;+ transition: border-color 0.15s ease, background 0.15s ease;+}++.nich-model-select:hover {+ border-color: rgba(255, 255, 255, 0.25);+ background: rgba(255, 255, 255, 0.1);+}++.nich-model-select:focus {+ border-color: var(--nich-accent, rgba(120, 180, 255, 0.6));+}++.nich-model-select option {+ background: #1a1a1a;+ color: #e0e0e0;+}+.nich-toggle-label {font-size: 10px;margin-top: 3px;diff --git a/vite.config.js b/vite.config.jsindex 55e82ef75..5276ab9bb 100644--- a/vite.config.js+++ b/vite.config.js@@ -13,6 +13,12 @@ import { VitePWA } from 'vite-plugin-pwa';// npm run build:all → bothconst TARGET = process.env.TARGET || 'app';+// Vercel serverless functions live under /api/* in production but Vite dev+// does not run them. Forward /api/* to a real upstream (default: production)+// so pages like /pumpfun see real SSE feeds and JSON responses in dev.+// Override with DEV_API_PROXY=http://localhost:3001 to point at vercel-dev.+const DEV_API_PROXY = process.env.DEV_API_PROXY || 'https://three.ws';+const appConfig = {server: {proxy: {@@ -20,6 +26,22 @@ const appConfig = {target: 'http://localhost:5174',changeOrigin: true,},+ '/api': {+ target: DEV_API_PROXY,+ changeOrigin: true,+ secure: true,+ ws: true,+ // SSE responses (text/event-stream) must not be buffered.+ // http-proxy + Node's stream pipe handle this when we don't+ // touch the response, so leave selfHandleResponse off.+ configure: (proxy) => {+ proxy.on('proxyReq', (proxyReq) => {+ // Disable any compression that would force buffering+ // of streaming responses on the upstream side.+ proxyReq.setHeader('accept-encoding', 'identity');+ });+ },+ },},},esbuild: {@@ -138,15 +160,8 @@ const appConfig = {if (url.includes('html-proxy') || url.includes('@id/') || url.includes('@vite/'))return next();const path = url.split('?')[0];- // Vercel serverless functions live under /api/* in production but- // Vite dev does not run them. Return JSON 404 so client fetch()- // callers see a normal "not found" instead of leaking the JS- // source of api/*.js (which crashes JSON.parse with a comment).- if (path.startsWith('/api/')) {- res.statusCode = 404;- res.setHeader('Content-Type', 'application/json');- return res.end('{"error":"api not available in vite dev","path":"' + path + '"}');- }+ // /api/* is handled by the http proxy in server.proxy above —+ // the middleware must not intercept those requests.if (dirRoutes.has(path)) {res.statusCode = 301;res.setHeader('Location', path + '/' + (req.url.slice(path.length) || ''));