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
improving mobile site and more features
nirholas7fe8b8ad4435
diff --git a/api/_lib/embed-policy.js b/api/_lib/embed-policy.jsindex 5b0337396..b84588bec 100644--- a/api/_lib/embed-policy.js+++ b/api/_lib/embed-policy.js@@ -46,11 +46,14 @@ export function defaultEmbedPolicy() {origins: { mode: 'allowlist', hosts: [] },surfaces: { script: true, iframe: true, widget: true, mcp: false },brain: {+ // Default to free OpenRouter Llama 3.3 70B: tool-call capable, no+ // per-token cost to the host, daily rate cap shared across the org+ // key. Owners can switch to a paid Claude model from the dashboard.mode: 'we-pay',proxy_url: null,monthly_quota: 1000,rate_limit_per_min: 10,- model: 'claude-opus-4-6',+ model: 'meta-llama/llama-3.3-70b-instruct:free',},storage: { primary: 'r2', pinned_ipfs: false, onchain_attested: false },};diff --git a/api/_lib/env.js b/api/_lib/env.jsindex 2b8514f0f..f24ac165d 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -75,8 +75,10 @@ export const env = {return trimSlash(opt('AVATURN_API_URL', 'https://api.avaturn.me'));},- // Anthropic API key — used by the we-pay LLM proxy (/api/llm/anthropic).- // Must be set in production; optional in local dev if the proxy is unused.+ // Anthropic API key — required by persona / memory-seeding endpoints+ // and used by the we-pay LLM proxy (/api/llm/anthropic) when an agent+ // selects a Claude model. Free OpenRouter/Groq models routed through+ // the same proxy use OPENROUTER_API_KEY / GROQ_API_KEY instead.get ANTHROPIC_API_KEY() {return req('ANTHROPIC_API_KEY');},diff --git a/api/_lib/render-clip.js b/api/_lib/render-clip.jsnew file mode 100644index 000000000..9fc0ba570--- /dev/null+++ b/api/_lib/render-clip.js@@ -0,0 +1,234 @@+// Server-side renderer for the `render_avatar_clip` MCP tool and+// `/api/render/avatar-clip` HTTP endpoint.+//+// Boots headless chromium via puppeteer-core + @sparticuz/chromium-min,+// loads an inlined three.js viewer that:+// 1. Loads a GLB,+// 2. Optionally applies a pose preset's joint Euler rotations,+// 3. Frames the camera by the model's bounding box plus the requested+// `cameraOrbit` (theta, phi, radius) in degrees / meters,+// 4. Renders one PNG.+//+// The same module powers both transparent OG cards and the full clip+// renderer — single source of truth for headless three.js rendering so the+// MCP tool, the OG card, and any future video renderer share lighting ++// framing.++import puppeteer from 'puppeteer-core';+import chromium from '@sparticuz/chromium-min';+import { env } from './env.js';+import { PRESETS } from '../../src/pose-presets.js';++const DEFAULT_CHROMIUM_PACK =+ 'https://github.com/Sparticuz/chromium/releases/download/v148.0.0/chromium-v148.0.0-pack.x64.tar';+const CHROMIUM_PACK = env.CHROMIUM_PACK_URL || DEFAULT_CHROMIUM_PACK;+const THREE_VERSION = '0.176.0';++let _browserPromise = null;+async function getBrowser() {+ if (_browserPromise) return _browserPromise;+ _browserPromise = (async () => {+ const executablePath = await chromium.executablePath(CHROMIUM_PACK);+ return puppeteer.launch({+ args: chromium.args,+ defaultViewport: { width: 1024, height: 1024, deviceScaleFactor: 1 },+ executablePath,+ headless: chromium.headless,+ });+ })().catch((err) => {+ _browserPromise = null;+ throw err;+ });+ return _browserPromise;+}++function poseById(id) {+ if (!id) return null;+ const found = PRESETS.find((p) => p.id === id);+ return found ? { id: found.id, label: found.label, pose: found.pose } : null;+}++function viewerHtml({ glbUrl, width, height, background, pose, cameraOrbit, expression }) {+ const bg = background === 'transparent' ? 'null' : JSON.stringify(background || '#0a0a0a');+ const poseJson = pose ? JSON.stringify(pose.pose) : 'null';+ const orbitJson = JSON.stringify(cameraOrbit || { theta: 0, phi: 80, radius: null });+ const expressionJson = JSON.stringify(expression || null);+ return `<!doctype html>+<html><head><meta charset="utf-8" />+<style>html,body{margin:0;padding:0;background:transparent;overflow:hidden}</style>+</head><body>+<canvas id="c" width="${width}" height="${height}" style="display:block;width:${width}px;height:${height}px"></canvas>+<script type="importmap">{ "imports": {+ "three": "https://unpkg.com/three@${THREE_VERSION}/build/three.module.js",+ "three/addons/": "https://unpkg.com/three@${THREE_VERSION}/examples/jsm/"+}}</script>+<script type="module">+import * as THREE from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';++window.__renderDone = false;+window.__renderError = null;++const canvas = document.getElementById('c');+const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true, preserveDrawingBuffer: true });+renderer.setSize(${width}, ${height}, false);+renderer.setPixelRatio(1);+renderer.outputColorSpace = THREE.SRGBColorSpace;+renderer.toneMapping = THREE.ACESFilmicToneMapping;+renderer.toneMappingExposure = 1.0;++const scene = new THREE.Scene();+const bgColor = ${bg};+if (bgColor !== null) scene.background = new THREE.Color(bgColor);++const camera = new THREE.PerspectiveCamera(28, ${width}/${height}, 0.01, 100);+scene.add(new THREE.AmbientLight(0xffffff, 0.55));+const key = new THREE.DirectionalLight(0xffffff, 1.4); key.position.set(2, 3, 4); scene.add(key);+const fill = new THREE.DirectionalLight(0xbfd6ff, 0.6); fill.position.set(-3, 1, 2); scene.add(fill);+const rim = new THREE.DirectionalLight(0xc7a8ff, 0.5); rim.position.set(0, 2, -4); scene.add(rim);++const aliases = {+ shoulderl: ['leftshoulder','shoulder_l','l_shoulder','mixamorig:leftshoulder'],+ shoulderr: ['rightshoulder','shoulder_r','r_shoulder','mixamorig:rightshoulder'],+ elbowl: ['leftforearm','leftelbow','elbow_l','mixamorig:leftforearm','mixamorig:leftelbow'],+ elbowr: ['rightforearm','rightelbow','elbow_r','mixamorig:rightforearm','mixamorig:rightelbow'],+ wristl: ['lefthand','wrist_l','mixamorig:lefthand'],+ wristr: ['righthand','wrist_r','mixamorig:righthand'],+ hipl: ['leftupleg','hip_l','mixamorig:leftupleg'],+ hipr: ['rightupleg','hip_r','mixamorig:rightupleg'],+ kneel: ['leftleg','knee_l','mixamorig:leftleg'],+ kneer: ['rightleg','knee_r','mixamorig:rightleg'],+ anklel: ['leftfoot','ankle_l','mixamorig:leftfoot'],+ ankler: ['rightfoot','ankle_r','mixamorig:rightfoot'],+ head: ['head','mixamorig:head'],+ neck: ['neck','mixamorig:neck'],+ spine: ['spine','spine1','mixamorig:spine','mixamorig:spine1'],+ hips: ['hips','mixamorig:hips'],+};++function applyPose(root, poseMap) {+ if (!poseMap) return;+ const byName = new Map();+ root.traverse((o) => { if (o.name) byName.set(o.name.toLowerCase(), o); });+ function findJoint(k) {+ const key = k.toLowerCase();+ const direct = byName.get(key);+ if (direct) return direct;+ const list = aliases[key] || [];+ for (const a of list) { const j = byName.get(a); if (j) return j; }+ return null;+ }+ for (const [key, rot] of Object.entries(poseMap)) {+ const joint = findJoint(key);+ if (!joint) continue;+ joint.rotation.set(rot.x || 0, rot.y || 0, rot.z || 0);+ }+}++function applyExpression(root, expression) {+ if (!expression || typeof expression !== 'object') return;+ root.traverse((o) => {+ if (!o.isMesh || !o.morphTargetDictionary || !o.morphTargetInfluences) return;+ for (const [name, value] of Object.entries(expression)) {+ const idx = o.morphTargetDictionary[name] ?? o.morphTargetDictionary[name.toLowerCase()];+ if (typeof idx === 'number') o.morphTargetInfluences[idx] = Number(value) || 0;+ }+ });+}++function frameCamera(root, orbit) {+ const box = new THREE.Box3().setFromObject(root);+ const size = new THREE.Vector3(); box.getSize(size);+ const center = new THREE.Vector3(); box.getCenter(center);+ root.position.sub(center);+ root.position.y += size.y * 0.05;+ const maxDim = Math.max(size.x, size.y, size.z);+ const fov = THREE.MathUtils.degToRad(camera.fov);+ const defaultDist = (maxDim / 2) / Math.tan(fov / 2) * 1.45;+ const radius = (typeof orbit.radius === 'number' && orbit.radius > 0) ? orbit.radius : defaultDist;+ const theta = THREE.MathUtils.degToRad(Number(orbit.theta) || 0);+ const phi = THREE.MathUtils.degToRad(Number(orbit.phi) || 80);+ const x = radius * Math.sin(phi) * Math.sin(theta);+ const y = radius * Math.cos(phi);+ const z = radius * Math.sin(phi) * Math.cos(theta);+ camera.position.set(x, y, z);+ camera.lookAt(0, 0, 0);+}++const orbit = ${orbitJson};+const poseMap = ${poseJson};+const expression = ${expressionJson};++new GLTFLoader().load(${JSON.stringify(glbUrl)}, (gltf) => {+ try {+ const root = gltf.scene;+ scene.add(root);+ applyPose(root, poseMap);+ applyExpression(root, expression);+ frameCamera(root, orbit);+ renderer.render(scene, camera);+ requestAnimationFrame(() => {+ renderer.render(scene, camera);+ window.__renderDone = true;+ });+ } catch (err) {+ window.__renderError = err.message || String(err);+ }+}, undefined, (err) => {+ window.__renderError = 'glb load failed: ' + (err?.message || err);+});+</script></body></html>`;+}++/**+ * Render a GLB to a PNG buffer with optional pose preset and camera orbit.+ *+ * @param {object} opts+ * @param {string} opts.glbUrl+ * @param {number} [opts.width=1024]+ * @param {number} [opts.height=1024]+ * @param {string} [opts.background='#0a0a0a']+ * @param {string} [opts.posePresetId]+ * @param {{theta?:number,phi?:number,radius?:number}} [opts.cameraOrbit]+ * @param {Object<string,number>} [opts.expression]+ * @returns {Promise<{png:Buffer,pose:object|null}>}+ */+export async function renderClip({+ glbUrl,+ width = 1024,+ height = 1024,+ background = '#0a0a0a',+ posePresetId = null,+ cameraOrbit = null,+ expression = null,+} = {}) {+ if (!glbUrl || typeof glbUrl !== 'string') {+ throw Object.assign(new Error('glbUrl required'), { status: 400, code: 'invalid_args' });+ }+ const W = Math.max(64, Math.min(2048, Number(width) || 1024));+ const H = Math.max(64, Math.min(2048, Number(height) || 1024));+ const pose = poseById(posePresetId);+ const browser = await getBrowser();+ const page = await browser.newPage();+ try {+ await page.setViewport({ width: W, height: H, deviceScaleFactor: 1 });+ const html = viewerHtml({ glbUrl, width: W, height: H, background, pose, cameraOrbit, expression });+ await page.setContent(html, { waitUntil: 'domcontentloaded' });+ await page.waitForFunction(+ 'window.__renderDone === true || window.__renderError !== null',+ { timeout: 20_000 },+ );+ const err = await page.evaluate(() => window.__renderError);+ if (err) {+ throw Object.assign(new Error(`render failed: ${err}`), { status: 502, code: 'render_failed' });+ }+ const png = await page.screenshot({+ type: 'png',+ omitBackground: background === 'transparent',+ clip: { x: 0, y: 0, width: W, height: H },+ });+ return { png, pose };+ } finally {+ await page.close().catch(() => {});+ }+}diff --git a/api/agents/talk.js b/api/agents/talk.jsnew file mode 100644index 000000000..2190c1350--- /dev/null+++ b/api/agents/talk.js@@ -0,0 +1,123 @@+// POST /api/agents/talk+//+// Open agent-conversation endpoint, the public counterpart to+// /api/agent-delegate.js. The original endpoint required session auth and+// was scoped to user-owned agents; this one is auth-optional and is+// callable from the paid `agent_delegate_action` MCP tool (which gates+// access via x402 USDC payment).+//+// Body:+// { agentId: string, message: string, model?: string }+//+// Response:+// { ok, agentId, agentName, response, model, durationMs, fetchedAt }+//+// Safety: agents with surfaces.mcp === false (their owner's embed policy)+// are refused — owners can opt their agent out of public MCP use.++import { z } from 'zod';+import { sql } from '../_lib/db.js';+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { normalizeLegacyPolicy } from '../_lib/embed-policy.js';+import { env } from '../_lib/env.js';++const ALLOWED_MODELS = new Set([+ 'claude-haiku-4-5-20251001',+ 'claude-sonnet-4-5',+ 'claude-sonnet-4-6',+ 'claude-opus-4-7',+ 'claude-3-5-haiku-20241022',+]);++const bodySchema = z.object({+ agentId: z.string().min(1).max(120),+ message: z.string().min(1).max(4000),+ model: z.string().min(1).max(100).optional(),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: false })) return;+ if (!method(req, res, ['POST'])) return;++ if (parseInt(req.headers['x-delegate-depth'] || '0', 10) > 0) {+ return error(res, 400, 'recursion_denied', 'nested agent delegation is not allowed');+ }++ const rl = await limits.agentDelegate(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'agent delegate rate limit');++ let raw;+ try {+ raw = await readJson(req);+ } catch {+ return error(res, 400, 'invalid_json', 'body must be JSON');+ }+ const parsed = bodySchema.safeParse(raw);+ if (!parsed.success) {+ return error(res, 400, 'validation_error', parsed.error.issues[0]?.message ?? 'invalid body');+ }+ const { agentId, message, model: requestedModel } = parsed.data;++ const [agent] = await sql`+ SELECT id, name, description, embed_policy, meta+ FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 404, 'agent_not_found', 'agent not found');++ const policy = normalizeLegacyPolicy(agent.embed_policy);+ if (policy?.surfaces?.mcp === false) {+ return error(res, 403, 'mcp_disabled', 'this agent has opted out of MCP delegation');+ }++ const defaultModel = policy?.brain?.model || 'claude-haiku-4-5-20251001';+ const model = requestedModel && ALLOWED_MODELS.has(requestedModel) ? requestedModel : defaultModel;++ const systemPrompt =+ agent.meta?.brain?.instructions ||+ `You are ${agent.name}. ${agent.description || ''}`.trim();++ if (!env.ANTHROPIC_API_KEY) {+ return error(res, 503, 'not_configured', 'agent delegation is unavailable: ANTHROPIC_API_KEY not configured');+ }++ const started = Date.now();+ let upstream;+ try {+ upstream = await fetch('https://api.anthropic.com/v1/messages', {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ 'anthropic-version': '2023-06-01',+ 'x-api-key': env.ANTHROPIC_API_KEY,+ 'x-delegate-depth': '1',+ },+ body: JSON.stringify({+ model,+ max_tokens: 1024,+ system: systemPrompt,+ messages: [{ role: 'user', content: message }],+ }),+ });+ } catch (err) {+ return error(res, 502, 'upstream_unreachable', err?.message || 'anthropic fetch failed');+ }+ if (!upstream.ok) {+ const msg = await upstream.text().catch(() => '');+ return error(res, 502, 'upstream_error', `LLM call failed: ${upstream.status} ${msg.slice(0, 200)}`);+ }+ const data = await upstream.json().catch(() => ({}));+ const response = data?.content?.[0]?.text || '';++ return json(res, 200, {+ ok: true,+ agentId: agent.id,+ agentName: agent.name,+ response,+ model,+ usage: data?.usage || null,+ durationMs: Date.now() - started,+ fetchedAt: new Date().toISOString(),+ });+});diff --git a/api/chat-skills.js b/api/chat-skills.jsnew file mode 100644index 000000000..ad14049cb--- /dev/null+++ b/api/chat-skills.js@@ -0,0 +1,119 @@+// GET /api/chat-skills - rich local-skill feed for the chat Skills modal.+//+// Returns a normalized list that combines:+// 1. In-code AgentSkills (66+) - MCP-exposed handlers, surfaced as+// installable tool packs whose clientDefinition.body POSTs to /api/mcp.+// 2. SKILL.md packs on disk (.agents/skills, pump-fun-skills,+// public/skills, examples/skills) - surfaced as knowledge skills+// whose body is injected into the system prompt on install.+//+// Kept separate from /api/skills-manifest (which preserves the simpler+// machine-readable shape consumed by external manifest readers).++import { readFileSync } from 'fs';+import { cors, json, method, wrap } from './_lib/http.js';+import { AgentSkills } from '../src/agent-skills.js';+import { loadLocalSkillPacks } from '../src/skills/local-packs.js';++const { version } = JSON.parse(+ readFileSync(new URL('../package.json', import.meta.url), 'utf8'),+);++const _noop = () => {};+const _stub = { emit: _noop, on: _noop, off: _noop, add: _noop, query: () => [] };+const _skills = new AgentSkills(_stub, _stub);++function mcpToolNameFor(skillName) {+ return `skill_${skillName.replace(/[-.]/g, '_')}`;+}++function buildClientToolFor(skill) {+ const mcpName = mcpToolNameFor(skill.name);+ const inputSchema = skill.inputSchema || { type: 'object', properties: {} };+ const argsList = Object.entries(inputSchema.properties || {}).map(([k, p]) => ({+ name: k,+ type: p.type || 'any',+ description: p.description || '',+ }));+ const body = [+ "const _r = await fetch('/api/mcp', {",+ " method: 'POST',",+ " headers: { 'content-type': 'application/json' },",+ " credentials: 'include',",+ " body: JSON.stringify({",+ " jsonrpc: '2.0', id: 1, method: 'tools/call',",+ ` params: { name: ${JSON.stringify(mcpName)}, arguments: args || {} },`,+ " }),",+ "});",+ "const _t = await _r.text();",+ "let _d = null; try { _d = _t ? JSON.parse(_t) : null; } catch {}",+ "if (!_r.ok) return JSON.stringify({ error: (_d && (_d.error?.message || _d.error)) || ('HTTP ' + _r.status) });",+ "if (_d && _d.error) return JSON.stringify({ error: _d.error.message || _d.error });",+ "const _c = _d && _d.result && _d.result.content;",+ "if (Array.isArray(_c)) return _c.map(x => x.text || JSON.stringify(x)).join('\\n');",+ "return JSON.stringify(_c ?? _d ?? null, null, 2);",+ ].join('\n');+ return {+ clientDefinition: {+ id: `local-skill-${skill.name}`,+ name: skill.name,+ description: skill.description,+ arguments: argsList,+ body,+ },+ type: 'function',+ function: {+ name: skill.name,+ description: skill.description,+ parameters: inputSchema,+ },+ };+}++function buildAgentRuntimeEntries() {+ const out = [];+ for (const skill of _skills.list()) {+ if (!skill.description) continue;+ const base = {+ id: `local:agent-runtime:${skill.name}`,+ source: 'agent-runtime',+ category: 'agent-runtime',+ name: skill.name,+ slug: skill.name,+ description: skill.description,+ mcp_exposed: !!skill.mcpExposed,+ };+ if (skill.mcpExposed) {+ out.push({ ...base, kind: 'tool', schema_json: [buildClientToolFor(skill)] });+ } else {+ out.push({ ...base, kind: 'tool', schema_json: [], unavailable: true });+ }+ }+ return out;+}++let _cache = null;+function build() {+ if (_cache) return _cache;+ const runtime = buildAgentRuntimeEntries();+ const packs = loadLocalSkillPacks();+ const all = [...runtime, ...packs];+ _cache = {+ agent: { id: '3d-agent', version },+ skills: all,+ sources: {+ 'agent-runtime': runtime,+ 'agentic-wallet': packs.filter((p) => p.source === 'agentic-wallet'),+ 'pump-fun-skills': packs.filter((p) => p.source === 'pump-fun-skills'),+ 'public-skills': packs.filter((p) => p.source === 'public-skills'),+ examples: packs.filter((p) => p.source === 'examples'),+ },+ };+ return _cache;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;+ return json(res, 200, build(), { 'cache-control': 'public, max-age=60' });+});diff --git a/api/llm/anthropic.js b/api/llm/anthropic.jsindex 87f70a32d..36f0515e4 100644--- a/api/llm/anthropic.js+++ b/api/llm/anthropic.js@@ -1,5 +1,14 @@-// We-pay LLM proxy: forwards Anthropic messages requests on behalf of an agent-// after enforcing embed-policy (brain.mode, origins, surfaces) and quota/rate limits.+// We-pay LLM proxy. The browser always sends an Anthropic-shape body+// ({ system, messages, tools, model, ... }) regardless of the upstream+// model — this file inspects `model` and either forwards to Anthropic+// unchanged, or translates request/response to/from the OpenAI shape+// used by Groq and OpenRouter. Embed-policy origin / quota / rate-limit+// checks run identically for every route.+//+// Why "everything as Anthropic-shape": the browser-side AnthropicProvider+// (src/runtime/providers.js) parses Anthropic SSE events directly. Hiding+// the upstream difference here means free-tier Groq/OpenRouter models work+// in every avatar embed without changing a line of client code.import { z } from 'zod';import { Redis } from '@upstash/redis';@@ -25,22 +34,40 @@ function getRedis() {return _redis;}-// ── Helpers ───────────────────────────────────────────────────────────────────+// ── Model → upstream routing ─────────────────────────────────────────────────+//+// Adding a model: append it here. `kind` decides how the request body and+// response stream are shaped. Groq/OpenRouter both speak OpenAI's wire+// format so they share the 'openai' branch; only the upstream URL and the+// env var differ.++const MODELS = {+ // Anthropic (paid — host's key)+ 'claude-opus-4-7': { kind: 'anthropic', envKey: 'ANTHROPIC_API_KEY' },+ 'claude-opus-4-6': { kind: 'anthropic', envKey: 'ANTHROPIC_API_KEY' },+ 'claude-sonnet-4-6': { kind: 'anthropic', envKey: 'ANTHROPIC_API_KEY' },+ 'claude-haiku-4-5-20251001': { kind: 'anthropic', envKey: 'ANTHROPIC_API_KEY' },++ // OpenRouter free tier (no per-token cost; daily rate cap shared across host).+ // All three are tool-call capable in OpenRouter's catalog.+ 'meta-llama/llama-3.3-70b-instruct:free': { kind: 'openai', provider: 'openrouter', envKey: 'OPENROUTER_API_KEY' },+ 'openai/gpt-oss-120b:free': { kind: 'openai', provider: 'openrouter', envKey: 'OPENROUTER_API_KEY' },+ 'nousresearch/hermes-3-llama-3.1-405b:free': { kind: 'openai', provider: 'openrouter', envKey: 'OPENROUTER_API_KEY' },++ // Groq free tier (sub-second latency; per-IP+per-key minute caps).+ 'llama-3.3-70b-versatile': { kind: 'openai', provider: 'groq', envKey: 'GROQ_API_KEY' },+ 'llama-3.1-8b-instant': { kind: 'openai', provider: 'groq', envKey: 'GROQ_API_KEY' },+};++const UPSTREAM_URL = {+ anthropic: 'https://api.anthropic.com/v1/messages',+ openrouter: 'https://openrouter.ai/api/v1/chat/completions',+ groq: 'https://api.groq.com/openai/v1/chat/completions',+};-const MODEL_ALLOWLIST = new Set([- 'claude-opus-4-6',- 'claude-opus-4-7',- 'claude-sonnet-4-6',- 'claude-haiku-4-5-20251001',-]);--// First-party hostnames always pass origin checks (same as element.js).const FIRST_PARTY = ['three.ws', 'localhost'];-// Default per-agent monthly token budget when policy.brain.cost_limit_cents is unset.const DEFAULT_MONTHLY_TOKEN_BUDGET = 1_000_000;-// Rough cents-per-token conversion when a cost budget is provided. Conservative-// blended estimate across input+output for the allowlisted models.const CENTS_PER_1K_TOKENS = 1.5;function tokenBudgetFromPolicy(policy) {@@ -57,7 +84,7 @@ function monthKey() {}function originAllowed(originHeader, policy) {- if (!originHeader) return true; // server-to-server / curl — allow+ if (!originHeader) return true;let host;try {host = new URL(originHeader).hostname.toLowerCase();@@ -75,8 +102,6 @@ function originAllowed(originHeader, policy) {return mode === 'allowlist' ? matches : !matches;}-// Build the strict CORS allowlist: first-party origins + any origin the agent's-// embed policy declares. Returns an array of exact-match origin strings.function buildCorsAllowlist(policy) {const out = new Set();if (env.APP_ORIGIN) out.add(env.APP_ORIGIN);@@ -85,12 +110,10 @@ function buildCorsAllowlist(policy) {} catch {// ISSUER derives from APP_ORIGIN; ignore if unset.}- // Localhost for dev parity with the same-origin check above.const hosts = policy?.origins?.hosts ?? [];for (const h of hosts) {const lower = String(h).toLowerCase();if (lower.startsWith('*.')) {- // Wildcard — convert to a regex matching https://<sub>.<base>.const base = lower.slice(2).replace(/[.+?^${}()|[\]\\]/g, '\\$&');out.add(new RegExp(`^https?://([a-z0-9-]+\\.)+${base}$`));} else {@@ -98,7 +121,6 @@ function buildCorsAllowlist(policy) {out.add(`http://${lower}`);}}- // Allow localhost only outside production, matching isAllowedOrigin's default.if (process.env.NODE_ENV !== 'production') {out.add(/^https?:\/\/localhost(:\d+)?$/);}@@ -107,15 +129,13 @@ function buildCorsAllowlist(policy) {async function incrementMonthlyQuota(agentId) {const r = getRedis();- if (!r) return 0; // no Redis → quota not enforced+ if (!r) return 0;const key = `llm:quota:${agentId}:${monthKey()}`;const count = await r.incr(key);- if (count === 1) await r.expire(key, 40 * 24 * 3600); // expire after 40 days+ if (count === 1) await r.expire(key, 40 * 24 * 3600);return count;}-// Peek at the current month's token total without incrementing. Returns 0 when-// Redis is unavailable (quota not enforced).async function getMonthlyTokens(agentId) {const r = getRedis();if (!r) return 0;@@ -135,10 +155,7 @@ async function addMonthlyTokens(agentId, delta) {// ── Request schema ────────────────────────────────────────────────────────────-const messageContentSchema = z.union([- z.string(),- z.array(z.any()), // Anthropic content blocks; pass through-]);+const messageContentSchema = z.union([z.string(), z.array(z.any())]);const bodySchema = z.object({system: z.string().max(64_000).optional(),@@ -162,14 +179,9 @@ const bodySchema = z.object({// ── Handler ───────────────────────────────────────────────────────────────────export default wrap(async (req, res) => {- // Resolve the agent up front so CORS can use the agent's embed policy.const url = new URL(req.url, 'http://x');const agentId = url.searchParams.get('agent');- // Load policy first (when possible) so CORS allowlist can include the- // agent-declared origins. If no agent is supplied or not found, fall back- // to first-party only — the preflight will then be rejected for unknown- // third-party origins, which is the desired hardening.let policy = null;if (agentId) policy = await readEmbedPolicy(agentId);@@ -193,29 +205,20 @@ export default wrap(async (req, res) => {return error(res, 403, 'embed_denied_surface', 'script surface disabled for this agent');}- // 2. Origin / Referer checkconst originHeader = req.headers.origin || req.headers.referer || '';if (!originAllowed(originHeader, policy)) {- return error(- res,- 403,- 'embed_denied_origin',- "origin not permitted by this agent's embed policy",- );+ return error(res, 403, 'embed_denied_origin', "origin not permitted by this agent's embed policy");}- // 3. Per-IP rate limitconst ipRl = await limits.embedLlmIp(clientIp(req));if (!ipRl.success) return error(res, 429, 'rate_limited', 'too many requests from this IP');- // 4. Per-agent rate limit (dynamic, from policy)const perMin = policy.brain?.rate_limit_per_min;if (perMin && perMin > 0) {const agentRl = await limits.embedLlmAgent(agentId, perMin);if (!agentRl.success) return error(res, 429, 'rate_limited', 'agent rate limit exceeded');}- // 5a. Monthly call-count quota (existing)const quota = policy.brain?.monthly_quota;if (typeof quota === 'number' && quota !== null) {const used = await incrementMonthlyQuota(agentId);@@ -224,84 +227,113 @@ export default wrap(async (req, res) => {}}- // 5b. Monthly token budget (input+output). Check before forwarding; debit- // the actual usage after the upstream response so we never under-count but- // may serve one request that tips over — acceptable for a soft budget.const tokenBudget = tokenBudgetFromPolicy(policy);const tokensUsedSoFar = await getMonthlyTokens(agentId);if (tokensUsedSoFar >= tokenBudget) {return error(res, 429, 'quota_exceeded', `monthly token budget of ${tokenBudget} reached`);}- // 6. Validate + normalize request bodyconst rawBody = await readJson(req);const body = parse(bodySchema, rawBody);- const model = body.model || policy.brain?.model || 'claude-opus-4-6';- if (!MODEL_ALLOWLIST.has(model)) {+ const model = body.model || policy.brain?.model || 'meta-llama/llama-3.3-70b-instruct:free';+ const route = MODELS[model];+ if (!route) {return error(res, 400, 'validation_error', `model "${model}" not in allowlist`);}- const isStreaming = body.stream === true;+ const apiKey = process.env[route.envKey];+ if (!apiKey) {+ return error(res, 503, 'provider_unavailable', `${route.envKey} not configured on host`);+ }- // 7. Forward to Anthropic+ const isStreaming = body.stream === true;const t0 = Date.now();- const upstream = await fetch('https://api.anthropic.com/v1/messages', {++ const upstreamUrl = route.kind === 'anthropic' ? UPSTREAM_URL.anthropic : UPSTREAM_URL[route.provider];+ const upstreamHeaders =+ route.kind === 'anthropic'+ ? {+ 'content-type': 'application/json',+ 'anthropic-version': '2023-06-01',+ 'x-api-key': apiKey,+ }+ : {+ 'content-type': 'application/json',+ authorization: `Bearer ${apiKey}`,+ ...(route.provider === 'openrouter'+ ? { 'HTTP-Referer': 'https://three.ws', 'X-Title': 'three.ws agent' }+ : {}),+ };+ const upstreamBody =+ route.kind === 'anthropic'+ ? JSON.stringify({ ...body, model })+ : JSON.stringify(anthropicBodyToOpenAI({ ...body, model }));++ const upstream = await fetch(upstreamUrl, {method: 'POST',- headers: {- 'content-type': 'application/json',- 'anthropic-version': '2023-06-01',- 'x-api-key': env.ANTHROPIC_API_KEY,- },- body: JSON.stringify({ ...body, model }),+ headers: upstreamHeaders,+ body: upstreamBody,});- // 8a. Sanitize upstream errors before branching — do not forward Anthropic's error JSON.if (upstream.status >= 400) {const errText = await upstream.text();- log.error('upstream_error', { agentId, model, status: upstream.status, body: errText.slice(0, 2000) });+ log.error('upstream_error', {+ agentId,+ model,+ kind: route.kind,+ provider: route.provider || 'anthropic',+ status: upstream.status,+ body: errText.slice(0, 2000),+ });return json(res, 502, { error: 'upstream_error', status: upstream.status });}- // 8b. Streaming path — pipe SSE chunks directly; extract token counts in-flight.+ // ── Streaming path ────────────────────────────────────────────────────────if (isStreaming) {- res.statusCode = upstream.status;+ res.statusCode = 200;res.setHeader('content-type', 'text/event-stream');res.setHeader('cache-control', 'no-cache');res.setHeader('x-accel-buffering', 'no');- const reader = upstream.body.getReader();- const decoder = new TextDecoder();let inputTokens = 0;let outputTokens = 0;- let sseBuffer = '';- try {- while (true) {- const { done, value } = await reader.read();- if (done) break;- res.write(value);-- // Parse SSE lines for usage events without buffering the whole body.- sseBuffer += decoder.decode(value, { stream: true });- const lines = sseBuffer.split('\n');- sseBuffer = lines.pop(); // keep the incomplete trailing line- for (const line of lines) {- if (!line.startsWith('data: ')) continue;- try {- const ev = JSON.parse(line.slice(6));- if (ev.type === 'message_start') inputTokens = ev.message?.usage?.input_tokens ?? 0;- if (ev.type === 'message_delta') outputTokens = ev.usage?.output_tokens ?? 0;- } catch {- // not every data line is JSON (e.g. [DONE]) — skip+ if (route.kind === 'anthropic') {+ // Pass upstream Anthropic SSE through verbatim; sniff usage events+ // for token accounting.+ const reader = upstream.body.getReader();+ const decoder = new TextDecoder();+ let sseBuffer = '';+ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ res.write(value);+ sseBuffer += decoder.decode(value, { stream: true });+ const lines = sseBuffer.split('\n');+ sseBuffer = lines.pop();+ for (const line of lines) {+ if (!line.startsWith('data: ')) continue;+ try {+ const ev = JSON.parse(line.slice(6));+ if (ev.type === 'message_start') inputTokens = ev.message?.usage?.input_tokens ?? 0;+ if (ev.type === 'message_delta') outputTokens = ev.usage?.output_tokens ?? 0;+ } catch {+ // not every data line is JSON (e.g. [DONE]) — skip+ }}}+ } finally {+ res.end();}- } finally {- res.end();+ } else {+ // OpenAI-shape upstream → translate to Anthropic SSE shape on the fly.+ const usage = await pipeOpenAIAsAnthropic(upstream, res, { model });+ inputTokens = usage.inputTokens;+ outputTokens = usage.outputTokens;}const latencyMs = Date.now() - t0;-if (inputTokens || outputTokens) {try {await addMonthlyTokens(agentId, inputTokens + outputTokens);@@ -309,21 +341,19 @@ export default wrap(async (req, res) => {log.warn('token_counter_write_failed', { agentId, msg: err?.message });}}-recordEvent({kind: 'llm',- tool: 'anthropic.messages',+ tool: route.kind === 'anthropic' ? 'anthropic.messages' : `${route.provider}.chat`,agentId,bytes: 0,latencyMs,status: 'ok',meta: { model, input_tokens: inputTokens, output_tokens: outputTokens, upstream_status: upstream.status },});-return;}- // 8c. Non-streaming path — buffer and parse as before.+ // ── Non-streaming path ────────────────────────────────────────────────────const upstreamText = await upstream.text();const latencyMs = Date.now() - t0;@@ -331,10 +361,24 @@ export default wrap(async (req, res) => {try {upstreamJson = JSON.parse(upstreamText);} catch {- // Non-JSON body — treated as an opaque upstream failure below.+ // Non-JSON body — leave as opaque pass-through.+ }++ let inputTokens = 0;+ let outputTokens = 0;+ let outBody = upstreamText;+ let outContentType = upstream.headers.get('content-type') || 'application/json';++ if (route.kind === 'anthropic') {+ inputTokens = upstreamJson?.usage?.input_tokens ?? 0;+ outputTokens = upstreamJson?.usage?.output_tokens ?? 0;+ } else if (upstreamJson) {+ inputTokens = upstreamJson?.usage?.prompt_tokens ?? 0;+ outputTokens = upstreamJson?.usage?.completion_tokens ?? 0;+ const translated = openAIResponseToAnthropic(upstreamJson, { model });+ outBody = JSON.stringify(translated);+ outContentType = 'application/json';}- const inputTokens = upstreamJson?.usage?.input_tokens ?? 0;- const outputTokens = upstreamJson?.usage?.output_tokens ?? 0;if (inputTokens || outputTokens) {try {@@ -344,24 +388,308 @@ export default wrap(async (req, res) => {}}- // 9. Record usage (fire-and-forget)recordEvent({kind: 'llm',- tool: 'anthropic.messages',+ tool: route.kind === 'anthropic' ? 'anthropic.messages' : `${route.provider}.chat`,agentId,bytes: upstreamText.length,latencyMs,status: 'ok',- meta: {- model,- input_tokens: inputTokens,- output_tokens: outputTokens,- upstream_status: upstream.status,- },+ meta: { model, input_tokens: inputTokens, output_tokens: outputTokens, upstream_status: upstream.status },});- // 10. Proxy Anthropic's successful response faithfully (unchanged shape).- res.statusCode = upstream.status;- res.setHeader('content-type', upstream.headers.get('content-type') || 'application/json');- return res.end(upstreamText);+ res.statusCode = 200;+ res.setHeader('content-type', outContentType);+ return res.end(outBody);});++// ── Shape translation: Anthropic ⇄ OpenAI ────────────────────────────────────++function anthropicBodyToOpenAI(body) {+ const messages = [];+ if (body.system) messages.push({ role: 'system', content: body.system });++ for (const m of body.messages) {+ if (typeof m.content === 'string') {+ messages.push({ role: m.role, content: m.content });+ continue;+ }+ if (!Array.isArray(m.content)) continue;++ if (m.role === 'user') {+ const textParts = [];+ for (const block of m.content) {+ if (block?.type === 'text' && typeof block.text === 'string') {+ textParts.push(block.text);+ } else if (block?.type === 'tool_result') {+ messages.push({+ role: 'tool',+ tool_call_id: block.tool_use_id,+ content:+ typeof block.content === 'string'+ ? block.content+ : JSON.stringify(block.content ?? ''),+ });+ }+ }+ if (textParts.length) messages.push({ role: 'user', content: textParts.join('\n') });+ } else if (m.role === 'assistant') {+ const textParts = [];+ const toolCalls = [];+ for (const block of m.content) {+ if (block?.type === 'text' && typeof block.text === 'string') {+ textParts.push(block.text);+ } else if (block?.type === 'tool_use') {+ toolCalls.push({+ id: block.id,+ type: 'function',+ function: {+ name: block.name,+ arguments: JSON.stringify(block.input ?? {}),+ },+ });+ }+ }+ const msg = { role: 'assistant', content: textParts.join('\n') || null };+ if (toolCalls.length) msg.tool_calls = toolCalls;+ messages.push(msg);+ }+ }++ const out = {+ model: body.model,+ max_tokens: body.max_tokens ?? 4096,+ messages,+ stream: !!body.stream,+ };+ if (typeof body.temperature === 'number') out.temperature = body.temperature;++ if (Array.isArray(body.tools) && body.tools.length) {+ out.tools = body.tools.map((t) => ({+ type: 'function',+ function: {+ name: t.name,+ description: t.description,+ parameters: t.input_schema,+ },+ }));+ out.tool_choice = 'auto';+ }+ return out;+}++function openAIResponseToAnthropic(resp, { model }) {+ const choice = resp?.choices?.[0];+ const msg = choice?.message || {};+ const content = [];+ if (typeof msg.content === 'string' && msg.content.length) {+ content.push({ type: 'text', text: msg.content });+ }+ for (const tc of msg.tool_calls || []) {+ let input = {};+ try {+ input = tc.function?.arguments ? JSON.parse(tc.function.arguments) : {};+ } catch {+ input = {};+ }+ content.push({ type: 'tool_use', id: tc.id, name: tc.function?.name, input });+ }+ return {+ id: resp.id || `msg_${Date.now()}`,+ type: 'message',+ role: 'assistant',+ model,+ content,+ stop_reason: choice?.finish_reason === 'tool_calls' ? 'tool_use' : 'end_turn',+ stop_sequence: null,+ usage: {+ input_tokens: resp?.usage?.prompt_tokens ?? 0,+ output_tokens: resp?.usage?.completion_tokens ?? 0,+ },+ };+}++// Stream an OpenAI-shape SSE upstream into the client as Anthropic-shape SSE.+// Returns { inputTokens, outputTokens } extracted from the final usage event.+async function pipeOpenAIAsAnthropic(upstream, res, { model }) {+ const reader = upstream.body.getReader();+ const decoder = new TextDecoder();+ let buf = '';++ let inputTokens = 0;+ let outputTokens = 0;++ const messageId = `msg_${Date.now()}`;+ let messageStartSent = false;+ let textBlockOpen = false;+ let textIndex = 0;+ // Map OpenAI tool-call index → { anthropicIndex, started, finished, name, id, argsBuf }+ const toolBlocks = new Map();+ let nextBlockIndex = 1; // index 0 reserved for the text block+ let stopReason = 'end_turn';++ function write(obj, eventName) {+ const evt = eventName ? `event: ${eventName}\n` : '';+ res.write(`${evt}data: ${JSON.stringify(obj)}\n\n`);+ }++ function ensureMessageStart() {+ if (messageStartSent) return;+ messageStartSent = true;+ write(+ {+ type: 'message_start',+ message: {+ id: messageId,+ type: 'message',+ role: 'assistant',+ content: [],+ model,+ stop_reason: null,+ stop_sequence: null,+ usage: { input_tokens: 0, output_tokens: 0 },+ },+ },+ 'message_start',+ );+ }++ function ensureTextBlockStart() {+ ensureMessageStart();+ if (textBlockOpen) return;+ textBlockOpen = true;+ textIndex = 0;+ write(+ {+ type: 'content_block_start',+ index: textIndex,+ content_block: { type: 'text', text: '' },+ },+ 'content_block_start',+ );+ }++ function closeTextBlockIfOpen() {+ if (!textBlockOpen) return;+ write({ type: 'content_block_stop', index: textIndex }, 'content_block_stop');+ textBlockOpen = false;+ }++ function startToolBlock(slot, openAIToolCall) {+ ensureMessageStart();+ closeTextBlockIfOpen();+ slot.anthropicIndex = nextBlockIndex++;+ slot.started = true;+ slot.id = openAIToolCall.id || `tool_${slot.anthropicIndex}`;+ slot.name = openAIToolCall.function?.name || slot.name || '';+ write(+ {+ type: 'content_block_start',+ index: slot.anthropicIndex,+ content_block: { type: 'tool_use', id: slot.id, name: slot.name, input: {} },+ },+ 'content_block_start',+ );+ }++ function finishToolBlocks() {+ for (const slot of toolBlocks.values()) {+ if (slot.started && !slot.finished) {+ write({ type: 'content_block_stop', index: slot.anthropicIndex }, 'content_block_stop');+ slot.finished = true;+ }+ }+ }++ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ buf += decoder.decode(value, { stream: true });+ const lines = buf.split('\n');+ buf = lines.pop();+ for (const rawLine of lines) {+ const line = rawLine.trim();+ if (!line.startsWith('data:')) continue;+ const payload = line.slice(5).trim();+ if (!payload || payload === '[DONE]') continue;+ let ev;+ try {+ ev = JSON.parse(payload);+ } catch {+ continue;+ }++ if (ev.usage) {+ inputTokens = ev.usage.prompt_tokens ?? inputTokens;+ outputTokens = ev.usage.completion_tokens ?? outputTokens;+ }++ const choice = ev.choices?.[0];+ const delta = choice?.delta;++ if (delta?.content) {+ ensureTextBlockStart();+ write(+ {+ type: 'content_block_delta',+ index: textIndex,+ delta: { type: 'text_delta', text: delta.content },+ },+ 'content_block_delta',+ );+ }++ if (Array.isArray(delta?.tool_calls)) {+ for (const tc of delta.tool_calls) {+ const idx = tc.index ?? 0;+ let slot = toolBlocks.get(idx);+ if (!slot) {+ slot = { started: false, finished: false, name: '', id: null, argsBuf: '' };+ toolBlocks.set(idx, slot);+ }+ if (!slot.started && (tc.id || tc.function?.name)) {+ startToolBlock(slot, tc);+ } else if (tc.function?.name && !slot.started) {+ slot.name += tc.function.name;+ }+ if (tc.function?.arguments) {+ slot.argsBuf += tc.function.arguments;+ if (slot.started) {+ write(+ {+ type: 'content_block_delta',+ index: slot.anthropicIndex,+ delta: { type: 'input_json_delta', partial_json: tc.function.arguments },+ },+ 'content_block_delta',+ );+ }+ }+ }+ }++ if (choice?.finish_reason) {+ stopReason = choice.finish_reason === 'tool_calls' ? 'tool_use' : 'end_turn';+ }+ }+ }+ } finally {+ closeTextBlockIfOpen();+ finishToolBlocks();+ if (messageStartSent) {+ write(+ {+ type: 'message_delta',+ delta: { stop_reason: stopReason, stop_sequence: null },+ usage: { output_tokens: outputTokens },+ },+ 'message_delta',+ );+ write({ type: 'message_stop' }, 'message_stop');+ }+ res.end();+ }++ return { inputTokens, outputTokens };+}diff --git a/api/marketplace/[action].js b/api/marketplace/[action].jsindex 5aa7346ef..79a90b715 100644--- a/api/marketplace/[action].js+++ b/api/marketplace/[action].js@@ -99,6 +99,13 @@ export default wrap(async (req, res) => {if (sub === 'publish') return handlePublish(req, res, id);if (sub === 'view') return handleView(req, res, id);if (sub === 'preview') return handlePreview(req, res, id);+ if (sub === 'reviews') {+ const mod = await import('./reviews.js');+ req.url = req.url.includes('?')+ ? `${req.url}&agent_id=${id}`+ : `${req.url}?agent_id=${id}`;+ return mod.default(req, res);+ }return error(res, 404, 'not_found', 'unknown marketplace action');}@@ -300,7 +307,9 @@ async function handleList(req, res, url) {WHERE sp.agent_id = ai.id AND sp.status = 'confirmed') AS buyers_total,(SELECT count(*)::int FROM skill_purchases spWHERE sp.agent_id = ai.id AND sp.status = 'confirmed'- AND sp.confirmed_at > now() - interval '24 hours') AS buyers_24h+ AND sp.confirmed_at > now() - interval '24 hours') AS buyers_24h,+ COALESCE((SELECT AVG(rating)::numeric(3,2) FROM agent_reviews r WHERE r.agent_id = ai.id), 0) AS rating_avg,+ COALESCE((SELECT count(*)::int FROM agent_reviews r WHERE r.agent_id = ai.id), 0) AS rating_countFROM agent_identities aiLEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULLLEFT JOIN users u ON u.id = ai.user_id@@ -352,7 +361,9 @@ async function handleDetail(req, res, id) {WHERE sp.agent_id = a.id AND sp.status = 'confirmed') AS buyers_total,(SELECT count(*)::int FROM skill_purchases spWHERE sp.agent_id = a.id AND sp.status = 'confirmed'- AND sp.confirmed_at > now() - interval '24 hours') AS buyers_24h+ AND sp.confirmed_at > now() - interval '24 hours') AS buyers_24h,+ COALESCE((SELECT AVG(rating)::numeric(3,2) FROM agent_reviews r WHERE r.agent_id = a.id), 0) AS rating_avg,+ COALESCE((SELECT count(*)::int FROM agent_reviews r WHERE r.agent_id = a.id), 0) AS rating_countFROM agent_identities aLEFT JOIN users u ON u.id = a.user_idLEFT JOIN avatars av ON av.id = a.avatar_id AND av.deleted_at IS NULL@@ -902,6 +913,8 @@ function toCard(row) {published_at: row.published_at,created_at: row.created_at,has_paid_skills: row.has_paid_skills || false,+ rating_avg: Number(row.rating_avg || 0),+ rating_count: row.rating_count || 0,};}diff --git a/api/marketplace/reviews.js b/api/marketplace/reviews.jsnew file mode 100644index 000000000..12495a0d5--- /dev/null+++ b/api/marketplace/reviews.js@@ -0,0 +1,209 @@+/**+ * Agent reviews API.+ * ──────────────────+ * GET /api/marketplace/agents/:id/reviews — list reviews + summary+ * POST /api/marketplace/agents/:id/reviews — upsert caller's review+ * body: { rating: 1..5, body?: string<=2000 }+ * DELETE /api/marketplace/agents/:id/reviews — delete caller's review+ *+ * Routed via vercel.json — see top of file path patterns.+ *+ * Schema lives in api/_lib/migrations/2026-05-21-agent-reviews.sql.+ * One review per (agent_id, user_id); POST upserts in place.+ */++import { z } from 'zod';++import { sql } from '../_lib/db.js';+import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { requireCsrf } from '../_lib/csrf.js';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++const reviewSchema = z.object({+ rating: z.number().int().min(1).max(5),+ body: z.string().trim().max(2000).optional().nullable(),+});++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId };+ return null;+}++export default wrap(async (req, res) => {+ const url = new URL(req.url, 'http://x');+ const parts = url.pathname.split('/').filter(Boolean); // [api, marketplace, agents, :id, reviews]+ const agentId = url.searchParams.get('agent_id') || parts[3];++ if (!agentId || !UUID_RE.test(agentId)) {+ return error(res, 400, 'validation_error', 'agent_id required');+ }++ if (req.method === 'GET' || (req.method === 'OPTIONS' && req.headers['access-control-request-method'] === 'GET')) {+ return handleList(req, res, agentId);+ }+ if (req.method === 'POST' || (req.method === 'OPTIONS' && req.headers['access-control-request-method'] === 'POST')) {+ return handleUpsert(req, res, agentId);+ }+ if (req.method === 'DELETE' || (req.method === 'OPTIONS' && req.headers['access-control-request-method'] === 'DELETE')) {+ return handleDelete(req, res, agentId);+ }+ return error(res, 405, 'method_not_allowed', 'GET/POST/DELETE only');+});++// ── list + summary ───────────────────────────────────────────────────────────++async function handleList(req, res, agentId) {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.widgetRead(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const [agent] = await sql`+ SELECT id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');++ const auth = await resolveAuth(req).catch(() => null);++ const [summary] = await sql`+ SELECT+ COALESCE(AVG(rating)::numeric(3,2), 0) AS rating_avg,+ COUNT(*)::int AS rating_count,+ SUM(CASE WHEN rating = 5 THEN 1 ELSE 0 END)::int AS r5,+ SUM(CASE WHEN rating = 4 THEN 1 ELSE 0 END)::int AS r4,+ SUM(CASE WHEN rating = 3 THEN 1 ELSE 0 END)::int AS r3,+ SUM(CASE WHEN rating = 2 THEN 1 ELSE 0 END)::int AS r2,+ SUM(CASE WHEN rating = 1 THEN 1 ELSE 0 END)::int AS r1+ FROM agent_reviews+ WHERE agent_id = ${agentId}+ `;++ const rows = await sql`+ SELECT r.id, r.rating, r.body, r.created_at, r.updated_at,+ r.user_id, u.display_name, u.avatar_url+ FROM agent_reviews r+ LEFT JOIN users u ON u.id = r.user_id+ WHERE r.agent_id = ${agentId}+ ORDER BY r.created_at DESC+ LIMIT 50+ `;++ let myReview = null;+ if (auth) {+ const [mine] = await sql`+ SELECT id, rating, body, created_at, updated_at+ FROM agent_reviews+ WHERE agent_id = ${agentId} AND user_id = ${auth.userId}+ `;+ if (mine) myReview = mine;+ }++ const reviews = rows.map((r) => ({+ id: r.id,+ rating: r.rating,+ body: r.body,+ created_at: r.created_at,+ updated_at: r.updated_at,+ author_name: r.display_name || 'Anonymous',+ author_avatar: r.avatar_url || null,+ is_mine: auth && r.user_id === auth.userId,+ }));++ return json(+ res,+ 200,+ {+ data: {+ summary: {+ rating_avg: Number(summary.rating_avg || 0),+ rating_count: summary.rating_count || 0,+ breakdown: { 5: summary.r5 || 0, 4: summary.r4 || 0, 3: summary.r3 || 0, 2: summary.r2 || 0, 1: summary.r1 || 0 },+ },+ reviews,+ my_review: myReview,+ },+ },+ { 'cache-control': 'no-store' },+ );+}++// ── upsert ───────────────────────────────────────────────────────────────────++async function handleUpsert(req, res, agentId) {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');++ if (!(await requireCsrf(req, res, auth.userId))) return;++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const [agent] = await sql`+ SELECT id, user_id FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL AND is_published = true+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');+ if (agent.user_id === auth.userId) {+ return error(res, 422, 'self_review_forbidden', 'you cannot review your own agent');+ }++ const body = await readJson(req).catch(() => null);+ const parsed = reviewSchema.safeParse(body);+ if (!parsed.success) {+ return error(res, 400, 'validation_error', parsed.error.issues[0]?.message || 'invalid review');+ }+ const reviewBody = (parsed.data.body || '').trim() || null;++ const [row] = await sql`+ INSERT INTO agent_reviews (agent_id, user_id, rating, body)+ VALUES (${agentId}, ${auth.userId}, ${parsed.data.rating}, ${reviewBody})+ ON CONFLICT (agent_id, user_id)+ DO UPDATE SET rating = EXCLUDED.rating, body = EXCLUDED.body, updated_at = now()+ RETURNING id, rating, body, created_at, updated_at+ `;++ const [summary] = await sql`+ SELECT+ COALESCE(AVG(rating)::numeric(3,2), 0) AS rating_avg,+ COUNT(*)::int AS rating_count+ FROM agent_reviews WHERE agent_id = ${agentId}+ `;++ return json(res, 200, {+ data: {+ review: row,+ summary: {+ rating_avg: Number(summary.rating_avg || 0),+ rating_count: summary.rating_count || 0,+ },+ },+ });+}++// ── delete ───────────────────────────────────────────────────────────────────++async function handleDelete(req, res, agentId) {+ if (cors(req, res, { methods: 'DELETE,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['DELETE'])) return;++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');++ if (!(await requireCsrf(req, res, auth.userId))) return;++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ await sql`DELETE FROM agent_reviews WHERE agent_id = ${agentId} AND user_id = ${auth.userId}`;+ return json(res, 200, { data: { deleted: true } });+}diff --git a/api/social/sentiment-pulse.js b/api/social/sentiment-pulse.jsnew file mode 100644index 000000000..752730ef2--- /dev/null+++ b/api/social/sentiment-pulse.js@@ -0,0 +1,120 @@+// POST /api/social/sentiment-pulse+//+// One-call sentiment pulse for a Solana token. Pulls recent commentary+// from pump.fun's frontend-api-v3 comments endpoint (the same source the+// pump.fun coin page renders) and scores it with the in-repo lexicon+// scorer. Optionally accepts a list of additional text snippets to fold+// into the score (e.g. X posts the caller has already collected).+//+// This is the unauthenticated, no-key endpoint behind the paid+// `sentiment_pulse` MCP tool — it does no caching of its own (callers+// should hit /api/social/sentiment if they already have the texts).+//+// Body:+// {+// token: string, // Solana SPL or pump.fun mint pubkey+// limit?: number, // max comments to fetch (default 100, max 200)+// extraTexts?: string[], // additional snippets to score+// }+//+// Response:+// {+// ok: true,+// token,+// overall: { score, posPct, negPct, neuPct, count, examples },+// breakdown: { pumpfun: <result>, extra: <result> },+// sources: { pumpfun: 'https://...', extra: <n> },+// fetchedAt+// }++import { z } from 'zod';+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';++const PUMPFUN_BASE = 'https://frontend-api-v3.pump.fun';+const SOLANA_MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++const bodySchema = z.object({+ token: z.string().regex(SOLANA_MINT_RE, 'token must be a base58 Solana mint pubkey'),+ limit: z.number().int().min(1).max(200).optional(),+ extraTexts: z.array(z.string().max(2000)).max(200).optional(),+});++async function fetchPumpFunComments(mint, limit) {+ // frontend-api-v3 returns the most recent comments first. The endpoint+ // supports limit + offset; we just take the most recent batch.+ const url = `${PUMPFUN_BASE}/replies/${mint}?limit=${limit}&offset=0`;+ let res;+ try {+ const controller = new AbortController();+ const t = setTimeout(() => controller.abort(), 8000);+ try {+ res = await fetch(url, { signal: controller.signal });+ } finally {+ clearTimeout(t);+ }+ } catch (err) {+ return { error: err?.message || 'fetch failed', url };+ }+ if (!res.ok) return { error: `pump.fun returned ${res.status}`, url };+ const data = await res.json().catch(() => null);+ if (!data) return { error: 'invalid json from pump.fun', url };+ const replies = Array.isArray(data?.replies) ? data.replies : Array.isArray(data) ? data : [];+ const posts = replies+ .map((r) => ({+ id: r.id || r.signature || undefined,+ ts: r.timestamp ? new Date(r.timestamp).toISOString() : undefined,+ text: String(r.text || r.message || '').slice(0, 2000),+ author: r.user || r.username || undefined,+ }))+ .filter((p) => p.text);+ return { posts, url };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: false })) return;+ if (!method(req, res, ['POST'])) return;++ const rl = await limits.mcpIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ let raw;+ try {+ raw = await readJson(req);+ } catch {+ return error(res, 400, 'invalid_json', 'invalid json');+ }+ const parsed = bodySchema.safeParse(raw);+ if (!parsed.success) {+ return error(res, 400, 'validation_error', parsed.error.issues[0]?.message ?? 'invalid body');+ }+ const { token, limit = 100, extraTexts = [] } = parsed.data;++ const { scoreSentiment } = await import('../../src/social/sentiment.js');++ const pumpfun = await fetchPumpFunComments(token, limit);+ const pumpfunPosts = pumpfun.error ? [] : pumpfun.posts;+ const extraPosts = extraTexts.map((t, i) => ({ id: `extra-${i}`, text: t }));++ const all = [...pumpfunPosts, ...extraPosts];+ const overall = scoreSentiment(all);+ const breakdown = {+ pumpfun: pumpfun.error+ ? { error: pumpfun.error, count: 0 }+ : scoreSentiment(pumpfunPosts),+ extra: scoreSentiment(extraPosts),+ };++ return json(res, 200, {+ ok: true,+ token,+ overall,+ breakdown,+ sources: {+ pumpfun: pumpfun.error ? null : pumpfun.url,+ pumpfunCount: pumpfunPosts.length,+ extraCount: extraPosts.length,+ },+ fetchedAt: new Date().toISOString(),+ });+});diff --git a/chat/src/App.svelte b/chat/src/App.svelteindex e40ea73ad..1eb981d44 100644--- a/chat/src/App.svelte+++ b/chat/src/App.svelte@@ -1487,6 +1487,46 @@console.warn('[x402-pay] bootstrap failed:', err);}+ // When the user installs a Local skill from the Skills modal, auto-enable+ // the new tools in the current conversation so the LLM can call them on+ // the next turn — same UX as the x402-pay bootstrap above, but+ // triggered on-demand instead of once at startup. We only enable for+ // the active convo; other convos pick up the new tools through the+ // usual Tools dropdown.+ window.addEventListener('local-skill-installed', (e) => {+ try {+ const skill = e.detail?.skill;+ if (!skill || !convo) return;+ if (skill.kind === 'tool' && Array.isArray(skill.schema_json)) {+ const names = skill.schema_json+ .map((t) => t.function?.name || t.clientDefinition?.name)+ .filter(Boolean);+ if (names.length === 0) return;+ convo.tools = Array.from(new Set([...(convo.tools || []), ...names]));+ saveConversation(convo);+ }+ } catch (err) {+ console.warn('[local-skill] enable failed:', err);+ }+ });+ window.addEventListener('local-skill-uninstalled', (e) => {+ try {+ const skill = e.detail?.skill;+ if (!skill || !convo) return;+ if (skill.kind === 'tool' && Array.isArray(skill.schema_json)) {+ const names = new Set(+ skill.schema_json+ .map((t) => t.function?.name || t.clientDefinition?.name)+ .filter(Boolean),+ );+ convo.tools = (convo.tools || []).filter((n) => !names.has(n));+ saveConversation(convo);+ }+ } catch (err) {+ console.warn('[local-skill] disable failed:', err);+ }+ });+initializePWAStyles();// Only probe the local tool server if the user has opted in or clearlydiff --git a/chat/src/SkillsMarketplaceModal.svelte b/chat/src/SkillsMarketplaceModal.svelteindex eb6725c1f..76c08ee0b 100644--- a/chat/src/SkillsMarketplaceModal.svelte+++ b/chat/src/SkillsMarketplaceModal.svelte@@ -31,7 +31,13 @@async function loadLocalSkills() {try {- const res = await fetch('/api/skills-manifest');+ // /api/chat-skills returns the rich feed: AgentSkills as tool packs+ // (kind=tool, schema_json wired to /api/mcp) plus every SKILL.md on+ // disk as a knowledge skill (kind=knowledge, content=full SKILL.md).+ // Falls back to the slimmer /api/skills-manifest if the rich+ // endpoint isn't deployed yet, so prod stays resilient.+ let res = await fetch('/api/chat-skills');+ if (!res.ok) res = await fetch('/api/skills-manifest');if (res.ok) {const manifest = await res.json();localSkills = manifest.skills || [];@@ -41,6 +47,75 @@}}+ function isLocalInstalled(skill) {+ if (skill.kind === 'knowledge') {+ return $knowledgeSkills.some((k) => k.id === skill.id);+ }+ return $toolSchema.some((g) => g.id === skill.id || g.name === skill.name);+ }++ function localKindLabel(skill) {+ if (skill.kind === 'knowledge') return 'Knowledge';+ if (skill.unavailable) return 'Server-only';+ return 'Tool';+ }++ /**+ * Install a Local skill into the chat. No HTTP round-trip — local skills+ * are not stored in the marketplace DB; they live on disk (SKILL.md packs)+ * or in-code (AgentSkills). Install just mutates the two client stores:+ * - knowledgeSkills: full SKILL.md body injected into the system prompt+ * - toolSchema: schema_json with a clientDefinition that POSTs to+ * /api/mcp under the hood+ * Removal is symmetric.+ */+ function toggleLocalInstall(skill) {+ const installed = isLocalInstalled(skill);+ if (skill.kind === 'knowledge') {+ if (installed) {+ $knowledgeSkills = $knowledgeSkills.filter((k) => k.id !== skill.id);+ notify(`Removed “${skill.name}”`, 'success');+ } else {+ $knowledgeSkills = [+ ...$knowledgeSkills.filter((k) => k.id !== skill.id),+ {+ id: skill.id,+ name: skill.name,+ slug: skill.slug,+ content: skill.content || skill.body || '',+ },+ ];+ notify(`Installed “${skill.name}”`, 'success');+ }+ return;+ }+ // kind === 'tool'+ if (skill.unavailable) {+ notify(`${skill.name} is server-only and not callable from the chat`, 'info');+ return;+ }+ if (installed) {+ $toolSchema = $toolSchema.filter((g) => g.id !== skill.id && g.name !== skill.name);+ try {+ window.dispatchEvent(+ new CustomEvent('local-skill-uninstalled', { detail: { skill } }),+ );+ } catch {}+ notify(`Removed “${skill.name}”`, 'success');+ } else {+ $toolSchema = [+ ...$toolSchema,+ { id: skill.id, name: skill.name, schema: skill.schema_json || [] },+ ];+ try {+ window.dispatchEvent(+ new CustomEvent('local-skill-installed', { detail: { skill } }),+ );+ } catch {}+ notify(`Installed “${skill.name}”`, 'success');+ }+ }+// Detail expansion statelet expandedSkillId = null;let detailLoading = false;@@ -666,14 +741,93 @@{#if loading && skills.length === 0}<p class="mt-8 text-center text-[13px] text-slate-400">Loading skills...</p>{:else if showLocalSkills}- <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">- {#each localSkills as skill (skill.name)}- <div class="rounded-lg border border-slate-200 px-3 py-3">- <h3 class="font-semibold text-slate-800 text-[13px]">{skill.name}</h3>- <p class="mt-0.5 line-clamp-2 text-[11px] leading-relaxed text-slate-500">{skill.description}</p>+ {@const filteredLocal = (localSkills || []).filter((s) => {+ if (!debouncedSearch) return true;+ const q = debouncedSearch.toLowerCase();+ return (+ (s.name || '').toLowerCase().includes(q) ||+ (s.description || '').toLowerCase().includes(q) ||+ (s.source || '').toLowerCase().includes(q)+ );+ })}+ {@const groupedLocal = filteredLocal.reduce((acc, s) => {+ const k = s.source || 'other';+ (acc[k] ||= []).push(s);+ return acc;+ }, {})}+ {#if filteredLocal.length === 0}+ <p class="mt-8 text-center text-[13px] text-slate-400">+ {localSkills.length === 0 ? 'Loading local skills…' : 'No local skills match your search'}+ </p>+ {:else}+ {#each Object.entries(groupedLocal) as [source, group] (source)}+ <div class="mb-5">+ <div class="mb-2 flex items-baseline justify-between">+ <h4 class="text-[12px] font-semibold uppercase tracking-wide text-slate-500">+ {source}+ </h4>+ <span class="text-[11px] text-slate-400">{group.length} skill{group.length === 1 ? '' : 's'}</span>+ </div>+ <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">+ {#each group as skill (skill.id || skill.name)}+ {@const installed = isLocalInstalled(skill)}+ <div+ class="rounded-lg border px-3 py-3 transition-colors {installed+ ? 'border-indigo-300 bg-indigo-50/30'+ : 'border-slate-200 hover:border-slate-300'} {skill.unavailable+ ? 'opacity-60'+ : ''}"+ >+ <div class="flex items-start justify-between gap-x-3">+ <div class="min-w-0 flex-1">+ <div class="flex flex-wrap items-center gap-x-1.5 gap-y-1">+ <span class="text-[13px] font-medium text-slate-800">{skill.name}</span>+ <span+ class="rounded-full px-2 py-0.5 text-[10px] font-medium {skill.kind === 'knowledge'+ ? 'bg-amber-50 text-amber-700'+ : skill.unavailable+ ? 'bg-slate-100 text-slate-500'+ : 'bg-sky-50 text-sky-700'}"+ >+ {localKindLabel(skill)}+ </span>+ {#if skill.category}+ <span class="rounded-full bg-slate-100 px-2 py-0.5 text-[10px] text-slate-500"+ >{skill.category}</span+ >+ {/if}+ </div>+ <p class="mt-0.5 line-clamp-2 text-[11px] leading-relaxed text-slate-500">+ {skill.description || ''}+ </p>+ {#if skill.path}+ <p class="mt-1 text-[10px] text-slate-400">{skill.path}</p>+ {/if}+ </div>+ {#if skill.unavailable}+ <span class="shrink-0 text-[11px] text-slate-400">Not callable</span>+ {:else if installed}+ <button+ class="shrink-0 rounded-lg border border-slate-200 px-3 py-1.5 text-[11px] text-slate-500 transition-colors hover:border-red-200 hover:bg-red-50 hover:text-red-600"+ on:click={() => toggleLocalInstall(skill)}+ >+ Remove+ </button>+ {:else}+ <button+ class="shrink-0 rounded-lg border border-slate-200 bg-slate-50 px-3 py-1.5 text-[11px] font-medium text-slate-700 transition-colors hover:bg-slate-100"+ on:click={() => toggleLocalInstall(skill)}+ >+ Install+ </button>+ {/if}+ </div>+ </div>+ {/each}+ </div></div>{/each}- </div>+ {/if}{:else if skills.length === 0}<p class="mt-8 text-center text-[13px] text-slate-400">No skills found</p>{:else}diff --git a/mcp-server/src/index.js b/mcp-server/src/index.jsindex 36c9001f1..5def2218d 100755--- a/mcp-server/src/index.js+++ b/mcp-server/src/index.js@@ -20,6 +20,13 @@ import { buildPoseSeedTool } from './tools/pose-seed.js';import { buildPumpSnapshotTool } from './tools/pump-snapshot.js';import { buildAgentReputationTool } from './tools/agent-reputation.js';import { buildVanityGrinderTool } from './tools/vanity-grinder.js';+import { buildTextToAvatarTool } from './tools/text-to-avatar.js';+import { buildRenderAvatarClipTool } from './tools/render-avatar-clip.js';+import { buildTtsSpeakTool } from './tools/tts-speak.js';+import { buildOptimizeGlbTool } from './tools/optimize-glb.js';+import { buildSentimentPulseTool } from './tools/sentiment-pulse.js';+import { buildEnsSnsResolveTool } from './tools/ens-sns-resolve.js';+import { buildAgentDelegateActionTool } from './tools/agent-delegate-action.js';async function main() {// Force the shared x402 resource server to initialize before any tool is@@ -39,12 +46,23 @@ async function main() {instructions:'Paid x402 MCP tools from three.ws. Each tool quotes its USDC price in its description. ' +'Tool calls without an x402 payment payload in _meta return a PaymentRequired structuredContent ' +- '(v2 MCP transport spec). Tools cover pose generation (get_pose_seed), Solana token snapshots ' +- '(pump_snapshot), ERC-8004 agent reputation (agent_reputation), and Solana vanity address ' +- 'mining (vanity_grinder, upto-priced).',+ '(v2 MCP transport spec). Tools cover: 3D avatar generation (text_to_avatar), server-side ' ++ 'avatar rendering with pose + camera (render_avatar_clip), GLB transcoding/draco/texture ' ++ 'compression (optimize_glb), text-to-speech (tts_speak), ENS + SNS name resolution ' ++ '(ens_sns_resolve), agent-to-agent delegation (agent_delegate_action), token sentiment pulse ' ++ '(sentiment_pulse), pose generation (get_pose_seed), Solana token snapshots (pump_snapshot), ' ++ 'ERC-8004 agent reputation (agent_reputation), and Solana vanity address mining ' ++ '(vanity_grinder, upto-priced).',});const tools = await Promise.all([+ buildTextToAvatarTool(),+ buildRenderAvatarClipTool(),+ buildOptimizeGlbTool(),+ buildTtsSpeakTool(),+ buildEnsSnsResolveTool(),+ buildAgentDelegateActionTool(),+ buildSentimentPulseTool(),buildPoseSeedTool(),buildPumpSnapshotTool(),buildAgentReputationTool(),diff --git a/mcp-server/src/tools/agent-delegate-action.js b/mcp-server/src/tools/agent-delegate-action.jsnew file mode 100644index 000000000..bcc1a8f14--- /dev/null+++ b/mcp-server/src/tools/agent-delegate-action.js@@ -0,0 +1,97 @@+// `agent_delegate_action` — paid MCP tool that lets an external agent+// send a message to any three.ws-registered agent and get its reply.+//+// Pricing: $0.01 USDC, settled `exact` on Base or Solana.+//+// Implementation: calls POST /api/agents/talk with the target agentId+// and message. The target's brain is driven by its embed_policy.brain+// settings on three.ws (which model, system prompt). Agents whose owner+// has set surfaces.mcp = false in their embed policy are refused.+//+// Recursion is prevented server-side via the x-delegate-depth header.++import { z } from 'zod';++import { paid } from '../payments.js';++const TOOL_NAME = 'agent_delegate_action';+const TOOL_DESCRIPTION =+ 'Send a message to a three.ws-registered agent and receive its response. The target agent uses its configured brain (Claude model and system prompt set via its embed policy). Agents that have opted out of MCP delegation are refused. Useful for agent-to-agent collaboration and tool composition. Paid: $0.01 USDC.';++function env(k, def) {+ const v = process.env[k];+ return v && String(v).trim() ? String(v).trim() : def;+}++const inputJsonSchema = {+ type: 'object',+ properties: {+ agentId: { type: 'string', description: 'three.ws agent id (UUID).', minLength: 1, maxLength: 120 },+ message: { type: 'string', minLength: 1, maxLength: 4000 },+ model: {+ type: 'string',+ description: 'Optional Claude model override (e.g. claude-sonnet-4-6). Must be in the allowlist.',+ },+ },+ required: ['agentId', 'message'],+ additionalProperties: false,+};++const inputZodShape = {+ agentId: z.string().min(1).max(120),+ message: z.string().min(1).max(4000),+ model: z.string().min(1).max(100).optional(),+};++export async function buildAgentDelegateActionTool() {+ const handler = await paid(+ {+ toolName: TOOL_NAME,+ description: TOOL_DESCRIPTION,+ scheme: 'exact',+ priceUsd: '$0.01',+ inputSchema: inputJsonSchema,+ example: {+ agentId: '5a4b3c2d-1234-5678-90ab-cdef01234567',+ message: 'Summarise the latest pump.fun graduations in 3 bullets.',+ },+ outputExample: {+ ok: true,+ agentId: '5a4b3c2d-1234-5678-90ab-cdef01234567',+ agentName: 'Pump Sage',+ response: '...',+ model: 'claude-haiku-4-5-20251001',+ durationMs: 1840,+ },+ },+ async ({ agentId, message, model }) => {+ const endpoint = env('MCP_AGENT_TALK_ENDPOINT', 'https://three.ws/api/agents/talk');+ let res;+ try {+ res = await fetch(endpoint, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ agentId, message, model }),+ });+ } catch (err) {+ return { ok: false, error: 'upstream_unreachable', message: err?.message || 'fetch failed' };+ }+ const data = await res.json().catch(() => null);+ if (!res.ok || !data || data.ok === false) {+ return {+ ok: false,+ error: data?.code || data?.error || 'agent_delegate_failed',+ message: data?.message || `endpoint returned ${res.status}`,+ };+ }+ return data;+ },+ );+ return {+ name: TOOL_NAME,+ title: 'Agent delegate action ($0.01)',+ description: TOOL_DESCRIPTION,+ inputSchema: inputZodShape,+ handler,+ };+}diff --git a/mcp-server/src/tools/ens-sns-resolve.js b/mcp-server/src/tools/ens-sns-resolve.jsnew file mode 100644index 000000000..a92dd42fc--- /dev/null+++ b/mcp-server/src/tools/ens-sns-resolve.js@@ -0,0 +1,170 @@+// `ens_sns_resolve` — paid MCP tool that resolves a human-readable name+// to one or more on-chain addresses across ENS (Ethereum) and SNS (Solana).+//+// Pricing: $0.0005 USDC, settled `exact` on Base or Solana.+//+// Resolution paths:+// - ENS (foo.eth, sub.foo.eth) → Ethereum mainnet via the configured+// RPC (MAINNET_RPC_URL or MCP_ENS_RPC_URL), with a 3-second timeout.+// Falls back to ethers' default public provider rotation.+// - SNS (foo.sol) → Solana via Bonfida sns-api.bonfida.com+// (the same source the three.ws site uses). Returns the owner wallet+// plus reverse-lookup of any other domains the wallet holds.+//+// Inputs accepting "foo" or "foo.eth/.sol" disambiguate via the suffix.+// Inputs ending in neither are tried against both — whichever resolves wins.++import { ethers } from 'ethers';+import { z } from 'zod';++import { paid } from '../payments.js';++const TOOL_NAME = 'ens_sns_resolve';+const TOOL_DESCRIPTION =+ 'Resolve a human-readable name to addresses across ENS (Ethereum) and SNS (Solana). For .eth: returns Ethereum address via ethers. For .sol: returns Solana owner wallet via Bonfida SNS plus the wallet\'s other owned .sol domains. Names without a suffix are tried against both registries. Paid: $0.0005 USDC.';++const ENS_RE = /^(?:[a-z0-9-]+\.)*[a-z0-9-]+\.eth$/i;+const SOL_RE = /^[a-z0-9-]{1,63}(?:\.sol)?$/i;+const SNS_API = 'https://sns-api.bonfida.com';++function env(k, def) {+ const v = process.env[k];+ return v && String(v).trim() ? String(v).trim() : def;+}++async function withTimeout(promise, ms, label) {+ const timeout = new Promise((_, rej) => setTimeout(() => rej(new Error(`${label} timed out after ${ms}ms`)), ms));+ return Promise.race([promise, timeout]);+}++async function resolveEns(name) {+ const rpcUrl = env('MCP_ENS_RPC_URL') || env('MAINNET_RPC_URL');+ const provider = rpcUrl+ ? new ethers.JsonRpcProvider(rpcUrl)+ : ethers.getDefaultProvider('mainnet');+ const address = await withTimeout(provider.resolveName(name), 4000, 'ens');+ if (!address) return null;+ let reverseName = null;+ try {+ reverseName = await withTimeout(provider.lookupAddress(address), 3000, 'ens-reverse');+ } catch {+ // reverse lookup is best-effort+ }+ return { network: 'ethereum', name, address, reverseName, rpc: rpcUrl || 'ethers-default' };+}++async function resolveSns(name) {+ const bare = name.toLowerCase().replace(/\.sol$/, '');+ if (!/^[a-z0-9-]{1,63}$/.test(bare)) return null;+ const lookup = await fetch(`${SNS_API}/v2/domain/lookup/${bare}.sol`).catch(() => null);+ if (!lookup || !lookup.ok) return null;+ const data = await lookup.json().catch(() => null);+ const owner = data?.owner || data?.[bare + '.sol']?.owner || data?.data?.owner || null;+ if (!owner) return null;++ // Reverse fetch: other domains the owner holds.+ let allDomains = [];+ try {+ const r = await fetch(`${SNS_API}/v2/user/domains/${owner}`);+ if (r.ok) {+ const body = await r.json();+ const list = body?.[owner] || body?.data?.[owner] || [];+ if (Array.isArray(list)) {+ allDomains = list+ .map((d) => (typeof d === 'string' ? d : d?.domain || d?.name))+ .filter(Boolean);+ }+ }+ } catch {+ // best effort+ }++ let favoriteDomain = null;+ try {+ const r = await fetch(`${SNS_API}/v2/user/fav-domains/${owner}`);+ if (r.ok) {+ const body = await r.json();+ favoriteDomain = body?.[owner] || body?.data?.[owner] || null;+ }+ } catch {+ // best effort+ }++ return {+ network: 'solana',+ name: `${bare}.sol`,+ address: owner,+ favoriteDomain,+ allDomains,+ source: `${SNS_API}/v2/domain/lookup/${bare}.sol`,+ };+}++const inputJsonSchema = {+ type: 'object',+ properties: {+ name: {+ type: 'string',+ description: 'Name to resolve (e.g. "vitalik.eth", "bonfida.sol", or bare "vitalik" which is tried in both).',+ minLength: 1,+ maxLength: 253,+ },+ },+ required: ['name'],+ additionalProperties: false,+};++const inputZodShape = {+ name: z.string().min(1).max(253),+};++export async function buildEnsSnsResolveTool() {+ const handler = await paid(+ {+ toolName: TOOL_NAME,+ description: TOOL_DESCRIPTION,+ scheme: 'exact',+ priceUsd: '$0.0005',+ inputSchema: inputJsonSchema,+ example: { name: 'vitalik.eth' },+ outputExample: {+ ok: true,+ input: 'vitalik.eth',+ ens: { network: 'ethereum', name: 'vitalik.eth', address: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', reverseName: 'vitalik.eth' },+ sns: null,+ },+ },+ async ({ name }) => {+ const trimmed = String(name || '').trim().toLowerCase();+ const isEns = ENS_RE.test(trimmed);+ const isSol = /\.sol$/.test(trimmed) || (!isEns && SOL_RE.test(trimmed));++ const tasks = [];+ if (isEns) tasks.push(['ens', resolveEns(trimmed).catch((e) => ({ error: e?.message || 'ens failed' }))]);+ if (isSol) tasks.push(['sns', resolveSns(trimmed).catch((e) => ({ error: e?.message || 'sns failed' }))]);+ if (!isEns && !isSol) {+ return { ok: false, error: 'invalid_name', message: 'name does not look like a .eth, .sol, or bare label' };+ }+ const results = await Promise.all(tasks.map((t) => t[1]));+ const out = { ok: false, input: trimmed, ens: null, sns: null };+ tasks.forEach(([key], i) => {+ out[key] = results[i] || null;+ });+ if (out.ens && !out.ens.error) out.ok = true;+ if (out.sns && !out.sns.error) out.ok = true;+ if (!out.ok) {+ out.error = 'not_found';+ out.message = 'name did not resolve in either ENS or SNS';+ }+ out.fetchedAt = new Date().toISOString();+ return out;+ },+ );+ return {+ name: TOOL_NAME,+ title: 'ENS + SNS resolve ($0.0005)',+ description: TOOL_DESCRIPTION,+ inputSchema: inputZodShape,+ handler,+ };+}diff --git a/mcp-server/src/tools/sentiment-pulse.js b/mcp-server/src/tools/sentiment-pulse.jsnew file mode 100644index 000000000..b1b8eb774--- /dev/null+++ b/mcp-server/src/tools/sentiment-pulse.js@@ -0,0 +1,107 @@+// `sentiment_pulse` — paid MCP tool that returns a real-time sentiment+// pulse for a Solana token by pulling recent pump.fun comments and+// scoring them with the three.ws lexicon scorer. Callers may attach+// additional texts (e.g. X posts they have collected) to fold into the+// overall score.+//+// Pricing: $0.003 USDC, settled `exact` on Base or Solana.+//+// Implementation: calls POST /api/social/sentiment-pulse on the three.ws+// API surface. No keys are required — the endpoint relies on the public+// pump.fun frontend-api-v3 replies route.++import { z } from 'zod';++import { paid } from '../payments.js';++const TOOL_NAME = 'sentiment_pulse';+const TOOL_DESCRIPTION =+ 'Sentiment pulse for a Solana token: fetches the most recent pump.fun comments via frontend-api-v3, optionally folds in caller-supplied snippets (e.g. recent X cashtag posts), and scores the combined stream with the three.ws deterministic lexicon. Returns overall + per-source breakdown with examples. Pairs naturally with pump_snapshot. Paid: $0.003 USDC.';++function env(k, def) {+ const v = process.env[k];+ return v && String(v).trim() ? String(v).trim() : def;+}++const SOLANA_MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++const inputJsonSchema = {+ type: 'object',+ properties: {+ token: {+ type: 'string',+ description: 'Solana SPL or pump.fun mint pubkey (base58).',+ minLength: 32,+ maxLength: 44,+ },+ limit: {+ type: 'integer',+ minimum: 1,+ maximum: 200,+ default: 100,+ description: 'Max pump.fun comments to score.',+ },+ extraTexts: {+ type: 'array',+ items: { type: 'string', maxLength: 2000 },+ maxItems: 200,+ description: 'Extra text snippets to include (e.g. X posts you have already collected).',+ },+ },+ required: ['token'],+ additionalProperties: false,+};++const inputZodShape = {+ token: z.string().refine((v) => SOLANA_MINT_RE.test(v), 'token must be a base58 Solana mint pubkey'),+ limit: z.number().int().min(1).max(200).optional(),+ extraTexts: z.array(z.string().max(2000)).max(200).optional(),+};++export async function buildSentimentPulseTool() {+ const handler = await paid(+ {+ toolName: TOOL_NAME,+ description: TOOL_DESCRIPTION,+ scheme: 'exact',+ priceUsd: '$0.003',+ inputSchema: inputJsonSchema,+ example: { token: 'HZ1JovNiVvGrGNiiYvEozEVgZ58xaU3RKwX8eACQBCt3', limit: 100 },+ outputExample: {+ ok: true,+ token: 'HZ1JovNiVvGrGNiiYvEozEVgZ58xaU3RKwX8eACQBCt3',+ overall: { score: 0.42, posPct: 58, negPct: 16, neuPct: 26, count: 100 },+ breakdown: { pumpfun: { score: 0.4, count: 90 }, extra: { score: 0.5, count: 10 } },+ },+ },+ async ({ token, limit, extraTexts }) => {+ const endpoint = env('MCP_SENTIMENT_PULSE_ENDPOINT', 'https://three.ws/api/social/sentiment-pulse');+ let res;+ try {+ res = await fetch(endpoint, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ token, limit, extraTexts }),+ });+ } catch (err) {+ return { ok: false, error: 'upstream_unreachable', message: err?.message || 'fetch failed' };+ }+ const data = await res.json().catch(() => null);+ if (!res.ok || !data || data.ok === false) {+ return {+ ok: false,+ error: data?.code || data?.error || 'sentiment_failed',+ message: data?.message || `endpoint returned ${res.status}`,+ };+ }+ return data;+ },+ );+ return {+ name: TOOL_NAME,+ title: 'Sentiment pulse ($0.003)',+ description: TOOL_DESCRIPTION,+ inputSchema: inputZodShape,+ handler,+ };+}diff --git a/mcp-server/src/tools/text-to-avatar.js b/mcp-server/src/tools/text-to-avatar.jsnew file mode 100644index 000000000..74ff5004e--- /dev/null+++ b/mcp-server/src/tools/text-to-avatar.js@@ -0,0 +1,285 @@+// `text_to_avatar` — paid MCP tool that generates a textured 3D GLB avatar+// from either a text prompt or one/more reference image URLs, by driving+// Replicate's text-to-3D / image-to-3D pipeline (Tencent Hunyuan-3D 3.1 by+// default, configurable via REPLICATE_TEXT_TO_AVATAR_MODEL).+//+// Pricing: $0.15 USDC, settled `exact` on Base or Solana.+//+// Behavior: synchronously submits a Replicate prediction and polls until the+// prediction reaches a terminal state or the configured timeout fires. The+// returned GLB URL is the Replicate-hosted output. To avoid the caller having+// to chase signed-URL expiration, this tool re-fetches the GLB and rehosts it+// on the three.ws R2 bucket when MCP_TEXT_TO_AVATAR_REHOST is enabled+// (default off; opt-in because rehosting writes a public object).+//+// Environment:+// REPLICATE_API_TOKEN — required.+// REPLICATE_TEXT_TO_AVATAR_MODEL — required version hash. Pin a+// commercial-OK image/text-to-3D model+// (e.g. tencent/hunyuan-3d-3.1 latest).+// MCP_TEXT_TO_AVATAR_TIMEOUT_MS — optional, defaults to 110_000.+// MCP_TEXT_TO_AVATAR_POLL_MS — optional, defaults to 2_000.+// MCP_TEXT_TO_AVATAR_REHOST — "1" to rehost via MCP_REHOST_ENDPOINT.+// MCP_REHOST_ENDPOINT — three.ws URL that ingests external+// GLB URLs.+// MCP_REHOST_KEY — bearer for MCP_REHOST_ENDPOINT.++import { z } from 'zod';++import { paid } from '../payments.js';++const TOOL_NAME = 'text_to_avatar';+const TOOL_DESCRIPTION =+ 'Generate a textured 3D GLB avatar from a text prompt or one or more reference image URLs. Drives Replicate (Hunyuan-3D 3.1 by default, configurable) and polls the prediction synchronously until a GLB is produced or the timeout fires. Returns the GLB URL, the source prompt/images, the picked model version, the prediction id, and timing metadata. Paid: $0.15 USDC.';++const REPLICATE_BASE = 'https://api.replicate.com/v1';++function env(k, def) {+ const v = process.env[k];+ return v && String(v).trim() ? String(v).trim() : def;+}++function authHeaders() {+ const token = env('REPLICATE_API_TOKEN');+ if (!token) {+ const err = new Error('REPLICATE_API_TOKEN is not configured on the MCP server');+ err.code = 'not_configured';+ throw err;+ }+ return { authorization: `Bearer ${token}`, 'content-type': 'application/json' };+}++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;+}++async function submitPrediction({ version, input }) {+ const res = await fetch(`${REPLICATE_BASE}/predictions`, {+ method: 'POST',+ headers: authHeaders(),+ body: JSON.stringify({ version, input }),+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) {+ const err = new Error(data?.detail || data?.title || `replicate returned ${res.status}`);+ err.code = 'provider_error';+ err.providerStatus = res.status;+ throw err;+ }+ return data;+}++async function pollPrediction(predictionId, { timeoutMs, intervalMs }) {+ const deadline = Date.now() + timeoutMs;+ let last = null;+ while (Date.now() < deadline) {+ const r = await fetch(`${REPLICATE_BASE}/predictions/${encodeURIComponent(predictionId)}`, {+ headers: authHeaders(),+ });+ const data = await r.json().catch(() => ({}));+ if (!r.ok) {+ const err = new Error(data?.detail || `replicate poll returned ${r.status}`);+ err.code = 'provider_error';+ throw err;+ }+ last = data;+ const s = data.status;+ if (s === 'succeeded' || s === 'failed' || s === 'canceled') return data;+ await new Promise((res) => setTimeout(res, intervalMs));+ }+ return { ...last, _timedOut: true };+}++async function rehostIfRequested(glbUrl, { prompt, images }) {+ if (env('MCP_TEXT_TO_AVATAR_REHOST', '0') !== '1') return null;+ const endpoint = env('MCP_REHOST_ENDPOINT', 'https://three.ws/api/avatars/ingest-url');+ const ingestKey = env('MCP_REHOST_KEY');+ if (!ingestKey) return null;+ try {+ const r = await fetch(endpoint, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ authorization: `Bearer ${ingestKey}`,+ },+ body: JSON.stringify({+ source_url: glbUrl,+ name: (prompt || 'mcp-text-to-avatar').slice(0, 80),+ source: 'mcp',+ source_meta: { provider: 'replicate', prompt, images },+ }),+ });+ if (!r.ok) return { error: `rehost failed: ${r.status}` };+ return await r.json();+ } catch (err) {+ return { error: err?.message || 'rehost call failed' };+ }+}++const inputJsonSchema = {+ type: 'object',+ properties: {+ prompt: {+ type: 'string',+ description: 'Natural-language description of the avatar to generate.',+ maxLength: 1000,+ },+ images: {+ type: 'array',+ description: 'Optional reference image URLs. When provided, the model performs image-to-3D reconstruction.',+ items: { type: 'string', format: 'uri' },+ maxItems: 4,+ },+ seed: { type: 'integer', minimum: 0, maximum: 2147483647 },+ texture: { type: 'boolean', description: 'Request PBR textures when supported (default true).' },+ },+ additionalProperties: false,+};++const inputZodShape = {+ prompt: z.string().max(1000).optional(),+ images: z.array(z.string().url()).max(4).optional(),+ seed: z.number().int().min(0).max(2147483647).optional(),+ texture: z.boolean().optional(),+};++export async function buildTextToAvatarTool() {+ const handler = await paid(+ {+ toolName: TOOL_NAME,+ description: TOOL_DESCRIPTION,+ scheme: 'exact',+ priceUsd: '$0.15',+ inputSchema: inputJsonSchema,+ example: { prompt: 'a cheerful cyberpunk fox in a red hoodie' },+ outputExample: {+ ok: true,+ predictionId: 'qb...8',+ glbUrl: 'https://replicate.delivery/.../mesh.glb',+ prompt: 'a cheerful cyberpunk fox in a red hoodie',+ model: 'tencent/hunyuan-3d-3.1@<version-hash>',+ durationMs: 41000,+ preview: 'https://three.ws/viewer?src=https%3A%2F%2Freplicate.delivery%2F...',+ },+ },+ async ({ prompt, images, seed, texture }) => {+ const version = env('REPLICATE_TEXT_TO_AVATAR_MODEL');+ if (!version) {+ return {+ ok: false,+ error: 'not_configured',+ message:+ 'REPLICATE_TEXT_TO_AVATAR_MODEL is not set on the MCP server. Pin a commercial-OK image/text-to-3D version (e.g. tencent/hunyuan-3d-3.1 latest).',+ };+ }+ if (!prompt && (!images || images.length === 0)) {+ return { ok: false, error: 'invalid_input', message: 'Provide either prompt or images[].' };+ }+ const input = {+ prompt: prompt || undefined,+ image: images && images.length ? images[0] : undefined,+ images: images && images.length ? images : undefined,+ seed: typeof seed === 'number' ? seed : undefined,+ texture: typeof texture === 'boolean' ? texture : true,+ };+ Object.keys(input).forEach((k) => input[k] === undefined && delete input[k]);++ const started = Date.now();+ let submitted;+ try {+ submitted = await submitPrediction({ version, input });+ } catch (err) {+ return { ok: false, error: err.code || 'provider_error', message: err.message };+ }++ const timeoutMs = Number(env('MCP_TEXT_TO_AVATAR_TIMEOUT_MS', '110000'));+ const intervalMs = Number(env('MCP_TEXT_TO_AVATAR_POLL_MS', '2000'));+ let finalState;+ try {+ finalState = await pollPrediction(submitted.id, { timeoutMs, intervalMs });+ } catch (err) {+ return {+ ok: false,+ error: err.code || 'provider_error',+ message: err.message,+ predictionId: submitted.id,+ };+ }++ const durationMs = Date.now() - started;++ if (finalState._timedOut) {+ return {+ ok: false,+ error: 'timeout',+ message: `prediction did not finish within ${timeoutMs}ms`,+ predictionId: submitted.id,+ status: finalState.status,+ resumeUrl: `${REPLICATE_BASE}/predictions/${submitted.id}`,+ durationMs,+ };+ }++ if (finalState.status === 'failed' || finalState.status === 'canceled') {+ return {+ ok: false,+ error: 'prediction_failed',+ message: finalState.error || `prediction ended with status ${finalState.status}`,+ predictionId: submitted.id,+ durationMs,+ };+ }++ const glbUrl = extractGlbUrl(finalState.output);+ if (!glbUrl) {+ return {+ ok: false,+ error: 'no_glb_in_output',+ message: 'prediction succeeded but no GLB url was found in output',+ rawOutput: finalState.output,+ predictionId: submitted.id,+ durationMs,+ };+ }++ const rehost = await rehostIfRequested(glbUrl, { prompt, images });+ const preview = `https://three.ws/viewer?src=${encodeURIComponent(glbUrl)}`;++ return {+ ok: true,+ predictionId: submitted.id,+ glbUrl,+ rehosted: rehost,+ prompt: prompt || null,+ images: images || null,+ seed: typeof seed === 'number' ? seed : null,+ model: version,+ durationMs,+ preview,+ fetchedAt: new Date().toISOString(),+ };+ },+ );+ return {+ name: TOOL_NAME,+ title: 'Text → 3D avatar ($0.15)',+ description: TOOL_DESCRIPTION,+ inputSchema: inputZodShape,+ handler,+ };+}diff --git a/pages/home.html b/pages/home.htmlindex af723d7ab..95a371110 100644--- a/pages/home.html+++ b/pages/home.html@@ -82,6 +82,478 @@<script src="/nav.js"></script><main id="main-content" class="home-parallax">+ <!-- ╔══════════════════════════════════════════════════════════════╗ -->+ <!-- ║ SaaS prologue — sits above the cinematic parallax hero. ║ -->+ <!-- ║ Self-contained inside .h-saas; styles in /home-saas.css. ║ -->+ <!-- ╚══════════════════════════════════════════════════════════════╝ -->+ <div class="h-saas">+ <!-- 1. Announcement bar -->+ <div class="h-saas-bar" data-saas-bar role="region" aria-label="Announcement">+ <div class="h-saas-bar-inner">+ <span class="h-saas-bar-pill"><span class="pulse"></span>Live</span>+ <span>v1.5.1 on Solana mainnet — open-source under Apache 2.0.</span>+ <a+ href="https://github.com/nirholas/three.ws"+ target="_blank"+ rel="noopener"+ >Star on GitHub →</a+ >+ <button+ type="button"+ class="h-saas-bar-close"+ data-saas-bar-close+ aria-label="Dismiss announcement"+ >+ ✕+ </button>+ </div>+ </div>++ <!-- 2. SaaS hero -->+ <section class="h-saas-hero" aria-label="Product overview">+ <div class="h-saas-inner h-saas-hero-inner">+ <div class="h-saas-hero-copy">+ <span class="h-saas-eyebrow h-saas-reveal">+ <span class="dot"></span>+ The 3D identity layer for AI agents+ </span>+ <h2 class="h-saas-h1 h-saas-reveal">+ Every AI agent deserves a <em>3D body</em> and a verifiable+ onchain home.+ </h2>+ <p class="h-saas-sub h-saas-reveal">+ three.ws is the open infrastructure for spawning 3D AI agents on+ Solana. Drop a GLB, connect any LLM via MCP or A2A, mint a+ portable identity, and embed it anywhere with one tag — no SDK+ required on the consumer side.+ </p>+ <div class="h-saas-cta h-saas-reveal">+ <a href="/create" class="h-saas-btn h-saas-btn--primary">+ <span>Start free</span>+ <span class="arrow">→</span>+ </a>+ <a href="#pick-animate" class="h-saas-btn h-saas-btn--ghost">+ Watch it live+ </a>+ </div>+ <div class="h-saas-proof h-saas-reveal">+ <div class="h-saas-avatars" aria-hidden="true">+ <span class="av"></span>+ <span class="av"></span>+ <span class="av"></span>+ <span class="av"></span>+ <span class="av">+</span>+ </div>+ <span class="h-saas-stars" aria-hidden="true">★★★★★</span>+ <span>Built for creators, devs, DAOs and brands shipping agentic UX.</span>+ </div>+ </div>++ <aside class="h-saas-pcard h-saas-reveal" aria-label="Live agent preview">+ <div class="h-saas-pcard-bar" aria-hidden="true">+ <span class="d"></span>+ <span class="d"></span>+ <span class="d"></span>+ <span class="url">three.ws/agent/preview</span>+ </div>+ <div class="h-saas-pcard-stage">+ <model-viewer+ src="/animations/robotexpressive.glb"+ auto-rotate+ auto-rotate-delay="0"+ rotation-per-second="22deg"+ interaction-prompt="none"+ camera-controls="false"+ disable-zoom+ shadow-intensity="0.4"+ exposure="0.8"+ environment-image="neutral"+ camera-orbit="0deg 80deg 5m"+ field-of-view="32deg"+ loading="lazy"+ ></model-viewer>+ <div class="h-saas-pcard-hud" aria-hidden="true">+ <span class="h-saas-pcard-chip">+ <span class="pulse"></span>+ A2A · MCP · ready+ </span>+ <span class="h-saas-pcard-chip tx">+ <code>3DAg…uPL</code>+ </span>+ </div>+ </div>+ </aside>+ </div>+ </section>++ <!-- 3. Compatible-with marquee -->+ <section class="h-saas-logos" aria-label="Compatible with">+ <p class="h-saas-logos-title">Compatible with the stack you already use</p>+ <div class="h-saas-marquee">+ <div class="h-saas-marquee-track">+ <span class="h-saas-mark"><span class="glyph">◎</span>Solana</span>+ <span class="h-saas-mark"><span class="glyph">M</span>Metaplex Core</span>+ <span class="h-saas-mark"><span class="glyph">⌘</span>MCP</span>+ <span class="h-saas-mark"><span class="glyph">A</span>A2A</span>+ <span class="h-saas-mark"><span class="glyph">8</span>ERC-8004</span>+ <span class="h-saas-mark"><span class="glyph">G</span>glTF 2.0</span>+ <span class="h-saas-mark"><span class="glyph">▲</span>Vercel</span>+ <span class="h-saas-mark"><span class="glyph">◬</span>Three.js</span>+ <span class="h-saas-mark"><span class="glyph">$</span>x402</span>+ <span class="h-saas-mark"><span class="glyph">H</span>Helius</span>+ <span class="h-saas-mark"><span class="glyph">N</span>Neon</span>+ <span class="h-saas-mark"><span class="glyph">P</span>Phantom</span>+ <span class="h-saas-mark" aria-hidden="true"><span class="glyph">◎</span>Solana</span>+ <span class="h-saas-mark" aria-hidden="true"><span class="glyph">M</span>Metaplex Core</span>+ <span class="h-saas-mark" aria-hidden="true"><span class="glyph">⌘</span>MCP</span>+ <span class="h-saas-mark" aria-hidden="true"><span class="glyph">A</span>A2A</span>+ <span class="h-saas-mark" aria-hidden="true"><span class="glyph">8</span>ERC-8004</span>+ <span class="h-saas-mark" aria-hidden="true"><span class="glyph">G</span>glTF 2.0</span>+ <span class="h-saas-mark" aria-hidden="true"><span class="glyph">▲</span>Vercel</span>+ <span class="h-saas-mark" aria-hidden="true"><span class="glyph">◬</span>Three.js</span>+ <span class="h-saas-mark" aria-hidden="true"><span class="glyph">$</span>x402</span>+ <span class="h-saas-mark" aria-hidden="true"><span class="glyph">H</span>Helius</span>+ <span class="h-saas-mark" aria-hidden="true"><span class="glyph">N</span>Neon</span>+ <span class="h-saas-mark" aria-hidden="true"><span class="glyph">P</span>Phantom</span>+ </div>+ </div>+ </section>++ <!-- 4. Live metrics (real /api/home-stats; hides if unavailable) -->+ <section+ class="h-saas-metrics"+ data-saas-metrics+ hidden+ aria-label="Live platform metrics"+ >+ <div class="h-saas-inner">+ <div class="h-saas-metrics-head h-saas-reveal">+ <span class="h-saas-eyebrow"+ ><span class="dot"></span>Live numbers</span+ >+ <h2 class="h-saas-section-title">Real agents. Real chains. Real time.</h2>+ <p class="h-saas-section-sub">+ Pulled directly from the index — refreshed every minute.+ </p>+ </div>+ <div class="h-saas-metrics-grid h-saas-reveal">+ <div class="h-saas-metric">+ <span class="h-saas-metric-num" data-saas-metric="agents">0</span>+ <span class="h-saas-metric-label">Agents created</span>+ </div>+ <div class="h-saas-metric">+ <span class="h-saas-metric-num" data-saas-metric="onchain_agents"+ >0</span+ >+ <span class="h-saas-metric-label">Onchain identities</span>+ </div>+ <div class="h-saas-metric">+ <span class="h-saas-metric-num" data-saas-metric="widgets">0</span>+ <span class="h-saas-metric-label">Widgets deployed</span>+ </div>+ <div class="h-saas-metric">+ <span class="h-saas-metric-num" data-saas-metric="chains">0</span>+ <span class="h-saas-metric-label">Chains indexed</span>+ </div>+ </div>+ </div>+ </section>++ <!-- 5. Audience tabs -->+ <section class="h-saas-section" aria-label="Built for">+ <div class="h-saas-inner">+ <div class="h-saas-section-head h-saas-reveal">+ <span class="h-saas-eyebrow"+ ><span class="dot"></span>Built for builders</span+ >+ <h2 class="h-saas-section-title">+ One platform.<br />+ Four kinds of teams.+ </h2>+ <p class="h-saas-section-sub">+ Whatever you ship, three.ws is the layer that gives your agent a face,+ a wallet, and a home onchain.+ </p>+ </div>+ <div class="h-saas-tabwrap h-saas-reveal">+ <div class="h-saas-tabs" role="tablist" data-saas-tabs>+ <button+ class="h-saas-tab"+ role="tab"+ aria-selected="true"+ data-saas-panel="<strong>Creators</strong> — turn your character into an animated 3D agent that chats on Twitter, replies to fans, and lives on its own page. Free to start, mint when you're ready."+ >+ Creators+ </button>+ <button+ class="h-saas-tab"+ role="tab"+ aria-selected="false"+ data-saas-panel="<strong>Developers</strong> — drop the <code><agent-3d></code> web component into any page; wire MCP tools and A2A endpoints; ship in minutes with no SDK on the consumer side."+ >+ Developers+ </button>+ <button+ class="h-saas-tab"+ role="tab"+ aria-selected="false"+ data-saas-panel="<strong>DAOs & protocols</strong> — give your governance agent or treasury bot a verifiable Metaplex Core identity, attestations, and a discoverable A2A endpoint."+ >+ DAOs+ </button>+ <button+ class="h-saas-tab"+ role="tab"+ aria-selected="false"+ data-saas-panel="<strong>Brands & enterprises</strong> — deploy customer-facing 3D agents with full white-label branding, embeddable widgets, and an audit trail of every interaction."+ >+ Brands+ </button>+ </div>+ <p class="h-saas-tabpanel" data-saas-tabpanel></p>+ </div>+ </div>+ </section>++ <!-- 6. Use cases (real avatars) -->+ <section class="h-saas-section" aria-label="What you can build">+ <div class="h-saas-inner">+ <div class="h-saas-section-head h-saas-reveal">+ <span class="h-saas-eyebrow"+ ><span class="dot"></span>What you can build</span+ >+ <h2 class="h-saas-section-title">From character to chain in 60 seconds.</h2>+ <p class="h-saas-section-sub">+ Three real agents shipped on three.ws — hover any card to interact.+ </p>+ </div>+ <div class="h-saas-cases">+ <article class="h-saas-case h-saas-reveal">+ <div class="h-saas-case-stage">+ <model-viewer+ src="/animations/robotexpressive.glb"+ auto-rotate+ auto-rotate-delay="0"+ rotation-per-second="24deg"+ interaction-prompt="none"+ camera-controls="false"+ disable-zoom+ shadow-intensity="0"+ exposure="0.85"+ environment-image="neutral"+ camera-orbit="15deg 80deg 4m"+ field-of-view="38deg"+ loading="lazy"+ ></model-viewer>+ </div>+ <div class="h-saas-case-body">+ <span class="h-saas-case-kicker">Character agent</span>+ <h3 class="h-saas-case-title">Robot — animated, embeddable.</h3>+ <p class="h-saas-case-desc">+ Drop a GLB, pick from 12+ animations, drop one tag on any+ page. Used by creators on Twitter and personal sites.+ </p>+ <a class="h-saas-case-link" href="/app">Open the viewer →</a>+ </div>+ </article>+ <article class="h-saas-case h-saas-reveal">+ <div class="h-saas-case-stage">+ <model-viewer+ src="/animations/soldier.glb"+ auto-rotate+ auto-rotate-delay="0"+ rotation-per-second="24deg"+ interaction-prompt="none"+ camera-controls="false"+ disable-zoom+ shadow-intensity="0"+ exposure="0.85"+ environment-image="neutral"+ camera-orbit="15deg 80deg 4m"+ field-of-view="38deg"+ loading="lazy"+ ></model-viewer>+ </div>+ <div class="h-saas-case-body">+ <span class="h-saas-case-kicker">Studio</span>+ <h3 class="h-saas-case-title">Soldier — full animation library.</h3>+ <p class="h-saas-case-desc">+ Idle, walk, run, jump, dance, wave, punch. Bring your own+ Mixamo or load any glTF rig directly in the studio.+ </p>+ <a class="h-saas-case-link" href="/studio">Open Widget Studio →</a>+ </div>+ </article>+ <article class="h-saas-case h-saas-reveal">+ <div class="h-saas-case-stage">+ <model-viewer+ src="/avatars/cz.glb"+ auto-rotate+ auto-rotate-delay="0"+ rotation-per-second="24deg"+ interaction-prompt="none"+ camera-controls="false"+ disable-zoom+ shadow-intensity="0"+ exposure="0.85"+ environment-image="neutral"+ camera-orbit="15deg 80deg 4m"+ field-of-view="38deg"+ loading="lazy"+ ></model-viewer>+ </div>+ <div class="h-saas-case-body">+ <span class="h-saas-case-kicker">Live onchain</span>+ <h3 class="h-saas-case-title">CZ — full talking agent.</h3>+ <p class="h-saas-case-desc">+ A real agent shipped on three.ws: 3D avatar, voice chat,+ animations, x402-paid skills, and a Solana wallet.+ </p>+ <a class="h-saas-case-link" href="/cz">Visit /cz →</a>+ </div>+ </article>+ </div>+ </div>+ </section>++ <!-- 7. Copyable snippet -->+ <section class="h-saas-section" aria-label="Drop one tag">+ <div class="h-saas-inner">+ <div class="h-saas-section-head h-saas-reveal">+ <span class="h-saas-eyebrow"+ ><span class="dot"></span>Ship in two lines</span+ >+ <h2 class="h-saas-section-title">+ Drop one script. Drop one tag. Done.+ </h2>+ <p class="h-saas-section-sub">+ The <code><agent-3d></code> web component lazy-loads, renders+ anywhere — Notion, Ghost, WordPress, Framer, your custom Next.js+ app — and connects to your stack via MCP or A2A.+ </p>+ </div>+ <div class="h-saas-codecard h-saas-reveal">+ <div class="h-saas-codecard-bar" aria-hidden="true">+ <span class="d"></span>+ <span class="d"></span>+ <span class="d"></span>+ <span class="filename">index.html</span>+ <button+ type="button"+ class="h-saas-copy"+ data-saas-copy="#h-saas-snippet"+ aria-label="Copy code"+ >+ Copy+ </button>+ </div>+ <pre id="h-saas-snippet"><code><span class="c"><!-- 1. Load the component (lazy, ~14kb gzipped) --></span>+<span class="tag"><script</span> <span class="attr">type</span>=<span class="val">"module"</span>+ <span class="attr">src</span>=<span class="val">"https://three.ws/agent-3d/latest/agent-3d.js"</span><span class="tag">></script></span>++<span class="c"><!-- 2. Drop the tag — that's it --></span>+<span class="tag"><agent-3d</span>+ <span class="attr">agent-id</span>=<span class="val">"3DAg…uPL"</span>+ <span class="attr">kiosk</span>+<span class="tag">></agent-3d></span></code></pre>+ </div>+ </div>+ </section>++ <!-- 8. Integration grid -->+ <section class="h-saas-section" aria-label="Integrations">+ <div class="h-saas-inner">+ <div class="h-saas-section-head h-saas-reveal">+ <span class="h-saas-eyebrow"+ ><span class="dot"></span>Open by design</span+ >+ <h2 class="h-saas-section-title">+ Plays nicely with everything in your stack.+ </h2>+ <p class="h-saas-section-sub">+ No vendor lock-in. Standards-first. Bring your own LLM, wallet, RPC,+ and host — three.ws stays out of the way.+ </p>+ </div>+ <div class="h-saas-int-grid h-saas-reveal">+ <div class="h-saas-int"><span class="glyph">◎</span><span class="h-saas-int-name">Solana</span></div>+ <div class="h-saas-int"><span class="glyph">M</span><span class="h-saas-int-name">Metaplex Core</span></div>+ <div class="h-saas-int"><span class="glyph">⌘</span><span class="h-saas-int-name">MCP</span></div>+ <div class="h-saas-int"><span class="glyph">A</span><span class="h-saas-int-name">A2A</span></div>+ <div class="h-saas-int"><span class="glyph">8</span><span class="h-saas-int-name">ERC-8004</span></div>+ <div class="h-saas-int"><span class="glyph">G</span><span class="h-saas-int-name">glTF 2.0</span></div>+ <div class="h-saas-int"><span class="glyph">◬</span><span class="h-saas-int-name">Three.js</span></div>+ <div class="h-saas-int"><span class="glyph">▲</span><span class="h-saas-int-name">Vercel</span></div>+ <div class="h-saas-int"><span class="glyph">$</span><span class="h-saas-int-name">x402</span></div>+ <div class="h-saas-int"><span class="glyph">H</span><span class="h-saas-int-name">Helius</span></div>+ <div class="h-saas-int"><span class="glyph">N</span><span class="h-saas-int-name">Neon</span></div>+ <div class="h-saas-int"><span class="glyph">P</span><span class="h-saas-int-name">Phantom</span></div>+ </div>+ </div>+ </section>++ <!-- 9. Pricing teaser -->+ <section class="h-saas-section" aria-label="Pricing">+ <div class="h-saas-inner h-saas-price">+ <div class="h-saas-price-copy h-saas-reveal">+ <span class="h-saas-eyebrow"+ ><span class="dot"></span>Free to start</span+ >+ <h2>No subscription.<br />Just per-mint costs.</h2>+ <p>+ Use the viewer, embed widgets, build agents, and explore the studio+ for free. Pay only the Solana network fee — about a cent — when you+ mint an onchain identity. Optional paid plans unlock higher quotas,+ team seats and audit logs.+ </p>+ <ul class="h-saas-price-bullets">+ <li>Unlimited drafts and animations in the studio.</li>+ <li>Embed widgets on any site with one tag.</li>+ <li>Native MCP + A2A endpoints out of the box.</li>+ <li>Your keys, your asset — owned on Solana.</li>+ </ul>+ <a href="/pricing" class="h-saas-btn h-saas-btn--ghost">+ Compare plans+ <span class="arrow">→</span>+ </a>+ </div>+ <div class="h-saas-price-card h-saas-reveal">+ <span class="h-saas-price-tier">Free forever</span>+ <div class="h-saas-price-amount">$0<small>/month</small></div>+ <p class="h-saas-price-note">+ ~$0.01 one-time mint fee on Solana</p>+ <a href="/create" class="h-saas-btn h-saas-btn--primary">+ <span>Create your agent</span>+ <span class="arrow">→</span>+ </a>+ <div class="h-saas-price-foot">+ <span>No credit card.</span>+ <a href="/docs">Read the docs</a>+ </div>+ </div>+ </div>+ </section>++ <!-- 10. Closing CTA band -->+ <section class="h-saas-cta-band" aria-label="Get started">+ <span class="h-saas-eyebrow h-saas-reveal"+ ><span class="dot"></span>Ship today</span+ >+ <h2 class="h-saas-cta-h h-saas-reveal">+ Give your AI a <em>body</em>.<br />In 60 seconds.+ </h2>+ <p class="h-saas-cta-p h-saas-reveal">+ No install. No SDK on the consumer side. Free to start. Owned on Solana.+ </p>+ <div class="h-saas-cta-row h-saas-reveal">+ <a href="/create" class="h-saas-btn h-saas-btn--primary">+ <span>Start free</span>+ <span class="arrow">→</span>+ </a>+ <a href="/docs" class="h-saas-btn h-saas-btn--ghost">Read the docs</a>+ </div>+ </section>+ </div>+<!-- ── Hero (parallax act) ── --><section class="h-hero-act"><!-- Depth 8: fluid particles + nebula -->diff --git a/pages/marketplace.html b/pages/marketplace.htmlindex 6e98faf98..460278b5d 100644--- a/pages/marketplace.html+++ b/pages/marketplace.html@@ -16,6 +16,7 @@<link rel="stylesheet" href="/marketplace.css" /><link rel="stylesheet" href="/marketplace-skills.css" /><link rel="stylesheet" href="/marketplace-v2.css" />+ <link rel="stylesheet" href="/marketplace-improvements.css" /><link rel="stylesheet" href="/fonts/fonts.css" /><style>/* Author display rules on modal overlays override the UA stylesheet's@@ -1494,6 +1495,30 @@<h3>What can you do with this Agent?</h3><p id="d-overview">—</p></div>++ <!-- Ratings & reviews -->+ <section class="d-rating-widget" id="d-rating-widget" aria-label="Ratings and reviews">+ <div class="d-rating-summary" id="d-rating-summary">+ <span class="avg" id="d-rating-avg">—</span>+ <span class="stars" id="d-rating-stars">☆☆☆☆☆</span>+ <span class="count" id="d-rating-count">No reviews yet</span>+ </div>+ <div class="d-rating-input" id="d-rating-input" hidden>+ <span style="font-size:12px;color:var(--mk-text-2)">Your rating:</span>+ <span class="stars" id="d-rating-pick" role="radiogroup" aria-label="Pick a rating">+ <button type="button" class="star-pick" data-rating="1" aria-label="1 star">☆</button>+ <button type="button" class="star-pick" data-rating="2" aria-label="2 stars">☆</button>+ <button type="button" class="star-pick" data-rating="3" aria-label="3 stars">☆</button>+ <button type="button" class="star-pick" data-rating="4" aria-label="4 stars">☆</button>+ <button type="button" class="star-pick" data-rating="5" aria-label="5 stars">☆</button>+ </span>+ <textarea id="d-review-body" placeholder="Write a short review (optional)" maxlength="2000"></textarea>+ <button type="button" class="submit-review" id="d-review-submit" disabled>Submit review</button>+ </div>+ <div class="d-rating-msg" id="d-rating-msg" role="status" aria-live="polite"></div>+ <div class="d-reviews-list" id="d-reviews-list"></div>+ </section>+<div class="market-preview-card" id="d-preview-card"><div class="market-preview-head"><h2 class="market-section-title" style="margin:0">Try it now</h2>diff --git a/public/dashboard/embed-policy.html b/public/dashboard/embed-policy.htmlindex 5d4d631c6..68333d517 100644--- a/public/dashboard/embed-policy.html+++ b/public/dashboard/embed-policy.html@@ -358,7 +358,31 @@</div><label for="brain-model">Model</label>- <input type="text" id="brain-model" placeholder="claude-opus-4-6" />+ <select id="brain-model">+ <optgroup label="Free — host-paid (recommended)">+ <option value="meta-llama/llama-3.3-70b-instruct:free">+ OpenRouter · Llama 3.3 70B (free) — default+ </option>+ <option value="openai/gpt-oss-120b:free">+ OpenRouter · GPT-OSS 120B (free)+ </option>+ <option value="nousresearch/hermes-3-llama-3.1-405b:free">+ OpenRouter · Hermes 3 405B (free)+ </option>+ <option value="llama-3.3-70b-versatile">+ Groq · Llama 3.3 70B (free, sub-second)+ </option>+ <option value="llama-3.1-8b-instant">+ Groq · Llama 3.1 8B (free, fastest)+ </option>+ </optgroup>+ <optgroup label="Paid Claude — uses host's Anthropic key">+ <option value="claude-haiku-4-5-20251001">Claude Haiku 4.5</option>+ <option value="claude-sonnet-4-6">Claude Sonnet 4.6</option>+ <option value="claude-opus-4-6">Claude Opus 4.6</option>+ <option value="claude-opus-4-7">Claude Opus 4.7</option>+ </optgroup>+ </select></fieldset></div>@@ -490,7 +514,8 @@document.getElementById('brain-proxy-url').value = '';document.getElementById('brain-quota').value = '1000';document.getElementById('brain-rate').value = '10';- document.getElementById('brain-model').value = 'claude-opus-4-6';+ document.getElementById('brain-model').value =+ 'meta-llama/llama-3.3-70b-instruct:free';document.getElementById('storage-primary').value = 'r2';document.getElementById('storage-ipfs').checked = false;document.getElementById('storage-attested').checked = false;@@ -516,7 +541,8 @@brain.monthly_quota != null ? String(brain.monthly_quota) : '';document.getElementById('brain-rate').value =brain.rate_limit_per_min != null ? String(brain.rate_limit_per_min) : '';- document.getElementById('brain-model').value = brain.model || 'claude-opus-4-6';+ document.getElementById('brain-model').value =+ brain.model || 'meta-llama/llama-3.3-70b-instruct:free';const storage = policy.storage || {};document.getElementById('storage-primary').value = storage.primary || 'r2';@@ -569,7 +595,7 @@rate_limit_per_min: numOrNull('brain-rate'),model:document.getElementById('brain-model').value.trim() ||- 'claude-opus-4-6',+ 'meta-llama/llama-3.3-70b-instruct:free',},storage: {primary: document.getElementById('storage-primary').value,diff --git a/public/docs/api-reference.md b/public/docs/api-reference.mdindex 9f4bc2312..cebd61543 100644--- a/public/docs/api-reference.md+++ b/public/docs/api-reference.md@@ -558,26 +558,31 @@ Usage events (token counts, latency, triggered actions) are recorded after each----### Anthropic LLM proxy+### We-pay LLM proxy```POST /api/llm/anthropic?agent=<agent_id>```-"We-pay" proxy to the Anthropic Messages API. Enforces the agent's embed policy (allowed origins, allowed surfaces, brain mode) and deducts from the agent's monthly token budget.+"We-pay" proxy. Enforces the agent's embed policy (allowed origins, allowed surfaces, brain mode) and deducts from the agent's monthly token budget. The request body is always Anthropic-shape; the server inspects `model` and routes to Anthropic, Groq, or OpenRouter, translating wire formats both ways so the response stream is also Anthropic-shape.Requires that the calling origin is listed in the agent's declared `origins`. Wildcard patterns are supported.**Supported models**-| Model ID | Notes |-|----------|-------|-| `claude-opus-4-6` | |-| `claude-opus-4-7` | |-| `claude-sonnet-4-6` | |-| `claude-haiku-4-5` | |--Request and response format match the [Anthropic Messages API](https://docs.anthropic.com/en/api/messages) exactly. Upstream errors are sanitized before being returned to the client.+| Model ID | Upstream | Cost |+|----------|----------|------|+| `meta-llama/llama-3.3-70b-instruct:free` | OpenRouter | free (default) |+| `openai/gpt-oss-120b:free` | OpenRouter | free |+| `nousresearch/hermes-3-llama-3.1-405b:free` | OpenRouter | free |+| `llama-3.3-70b-versatile` | Groq | free, sub-second |+| `llama-3.1-8b-instant` | Groq | free, fastest |+| `claude-haiku-4-5-20251001` | Anthropic | paid |+| `claude-sonnet-4-6` | Anthropic | paid |+| `claude-opus-4-6` | Anthropic | paid |+| `claude-opus-4-7` | Anthropic | paid |++Request and response format match the [Anthropic Messages API](https://docs.anthropic.com/en/api/messages) exactly. Free-model routes are translated server-side. Upstream errors are sanitized before being returned to the client.**Rate limits:** Per-IP and per-agent limits apply in addition to the standard platform limits.diff --git a/public/home-saas.js b/public/home-saas.jsindex 19e324271..7bb9b4beb 100644--- a/public/home-saas.js+++ b/public/home-saas.js@@ -153,7 +153,7 @@t.tabIndex = on ? 0 : -1;});const active = tabs[idx];- panel.innerHTML = active.dataset.saasCopy || '';+ panel.innerHTML = active.dataset.saasPanel || '';};tabs.forEach((tab, i) => {diff --git a/scratch/verify-create-review.mjs b/scratch/verify-create-review.mjsnew file mode 100644index 000000000..e2421d17a--- /dev/null+++ b/scratch/verify-create-review.mjs@@ -0,0 +1,143 @@+import { chromium } from 'playwright';+import { readFileSync } from 'fs';+import { resolve } from 'path';++const BASE = process.env.BASE_URL || 'http://localhost:3000';+const GLB_PATH = resolve(process.cwd(), 'public/avatars/default.glb');++const step = (m) => console.log(`\n── ${m}`);++(async () => {+ const browser = await chromium.launch();+ const ctx = await browser.newContext();+ const page = await ctx.newPage();+ const consoleErrors = [];+ page.on('console', (m) => {+ if (m.type() === 'error') consoleErrors.push(m.text());+ });+ page.on('pageerror', (e) => consoleErrors.push(`[pageerror] ${e.message}`));++ try {+ step('1. /create loads anonymously, cards enabled');+ await page.goto(`${BASE}/create`, { waitUntil: 'networkidle' });+ await page.waitForFunction(() => window.__authed !== undefined, null, { timeout: 10000 });+ const authed = await page.evaluate(() => window.__authed);+ console.log(` __authed = ${authed}`);+ if (authed) throw new Error('expected anonymous; dev API proxy returned an authed user');+ const cards = await page.$$eval('[role="button"][id^="card-"]', (els) =>+ els.map((el) => ({ id: el.id, disabled: el.getAttribute('aria-disabled') })),+ );+ console.log(' cards:', Object.fromEntries(cards.map((c) => [c.id, c.disabled || 'enabled'])));+ const upload = cards.find((c) => c.id === 'card-upload-glb');+ if (upload?.disabled === 'true') throw new Error('upload card disabled while unauthed');++ step('2. upload a real GLB → stage → navigate to /create-review');+ const glbBytes = readFileSync(GLB_PATH);+ console.log(` GLB = ${glbBytes.length} bytes`);+ const navPromise = page.waitForURL(/\/create-review/, { timeout: 15000 });+ const fileInput = await page.$('#glb-input');+ if (!fileInput) throw new Error('#glb-input not found');+ await fileInput.setInputFiles({+ name: 'test-avatar.glb',+ mimeType: 'model/gltf-binary',+ buffer: glbBytes,+ });+ await navPromise;+ console.log(' ✓ landed on /create-review');++ step('3. review page renders the blob');+ await page.waitForSelector('#content:not([hidden])', { timeout: 5000 });+ await page.waitForFunction(+ () => {+ const mv = document.getElementById('mv');+ return mv && mv.src && mv.style.visibility !== 'hidden';+ },+ null,+ { timeout: 15000 },+ );+ const src = await page.$eval('#mv', (el) => el.src);+ if (!src?.startsWith('blob:')) throw new Error(`expected blob: src, got ${src}`);+ console.log(` ✓ #mv.src = ${src.slice(0, 50)}…`);+ console.log(` tag-size = ${await page.$eval('#tag-size', (el) => el.textContent)}`);++ step('4. guest CTA flips to "Sign in to save"');+ await page.waitForFunction(() => window.__authed === false, null, { timeout: 5000 });+ await page.waitForFunction(+ () => document.querySelector('#save-btn')?.textContent.trim() === 'Sign in to save',+ null,+ { timeout: 5000 },+ );+ const guestVisible = await page.$eval('#guest-note', (el) => !el.hidden);+ if (!guestVisible) throw new Error('#guest-note hidden for unauthed user');+ console.log(' ✓ save btn + guest note correct');++ step('5. IDB record matches uploaded bytes');+ const idb = await page.evaluate(async () => {+ return new Promise((resolve) => {+ const r = indexedDB.open('three-ws-guest', 1);+ r.onsuccess = () => {+ const db = r.result;+ const g = db.transaction('avatars', 'readonly').objectStore('avatars').get('pending');+ g.onsuccess = () =>+ resolve(+ g.result+ ? { id: g.result.id, size: g.result.size, blobSize: g.result.blob?.size }+ : null,+ );+ g.onerror = () => resolve(null);+ };+ r.onerror = () => resolve(null);+ });+ });+ console.log(' IDB:', idb);+ if (!idb?.id) throw new Error('no IDB record at three-ws-guest/pending');+ if (idb.blobSize !== glbBytes.length) {+ throw new Error(`IDB blob size mismatch: ${idb.blobSize} vs ${glbBytes.length}`);+ }++ step('6. Start over clears IDB + returns to /create');+ page.once('dialog', (d) => d.accept());+ const back = page.waitForURL(/\/create(\?|$)/, { timeout: 5000 });+ await page.click('#start-over-btn');+ await back;+ const cleared = await page.evaluate(async () => {+ return new Promise((resolve) => {+ const r = indexedDB.open('three-ws-guest', 1);+ r.onsuccess = () => {+ const db = r.result;+ const g = db.transaction('avatars', 'readonly').objectStore('avatars').get('pending');+ g.onsuccess = () => resolve(g.result || null);+ g.onerror = () => resolve(null);+ };+ r.onerror = () => resolve(null);+ });+ });+ if (cleared) throw new Error('IDB not cleared after Start over');+ console.log(' ✓ IDB cleared');++ step('7. /create-review with nothing staged → empty state');+ await page.goto(`${BASE}/create-review`, { waitUntil: 'networkidle' });+ await page.waitForSelector('#empty-card:not([hidden])', { timeout: 5000 });+ if (!(await page.$eval('#content', (el) => el.hidden))) {+ throw new Error('expected #content hidden when nothing staged');+ }+ console.log(' ✓ empty state shown');++ const fatal = consoleErrors.filter(+ (e) =>+ !/model-viewer|webxr|favicon|@vite|\/api\/|Failed to load resource/.test(e),+ );+ if (fatal.length) {+ console.log('\n── fatal console errors:');+ for (const e of fatal) console.log(' ' + e);+ throw new Error(`${fatal.length} fatal console error(s)`);+ }+ console.log(`\n (${consoleErrors.length} non-fatal console messages filtered)`);+ console.log('\n✓ all checks passed');+ } finally {+ await browser.close();+ }+})().catch((err) => {+ console.error('\n✗ verification failed:', err.message);+ process.exitCode = 1;+});diff --git a/scratch/verify-home-v2.mjs b/scratch/verify-home-v2.mjsnew file mode 100644index 000000000..2fd5b7e4c--- /dev/null+++ b/scratch/verify-home-v2.mjs@@ -0,0 +1,38 @@+import { chromium } from 'playwright';+import { mkdirSync } from 'fs';+const OUT = '/workspaces/three.ws/scratch/home-v2-shots';+mkdirSync(OUT, { recursive: true });+const browser = await chromium.launch({ headless: true });+const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } });+const page = await ctx.newPage();+const errs = [];+page.on('console', (m) => { if (m.type() === 'error') errs.push(m.text()); });+page.on('pageerror', (e) => errs.push('PAGEERROR: ' + e.message));+console.log('→ loading /home-v2');+await page.goto('http://localhost:3000/home-v2', { waitUntil: 'domcontentloaded', timeout: 60_000 });+await page.waitForSelector('#hv2-chips .hv2-chip', { timeout: 10_000 });+const chipCount = await page.$$eval('#hv2-chips .hv2-chip', (els) => els.length);+console.log(`✓ chip strip rendered, ${chipCount} chips`);+console.log(`✓ tryme visible: ${await page.isVisible('#hv2-tryme')}`);+await page.waitForFunction(() => {+ const c = document.getElementById('hero-avatar');+ return c && getComputedStyle(c).opacity === '1';+}, { timeout: 30_000 }).catch(() => console.log('… hero canvas opacity never reached 1'));+await page.screenshot({ path: `${OUT}/01-hero-initial.png` });+console.log(`✓ saved ${OUT}/01-hero-initial.png`);+console.log('→ clicking Wave chip');+await page.click('.hv2-chip[data-anim="wave"]');+await page.waitForTimeout(1200);+console.log(`✓ counter: ${await page.textContent('#hv2-counter-num')}`);+console.log(`✓ tryme hidden: ${await page.$eval('#hv2-tryme', (el) => el.classList.contains('is-hidden'))}`);+await page.screenshot({ path: `${OUT}/02-after-wave.png` });+console.log(`✓ saved ${OUT}/02-after-wave.png`);+console.log('→ clicking Random');+await page.click('.hv2-chip[data-anim="__random"]');+await page.waitForTimeout(1500);+await page.screenshot({ path: `${OUT}/03-after-random.png` });+console.log(`✓ saved ${OUT}/03-after-random.png`);+console.log('\nconsole errors:', errs.length === 0 ? '(none)' : '');+for (const e of errs) console.log(' ' + e);+await browser.close();+console.log('✓ done');diff --git a/scripts/verify-home-saas.mjs b/scripts/verify-home-saas.mjsnew file mode 100644index 000000000..4ced44530--- /dev/null+++ b/scripts/verify-home-saas.mjs@@ -0,0 +1,100 @@+#!/usr/bin/env node+/**+ * Headless verification of the SaaS prologue on /home.+ * Loads the home page in Chromium against the running dev server, asserts:+ * - .h-saas exists and is positioned ABOVE the parallax hero+ * - hero h2 rendered, 12+ marquee items, 4 tabs, copy button present+ * - no console errors+ * Saves a full-page screenshot to /tmp/home-saas.png for visual review.+ */++import { chromium } from 'playwright';+import { argv } from 'node:process';++const BASE = argv[2] || 'http://localhost:3000';+const OUT = argv[3] || '/tmp/home-saas.png';++const consoleErrors = [];++const browser = await chromium.launch({ headless: true });+const ctx = await browser.newContext({+ viewport: { width: 1440, height: 900 },+ deviceScaleFactor: 1,+});+const page = await ctx.newPage();++page.on('console', (msg) => {+ if (msg.type() === 'error') consoleErrors.push(msg.text());+});+page.on('pageerror', (err) => consoleErrors.push('pageerror: ' + err.message));++await page.goto(BASE + '/', { waitUntil: 'networkidle', timeout: 60_000 });+await page.waitForTimeout(1500);++const saas = page.locator('.h-saas').first();+if (!(await saas.isVisible())) throw new Error('FAIL: .h-saas not visible');++const saasBox = await saas.boundingBox();+const heroBox = await page.locator('.h-hero-act').first().boundingBox();+if (!saasBox || !heroBox) throw new Error('FAIL: layout box missing');+if (saasBox.y >= heroBox.y) {+ throw new Error(+ `FAIL: prologue (y=${saasBox.y}) not above parallax hero (y=${heroBox.y})`,+ );+}++const h1 = (await page.locator('.h-saas-h1').first().innerText()).trim();+if (h1.length < 10) throw new Error('FAIL: SaaS h1 empty');++const marks = await page.locator('.h-saas-marquee-track .h-saas-mark').count();+if (marks < 12) throw new Error(`FAIL: expected 12+ marquee items, got ${marks}`);++const tabs = page.locator('[data-saas-tabs] [role="tab"]');+const tabCount = await tabs.count();+if (tabCount !== 4) throw new Error(`FAIL: expected 4 tabs, got ${tabCount}`);++await tabs.nth(2).click();+await page.waitForTimeout(140);+const panelText = await page.locator('[data-saas-tabpanel]').innerText();+if (!/DAO/i.test(panelText)) throw new Error('FAIL: tab switch did not update panel');++const copyBtns = await page.locator('[data-saas-copy]').count();+if (copyBtns === 0) throw new Error('FAIL: no copy button');++const statsResp = await page.evaluate(async () => {+ try {+ const r = await fetch('/api/home-stats');+ const txt = await r.text();+ let body = null;+ try {+ body = JSON.parse(txt);+ } catch {+ body = txt.slice(0, 80);+ }+ return { ok: r.ok, status: r.status, body };+ } catch (e) {+ return { ok: false, status: 0, err: String(e) };+ }+});++if (consoleErrors.length) {+ console.warn('--- console errors observed ---');+ consoleErrors.slice(0, 10).forEach((e) => console.warn(' ', e));+}++await page.screenshot({ path: OUT, fullPage: true });++console.log(JSON.stringify({+ prologueY: Math.round(saasBox.y),+ heroY: Math.round(heroBox.y),+ prologueHeight: Math.round(saasBox.height),+ h1: h1.slice(0, 90),+ marqueeItems: marks,+ tabs: tabCount,+ copyButtons: copyBtns,+ stats: statsResp,+ consoleErrors: consoleErrors.length,+ screenshot: OUT,+}, null, 2));++await browser.close();diff --git a/src/agent-detail.js b/src/agent-detail.jsindex 44dc367ff..397d515de 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -17,6 +17,7 @@ import {clusterApiUrl,} from '@solana/web3.js';const solanaWeb3 = { Connection, PublicKey, Transaction, SystemProgram, LAMPORTS_PER_SOL, clusterApiUrl };+import { openSwapModal } from './swap-jupiter.js';const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;@@ -530,8 +531,7 @@ function bindWalletActions() {});swapBtn.addEventListener('click', () => {- alert("Swap functionality coming soon!");-+ openSwapModal({ wallet, getProvider });});}diff --git a/src/attach-avatar-to-agent.js b/src/attach-avatar-to-agent.jsindex 3015f2b53..7df9038b3 100644--- a/src/attach-avatar-to-agent.js+++ b/src/attach-avatar-to-agent.js@@ -5,7 +5,7 @@ import { apiFetch } from './account.js';* endpoint doesn't accept `avatar_id`, so we get-or-create via /me and then* PUT to attach. Returns the updated agent record.*- * Shared by /create and /create/review — kept in its own module so neither+ * Shared by /create and /create-review — kept in its own module so neither* page's top-level boot() runs when the other imports it.** @param {string} avatarIddiff --git a/src/create-review.js b/src/create-review.jsindex 6a7d03c22..72dd8c1e1 100644--- a/src/create-review.js+++ b/src/create-review.js@@ -1,11 +1,11 @@/**- * /create/review — preview the in-progress avatar before it touches the server.+ * /create-review — preview the in-progress avatar before it touches the server.** Flow:* 1. Read the staged blob from IndexedDB via guest-avatar.js.* 2. Render it in the page's <model-viewer> from an object URL.* 3. "Save to my account":- * - If unauthed: redirect to /login?next=/create/review with a sentinel+ * - If unauthed: redirect to /login?next=/create-review with a sentinel* flag so we auto-resume the save when the user returns.* - If authed: presign + upload + attach to default agent, then go to /app.* 4. "Start over": clear the staged record and bounce back to /create.@@ -116,7 +116,7 @@ async function onSave({ auto = false } = {}) {if (window.__authed === false) {// Stash a sentinel so the post-login round-trip auto-resumes the save.sessionStorage.setItem(RESUME_KEY, '1');- const next = encodeURIComponent('/create/review');+ const next = encodeURIComponent('/create-review');window.location.href = `/login?next=${next}`;return;}@@ -147,7 +147,7 @@ async function onSave({ auto = false } = {}) {if (err.code === 'not_signed_in') {// Session expired between the cached auth hint and the actual save.sessionStorage.setItem(RESUME_KEY, '1');- const next = encodeURIComponent('/create/review');+ const next = encodeURIComponent('/create-review');window.location.href = `/login?next=${next}`;return;}diff --git a/src/create.js b/src/create.jsindex 603f4628a..df1832275 100644--- a/src/create.js+++ b/src/create.js@@ -23,7 +23,7 @@ document.addEventListener('three-ws:arkit-report', (event) => {// The selfie pipeline (/create/selfie) hits a server-side reconstruction job// that requires auth + counts against plan quota — we keep that gate. The// default editor, Studio iframe and direct GLB upload all stay anonymous;-// we stash the resulting blob in IndexedDB and let /create/review handle the+// we stash the resulting blob in IndexedDB and let /create-review handle the// "sign in to save" step after the user has seen their avatar.function requireAuthForSelfie() {if (window.__authed === false) {@@ -126,7 +126,7 @@ async function isAtAvatarLimit() {return false;}-// Stash the freshly generated GLB locally and send the user to /create/review,+// Stash the freshly generated GLB locally and send the user to /create-review,// where they preview the avatar before deciding whether to sign in and save.// Anonymous users get to see what they built before the auth wall; signed-in// users still go through the same review step so the flow is consistent.@@ -141,7 +141,7 @@ async function stageAndReview(blob, meta = {}) {return;}updateSaveOverlay('Opening preview…');- window.location.href = '/create/review';+ window.location.href = '/create-review';}function showSaveOverlay(label, sublabel) {diff --git a/src/editor/manifest-builder.js b/src/editor/manifest-builder.jsindex 368ed1169..f9dc9f75b 100644--- a/src/editor/manifest-builder.js+++ b/src/editor/manifest-builder.js@@ -8,10 +8,21 @@ import { PersonaInterview } from './persona-interview.js';// ─── Constants ────────────────────────────────────────────────────────────────+// Free models routed via the we-pay proxy (/api/llm/anthropic). Listed+// first so they're the default. The proxy translates request/response+// shapes server-side, so the browser provider stays Anthropic-shape.+const FREE_MODELS = [+ { id: 'meta-llama/llama-3.3-70b-instruct:free', label: 'Llama 3.3 70B (OpenRouter · free)' },+ { id: 'openai/gpt-oss-120b:free', label: 'GPT-OSS 120B (OpenRouter · free)' },+ { id: 'nousresearch/hermes-3-llama-3.1-405b:free', label: 'Hermes 3 405B (OpenRouter · free)' },+ { id: 'llama-3.3-70b-versatile', label: 'Llama 3.3 70B (Groq · free, sub-second)' },+ { id: 'llama-3.1-8b-instant', label: 'Llama 3.1 8B (Groq · free, fastest)' },+];const ANTHROPIC_MODELS = [- { id: 'claude-opus-4-7', label: 'Claude Opus 4.7' },- { id: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6' },{ id: 'claude-haiku-4-5-20251001', label: 'Claude Haiku 4.5' },+ { id: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6' },+ { id: 'claude-opus-4-6', label: 'Claude Opus 4.6' },+ { id: 'claude-opus-4-7', label: 'Claude Opus 4.7' },];const OPENAI_MODELS = [{ id: 'gpt-4o-2024-11-20', label: 'GPT-4o (Nov 2024)' },@@ -104,7 +115,7 @@ function defaultState() {rig: 'mixamo',boundingBoxHeight: 1.78,brainProvider: 'anthropic',- brainModel: 'claude-opus-4-6',+ brainModel: 'meta-llama/llama-3.3-70b-instruct:free',temperature: 0.7,maxTokens: 4096,thinking: 'auto',@@ -508,6 +519,10 @@ export function mountManifestBuilder(rootEl, options = {}) {function brainHtml() {const modelOpts = (models) =>models.map((m) => `<option value="${m.id}">${m.label}</option>`).join('');+ const groupedModelOpts = `+ <optgroup label="Free — host-paid (recommended)">${modelOpts(FREE_MODELS)}</optgroup>+ <optgroup label="Paid Claude (host's Anthropic key)">${modelOpts(ANTHROPIC_MODELS)}</optgroup>+ `;return `<details><summary>Brain</summary><div class="section-body">@@ -520,7 +535,7 @@ export function mountManifestBuilder(rootEl, options = {}) {<div class="field" id="brain-model-wrap"><label>Model</label><select id="f-brain-model">- ${modelOpts(ANTHROPIC_MODELS)}+ ${groupedModelOpts}</select></div><div class="field">@@ -957,9 +972,20 @@ export function mountManifestBuilder(rootEl, options = {}) {return;}if (wrap) wrap.style.display = '';- const models = provider === 'openai' ? OPENAI_MODELS : ANTHROPIC_MODELS;- sel.innerHTML = models.map((m) => `<option value="${m.id}">${m.label}</option>`).join('');- // Keep current value if it's in the new list+ const optHtml = (m) => `<option value="${m.id}">${m.label}</option>`;+ // 'anthropic' is the proxy-routed provider — surface free models alongside+ // Claude so users default to free unless they explicitly pick paid.+ let models;+ if (provider === 'openai') {+ models = OPENAI_MODELS;+ sel.innerHTML = models.map(optHtml).join('');+ } else {+ models = [...FREE_MODELS, ...ANTHROPIC_MODELS];+ sel.innerHTML = `+ <optgroup label="Free — host-paid (recommended)">${FREE_MODELS.map(optHtml).join('')}</optgroup>+ <optgroup label="Paid Claude (host's Anthropic key)">${ANTHROPIC_MODELS.map(optHtml).join('')}</optgroup>+ `;+ }if (models.find((m) => m.id === state.brainModel)) {sel.value = state.brainModel;} else {diff --git a/src/guest-avatar.js b/src/guest-avatar.jsindex 2e3f465e3..94e023a0f 100644--- a/src/guest-avatar.js+++ b/src/guest-avatar.js@@ -3,9 +3,9 @@* finish the create flow without signing in first. The flow is:** 1. /create produces a GLB Blob from the default editor / Studio / file upload.- * 2. We stage(blob, meta) into IndexedDB before navigating to /create/review.- * 3. /create/review reads it back, renders it, and on "Save" either uploads- * immediately (signed-in user) or sends the user through /login?next=/create/review+ * 2. We stage(blob, meta) into IndexedDB before navigating to /create-review.+ * 3. /create-review reads it back, renders it, and on "Save" either uploads+ * immediately (signed-in user) or sends the user through /login?next=/create-review* and the page picks up where it left off after auth.** Blobs go in IndexedDB (multi-MB GLBs would blow the localStorage quota).diff --git a/src/marketplace.js b/src/marketplace.jsindex e1f0fdd03..2b30dfa5d 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -1226,109 +1226,363 @@ async function startAgentFromAvatar() {}// ── Skills marketplace tab ───────────────────────────────────────────────+//+// Backed by /api/skills (marketplace_skills table). Server-side search ++// category + sort with cursor pagination, plus client-side free/paid filter,+// install/uninstall, and 1–5 star ratings.const skillsState = {loaded: false,loading: false,+ loadingMore: false,skills: [],+ cursor: null,q: '',filter: 'all',+ sort: 'popular',+ category: null,+ categories: [],+ detailId: null,};-async function loadSkillsTab(force = false) {- if (skillsState.loading) return;- if (skillsState.loaded && !force) {+async function loadSkillCategories() {+ try {+ const r = await fetch(`${API}/skills/categories`);+ if (!r.ok) return;+ const j = await r.json();+ skillsState.categories = Array.isArray(j?.categories) ? j.categories : [];+ renderSkillCategoryChips();+ } catch (err) {+ console.error('[marketplace] skills categories', err);+ }+}++function renderSkillCategoryChips() {+ const wrap = $('skills-cat-chips');+ if (!wrap) return;+ const all = `<button class="market-chip ${skillsState.category == null ? 'active' : ''}" data-skill-cat="">All</button>`;+ const chips = skillsState.categories.map((c) => {+ const active = skillsState.category === c.slug ? 'active' : '';+ return `<button class="market-chip ${active}" data-skill-cat="${escapeHtml(c.slug)}">${escapeHtml(c.label)}<span class="chip-count">${c.count}</span></button>`;+ }).join('');+ wrap.innerHTML = all + chips;+ wrap.querySelectorAll('[data-skill-cat]').forEach((b) => {+ b.addEventListener('click', () => {+ const slug = b.dataset.skillCat || null;+ if (slug === skillsState.category) return;+ skillsState.category = slug;+ renderSkillCategoryChips();+ loadSkillsTab(true);+ });+ });+}++async function loadSkillsTab(force = false, append = false) {+ if (skillsState.loading || skillsState.loadingMore) return;+ if (skillsState.loaded && !force && !append) {renderSkillsGrid();return;}- skillsState.loading = true;+ if (append) skillsState.loadingMore = true;+ else skillsState.loading = true;+const grid = $('skills-grid');- if (grid) grid.innerHTML = renderSkeletons(8);+ if (grid && !append) grid.innerHTML = renderSkeletons(8);try {- const url = new URL(`${API}/marketplace/agents`, location.origin);- url.searchParams.set('limit', '48');- const r = await fetch(url);+ const url = new URL(`${API}/skills`, location.origin);+ url.searchParams.set('limit', '24');+ if (skillsState.q) url.searchParams.set('q', skillsState.q);+ if (skillsState.category) url.searchParams.set('category', skillsState.category);+ if (skillsState.sort) url.searchParams.set('sort', skillsState.sort);+ if (append && skillsState.cursor) url.searchParams.set('cursor', skillsState.cursor);++ const r = await fetch(url, { credentials: 'include' });+ if (!r.ok) throw new Error(`HTTP ${r.status}`);const j = await r.json();- const items = Array.isArray(j) ? j : (j?.data?.items ?? []);-- const flat = [];- for (const a of items) {- const skills = Array.isArray(a.skills) ? a.skills : [];- for (const s of skills) {- const name = typeof s === 'string' ? s : s?.name;- if (!name) continue;- flat.push({- name: String(name),- agentId: a.id,- agentName: a.name || 'Untitled',- agentAuthor: a.author_name || 'Anonymous',- agentAvatar: a.thumbnail_url || null,- paid: !!a.has_paid_skills,- category: a.category,- });- }- }- flat.sort((a, b) => Number(b.paid) - Number(a.paid) || a.name.localeCompare(b.name));- skillsState.skills = flat;+ const incoming = Array.isArray(j?.skills) ? j.skills : [];++ if (append) skillsState.skills = skillsState.skills.concat(incoming);+ else skillsState.skills = incoming;+ skillsState.cursor = j?.next_cursor || null;skillsState.loaded = true;} catch (err) {console.error('[marketplace] skills load', err);+ if (grid && !append) {+ grid.innerHTML = `<div class="market-empty">Failed to load skills. <button id="skills-retry" class="market-empty-cta-btn">Retry</button></div>`;+ $('skills-retry')?.addEventListener('click', () => loadSkillsTab(true));+ }} finally {skillsState.loading = false;+ skillsState.loadingMore = false;}renderSkillsGrid();}+function isPaidSkill(s) {+ return Number(s?.price_per_call_usd) > 0;+}++function skillToolCount(s) {+ return Array.isArray(s?.schema_json) ? s.schema_json.length : 0;+}+function renderSkillsGrid() {const grid = $('skills-grid');if (!grid) return;- const q = skillsState.q.toLowerCase();const filtered = skillsState.skills.filter((s) => {- if (skillsState.filter === 'paid' && !s.paid) return false;- if (skillsState.filter === 'free' && s.paid) return false;- if (q && !(s.name.toLowerCase().includes(q) || s.agentName.toLowerCase().includes(q))) return false;+ if (skillsState.filter === 'paid' && !isPaidSkill(s)) return false;+ if (skillsState.filter === 'free' && isPaidSkill(s)) return false;return true;});+const sub = $('skills-subtitle');- if (sub) sub.textContent = `${filtered.length} ${filtered.length === 1 ? 'skill' : 'skills'} across the marketplace`;+ if (sub) {+ const cat = skillsState.category+ ? (skillsState.categories.find((c) => c.slug === skillsState.category)?.label || skillsState.category)+ : null;+ const noun = filtered.length === 1 ? 'skill' : 'skills';+ sub.textContent = cat+ ? `${filtered.length} ${noun} in ${cat}${skillsState.cursor ? '+' : ''}`+ : `Browse ${filtered.length}${skillsState.cursor ? '+' : ''} ${noun} from the community`;+ }++ const loadMoreRow = $('skills-loadmore-row');+ if (loadMoreRow) loadMoreRow.hidden = !skillsState.cursor;if (!filtered.length) {const msg = !skillsState.skills.length? `<div class="market-empty-cta">- <h3>No skills published yet</h3>- <p>Skills appear here once agents are published with capabilities. Be the first to publish.</p>- <button id="skills-empty-publish">Submit an Agent</button>+ <h3>No skills found</h3>+ <p>Try a different category, clear your search, or publish your own skill.</p>+ <div class="market-empty-cta-actions">+ <button class="market-empty-cta-btn" id="skills-empty-clear">Clear filters</button>+ <button class="market-empty-cta-btn primary" id="skills-empty-publish">Publish a Skill</button>+ </div></div>`- : '<div class="market-empty">No skills match your filter.</div>';+ : '<div class="market-empty">No skills match your free/paid filter.</div>';grid.innerHTML = msg;- const btn = $('skills-empty-publish');- if (btn) btn.addEventListener('click', openSubmitModal);+ $('skills-empty-clear')?.addEventListener('click', () => {+ skillsState.q = '';+ skillsState.category = null;+ skillsState.filter = 'all';+ const input = $('skills-search'); if (input) input.value = '';+ document.querySelectorAll('[data-skill-filter]').forEach((c) => {+ c.classList.toggle('active', c.dataset.skillFilter === 'all');+ });+ renderSkillCategoryChips();+ loadSkillsTab(true);+ });+ $('skills-empty-publish')?.addEventListener('click', openSubmitModal);return;}+grid.innerHTML = filtered.map(renderSkillCard).join('');- grid.querySelectorAll('[data-agent-id]').forEach((card) => {+ grid.querySelectorAll('[data-skill-id]').forEach((card) => {card.addEventListener('click', () => {- const id = card.dataset.agentId;- if (id) navTo(`/marketplace/agents/${id}`);+ const id = card.dataset.skillId;+ if (id) openSkillModal(id);});});}function renderSkillCard(s) {- const av = s.agentAvatar- ? `<span class="av" style="background:url('${escapeHtml(s.agentAvatar)}') center/cover"></span>`- : `<span class="av">${escapeHtml(initial(s.agentName))}</span>`;- return `<div class="market-skill-card" data-agent-id="${escapeHtml(s.agentId)}">+ const paid = isPaidSkill(s);+ const installed = !!s.installed;+ const rating = Number(s.avg_rating) || 0;+ const installs = Number(s.install_count) || 0;+ const tools = skillToolCount(s);+ const category = s.category || 'general';+ const ratingDisplay = s.rating_count > 0+ ? `<span class="rating" title="${rating.toFixed(1)} from ${s.rating_count} ${s.rating_count === 1 ? 'rating' : 'ratings'}">★ ${rating.toFixed(1)}</span>`+ : '';+ const installsDisplay = installs > 0+ ? `<span class="installs" title="${installs.toLocaleString()} installs">${fmtNumber(installs)} installs</span>`+ : '';+ const toolsDisplay = tools > 0+ ? `<span class="installs">${tools} tool${tools === 1 ? '' : 's'}</span>`+ : '';+ const installedTag = installed+ ? `<span class="skill-installed-tag" title="Installed">✓ Installed</span>`+ : '';+ const desc = escapeHtml(s.description || s.content_preview || '');+ return `<div class="market-skill-card ${installed ? 'installed' : ''}" data-skill-id="${escapeHtml(s.id)}"><div class="skill-head"><div class="skill-name">${escapeHtml(s.name)}</div>- <div class="skill-price ${s.paid ? 'paid' : 'free'}">${s.paid ? 'Paid' : 'Free'}</div>+ <div class="skill-price ${paid ? 'paid' : 'free'}">${paid ? `$${Number(s.price_per_call_usd).toFixed(3)}/call` : 'Free'}</div>+ </div>+ <div class="skill-desc">${desc || '<em style="color:#52525b">No description.</em>'}</div>+ <div class="skill-meta">+ <span class="cat-pill">${escapeHtml(category)}</span>+ ${installsDisplay}+ ${toolsDisplay}+ ${ratingDisplay}+ </div>+ <div class="skill-meta" style="justify-content:space-between">+ ${installedTag || '<span></span>'}+ <span class="open-cta" style="color:#fafafa;opacity:0.6;font-weight:500">Details →</span></div>- <div class="skill-agent">${av}<span>${escapeHtml(s.agentName)}</span></div>- <div class="skill-cta ${s.paid ? 'purchase' : ''}">${s.paid ? 'View & purchase →' : 'Open agent →'}</div></div>`;}+// ── Skill detail modal ──────────────────────────────────────────────────++async function openSkillModal(id) {+ const overlay = $('skill-modal-overlay');+ if (!overlay) return;+ skillsState.detailId = id;+ overlay.hidden = false;+ $('skill-modal-title').textContent = 'Loading…';+ $('skill-modal-desc').textContent = '';+ $('skill-modal-meta').innerHTML = '';+ $('skill-modal-tools').hidden = true;+ $('skill-modal-content').hidden = true;+ $('skill-modal-rating').hidden = true;+ $('skill-modal-install').disabled = true;++ try {+ const r = await fetch(`${API}/skills/${encodeURIComponent(id)}`, { credentials: 'include' });+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ const j = await r.json();+ renderSkillModal(j.skill);+ } catch (err) {+ console.error('[marketplace] skill detail', err);+ $('skill-modal-title').textContent = 'Failed to load skill';+ $('skill-modal-desc').textContent = err.message;+ }+}++function closeSkillModal() {+ const overlay = $('skill-modal-overlay');+ if (overlay) overlay.hidden = true;+ skillsState.detailId = null;+}++function renderSkillModal(skill) {+ if (!skill) return;+ skillsState.detailId = skill.id;+ const paid = isPaidSkill(skill);+ $('skill-modal-title').textContent = skill.name;+ $('skill-modal-desc').textContent = skill.description || '';+ $('skill-modal-eyebrow').textContent = paid ? 'Paid skill' : 'Free skill';++ const meta = $('skill-modal-meta');+ const installs = Number(skill.install_count) || 0;+ const rating = Number(skill.avg_rating) || 0;+ const tools = Array.isArray(skill.schema_json) ? skill.schema_json.length : 0;+ const author = skill.author?.display_name || 'System';+ meta.innerHTML = `+ <span class="stat-pill" style="text-transform:capitalize">${escapeHtml(skill.category || 'general')}</span>+ <span class="stat-pill">By ${escapeHtml(author)}</span>+ ${installs > 0 ? `<span class="stat-pill">${fmtNumber(installs)} installs</span>` : ''}+ ${skill.rating_count > 0 ? `<span class="stat-pill">★ ${rating.toFixed(1)} · ${skill.rating_count}</span>` : ''}+ ${tools > 0 ? `<span class="stat-pill">${tools} tool${tools === 1 ? '' : 's'}</span>` : ''}+ ${paid ? `<span class="stat-pill" style="color:#fde047;border-color:rgba(253,224,71,0.3)">$${Number(skill.price_per_call_usd).toFixed(3)}/call</span>` : `<span class="stat-pill" style="color:#34d399;border-color:rgba(52,211,153,0.3)">Free</span>`}+ `;++ const toolsEl = $('skill-modal-tools');+ if (Array.isArray(skill.schema_json) && skill.schema_json.length) {+ toolsEl.hidden = false;+ toolsEl.innerHTML = `<h4>Tools provided</h4><ul>${skill.schema_json.map((g) => {+ const name = escapeHtml(g?.function?.name || g?.clientDefinition?.name || '?');+ const desc = escapeHtml(g?.function?.description || g?.clientDefinition?.description || '');+ return `<li>${name}${desc ? `<small>${desc}</small>` : ''}</li>`;+ }).join('')}</ul>`;+ } else {+ toolsEl.hidden = true;+ }++ const contentEl = $('skill-modal-content');+ if (skill.content) {+ contentEl.hidden = false;+ contentEl.textContent = skill.content.length > 4000 ? skill.content.slice(0, 4000) + '\n\n…' : skill.content;+ } else {+ contentEl.hidden = true;+ }++ const ratingEl = $('skill-modal-rating');+ if (ratingEl) {+ ratingEl.hidden = false;+ const userRating = Math.round(rating);+ const stars = [1, 2, 3, 4, 5].map((n) => {+ const active = n <= userRating ? 'active' : '';+ return `<button class="${active}" data-rating="${n}" aria-label="Rate ${n} star${n === 1 ? '' : 's'}">★</button>`;+ }).join('');+ ratingEl.innerHTML = `${stars}<span class="rating-count">${skill.rating_count || 0} rating${skill.rating_count === 1 ? '' : 's'}</span>`;+ ratingEl.querySelectorAll('[data-rating]').forEach((btn) => {+ btn.addEventListener('click', async () => {+ const n = Number(btn.dataset.rating);+ await rateSkill(skill.id, n);+ });+ });+ }++ const installBtn = $('skill-modal-install');+ installBtn.disabled = false;+ installBtn.textContent = skill.installed ? '✓ Installed (click to remove)' : 'Install';+ installBtn.dataset.skillId = skill.id;+ installBtn.dataset.installed = skill.installed ? '1' : '0';++ const authorBtn = $('skill-modal-author');+ if (skill.author?.id) {+ authorBtn.hidden = false;+ authorBtn.textContent = `View ${author}'s skills →`;+ authorBtn.onclick = () => {+ closeSkillModal();+ openCreatorModal(skill.author.id);+ };+ } else {+ authorBtn.hidden = true;+ }+}++async function toggleSkillInstall() {+ const btn = $('skill-modal-install');+ if (!btn || btn.disabled) return;+ const id = btn.dataset.skillId;+ if (!id) return;+ const wasInstalled = btn.dataset.installed === '1';+ btn.disabled = true;+ btn.textContent = wasInstalled ? 'Removing…' : 'Installing…';+ try {+ const r = await fetch(`${API}/skills/${encodeURIComponent(id)}/install`, {+ method: wasInstalled ? 'DELETE' : 'POST',+ credentials: 'include',+ });+ if (r.status === 401) {+ location.href = `/login?next=${encodeURIComponent(location.pathname + location.search)}`;+ return;+ }+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ await openSkillModal(id);+ skillsState.loaded = false;+ loadSkillsTab(true);+ } catch (err) {+ console.error('[marketplace] skill install', err);+ btn.disabled = false;+ btn.textContent = wasInstalled ? '✓ Installed (click to remove)' : 'Install';+ }+}++async function rateSkill(id, rating) {+ try {+ const r = await fetch(`${API}/skills/${encodeURIComponent(id)}/rate`, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ rating }),+ });+ if (r.status === 401) {+ location.href = `/login?next=${encodeURIComponent(location.pathname + location.search)}`;+ return;+ }+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ await openSkillModal(id);+ } catch (err) {+ console.error('[marketplace] skill rate', err);+ }+}+// ── My Purchases tab ─────────────────────────────────────────────────────@@ -1724,6 +1978,8 @@ function renderCard(a) {const buyers = a.buyers_total ?? 0;const buyers24h = a.buyers_24h ?? 0;const paid = a.has_paid_skills || Object.keys(a.skill_prices || {}).length > 0;+ const ratingAvg = Number(a.rating_avg || 0);+ const ratingCount = Number(a.rating_count || 0);const avatarBlock = a.thumbnail_url? `<div class="avatar avatar-img" style="background-image:url('${escapeHtml(a.thumbnail_url)}')"></div>`: `<div class="avatar">${escapeHtml(initial(a.name))}</div>`;@@ -1750,7 +2006,8 @@ function renderCard(a) {<span class="stat-pill">⊙ ${fmtNumber(views)}</span><span class="stat-pill">⑂ ${fmtNumber(forks)}</span>${skillsCount ? `<span class="stat-pill">▤ ${skillsCount}</span>` : ''}- ${buyers > 0 ? `<span class="stat-pill" title="${buyers} confirmed purchase${buyers === 1 ? '' : 's'}${buyers24h ? `, ${buyers24h} in last 24h` : ''}">★ ${fmtNumber(buyers)}${buyers24h > 0 ? ` <em>(+${buyers24h}/24h)</em>` : ''}</span>` : ''}+ ${ratingCount > 0 ? `<span class="rating" title="${ratingAvg.toFixed(2)} avg from ${ratingCount} review${ratingCount === 1 ? '' : 's'}">★ ${ratingAvg.toFixed(1)} <span class="count">(${fmtNumber(ratingCount)})</span></span>` : ''}+ ${buyers > 0 ? `<span class="stat-pill" title="${buyers} confirmed purchase${buyers === 1 ? '' : 's'}${buyers24h ? `, ${buyers24h} in last 24h` : ''}">$ ${fmtNumber(buyers)}${buyers24h > 0 ? ` <em>(+${buyers24h}/24h)</em>` : ''}</span>` : ''}${paid ? `<span class="stat-pill paid-badge">$ Paid</span>` : ''}</div><div class="footer">@@ -1837,6 +2094,7 @@ async function loadDetail(id) {}detailState = { agent, bookmarked: !!agent.bookmarked };renderDetail(agent, !!agent.bookmarked);+ loadReviews(id);// Versions + similar (best-effort).Promise.all([@@ -3464,3 +3722,4 @@ function initPlugins() {}init();+diff --git a/src/runtime/providers.js b/src/runtime/providers.jsindex e9fece7a9..6162ec9ae 100644--- a/src/runtime/providers.js+++ b/src/runtime/providers.js@@ -1,9 +1,15 @@// LLM provider abstraction. Calls go through a proxy URL by default —-// never ship API keys in the browser.+// never ship API keys in the browser. The server-side proxy at+// /api/llm/anthropic accepts an Anthropic-shape body and routes to+// Anthropic, Groq, or OpenRouter based on the model id — so this client+// keeps emitting Anthropic-shape requests for every supported model+// (paid Claude *and* free Llama/Hermes/GPT-OSS).export class AnthropicProvider {constructor({- model = 'claude-opus-4-6',+ // Free OpenRouter Llama 3.3 70B — no per-token cost to the host.+ // Owners can override with a paid Claude model via embed-policy.+ model = 'meta-llama/llama-3.3-70b-instruct:free',proxyURL,apiKey,agentId,@@ -18,7 +24,9 @@ export class AnthropicProvider {this.maxTokens = maxTokens;this.thinking = thinking;- // Priority: explicit proxyURL > direct key > we-pay fallback+ // Priority: explicit proxyURL > direct key > we-pay fallback.+ // Direct-key mode is only safe for Claude models (apiKey is then an+ // Anthropic key); free Groq/OR models always go through the proxy.if (proxyURL) {this.proxyURL = proxyURL;} else if (!apiKey && agentId && apiOrigin) {diff --git a/src/skills/local-packs.js b/src/skills/local-packs.jsnew file mode 100644index 000000000..f8110e445--- /dev/null+++ b/src/skills/local-packs.js@@ -0,0 +1,140 @@+// Reads SKILL.md packs from every local skill directory in the repo and+// returns them as normalized records the chat marketplace can render and+// install. Packs are the Claude-style format: YAML frontmatter + markdown+// body. The body becomes a "knowledge skill" the chat injects into the+// system prompt; the agent reads it and follows the embedded instructions.++import { readdirSync, readFileSync, statSync, existsSync } from 'fs';+import { join, basename, relative } from 'path';+import { fileURLToPath } from 'url';++const REPO_ROOT = fileURLToPath(new URL('../..', import.meta.url));++const SKILL_DIRS = [+ { path: '.agents/skills', source: 'agentic-wallet', category: 'wallet' },+ { path: 'pump-fun-skills', source: 'pump-fun-skills', category: 'pump-fun' },+ { path: 'public/skills', source: 'public-skills', category: 'integrations' },+ { path: 'examples/skills', source: 'examples', category: 'examples' },+];++function unquote(v) {+ const s = v.trim();+ if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {+ return s.slice(1, -1);+ }+ return s;+}++function foldedJoin(f) {+ let indent = null;+ const out = [];+ for (const l of f.lines) {+ if (l === '') {+ out.push('');+ continue;+ }+ if (indent === null) {+ const m = l.match(/^(\s*)/);+ indent = m[1].length;+ }+ out.push(l.slice(indent));+ }+ const joined = out.join('\n').trim();+ if (f.mode === '>') return joined.replace(/\n+/g, ' ').replace(/\s+/g, ' ').trim();+ return joined;+}++function parseFrontmatter(src) {+ if (!src.startsWith('---\n')) return { data: {}, body: src };+ const end = src.indexOf('\n---', 4);+ if (end === -1) return { data: {}, body: src };+ const raw = src.slice(4, end);+ const body = src.slice(end + 4).replace(/^\s*\n/, '');+ const data = {};+ const lines = raw.split('\n');+ let key = null;+ let folded = null;+ for (const line of lines) {+ if (folded) {+ const m = line.match(/^(\s*)(.*)$/);+ const indent = m[1].length;+ const text = m[2];+ if (text === '' || indent >= 2) {+ folded.lines.push(text);+ continue;+ }+ data[key] = foldedJoin(folded);+ folded = null;+ }+ const m = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);+ if (!m) continue;+ key = m[1];+ const value = m[2];+ if (value === '>' || value === '|') {+ folded = { mode: value, indent: 0, lines: [] };+ continue;+ }+ data[key] = unquote(value);+ }+ if (folded) data[key] = foldedJoin(folded);+ return { data, body };+}++function scanDir({ path, source, category }) {+ const abs = join(REPO_ROOT, path);+ if (!existsSync(abs)) return [];+ let entries;+ try {+ entries = readdirSync(abs);+ } catch {+ return [];+ }+ const packs = [];+ for (const name of entries) {+ const dir = join(abs, name);+ let st;+ try {+ st = statSync(dir);+ } catch {+ continue;+ }+ if (!st.isDirectory()) continue;+ const skillPath = join(dir, 'SKILL.md');+ if (!existsSync(skillPath)) continue;+ let raw;+ try {+ raw = readFileSync(skillPath, 'utf8');+ } catch {+ continue;+ }+ const { data, body } = parseFrontmatter(raw);+ const slug = String(data.name || basename(dir));+ packs.push({+ id: `local:${source}:${slug}`,+ source,+ category: data.category || category,+ name: slug,+ slug,+ description: data.description || '',+ version: data.version || null,+ trust: data.trust || null,+ kind: 'knowledge',+ has_content: true,+ content: raw,+ body,+ path: relative(REPO_ROOT, skillPath),+ });+ }+ return packs;+}++let _cached = null;+export function loadLocalSkillPacks() {+ if (_cached) return _cached;+ const all = [];+ for (const dir of SKILL_DIRS) {+ all.push(...scanDir(dir));+ }+ _cached = all;+ return all;+}diff --git a/src/swap-jupiter.js b/src/swap-jupiter.jsnew file mode 100644index 000000000..494eabc10--- /dev/null+++ b/src/swap-jupiter.js@@ -0,0 +1,824 @@+/**+ * Real Jupiter v6 swap modal.+ *+ * Self-contained: injects its own CSS, builds its own modal DOM on first open,+ * and runs swaps against Jupiter v6 (https://lite-api.jup.ag/swap/v1/) using+ * the connected Phantom wallet on Solana mainnet.+ *+ * Public surface:+ * openSwapModal({ wallet, getProvider, defaultInputMint?, defaultOutputMint? })+ *+ * - `wallet` — a @solana/web3.js PublicKey (the connected wallet).+ * - `getProvider()` — must return the Phantom provider (signTransaction/connect).+ * - `defaultInputMint`/`defaultOutputMint` — optional mint addresses (defaults: SOL → USDC).+ */++import {+ Connection,+ PublicKey,+ VersionedTransaction,+} from '@solana/web3.js';++// Solana mint constants used as built-in defaults / quick picks.+const SOL_MINT = 'So11111111111111111111111111111111111111112';+const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++// Curated quick-pick list. Token picker also accepts any mint via paste.+// Decimals + symbols are baked in so the modal still works if Jupiter's+// /tokens endpoint is rate-limited or offline.+const QUICK_TOKENS = [+ { symbol: 'SOL', name: 'Solana', mint: SOL_MINT, decimals: 9, logoURI: 'https://raw.githubusercontent.com/solana-labs/token-list/main/assets/mainnet/So11111111111111111111111111111111111111112/logo.png' },+ { symbol: 'USDC', name: 'USD Coin', mint: USDC_MINT, decimals: 6, logoURI: 'https://raw.githubusercontent.com/solana-labs/token-list/main/assets/mainnet/EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v/logo.png' },+ { symbol: 'USDT', name: 'USDT', mint: 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB', decimals: 6, logoURI: 'https://raw.githubusercontent.com/solana-labs/token-list/main/assets/mainnet/Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB/logo.svg' },+ { symbol: 'BONK', name: 'Bonk', mint: 'DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263', decimals: 5, logoURI: 'https://arweave.net/hQiPZOsRZXGXBJd_82PhVdlM_hACsT_q6wqwf5cSY7I' },+ { symbol: 'JUP', name: 'Jupiter', mint: 'JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN', decimals: 6, logoURI: 'https://static.jup.ag/jup/icon.png' },+ { symbol: 'WIF', name: 'dogwifhat', mint: 'EKpQGSJtjMFqKZ9KQanSqYXRcF8fBopzLHYxdM65zcjm', decimals: 6, logoURI: 'https://bafkreibk3covs5ltyqxa272uodhculbr6kea6betidfwy3ajsav2vjzyum.ipfs.nftstorage.link' },+ { symbol: 'PYTH', name: 'Pyth Network', mint: 'HZ1JovNiVvGrGNiiYvEozEVgZ58xaU3RKwX8eACQBCt3', decimals: 6, logoURI: 'https://pyth.network/token.svg' },+ { symbol: 'JTO', name: 'Jito', mint: 'jtojtomepa8beP8AuQc6eXt5FriJwfFMwQx2v2f9mCL', decimals: 9, logoURI: 'https://metadata.jito.network/token/jto/image' },+];++const SOLANA_MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const JUP_QUOTE_URL = 'https://lite-api.jup.ag/swap/v1/quote';+const JUP_SWAP_URL = 'https://lite-api.jup.ag/swap/v1/swap';+const JUP_PRICE_URL = 'https://lite-api.jup.ag/price/v2';++// Mainnet RPC for swap submission. We route through the same-origin proxy so+// browser-side rate limits don't blow up the flow.+const SWAP_RPC = (typeof window !== 'undefined' ? window.location.origin : 'https://three.ws') + '/api/solana-rpc';++let _ui = null; // Lazily built DOM root. Created on first open.+let _styleInjected = false;+let _ctx = null; // Current open call's context: { wallet, getProvider, inputToken, outputToken, ... }+let _quoteSeq = 0;+let _quote = null; // Last successful quote response from Jupiter.++const STYLE = `+.sj-overlay {+ position: fixed; inset: 0;+ background: rgba(0,0,0,0.7);+ display: flex; align-items: center; justify-content: center;+ z-index: 1100;+}+.sj-overlay.sj-hidden { display: none; }+.sj-modal {+ background: #14181d; color: #e7e9ee;+ border: 1px solid rgba(255,255,255,0.07);+ border-radius: 14px;+ width: 92%; max-width: 460px;+ font-family: 'Inter', system-ui, sans-serif;+ box-shadow: 0 10px 25px rgba(0,0,0,0.4);+}+.sj-modal.sj-picker { max-width: 420px; }+.sj-head {+ display: flex; justify-content: space-between; align-items: center;+ padding: 16px 20px;+ border-bottom: 1px solid rgba(255,255,255,0.07);+}+.sj-head h3 { margin: 0; font-size: 16px; font-weight: 500; }+.sj-net {+ font-size: 11px; color: rgba(231,233,238,0.55);+ font-weight: 400; margin-left: 6px;+}+.sj-close {+ background: none; border: 0;+ font-size: 24px; line-height: 1;+ color: rgba(231,233,238,0.55); cursor: pointer;+}+.sj-close:hover { color: #e7e9ee; }+.sj-body { padding: 20px; }+.sj-foot {+ display: flex; justify-content: flex-end; gap: 10px;+ padding: 14px 20px;+ border-top: 1px solid rgba(255,255,255,0.07);+ background: #111418;+ border-bottom-left-radius: 14px;+ border-bottom-right-radius: 14px;+}++.sj-side {+ background: #111418;+ border: 1px solid rgba(255,255,255,0.07);+ border-radius: 12px;+ padding: 12px 14px;+}+.sj-side + .sj-side { margin-top: 4px; }+.sj-side-head {+ display: flex; justify-content: space-between;+ font-size: 12px; margin-bottom: 8px; color: rgba(231,233,238,0.55);+}+.sj-balance.sj-balance-link {+ cursor: pointer; color: #8b9bff;+}+.sj-balance.sj-balance-link:hover { color: #a7b3ff; }+.sj-row { display: flex; align-items: center; gap: 10px; }+.sj-amount {+ flex: 1; min-width: 0;+ background: transparent; border: 0; outline: none;+ color: #e7e9ee; font-family: inherit;+ font-size: 24px; font-weight: 500; padding: 4px 0;+}+.sj-amount[readonly] { opacity: 0.85; }+.sj-tokenbtn {+ display: inline-flex; align-items: center; gap: 8px;+ background: rgba(255,255,255,0.06);+ border: 1px solid rgba(255,255,255,0.07);+ color: #e7e9ee; padding: 6px 12px;+ border-radius: 999px;+ cursor: pointer;+ font-family: inherit; font-size: 14px; font-weight: 500;+ white-space: nowrap;+}+.sj-tokenbtn:hover { background: rgba(255,255,255,0.10); }+.sj-tokenbtn img {+ width: 18px; height: 18px; border-radius: 50%;+ background: rgba(255,255,255,0.05);+}+.sj-tokenbtn .sj-caret { font-size: 10px; opacity: 0.7; }+.sj-flip {+ display: block; margin: 4px auto;+ width: 32px; height: 32px; border-radius: 50%;+ border: 1px solid rgba(255,255,255,0.07);+ background: #14181d; color: rgba(231,233,238,0.55);+ cursor: pointer; font-size: 16px; line-height: 1;+}+.sj-flip:hover { color: #e7e9ee; background: #111418; }++.sj-meta { margin-top: 12px; font-size: 12px; color: rgba(231,233,238,0.55); min-height: 18px; }+.sj-meta-row { display: flex; justify-content: space-between; padding: 2px 0; }+.sj-warn { color: #f59e0b; }++.sj-controls {+ display: flex; align-items: center; gap: 8px;+ margin-top: 14px; font-size: 12px;+}+.sj-input {+ background: #111418;+ border: 1px solid rgba(255,255,255,0.07);+ color: #e7e9ee;+ border-radius: 8px;+ padding: 8px 10px;+ font-family: inherit;+ font-size: 13px;+}+.sj-input:focus { outline: none; border-color: rgba(255,255,255,0.12); }+.sj-slippage { width: 90px; }++.sj-status { margin-top: 12px; font-size: 12px; min-height: 16px; }+.sj-status.sj-err { color: #ef4444; }+.sj-status.sj-ok { color: #10b981; }+.sj-status a { color: inherit; text-decoration: underline; }++.sj-btn {+ background: #111418; color: #e7e9ee;+ border: 1px solid rgba(255,255,255,0.07);+ border-radius: 8px;+ padding: 8px 16px;+ font-family: inherit; font-size: 13px;+ cursor: pointer;+}+.sj-btn:hover { border-color: rgba(255,255,255,0.12); }+.sj-btn:disabled { opacity: 0.45; cursor: not-allowed; }+.sj-btn.sj-primary { background: #fff; color: #000; border-color: #fff; }+.sj-btn.sj-primary:hover { background: #f0f0f0; }+.sj-btn.sj-primary:disabled { background: rgba(255,255,255,0.5); color: rgba(0,0,0,0.4); }++.sj-picker .sj-body { padding: 16px 20px; }+.sj-search {+ width: 100%;+}+.sj-list {+ margin-top: 12px;+ max-height: 320px; overflow-y: auto;+ border-top: 1px solid rgba(255,255,255,0.07);+}+.sj-list-row {+ display: flex; align-items: center; gap: 10px;+ padding: 10px 4px;+ border-bottom: 1px solid rgba(255,255,255,0.07);+ cursor: pointer;+}+.sj-list-row:hover { background: #111418; }+.sj-list-row img {+ width: 28px; height: 28px; border-radius: 50%;+ background: #111418;+}+.sj-list-row .sj-list-main { flex: 1; min-width: 0; }+.sj-list-row .sj-list-sym { font-weight: 600; font-size: 14px; }+.sj-list-row .sj-list-name {+ font-size: 12px; color: rgba(231,233,238,0.55);+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+}+.sj-list-row .sj-list-mint {+ font-family: ui-monospace, monospace;+ font-size: 10px; color: rgba(231,233,238,0.55); opacity: 0.6;+}+.sj-empty {+ padding: 24px 8px; text-align: center;+ color: rgba(231,233,238,0.55); font-size: 13px;+}+`;++function injectStyle() {+ if (_styleInjected) return;+ const s = document.createElement('style');+ s.dataset.swapJupiter = '1';+ s.textContent = STYLE;+ document.head.appendChild(s);+ _styleInjected = true;+}++function el(tag, attrs = {}, ...kids) {+ const node = document.createElement(tag);+ for (const [k, v] of Object.entries(attrs)) {+ if (v == null || v === false) continue;+ if (k === 'class') node.className = v;+ else if (k === 'text') node.textContent = v;+ else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v);+ else node.setAttribute(k, v);+ }+ for (const k of kids.flat()) {+ if (k == null) continue;+ node.appendChild(typeof k === 'string' ? document.createTextNode(k) : k);+ }+ return node;+}++function buildUI() {+ injectStyle();++ // Swap modal+ const swapOverlay = el('div', { class: 'sj-overlay sj-hidden', id: 'sj-swap-overlay' });+ const swapModal = el('div', { class: 'sj-modal' });++ const head = el('div', { class: 'sj-head' },+ el('h3', {}, 'Swap tokens', el('span', { class: 'sj-net', text: ' · Jupiter · Solana mainnet' })),+ el('button', { class: 'sj-close', type: 'button', 'aria-label': 'Close', onclick: closeSwap }, '×'),+ );++ const fromSide = el('div', { class: 'sj-side' },+ el('div', { class: 'sj-side-head' },+ el('span', { text: 'From' }),+ el('span', { class: 'sj-balance', id: 'sj-from-balance' }),+ ),+ el('div', { class: 'sj-row' },+ el('input', { type: 'number', id: 'sj-from-amount', class: 'sj-amount', placeholder: '0.0', inputmode: 'decimal', autocomplete: 'off' }),+ el('button', { type: 'button', class: 'sj-tokenbtn', id: 'sj-from-token', onclick: () => openPicker('from') },+ el('img', { id: 'sj-from-logo', alt: '' }),+ el('span', { id: 'sj-from-sym' }),+ el('span', { class: 'sj-caret', text: '▾' }),+ ),+ ),+ );++ const flip = el('button', { type: 'button', class: 'sj-flip', 'aria-label': 'Flip direction', onclick: flipSides }, '↕');++ const toSide = el('div', { class: 'sj-side' },+ el('div', { class: 'sj-side-head' },+ el('span', { text: 'To (estimated)' }),+ ),+ el('div', { class: 'sj-row' },+ el('input', { type: 'text', id: 'sj-to-amount', class: 'sj-amount', placeholder: '0.0', readonly: 'readonly', tabindex: '-1' }),+ el('button', { type: 'button', class: 'sj-tokenbtn', id: 'sj-to-token', onclick: () => openPicker('to') },+ el('img', { id: 'sj-to-logo', alt: '' }),+ el('span', { id: 'sj-to-sym' }),+ el('span', { class: 'sj-caret', text: '▾' }),+ ),+ ),+ );++ const meta = el('div', { class: 'sj-meta', id: 'sj-meta', 'aria-live': 'polite' });++ const controls = el('div', { class: 'sj-controls' },+ el('label', { for: 'sj-slippage', text: 'Slippage (bps)' }),+ el('input', { type: 'number', id: 'sj-slippage', class: 'sj-input sj-slippage', value: '50', min: '1', max: '1000', step: '1' }),+ el('span', { id: 'sj-slippage-pct', text: '0.50%' }),+ );++ const status = el('div', { class: 'sj-status', id: 'sj-status', 'aria-live': 'polite' });++ const body = el('div', { class: 'sj-body' }, fromSide, flip, toSide, meta, controls, status);++ const foot = el('div', { class: 'sj-foot' },+ el('button', { type: 'button', class: 'sj-btn', onclick: closeSwap }, 'Cancel'),+ el('button', { type: 'button', class: 'sj-btn sj-primary', id: 'sj-confirm', disabled: 'disabled', onclick: executeSwap }, 'Get quote'),+ );++ swapModal.append(head, body, foot);+ swapOverlay.appendChild(swapModal);+ swapOverlay.addEventListener('click', (e) => { if (e.target === swapOverlay) closeSwap(); });++ // Token picker modal+ const pickerOverlay = el('div', { class: 'sj-overlay sj-hidden', id: 'sj-picker-overlay' });+ const pickerModal = el('div', { class: 'sj-modal sj-picker' });+ const pickerHead = el('div', { class: 'sj-head' },+ el('h3', { text: 'Select a token' }),+ el('button', { class: 'sj-close', type: 'button', 'aria-label': 'Close', onclick: closePicker }, '×'),+ );+ const pickerBody = el('div', { class: 'sj-body' },+ el('input', { type: 'text', class: 'sj-input sj-search', id: 'sj-search', placeholder: 'Search name, symbol, or paste mint address', autocomplete: 'off' }),+ el('div', { class: 'sj-list', id: 'sj-list', role: 'listbox' }),+ );+ pickerModal.append(pickerHead, pickerBody);+ pickerOverlay.appendChild(pickerModal);+ pickerOverlay.addEventListener('click', (e) => { if (e.target === pickerOverlay) closePicker(); });++ document.body.append(swapOverlay, pickerOverlay);++ // Wire input listeners+ document.getElementById('sj-from-amount').addEventListener('input', onAmountInput);+ document.getElementById('sj-slippage').addEventListener('input', onSlippageInput);+ document.getElementById('sj-search').addEventListener('input', renderTokenList);++ return { swapOverlay, pickerOverlay };+}++function ensureUI() {+ if (!_ui) _ui = buildUI();+ return _ui;+}++function $(id) { return document.getElementById(id); }++function setTokenUI(side, token) {+ $(`sj-${side}-sym`).textContent = token.symbol;+ const logo = $(`sj-${side}-logo`);+ if (token.logoURI) {+ logo.src = token.logoURI;+ logo.style.display = '';+ logo.onerror = () => { logo.style.display = 'none'; };+ } else {+ logo.style.display = 'none';+ }+}++function fmtAmount(raw, decimals) {+ const big = BigInt(raw);+ const divisor = 10n ** BigInt(decimals);+ const whole = big / divisor;+ const fracBig = big % divisor;+ if (fracBig === 0n) return whole.toString();+ const frac = fracBig.toString().padStart(decimals, '0').replace(/0+$/, '');+ return `${whole.toString()}.${frac}`;+}++function toBaseUnits(amount, decimals) {+ if (!amount) return null;+ const [whole, fracRaw = ''] = String(amount).trim().split('.');+ if (!/^\d*$/.test(whole) || !/^\d*$/.test(fracRaw)) return null;+ const frac = (fracRaw + '0'.repeat(decimals)).slice(0, decimals);+ const merged = `${whole || '0'}${frac}`.replace(/^0+/, '') || '0';+ try { return BigInt(merged).toString(); } catch { return null; }+}++function setStatus(text, cls = '') {+ const node = $('sj-status');+ node.className = `sj-status ${cls}`;+ if (typeof text === 'string') node.textContent = text;+ else { node.textContent = ''; node.append(text); }+}++function onSlippageInput() {+ const bps = Number($('sj-slippage').value);+ if (Number.isFinite(bps)) {+ $('sj-slippage-pct').textContent = `${(bps / 100).toFixed(2)}%`;+ debouncedQuote();+ }+}++let _quoteTimer = null;+function debouncedQuote() {+ if (_quoteTimer) clearTimeout(_quoteTimer);+ _quoteTimer = setTimeout(fetchQuote, 350);+}++function onAmountInput() {+ const v = $('sj-from-amount').value;+ if (!v || Number(v) <= 0) {+ $('sj-to-amount').value = '';+ $('sj-meta').textContent = '';+ _quote = null;+ updateConfirmButton();+ return;+ }+ debouncedQuote();+}++async function fetchQuote() {+ if (!_ctx) return;+ const amountStr = $('sj-from-amount').value;+ const baseUnits = toBaseUnits(amountStr, _ctx.inputToken.decimals);+ if (!baseUnits || baseUnits === '0') return;++ const seq = ++_quoteSeq;+ const slippageBps = Math.max(1, Math.min(1000, Number($('sj-slippage').value) || 50));+ const params = new URLSearchParams({+ inputMint: _ctx.inputToken.mint,+ outputMint: _ctx.outputToken.mint,+ amount: baseUnits,+ slippageBps: String(slippageBps),+ restrictIntermediateTokens: 'true',+ });++ setStatus('Fetching best route…');+ $('sj-confirm').disabled = true;+ $('sj-confirm').textContent = 'Quoting…';++ try {+ const resp = await fetch(`${JUP_QUOTE_URL}?${params}`);+ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Jupiter quote ${resp.status}: ${text.slice(0, 200)}`);+ }+ const quote = await resp.json();+ if (seq !== _quoteSeq) return; // Stale response.+ _quote = quote;++ $('sj-to-amount').value = fmtAmount(quote.outAmount, _ctx.outputToken.decimals);+ renderQuoteMeta(quote);+ setStatus('');+ updateConfirmButton();+ } catch (err) {+ if (seq !== _quoteSeq) return;+ console.error('[swap-jupiter] quote failed', err);+ _quote = null;+ $('sj-to-amount').value = '';+ setStatus(`Quote failed: ${err.message}`, 'sj-err');+ updateConfirmButton();+ }+}++function renderQuoteMeta(quote) {+ const meta = $('sj-meta');+ meta.innerHTML = '';++ const priceIn = Number(fmtAmount(quote.inAmount, _ctx.inputToken.decimals));+ const priceOut = Number(fmtAmount(quote.outAmount, _ctx.outputToken.decimals));+ if (priceIn > 0) {+ meta.append(el('div', { class: 'sj-meta-row' },+ el('span', { text: 'Rate' }),+ el('span', { text: `1 ${_ctx.inputToken.symbol} ≈ ${(priceOut / priceIn).toLocaleString(undefined, { maximumFractionDigits: 6 })} ${_ctx.outputToken.symbol}` }),+ ));+ }++ const minOut = quote.otherAmountThreshold+ ? fmtAmount(quote.otherAmountThreshold, _ctx.outputToken.decimals)+ : priceOut.toString();+ meta.append(el('div', { class: 'sj-meta-row' },+ el('span', { text: 'Min received' }),+ el('span', { text: `${Number(minOut).toLocaleString(undefined, { maximumFractionDigits: 6 })} ${_ctx.outputToken.symbol}` }),+ ));++ const impactPct = Number(quote.priceImpactPct || 0) * 100;+ if (impactPct) {+ const warn = impactPct >= 1 ? 'sj-warn' : '';+ meta.append(el('div', { class: `sj-meta-row ${warn}` },+ el('span', { text: 'Price impact' }),+ el('span', { text: `${impactPct.toFixed(2)}%` }),+ ));+ }++ const route = (quote.routePlan || []).map((r) => r.swapInfo?.label).filter(Boolean);+ if (route.length) {+ meta.append(el('div', { class: 'sj-meta-row' },+ el('span', { text: 'Route' }),+ el('span', { text: route.slice(0, 4).join(' → ') + (route.length > 4 ? ` (+${route.length - 4})` : '') }),+ ));+ }+}++function updateConfirmButton() {+ const btn = $('sj-confirm');+ if (!_ctx) { btn.disabled = true; return; }+ const amount = Number($('sj-from-amount').value);+ if (!_quote || !amount || amount <= 0) {+ btn.disabled = !amount || amount <= 0 ? true : false;+ btn.textContent = (amount && amount > 0) ? 'Get quote' : 'Enter amount';+ btn.disabled = !(_quote && amount > 0);+ return;+ }+ btn.disabled = false;+ btn.textContent = `Swap ${_ctx.inputToken.symbol} → ${_ctx.outputToken.symbol}`;+}++function flipSides() {+ if (!_ctx) return;+ const a = _ctx.inputToken;+ _ctx.inputToken = _ctx.outputToken;+ _ctx.outputToken = a;+ setTokenUI('from', _ctx.inputToken);+ setTokenUI('to', _ctx.outputToken);+ $('sj-from-amount').value = $('sj-to-amount').value || '';+ $('sj-to-amount').value = '';+ _quote = null;+ $('sj-meta').textContent = '';+ refreshBalance();+ if (Number($('sj-from-amount').value) > 0) debouncedQuote();+ updateConfirmButton();+}++async function refreshBalance() {+ if (!_ctx?.wallet) return;+ const target = $('sj-from-balance');+ target.textContent = '';+ target.classList.remove('sj-balance-link');+ try {+ const connection = new Connection(SWAP_RPC, 'confirmed');+ let bal = null;+ if (_ctx.inputToken.mint === SOL_MINT) {+ const lamports = await connection.getBalance(new PublicKey(_ctx.wallet));+ bal = lamports / 1e9;+ } else {+ const owner = new PublicKey(_ctx.wallet);+ const mint = new PublicKey(_ctx.inputToken.mint);+ const resp = await connection.getParsedTokenAccountsByOwner(owner, { mint });+ let total = 0;+ for (const acc of resp.value) {+ const ui = acc.account?.data?.parsed?.info?.tokenAmount?.uiAmount;+ if (typeof ui === 'number') total += ui;+ }+ bal = total;+ }+ if (bal == null) return;+ target.textContent = `Balance: ${bal.toLocaleString(undefined, { maximumFractionDigits: 6 })} ${_ctx.inputToken.symbol}`;+ target.classList.add('sj-balance-link');+ target.onclick = () => {+ // Leave a small buffer for SOL gas.+ const usable = _ctx.inputToken.mint === SOL_MINT ? Math.max(0, bal - 0.01) : bal;+ $('sj-from-amount').value = String(usable);+ onAmountInput();+ };+ } catch (err) {+ console.warn('[swap-jupiter] balance fetch failed', err);+ }+}++// ── Token picker ───────────────────────────────────────────────────────────++let _pickerSide = 'from';+let _remoteTokens = []; // Lazily fetched from Jupiter strict list.++function openPicker(side) {+ _pickerSide = side;+ $('sj-search').value = '';+ renderTokenList();+ _ui.pickerOverlay.classList.remove('sj-hidden');+ setTimeout(() => $('sj-search').focus(), 0);+ loadRemoteTokens();+}++function closePicker() {+ _ui.pickerOverlay.classList.add('sj-hidden');+}++async function loadRemoteTokens() {+ if (_remoteTokens.length) return;+ try {+ const resp = await fetch('https://lite-api.jup.ag/tokens/v1/tagged/verified', { mode: 'cors' });+ if (!resp.ok) return;+ const data = await resp.json();+ if (Array.isArray(data)) {+ _remoteTokens = data+ .filter((t) => t.address && t.symbol && t.decimals != null)+ .map((t) => ({+ symbol: t.symbol,+ name: t.name || t.symbol,+ mint: t.address,+ decimals: t.decimals,+ logoURI: t.logoURI || '',+ }));+ renderTokenList();+ }+ } catch (err) {+ console.warn('[swap-jupiter] verified token list unavailable', err);+ }+}++function dedupeBySymbolMint(list) {+ const seen = new Set();+ const out = [];+ for (const t of list) {+ const key = t.mint;+ if (seen.has(key)) continue;+ seen.add(key);+ out.push(t);+ }+ return out;+}++function renderTokenList() {+ const q = ($('sj-search')?.value || '').trim().toLowerCase();+ const list = $('sj-list');+ list.innerHTML = '';++ // Allow direct mint paste.+ if (SOLANA_MINT_RE.test(q)) {+ list.append(buildTokenRow({+ symbol: q.slice(0, 4).toUpperCase(),+ name: 'Custom mint',+ mint: q,+ decimals: 0,+ logoURI: '',+ needsDecimals: true,+ }));+ }++ const pool = dedupeBySymbolMint([...QUICK_TOKENS, ..._remoteTokens]);+ const filtered = !q+ ? QUICK_TOKENS+ : pool.filter((t) =>+ t.symbol.toLowerCase().includes(q) ||+ t.name.toLowerCase().includes(q) ||+ t.mint.toLowerCase().includes(q),+ ).slice(0, 50);++ if (!filtered.length && !SOLANA_MINT_RE.test(q)) {+ list.append(el('div', { class: 'sj-empty', text: 'No tokens match. Paste a mint address to add a custom token.' }));+ return;+ }+ filtered.forEach((t) => list.append(buildTokenRow(t)));+}++function buildTokenRow(t) {+ const row = el('div', { class: 'sj-list-row', role: 'option', tabindex: '0' },+ el('img', { src: t.logoURI || '', alt: '', onerror: function () { this.style.visibility = 'hidden'; } }),+ el('div', { class: 'sj-list-main' },+ el('div', { class: 'sj-list-sym', text: t.symbol }),+ el('div', { class: 'sj-list-name', text: t.name }),+ ),+ el('div', { class: 'sj-list-mint', text: `${t.mint.slice(0, 4)}…${t.mint.slice(-4)}` }),+ );+ row.addEventListener('click', () => selectToken(t));+ row.addEventListener('keydown', (e) => { if (e.key === 'Enter') selectToken(t); });+ return row;+}++async function selectToken(token) {+ if (token.needsDecimals) {+ // Custom-mint path: fetch decimals from chain before continuing.+ try {+ const connection = new Connection(SWAP_RPC, 'confirmed');+ const info = await connection.getParsedAccountInfo(new PublicKey(token.mint));+ const decimals = info?.value?.data?.parsed?.info?.decimals;+ if (typeof decimals !== 'number') throw new Error('Could not read mint decimals');+ token = { ...token, decimals, name: 'Custom mint' };+ } catch (err) {+ setStatus(`Custom mint failed: ${err.message}`, 'sj-err');+ closePicker();+ return;+ }+ }+ if (_pickerSide === 'from') _ctx.inputToken = token;+ else _ctx.outputToken = token;++ // Prevent picking the same token on both sides.+ if (_ctx.inputToken.mint === _ctx.outputToken.mint) {+ _ctx[_pickerSide === 'from' ? 'outputToken' : 'inputToken'] =+ _pickerSide === 'from' ? findToken(USDC_MINT) : findToken(SOL_MINT);+ }++ setTokenUI('from', _ctx.inputToken);+ setTokenUI('to', _ctx.outputToken);+ closePicker();+ refreshBalance();+ if (Number($('sj-from-amount').value) > 0) debouncedQuote();+}++function findToken(mint) {+ return [...QUICK_TOKENS, ..._remoteTokens].find((t) => t.mint === mint)+ || { symbol: mint.slice(0, 4), name: 'Token', mint, decimals: 6, logoURI: '' };+}++// ── Swap execution ─────────────────────────────────────────────────────────++async function executeSwap() {+ if (!_ctx || !_quote) return;+ const btn = $('sj-confirm');+ btn.disabled = true;+ btn.textContent = 'Preparing transaction…';+ setStatus('Building swap transaction…');++ const provider = _ctx.getProvider();+ if (!provider) {+ setStatus('Phantom wallet provider not available.', 'sj-err');+ btn.disabled = false;+ btn.textContent = 'Swap';+ return;+ }++ try {+ const userPubkey = _ctx.wallet.toString();++ const swapResp = await fetch(JUP_SWAP_URL, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ quoteResponse: _quote,+ userPublicKey: userPubkey,+ wrapAndUnwrapSol: true,+ dynamicComputeUnitLimit: true,+ prioritizationFeeLamports: { priorityLevelWithMaxLamports: { maxLamports: 1_000_000, priorityLevel: 'medium' } },+ }),+ });+ if (!swapResp.ok) {+ const text = await swapResp.text();+ throw new Error(`Jupiter swap ${swapResp.status}: ${text.slice(0, 240)}`);+ }+ const swapData = await swapResp.json();+ if (!swapData.swapTransaction) throw new Error('Jupiter returned no transaction');++ btn.textContent = 'Awaiting wallet signature…';+ setStatus('Approve the transaction in your wallet…');++ const txBuf = Uint8Array.from(atob(swapData.swapTransaction), (c) => c.charCodeAt(0));+ const tx = VersionedTransaction.deserialize(txBuf);++ // Sign via Phantom.+ const signed = await provider.signTransaction(tx);++ btn.textContent = 'Submitting…';+ setStatus('Submitting transaction…');++ const connection = new Connection(SWAP_RPC, 'confirmed');+ const sig = await connection.sendRawTransaction(signed.serialize(), {+ skipPreflight: false,+ maxRetries: 2,+ });++ const explorerLink = `https://solscan.io/tx/${sig}`;+ setStatus(el('span', {},+ 'Submitted. ',+ el('a', { href: explorerLink, target: '_blank', rel: 'noopener', text: 'View on Solscan ↗' }),+ ), 'sj-ok');++ // Confirm (non-blocking for UX — show signature first).+ btn.textContent = 'Confirming…';+ try {+ const latest = await connection.getLatestBlockhash('confirmed');+ await connection.confirmTransaction(+ { signature: sig, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight },+ 'confirmed',+ );+ setStatus(el('span', {},+ 'Swap confirmed. ',+ el('a', { href: explorerLink, target: '_blank', rel: 'noopener', text: 'View on Solscan ↗' }),+ ), 'sj-ok');+ btn.textContent = 'Done';+ } catch (confErr) {+ setStatus(el('span', {},+ 'Submitted, awaiting confirmation. ',+ el('a', { href: explorerLink, target: '_blank', rel: 'noopener', text: 'View on Solscan ↗' }),+ ), 'sj-ok');+ console.warn('[swap-jupiter] confirm failed', confErr);+ btn.textContent = 'Swap again';+ btn.disabled = false;+ }++ refreshBalance();+ } catch (err) {+ console.error('[swap-jupiter] swap failed', err);+ setStatus(`Swap failed: ${err.message}`, 'sj-err');+ btn.disabled = false;+ btn.textContent = `Swap ${_ctx.inputToken.symbol} → ${_ctx.outputToken.symbol}`;+ }+}++// ── Public API ─────────────────────────────────────────────────────────────++function closeSwap() {+ if (_ui) _ui.swapOverlay.classList.add('sj-hidden');+}++export function openSwapModal({ wallet, getProvider, defaultInputMint, defaultOutputMint } = {}) {+ if (!wallet) {+ alert('Connect your wallet first.');+ return;+ }+ if (typeof getProvider !== 'function') {+ throw new Error('openSwapModal: getProvider is required');+ }++ ensureUI();++ const inputToken =+ (defaultInputMint && findToken(defaultInputMint)) || QUICK_TOKENS[0];+ const outputToken =+ (defaultOutputMint && findToken(defaultOutputMint)) || QUICK_TOKENS[1];++ _ctx = { wallet, getProvider, inputToken, outputToken };+ _quote = null;++ setTokenUI('from', inputToken);+ setTokenUI('to', outputToken);+ $('sj-from-amount').value = '';+ $('sj-to-amount').value = '';+ $('sj-meta').textContent = '';+ setStatus('');+ $('sj-slippage').value = '50';+ $('sj-slippage-pct').textContent = '0.50%';+ updateConfirmButton();++ _ui.swapOverlay.classList.remove('sj-hidden');+ setTimeout(() => $('sj-from-amount').focus(), 0);++ refreshBalance();+}diff --git a/tests/api/llm-anthropic.test.js b/tests/api/llm-anthropic.test.jsindex 333ea8833..5c75208be 100644--- a/tests/api/llm-anthropic.test.js+++ b/tests/api/llm-anthropic.test.js@@ -408,3 +408,209 @@ describe('/api/llm/anthropic — upstream behaviour', () => {expect(usageEvents[0].meta.output_tokens).toBe(22);});});++// ── free-provider routing (Groq / OpenRouter) ──────────────────────────+//+// The browser sends Anthropic-shape bodies for every model; the proxy+// inspects `model`, picks the upstream URL + key, and translates request+// + response shapes both ways. These tests pin that translation contract.++describe('/api/llm/anthropic — free-provider routing', () => {+ const SYSTEM = 'you are a helpful agent';++ beforeEach(() => {+ process.env.OPENROUTER_API_KEY = 'sk-or-test';+ process.env.GROQ_API_KEY = 'gsk-test';+ // OpenAI-shape response by default; individual tests can override.+ fetchState.response = () =>+ upstreamOk({+ id: 'gen-1',+ choices: [+ {+ message: { role: 'assistant', content: 'hi from free model' },+ finish_reason: 'stop',+ },+ ],+ usage: { prompt_tokens: 7, completion_tokens: 9 },+ });+ });++ it('routes meta-llama/*:free models to OpenRouter with bearer auth', async () => {+ await invoke({+ body: {+ ...VALID_BODY,+ system: SYSTEM,+ model: 'meta-llama/llama-3.3-70b-instruct:free',+ },+ });+ const call = fetchState.calls[0];+ expect(call.url).toBe('https://openrouter.ai/api/v1/chat/completions');+ expect(call.init.headers.authorization).toBe('Bearer sk-or-test');+ expect(call.init.headers['HTTP-Referer']).toBe('https://three.ws');+ });++ it('routes Groq model ids to api.groq.com', async () => {+ await invoke({+ body: { ...VALID_BODY, model: 'llama-3.3-70b-versatile' },+ });+ const call = fetchState.calls[0];+ expect(call.url).toBe('https://api.groq.com/openai/v1/chat/completions');+ expect(call.init.headers.authorization).toBe('Bearer gsk-test');+ });++ it('returns 503 when the upstream API key is not configured', async () => {+ delete process.env.OPENROUTER_API_KEY;+ const { status, body } = await invoke({+ body: { ...VALID_BODY, model: 'meta-llama/llama-3.3-70b-instruct:free' },+ });+ expect(status).toBe(503);+ expect(body.error).toBe('provider_unavailable');+ });++ it('translates Anthropic body shape → OpenAI body shape', async () => {+ await invoke({+ body: {+ system: SYSTEM,+ model: 'meta-llama/llama-3.3-70b-instruct:free',+ max_tokens: 256,+ temperature: 0.4,+ messages: [+ { role: 'user', content: 'how are you?' },+ {+ role: 'assistant',+ content: [+ { type: 'text', text: 'let me check' },+ {+ type: 'tool_use',+ id: 'toolu_01',+ name: 'getTime',+ input: { tz: 'UTC' },+ },+ ],+ },+ {+ role: 'user',+ content: [+ { type: 'tool_result', tool_use_id: 'toolu_01', content: '12:00' },+ ],+ },+ ],+ tools: [+ {+ name: 'getTime',+ description: 'returns the current time',+ input_schema: {+ type: 'object',+ properties: { tz: { type: 'string' } },+ required: ['tz'],+ },+ },+ ],+ },+ });+ const sent = JSON.parse(fetchState.calls[0].init.body);+ expect(sent.model).toBe('meta-llama/llama-3.3-70b-instruct:free');+ expect(sent.max_tokens).toBe(256);+ expect(sent.temperature).toBe(0.4);+ // System collapses into the first message.+ expect(sent.messages[0]).toEqual({ role: 'system', content: SYSTEM });+ expect(sent.messages[1]).toEqual({ role: 'user', content: 'how are you?' });+ // Assistant turn with a tool_use → OpenAI tool_calls array.+ expect(sent.messages[2]).toMatchObject({+ role: 'assistant',+ content: 'let me check',+ tool_calls: [+ {+ id: 'toolu_01',+ type: 'function',+ function: { name: 'getTime', arguments: JSON.stringify({ tz: 'UTC' }) },+ },+ ],+ });+ // tool_result block → role:"tool" message.+ expect(sent.messages[3]).toEqual({+ role: 'tool',+ tool_call_id: 'toolu_01',+ content: '12:00',+ });+ // Tool schema converted to OpenAI function-tool shape.+ expect(sent.tools[0]).toEqual({+ type: 'function',+ function: {+ name: 'getTime',+ description: 'returns the current time',+ parameters: {+ type: 'object',+ properties: { tz: { type: 'string' } },+ required: ['tz'],+ },+ },+ });+ expect(sent.tool_choice).toBe('auto');+ });++ it('translates OpenAI-shape upstream response → Anthropic-shape body', async () => {+ const { status, body } = await invoke({+ body: { ...VALID_BODY, model: 'llama-3.3-70b-versatile' },+ });+ expect(status).toBe(200);+ expect(body).toMatchObject({+ type: 'message',+ role: 'assistant',+ model: 'llama-3.3-70b-versatile',+ content: [{ type: 'text', text: 'hi from free model' }],+ stop_reason: 'end_turn',+ usage: { input_tokens: 7, output_tokens: 9 },+ });+ });++ it('translates upstream tool_calls into Anthropic tool_use blocks', async () => {+ fetchState.response = () =>+ upstreamOk({+ id: 'gen-2',+ choices: [+ {+ message: {+ role: 'assistant',+ content: '',+ tool_calls: [+ {+ id: 'call_1',+ type: 'function',+ function: { name: 'getTime', arguments: '{"tz":"UTC"}' },+ },+ ],+ },+ finish_reason: 'tool_calls',+ },+ ],+ usage: { prompt_tokens: 4, completion_tokens: 5 },+ });+ const { body } = await invoke({+ body: { ...VALID_BODY, model: 'meta-llama/llama-3.3-70b-instruct:free' },+ });+ expect(body.content).toEqual([+ { type: 'tool_use', id: 'call_1', name: 'getTime', input: { tz: 'UTC' } },+ ]);+ expect(body.stop_reason).toBe('tool_use');+ });++ it('debits OpenAI-shape token usage (prompt + completion) onto the agent', async () => {+ await invoke({+ body: { ...VALID_BODY, model: 'meta-llama/llama-3.3-70b-instruct:free' },+ });+ const monthKey = new Date().toISOString().slice(0, 7);+ expect(redisStore.get(`llm:tokens:agent-1:${monthKey}`)).toBe(16);+ });++ it('records usage with the upstream provider tag', async () => {+ await invoke({+ body: { ...VALID_BODY, model: 'meta-llama/llama-3.3-70b-instruct:free' },+ });+ expect(usageEvents[0]).toMatchObject({+ kind: 'llm',+ tool: 'openrouter.chat',+ agentId: 'agent-1',+ });+ });+});diff --git a/tests/e2e/avatar-edit.spec.js b/tests/e2e/avatar-edit.spec.jsindex 9da6d8115..50605987f 100644--- a/tests/e2e/avatar-edit.spec.js+++ b/tests/e2e/avatar-edit.spec.js@@ -78,6 +78,16 @@ test('wardrobe editor: hover, commit, chip, search', async ({ page }) => {// Click to commit. Chip appears in the chip bar.await firstOutfit.click();await expect(firstOutfit).toHaveClass(/selected/);++ // Diagnostic: peek at chip bar innerHTML after the click settles.+ await page.waitForTimeout(300);+ const debug = await page.evaluate(() => ({+ chipsHtml: document.getElementById('ae-chips')?.innerHTML,+ chipCount: document.querySelectorAll('#ae-chips .ae-chip').length,+ firstOutfitClass: document.querySelector('[data-id="outfit-casual"]')?.className,+ }));+ console.log('debug after outfit click:', JSON.stringify(debug));+await expect(chipBar.locator('.ae-chip')).toHaveCount(1);await expect(chipBar.locator('.ae-chip')).toContainText('Casual');