Skip to content

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.

feat: add Microsoft Edge TTS proxy and skills seed generation script

nirholas5cd62010673a
diff --git a/api/_lib/migrations/2026-05-01-skills-chat-seed.sql b/api/_lib/migrations/2026-05-01-skills-chat-seed.sql
new file mode 100644
index 000000000..005486bb3
--- /dev/null
+++ b/api/_lib/migrations/2026-05-01-skills-chat-seed.sql
@@ -0,0 +1,121 @@
+-- Migration: seed curated chat skills into marketplace
+-- Generated from chat/src/tools.js curatedToolPacks (skips tradingview-charts and web-search which are already seeded)
+-- Idempotent via ON CONFLICT (slug) DO NOTHING.
+
+begin;
+
+insert into marketplace_skills (name, slug, description, category, tags, schema_json, is_public, author_id) values
+
+(
+ '3D Price Chart',
+ 'price-chart-3d',
+ 'Render an extruded 3D price chart for any crypto asset over a chosen window.',
+ 'finance',
+ '{"3d","chart","crypto","finance"}',
+ '[{"clientDefinition":{"id":"pack-price-chart-3d-001","name":"PriceChart3D","description":"Show a rotating 3D bar chart of price history for a crypto asset.","arguments":[{"name":"id","type":"string","description":"CoinGecko id (e.g. bitcoin) or ticker (e.g. BTC)."},{"name":"days","type":"number","description":"Window size in days (1, 7, 14, 30, 90, 180, 365, max)."}],"body":"const raw = String(args.id || '''').trim().toLowerCase();\nif (!raw) throw new Error(''id required'');\nconst days = String(args.days || 30);\nlet id = raw;\nif (raw.length <= 6 && !raw.includes(''-'')) {\n const s = await fetch(''https://api.coingecko.com/api/v3/search?query='' + encodeURIComponent(raw));\n if (!s.ok) throw new Error(''CoinGecko search failed: '' + s.status);\n const sj = await s.json();\n const hit = (sj.coins || []).find(c => c.symbol?.toLowerCase() === raw) || (sj.coins || [])[0];\n if (!hit?.id) throw new Error(''No CoinGecko match for \"'' + raw + ''\"'');\n id = hit.id;\n}\nconst html = `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\nhtml,body{margin:0;height:100%;background:#0b0d10;color:#e5e7eb;font-family:ui-sans-serif,system-ui,sans-serif;overflow:hidden}\n#hud{position:absolute;left:12px;top:10px;font-size:13px;line-height:1.45}\n#err{position:absolute;inset:0;display:none;align-items:center;justify-content:center;color:#fca5a5;padding:24px;text-align:center}\n</style></head><body>\n<div id=\"hud\">Loading…</div><div id=\"err\"></div>\n<script type=\"module\">\nimport * as THREE from ''https://esm.sh/[email protected]'';\nimport { OrbitControls } from ''https://esm.sh/[email protected]/examples/jsm/controls/OrbitControls.js'';\nconst ID = ${JSON.stringify(id)}, DAYS = ${JSON.stringify(days)};\nconst renderer = new THREE.WebGLRenderer({ antialias: true });\nrenderer.setPixelRatio(devicePixelRatio); renderer.setSize(innerWidth, innerHeight); renderer.setClearColor(0x0b0d10);\ndocument.body.appendChild(renderer.domElement);\naddEventListener(''resize'', () => { renderer.setSize(innerWidth, innerHeight); cam.aspect = innerWidth/innerHeight; cam.updateProjectionMatrix(); });\nconst scene = new THREE.Scene();\nconst cam = new THREE.PerspectiveCamera(45, innerWidth/innerHeight, 0.1, 1000); cam.position.set(0, 18, 28);\nconst ctl = new OrbitControls(cam, renderer.domElement); ctl.enableDamping = true; ctl.target.set(0, 4, 0);\nscene.add(new THREE.AmbientLight(0xffffff, 0.45));\nconst key = new THREE.DirectionalLight(0xffffff, 1.0); key.position.set(10, 20, 10); scene.add(key);\nfunction err(m){ document.getElementById(''err'').style.display=''flex''; document.getElementById(''err'').textContent=m; }\nasync function load(){\n const r = await fetch(''https://api.coingecko.com/api/v3/coins/'' + encodeURIComponent(ID) + ''/market_chart?vs_currency=usd&days='' + encodeURIComponent(DAYS));\n if (!r.ok) return err(''CoinGecko market_chart failed: '' + r.status);\n const j = await r.json();\n const prices = j.prices || [];\n if (!prices.length) return err(''No price data'');\n const N = prices.length, vals = prices.map(p => p[1]);\n const min = Math.min(...vals), max = Math.max(...vals), range = Math.max(1e-9, max - min);\n const width = 30, gap = width / N, barW = gap * 0.85;\n const group = new THREE.Group();\n for (let i = 0; i < N; i++) {\n const h = ((vals[i] - min) / range) * 14 + 0.05;\n const g = new THREE.BoxGeometry(barW, h, barW);\n const t = i / (N - 1);\n const col = new THREE.Color().setHSL(0.58 - 0.55 * t, 0.7, 0.55);\n const m = new THREE.MeshStandardMaterial({ color: col, roughness: 0.4, metalness: 0.2 });\n const cube = new THREE.Mesh(g, m);\n cube.position.set(-width/2 + i * gap + gap/2, h/2, 0);\n group.add(cube);\n }\n scene.add(group);\n const last = vals[vals.length - 1], first = vals[0];\n const chg = ((last - first) / first) * 100;\n document.getElementById(''hud'').innerHTML =\n ''<b>'' + ID.toUpperCase() + ''</b> · '' + DAYS + ''d<br>'' +\n ''Last $'' + last.toLocaleString(undefined,{maximumFractionDigits:6}) + ''<br>'' +\n ''Δ '' + chg.toFixed(2) + ''% over window'';\n}\nfunction tick(){ ctl.update(); renderer.render(scene, cam); requestAnimationFrame(tick); }\ntick(); load();\n</script></body></html>`;\nreturn { contentType: ''text/html'', content: html };"},"type":"function","function":{"name":"PriceChart3D","description":"Render an interactive 3D bar chart of crypto price history. Use whenever the user asks for a 3D chart, historical price visualization, or sparkline of a coin.","parameters":{"type":"object","properties":{"id":{"type":"string","description":"CoinGecko id (e.g. ethereum) or ticker (e.g. ETH)."},"days":{"type":"number","enum":[1,7,14,30,90,180,365],"description":"Window in days."}},"required":["id"]}}}]',
+ true,
+ null
+),
+
+(
+ 'Token Price',
+ 'token-price',
+ 'Look up real-time crypto prices and 24h change via CoinGecko.',
+ 'finance',
+ '{"crypto","price","finance","coingecko"}',
+ '[{"clientDefinition":{"id":"pack-token-price-001","name":"TokenPrice","description":"Returns current USD price, 24h change %, and market cap for a crypto asset.","arguments":[{"name":"id","type":"string","description":"CoinGecko id (e.g. bitcoin, ethereum, solana) OR a ticker symbol like BTC, ETH, SOL."}],"body":"const raw = String(args.id || '''').trim().toLowerCase();\nif (!raw) throw new Error(''id required'');\nlet id = raw;\nif (raw.length <= 6 && !raw.includes(''-'')) {\n const s = await fetch(''https://api.coingecko.com/api/v3/search?query='' + encodeURIComponent(raw));\n if (!s.ok) throw new Error(''CoinGecko search failed: '' + s.status);\n const sj = await s.json();\n const hit = (sj.coins || []).find(c => c.symbol?.toLowerCase() === raw) || (sj.coins || [])[0];\n if (hit?.id) id = hit.id;\n}\nconst r = await fetch(''https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids='' + encodeURIComponent(id));\nif (!r.ok) throw new Error(''CoinGecko markets failed: '' + r.status);\nconst arr = await r.json();\nif (!arr.length) throw new Error(''No CoinGecko match for \"'' + raw + ''\"'');\nconst c = arr[0];\nreturn {\n id: c.id,\n symbol: c.symbol,\n name: c.name,\n price_usd: c.current_price,\n change_24h_pct: c.price_change_percentage_24h,\n market_cap_usd: c.market_cap,\n volume_24h_usd: c.total_volume,\n last_updated: c.last_updated,\n};"},"type":"function","function":{"name":"TokenPrice","description":"Get the current USD price, 24h change %, market cap, and 24h volume for a crypto asset by CoinGecko id or ticker symbol.","parameters":{"type":"object","properties":{"id":{"type":"string","description":"CoinGecko id (e.g. solana) or symbol (e.g. SOL)."}},"required":["id"]}}}]',
+ true,
+ null
+),
+
+(
+ '3D Token Ticker',
+ 'token-ticker-3d',
+ 'Render a live rotating 3D coin and price plate for any crypto asset.',
+ 'finance',
+ '{"3d","crypto","ticker","finance"}',
+ '[{"clientDefinition":{"id":"pack-token-ticker-3d-001","name":"TokenTicker3D","description":"Show a live 3D rotating coin with current USD price and 24h change.","arguments":[{"name":"id","type":"string","description":"CoinGecko id (e.g. solana) or ticker (e.g. SOL)."}],"body":"const raw = String(args.id || '''').trim().toLowerCase();\nif (!raw) throw new Error(''id required'');\nlet id = raw;\nif (raw.length <= 6 && !raw.includes(''-'')) {\n const s = await fetch(''https://api.coingecko.com/api/v3/search?query='' + encodeURIComponent(raw));\n if (!s.ok) throw new Error(''CoinGecko search failed: '' + s.status);\n const sj = await s.json();\n const hit = (sj.coins || []).find(c => c.symbol?.toLowerCase() === raw) || (sj.coins || [])[0];\n if (!hit?.id) throw new Error(''No CoinGecko match for \"'' + raw + ''\"'');\n id = hit.id;\n}\nconst html = `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\nhtml,body{margin:0;height:100%;background:#0b0d10;color:#e5e7eb;font-family:ui-sans-serif,system-ui,sans-serif;overflow:hidden}\n#info{position:absolute;left:12px;top:12px;font-size:14px;letter-spacing:.02em}\n#price{font-size:28px;font-weight:600}\n#chg{font-size:14px}\n.up{color:#22c55e}.dn{color:#ef4444}\n#err{position:absolute;inset:0;display:none;align-items:center;justify-content:center;color:#fca5a5;padding:24px;text-align:center}\n</style></head><body>\n<div id=\"info\"><div id=\"name\">Loading…</div><div id=\"price\">—</div><div id=\"chg\">—</div></div>\n<div id=\"err\"></div>\n<script type=\"module\">\nimport * as THREE from ''https://esm.sh/[email protected]'';\nconst ID = ${JSON.stringify(id)};\nconst renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });\nrenderer.setPixelRatio(devicePixelRatio); renderer.setSize(innerWidth, innerHeight);\ndocument.body.appendChild(renderer.domElement);\naddEventListener(''resize'', () => { renderer.setSize(innerWidth, innerHeight); cam.aspect = innerWidth/innerHeight; cam.updateProjectionMatrix(); });\nconst scene = new THREE.Scene();\nconst cam = new THREE.PerspectiveCamera(45, innerWidth/innerHeight, 0.1, 100); cam.position.set(0, 0, 4);\nscene.add(new THREE.AmbientLight(0xffffff, 0.55));\nconst key = new THREE.DirectionalLight(0xffffff, 1.2); key.position.set(3, 4, 5); scene.add(key);\nconst coinGeo = new THREE.CylinderGeometry(1, 1, 0.18, 96);\nlet coin = null;\nfunction setError(msg) { document.getElementById(''err'').style.display = ''flex''; document.getElementById(''err'').textContent = msg; }\nasync function load() {\n const r = await fetch(''https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids='' + encodeURIComponent(ID));\n if (!r.ok) return setError(''CoinGecko markets failed: '' + r.status);\n const arr = await r.json();\n if (!arr.length) return setError(''No data for '' + ID);\n const c = arr[0];\n document.getElementById(''name'').textContent = c.name + '' · '' + c.symbol.toUpperCase();\n document.getElementById(''price'').textContent = ''$'' + Number(c.current_price).toLocaleString(undefined, { maximumFractionDigits: 6 });\n const chg = Number(c.price_change_percentage_24h || 0);\n const chgEl = document.getElementById(''chg'');\n chgEl.textContent = (chg >= 0 ? ''+'' : '''') + chg.toFixed(2) + ''% (24h)'';\n chgEl.className = chg >= 0 ? ''up'' : ''dn'';\n if (!coin) {\n const tex = await new THREE.TextureLoader().loadAsync(c.image);\n tex.colorSpace = THREE.SRGBColorSpace;\n const edge = new THREE.MeshStandardMaterial({ color: 0xc9a64b, roughness: 0.35, metalness: 0.85 });\n const face = new THREE.MeshStandardMaterial({ map: tex, roughness: 0.4, metalness: 0.5 });\n coin = new THREE.Mesh(coinGeo, [edge, face, face]);\n coin.rotation.x = Math.PI / 2;\n scene.add(coin);\n }\n}\nfunction tick() { if (coin) coin.rotation.z += 0.012; renderer.render(scene, cam); requestAnimationFrame(tick); }\ntick(); load(); setInterval(load, 30000);\n<\\/script></body></html>`;\nreturn { contentType: ''text/html'', content: html };"},"type":"function","function":{"name":"TokenTicker3D","description":"Render a live 3D rotating coin with the current USD price and 24h change for a crypto asset.","parameters":{"type":"object","properties":{"id":{"type":"string","description":"CoinGecko id (e.g. ethereum) or ticker (e.g. ETH)."}},"required":["id"]}}}]',
+ true,
+ null
+),
+
+(
+ 'Date & Time',
+ 'date-time',
+ 'Get the current time and timezone.',
+ 'utility',
+ '{"time","date","utility"}',
+ '[{"clientDefinition":{"id":"pack-datetime-001","name":"GetCurrentTime","description":"Returns the current date and time as an ISO string.","arguments":[],"body":"return new Date().toISOString();"},"type":"function","function":{"name":"GetCurrentTime","description":"Returns the current date and time as an ISO 8601 string.","parameters":{"type":"object","properties":{}}}},{"clientDefinition":{"id":"pack-datetime-002","name":"GetTimezone","description":"Returns the user''s current timezone.","arguments":[],"body":"return Intl.DateTimeFormat().resolvedOptions().timeZone;"},"type":"function","function":{"name":"GetTimezone","description":"Returns the user''s current IANA timezone string.","parameters":{"type":"object","properties":{}}}}]',
+ true,
+ null
+),
+
+(
+ 'Pump.fun Launch',
+ 'pump-launch',
+ 'Launch a real pump.fun token on Solana from chat (requires connected Solana wallet).',
+ 'web3',
+ '{"pump.fun","solana","token","web3"}',
+ '[{"clientDefinition":{"id":"pack-pump-launch-001","name":"LaunchPumpToken","description":"Create a new pump.fun token. Returns the real mint address on success.","arguments":[{"name":"agent_id","type":"string","description":"UUID of your 3D agent identity (required to bind the token)."},{"name":"name","type":"string","description":"Token name."},{"name":"symbol","type":"string","description":"Token symbol (1-10 chars)."},{"name":"uri","type":"string","description":"Metadata JSON URL (Arweave/IPFS URI with name, symbol, image, description fields)."},{"name":"network","type":"string","description":"mainnet or devnet (default mainnet)."},{"name":"sol_buy_in","type":"number","description":"Initial creator buy in SOL (>= 0, default 0)."},{"name":"buyback_bps","type":"number","description":"Buyback basis points 0-10000 (default 0)."}],"body":"if (!window.solana || !window.solana.isConnected) {\n try { await window.solana?.connect(); } catch(e) { throw new Error(''Solana wallet not connected: '' + (e?.message||e)); }\n}\nconst pubkey = window.solana?.publicKey?.toBase58?.();\nif (!pubkey) throw new Error(''No Solana public key available — connect a wallet first.'');\nconst agentId = String(args.agent_id || '''').trim();\nconst name = String(args.name || '''').trim();\nconst symbol = String(args.symbol || '''').trim();\nconst uri = String(args.uri || '''').trim();\nif (!agentId) throw new Error(''agent_id required'');\nif (!name || !symbol || !uri) throw new Error(''name, symbol, uri required'');\nconst network = args.network === ''devnet'' ? ''devnet'' : ''mainnet'';\nconst sol_buy_in = Number(args.sol_buy_in || 0);\nconst buyback_bps = Number(args.buyback_bps || 0);\nconst prep = await fetch(''/api/pump/launch-prep'', {\n method: ''POST'',\n headers: { ''content-type'': ''application/json'' },\n credentials: ''include'',\n body: JSON.stringify({ agent_id: agentId, wallet_address: pubkey, name, symbol, uri, network, sol_buy_in, buyback_bps }),\n});\nif (!prep.ok) throw new Error(''launch-prep failed: '' + prep.status + '' '' + await prep.text());\nconst { prep_id, mint, mint_secret_key_b64, tx_base64 } = await prep.json();\nif (!prep_id || !mint || !tx_base64) throw new Error(''launch-prep returned incomplete data'');\nconst { VersionedTransaction, Keypair } = await import(''https://esm.sh/@solana/web3.js@1'');\nconst txBytes = Uint8Array.from(atob(tx_base64), c => c.charCodeAt(0));\nconst tx = VersionedTransaction.deserialize(txBytes);\nif (mint_secret_key_b64) {\n const mintKp = Keypair.fromSecretKey(Uint8Array.from(atob(mint_secret_key_b64), c => c.charCodeAt(0)));\n tx.sign([mintKp]);\n}\nconst result = await window.solana.signAndSendTransaction(tx);\nconst tx_signature = result?.signature ?? String(result);\nif (!tx_signature) throw new Error(''wallet did not return a transaction signature'');\nconst conf = await fetch(''/api/pump/launch-confirm'', {\n method: ''POST'',\n headers: { ''content-type'': ''application/json'' },\n credentials: ''include'',\n body: JSON.stringify({ prep_id, tx_signature }),\n});\nif (!conf.ok) throw new Error(''launch-confirm failed: '' + conf.status + '' '' + await conf.text());\nconst confirmed = await conf.json();\nreturn { mint, tx_signature, pump_url: ''https://pump.fun/'' + mint, pump_agent_mint: confirmed.pump_agent_mint };"},"type":"function","function":{"name":"LaunchPumpToken","description":"Launch a real pump.fun token on Solana. Requires a connected Solana wallet and an existing agent identity. Calls launch-prep then wallet signs and submits then launch-confirm.","parameters":{"type":"object","properties":{"agent_id":{"type":"string","description":"UUID of the 3D agent identity to bind this token to."},"name":{"type":"string","description":"Token name."},"symbol":{"type":"string","description":"Token symbol (1-10 chars)."},"uri":{"type":"string","description":"Metadata JSON URL (Arweave/IPFS URI)."},"network":{"type":"string","enum":["mainnet","devnet"],"description":"Solana network (default mainnet)."},"sol_buy_in":{"type":"number","description":"Initial creator buy in SOL (default 0)."},"buyback_bps":{"type":"number","description":"Buyback basis points 0-10000 (default 0)."}},"required":["agent_id","name","symbol","uri"]}}}]',
+ true,
+ null
+),
+
+(
+ 'Tx Explainer',
+ 'tx-explain',
+ 'Decode a real Solana or Ethereum transaction into plain English plus a 3D flow diagram.',
+ 'web3',
+ '{"transaction","solana","evm","web3"}',
+ '[{"clientDefinition":{"id":"pack-tx-explain-001","name":"TxExplain","description":"Explain an on-chain transaction and visualize the token flow in 3D.","arguments":[{"name":"chain","type":"string","description":"solana | evm"},{"name":"sig","type":"string","description":"Transaction signature (Solana) or hash (EVM)."}],"body":"const chain = String(args.chain || '''').toLowerCase();\nconst sig = String(args.sig || '''').trim();\nif (![''solana'',''evm''].includes(chain)) throw new Error(''chain must be solana or evm'');\nif (!sig) throw new Error(''sig required'');\nconst r = await fetch(''/api/tx/explain'', { method: ''POST'', headers:{''content-type'':''application/json''}, credentials:''include'', body: JSON.stringify({ chain, sig }) });\nif (!r.ok) throw new Error(''tx explain failed: '' + r.status + '' '' + await r.text());\nconst d = await r.json();\nconst transfers = chain === ''solana''\n ? [...(d.tokenTransfers||[]).map(t => ({from: t.fromUserAccount, to: t.toUserAccount, amount: t.tokenAmount, label: t.mint || ''TOKEN''})),\n ...(d.nativeTransfers||[]).map(t => ({from: t.fromUserAccount, to: t.toUserAccount, amount: t.amount/1e9, label: ''SOL''}))]\n : (d.logs||[]).map(t => ({from: t.from, to: t.to, amount: t.amount, label: t.token}));\nconst html = `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\nhtml,body{margin:0;height:100%;background:#0b0d10;color:#e5e7eb;font-family:ui-sans-serif,system-ui,sans-serif;overflow:hidden}\n#hud{position:absolute;left:12px;top:10px;font-size:12px;background:rgba(0,0,0,.45);padding:8px 10px;border-radius:8px;max-width:380px;line-height:1.45}\n</style></head><body>\n<div id=\"hud\"></div>\n<script type=\"module\">\nimport * as THREE from ''https://esm.sh/[email protected]'';\nimport { OrbitControls } from ''https://esm.sh/[email protected]/examples/jsm/controls/OrbitControls.js'';\nconst TX = ${JSON.stringify(d)}, T = ${JSON.stringify(transfers)};\nconst renderer = new THREE.WebGLRenderer({ antialias: true });\nrenderer.setPixelRatio(devicePixelRatio); renderer.setSize(innerWidth, innerHeight); renderer.setClearColor(0x0b0d10);\ndocument.body.appendChild(renderer.domElement);\naddEventListener(''resize'', () => { renderer.setSize(innerWidth, innerHeight); cam.aspect = innerWidth/innerHeight; cam.updateProjectionMatrix(); });\nconst scene = new THREE.Scene();\nconst cam = new THREE.PerspectiveCamera(45, innerWidth/innerHeight, 0.01, 1000); cam.position.set(0, 6, 14);\nconst ctl = new OrbitControls(cam, renderer.domElement); ctl.enableDamping = true;\nscene.add(new THREE.AmbientLight(0xffffff, 0.6));\nconst k = new THREE.DirectionalLight(0xffffff,1); k.position.set(5,8,6); scene.add(k);\nconst accounts = Array.from(new Set(T.flatMap(t => [t.from, t.to]).filter(Boolean)));\nconst pos = new Map();\naccounts.forEach((a, i) => {\n const ang = (i / Math.max(1,accounts.length)) * Math.PI * 2;\n const r = 5 + (accounts.length > 6 ? 2 : 0);\n pos.set(a, new THREE.Vector3(Math.cos(ang)*r, 0, Math.sin(ang)*r));\n});\naccounts.forEach(a => {\n const m = new THREE.Mesh(new THREE.SphereGeometry(0.4, 24, 24), new THREE.MeshStandardMaterial({ color: 0x9aa0a6, roughness: 0.4 }));\n m.position.copy(pos.get(a)); scene.add(m);\n});\nT.forEach(t => {\n const a = pos.get(t.from), b = pos.get(t.to); if (!a || !b) return;\n const geo = new THREE.BufferGeometry().setFromPoints([a, b]);\n const line = new THREE.Line(geo, new THREE.LineBasicMaterial({ color: 0x60a5fa }));\n scene.add(line);\n});\nlet html = ''<div><b>'' + (TX.summary || TX.description || (TX.type || ''transaction'')) + ''</b></div>'';\nhtml += ''<div style=\"margin-top:6px\">'' + T.length + '' transfer(s) across '' + accounts.length + '' account(s)</div>'';\nT.slice(0,8).forEach(t => { html += ''<div>'' + (t.label||''TOKEN'') + '': '' + (t.amount||''?'') + ''</div>''; });\ndocument.getElementById(''hud'').innerHTML = html;\nfunction tick(){ ctl.update(); renderer.render(scene, cam); requestAnimationFrame(tick); }\ntick();\n</script></body></html>`;\nreturn { contentType: ''text/html'', content: html };"},"type":"function","function":{"name":"TxExplain","description":"Decode a real Solana or Ethereum transaction by signature/hash and render a 3D flow diagram of the transfers.","parameters":{"type":"object","properties":{"chain":{"type":"string","enum":["solana","evm"]},"sig":{"type":"string"}},"required":["chain","sig"]}}}]',
+ true,
+ null
+),
+
+(
+ 'Mint Scene NFT',
+ 'mint-scene-nft',
+ 'Snapshot the live 3D scene and mint it as a real Solana NFT via NFT.Storage + Metaplex.',
+ 'web3',
+ '{"nft","solana","mint","3d"}',
+ '[{"clientDefinition":{"id":"pack-mint-scene-001","name":"MintScene","description":"Mint the current 3D scene as a Solana NFT.","arguments":[{"name":"name","type":"string","description":"NFT name."},{"name":"description","type":"string","description":"NFT description."}],"body":"if (!window.solana?.publicKey) {\n try { await window.solana?.connect(); } catch(e) { throw new Error(''Connect a Solana wallet first: '' + (e?.message||e)); }\n}\nconst owner = window.solana.publicKey.toBase58();\n// Request GLB + screenshot from the viewer iframe.\nconst viewer = document.querySelector(''iframe[data-three-ws-viewer]'') || document.querySelector(''iframe'');\nif (!viewer?.contentWindow) throw new Error(''No 3D viewer iframe found in the page.'');\nfunction ask(action, payload = {}) {\n return new Promise((resolve, reject) => {\n const id = ''mint-scene-'' + Math.random().toString(36).slice(2);\n const onMsg = (e) => {\n const d = e.data || {};\n if (d.id !== id) return;\n window.removeEventListener(''message'', onMsg);\n if (d.error) reject(new Error(d.error)); else resolve(d.result);\n };\n window.addEventListener(''message'', onMsg);\n viewer.contentWindow.postMessage({ id, action, input: payload }, ''*'');\n setTimeout(() => { window.removeEventListener(''message'', onMsg); reject(new Error(''viewer timeout for '' + action)); }, 15000);\n });\n}\nconst glbBase64 = await ask(''exportGLB'');\nconst thumbnailBase64 = await ask(''takeScreenshot'', { width: 512, height: 512 });\nif (!glbBase64 || !thumbnailBase64) throw new Error(''Viewer returned empty asset(s).'');\nconst prep = await fetch(''/api/nft/mint-scene'', { method:''POST'', headers:{''content-type'':''application/json''}, credentials:''include'', body: JSON.stringify({ ownerPubkey: owner, glbBase64, thumbnailBase64, name: String(args.name||'''').trim(), description: String(args.description||'''').trim() }) });\nif (!prep.ok) throw new Error(''mint-scene prep failed: '' + prep.status + '' '' + await prep.text());\nconst { unsignedTxBase64, metadataUri, mint } = await prep.json();\nconst bin = Uint8Array.from(atob(unsignedTxBase64), c => c.charCodeAt(0));\nconst signed = await window.solana.signTransaction({ serialize: () => bin, _raw: bin });\nconst signedTxBase64 = btoa(String.fromCharCode(...(signed.serialize?.() || signed._raw || bin)));\nconst conf = await fetch(''/api/nft/mint-scene-confirm'', { method:''POST'', headers:{''content-type'':''application/json''}, credentials:''include'', body: JSON.stringify({ signedTxBase64 }) });\nif (!conf.ok) throw new Error(''mint confirm failed: '' + conf.status + '' '' + await conf.text());\nconst { signature } = await conf.json();\nreturn { mint, signature, metadataUri, explorer: ''https://solscan.io/tx/'' + signature };"},"type":"function","function":{"name":"MintScene","description":"Mint the currently displayed 3D scene as a real Solana NFT. Asks the viewer to export GLB + screenshot, uploads to NFT.Storage, and mints via Metaplex.","parameters":{"type":"object","properties":{"name":{"type":"string"},"description":{"type":"string"}},"required":["name"]}}}]',
+ true,
+ null
+),
+
+(
+ 'NFT 3D Import',
+ 'nft-3d-import',
+ 'Fetch a real NFT and render its 3D model (or image plane fallback) in an orbit viewer.',
+ 'web3',
+ '{"nft","3d","solana","evm"}',
+ '[{"clientDefinition":{"id":"pack-nft-3d-import-001","name":"NFTImport3D","description":"Resolve an NFT and render it in 3D.","arguments":[{"name":"chain","type":"string","description":"solana | evm"},{"name":"id","type":"string","description":"For solana: mint pubkey. For evm: \"contract:tokenId\" (Ethereum mainnet)."}],"body":"const chain = String(args.chain || '''').toLowerCase();\n\tconst id = String(args.id || '''').trim();\n\tif (![''solana'',''evm''].includes(chain)) throw new Error(''chain must be solana or evm'');\n\tif (!id) throw new Error(''id required'');\n\tconst r = await fetch(''/api/nft/resolve'', { method: ''POST'', headers: {''content-type'':''application/json''}, credentials: ''include'', body: JSON.stringify({ chain, id }) });\n\tif (!r.ok) throw new Error(''NFT resolve failed: '' + r.status + '' '' + await r.text());\n\tconst meta = await r.json();\n\tconst html = `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\n\thtml,body{margin:0;height:100%;background:#0b0d10;color:#e5e7eb;font-family:ui-sans-serif,system-ui,sans-serif;overflow:hidden}\n\t#hud{position:absolute;left:12px;top:10px;font-size:13px;background:rgba(0,0,0,.4);padding:6px 10px;border-radius:8px}\n\t</style></head><body>\n\t<div id=\"hud\">${meta.name || ''NFT''}</div>\n\t<script type=\"module\">\n\timport * as THREE from ''https://esm.sh/[email protected]'';\n\timport { OrbitControls } from ''https://esm.sh/[email protected]/examples/jsm/controls/OrbitControls.js'';\n\timport { GLTFLoader } from ''https://esm.sh/[email protected]/examples/jsm/loaders/GLTFLoader.js'';\n\tconst META = ${JSON.stringify(meta)};\n\tconst renderer = new THREE.WebGLRenderer({ antialias: true });\n\trenderer.setPixelRatio(devicePixelRatio); renderer.setSize(innerWidth, innerHeight); renderer.setClearColor(0x0b0d10);\n\tdocument.body.appendChild(renderer.domElement);\n\taddEventListener(''resize'', () => { renderer.setSize(innerWidth, innerHeight); cam.aspect = innerWidth/innerHeight; cam.updateProjectionMatrix(); });\n\tconst scene = new THREE.Scene();\n\tconst cam = new THREE.PerspectiveCamera(45, innerWidth/innerHeight, 0.01, 1000); cam.position.set(0, 1.2, 3);\n\tconst ctl = new OrbitControls(cam, renderer.domElement); ctl.enableDamping = true;\n\tscene.add(new THREE.AmbientLight(0xffffff, 0.6));\n\tconst k = new THREE.DirectionalLight(0xffffff, 1); k.position.set(3, 4, 5); scene.add(k);\n\tasync function loadModel(url){\n\t const gltf = await new GLTFLoader().loadAsync(url);\n\t const m = gltf.scene;\n\t const box = new THREE.Box3().setFromObject(m);\n\t const size = box.getSize(new THREE.Vector3()).length();\n\t const center = box.getCenter(new THREE.Vector3());\n\t m.position.sub(center); cam.position.set(0, 0, size * 1.4); ctl.target.set(0,0,0);\n\t scene.add(m);\n\t}\n\tasync function loadPlane(url){\n\t const tex = await new THREE.TextureLoader().loadAsync(url);\n\t tex.colorSpace = THREE.SRGBColorSpace;\n\t const aspect = (tex.image && tex.image.width && tex.image.height) ? tex.image.width / tex.image.height : 1;\n\t const w = 2.4, h = w / aspect;\n\t const mesh = new THREE.Mesh(new THREE.PlaneGeometry(w, h), new THREE.MeshBasicMaterial({ map: tex }));\n\t scene.add(mesh);\n\t}\n\t(async () => {\n\t if (META.model) await loadModel(META.model);\n\t else if (META.image) await loadPlane(META.image);\n\t else { document.getElementById(''hud'').textContent = ''No renderable asset returned.''; }\n\t})();\n\tfunction tick(){ ctl.update(); renderer.render(scene, cam); requestAnimationFrame(tick); }\n\ttick();\n\t</script></body></html>`;\n\treturn { contentType: ''text/html'', content: html };"},"type":"function","function":{"name":"NFTImport3D","description":"Resolve a real NFT (Solana mint or Ethereum contract:tokenId) and render its 3D model or image in an orbit viewer.","parameters":{"type":"object","properties":{"chain":{"type":"string","enum":["solana","evm"]},"id":{"type":"string"}},"required":["chain","id"]}}}]',
+ true,
+ null
+),
+
+(
+ 'Wallet Balances',
+ 'wallet-balances',
+ 'Real on-chain balances for a Solana or EVM wallet with a 3D coin-stack visualization.',
+ 'web3',
+ '{"wallet","solana","evm","web3"}',
+ '[{"clientDefinition":{"id":"pack-wallet-balances-001","name":"WalletBalances","description":"Look up native + top token balances for a wallet and render a 3D coin stack.","arguments":[{"name":"chain","type":"string","description":"solana | evm"},{"name":"address","type":"string","description":"Wallet address (base58 for Solana, 0x… for EVM)."}],"body":"const chain = String(args.chain || '''').toLowerCase();\n\tconst address = String(args.address || '''').trim();\n\tif (![''solana'',''evm''].includes(chain)) throw new Error(''chain must be solana or evm'');\n\tif (!address) throw new Error(''address required'');\n\tconst r = await fetch(''/api/wallet/balances'', { method:''POST'', headers:{''content-type'':''application/json''}, credentials:''include'', body: JSON.stringify({ chain, address }) });\n\tif (!r.ok) throw new Error(''balances failed: '' + r.status + '' '' + await r.text());\n\tconst d = await r.json();\n\tconst top = [d.native, ...(d.tokens || [])].filter(Boolean).slice(0, 10);\n\tconst html = `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\n\thtml,body{margin:0;height:100%;background:#0b0d10;color:#e5e7eb;font-family:ui-sans-serif,system-ui,sans-serif;overflow:hidden}\n\t#hud{position:absolute;left:12px;top:10px;font-size:12px;background:rgba(0,0,0,.4);padding:8px 10px;border-radius:8px;max-width:280px}\n\t.row{display:flex;justify-content:space-between;gap:8px}.row b{color:#fff}\n\t</style></head><body>\n\t<div id=\"hud\"></div>\n\t<script type=\"module\">\n\timport * as THREE from ''https://esm.sh/[email protected]'';\n\timport { OrbitControls } from ''https://esm.sh/[email protected]/examples/jsm/controls/OrbitControls.js'';\n\tconst TOP = ${JSON.stringify(top)};\n\tconst renderer = new THREE.WebGLRenderer({ antialias: true });\n\trenderer.setPixelRatio(devicePixelRatio); renderer.setSize(innerWidth, innerHeight); renderer.setClearColor(0x0b0d10);\n\tdocument.body.appendChild(renderer.domElement);\n\taddEventListener(''resize'', () => { renderer.setSize(innerWidth, innerHeight); cam.aspect = innerWidth/innerHeight; cam.updateProjectionMatrix(); });\n\tconst scene = new THREE.Scene();\n\tconst cam = new THREE.PerspectiveCamera(45, innerWidth/innerHeight, 0.01, 1000); cam.position.set(0, 8, 14);\n\tconst ctl = new OrbitControls(cam, renderer.domElement); ctl.enableDamping = true; ctl.target.set(0, 2, 0);\n\tscene.add(new THREE.AmbientLight(0xffffff, 0.6));\n\tconst k = new THREE.DirectionalLight(0xffffff, 1); k.position.set(5, 10, 7); scene.add(k);\n\tconst totalUsd = TOP.reduce((s,t) => s + (Number(t.usd)||0), 0) || 1;\n\tconst colors = [0xf7931a, 0x627eea, 0x14f195, 0x9945ff, 0xe6007a, 0xf3ba2f, 0xff007a, 0xfcd535, 0x2a5ada, 0x8a2be2];\n\tTOP.forEach((t, i) => {\n\t const usd = Number(t.usd) || 0;\n\t const stackH = Math.max(0.05, (usd / totalUsd) * 6);\n\t const x = (i - TOP.length/2) * 1.4;\n\t const geo = new THREE.CylinderGeometry(0.5, 0.5, stackH, 48);\n\t const mat = new THREE.MeshStandardMaterial({ color: colors[i % colors.length], metalness: 0.85, roughness: 0.3 });\n\t const m = new THREE.Mesh(geo, mat); m.position.set(x, stackH/2, 0); scene.add(m);\n\t});\n\tlet html = ''<div><b>'' + TOP.length + '' assets · $'' + totalUsd.toLocaleString(undefined,{maximumFractionDigits:2}) + ''</b></div>'';\n\tTOP.forEach(t => { html += ''<div class=\"row\"><span>'' + t.symbol + ''</span><span>'' + Number(t.amount||0).toLocaleString(undefined,{maximumFractionDigits:6}) + '' · $'' + Number(t.usd||0).toLocaleString(undefined,{maximumFractionDigits:2}) + ''</span></div>''; });\n\tdocument.getElementById(''hud'').innerHTML = html;\n\tfunction tick(){ ctl.update(); renderer.render(scene, cam); requestAnimationFrame(tick); }\n\ttick();\n\t</script></body></html>`;\n\treturn { contentType: ''text/html'', content: html };"},"type":"function","function":{"name":"WalletBalances","description":"Look up real on-chain native + token balances for a wallet (Solana or EVM) and render a 3D coin-stack visualization.","parameters":{"type":"object","properties":{"chain":{"type":"string","enum":["solana","evm"]},"address":{"type":"string"}},"required":["chain","address"]}}}]',
+ true,
+ null
+),
+
+(
+ 'Token-Gate Scene',
+ 'token-gate-scene',
+ 'Create a shareable URL for the current 3D scene that only loads for wallets holding a specific token or NFT.',
+ 'web3',
+ '{"token-gate","nft","solana","web3"}',
+ '[{"clientDefinition":{"id":"pack-token-gate-001","name":"TokenGateScene","description":"Token-gate the current scene and return a share URL.","arguments":[{"name":"sceneRef","type":"string","description":"Identifier for the current scene (the chat already exposes one via the viewer share API — pass the same string the existing /share command uses)."},{"name":"chain","type":"string","description":"solana | evm"},{"name":"kind","type":"string","description":"spl | collection | erc20 | erc721"},{"name":"address","type":"string","description":"Token mint, collection address, or contract address."},{"name":"minBalance","type":"number","description":"Minimum required balance (in whole units; default 1)."}],"body":"const sceneRef = String(args.sceneRef||'''').trim();\nconst chain = String(args.chain||'''').toLowerCase();\nconst kind = String(args.kind||'''').toLowerCase();\nconst address = String(args.address||'''').trim();\nconst minBalance = Number(args.minBalance ?? 1);\nif (!sceneRef) throw new Error(''sceneRef required'');\nif (![''solana'',''evm''].includes(chain)) throw new Error(''chain must be solana or evm'');\nif (![''spl'',''collection'',''erc20'',''erc721''].includes(kind)) throw new Error(''kind must be spl|collection|erc20|erc721'');\nif (!address) throw new Error(''address required'');\nconst r = await fetch(''/api/scene/gate-create'', { method:''POST'', headers:{''content-type'':''application/json''}, credentials:''include'', body: JSON.stringify({ sceneRef, gate: { chain, kind, address, minBalance } }) });\nif (!r.ok) throw new Error(''gate-create failed: '' + r.status + '' '' + await r.text());\nconst { shareUrl, gateId } = await r.json();\nreturn { shareUrl, gateId, gate: { chain, kind, address, minBalance } };"},"type":"function","function":{"name":"TokenGateScene","description":"Create a real shareable, token-gated URL for the current 3D scene. Visitors connect a wallet and prove ownership before the scene loads.","parameters":{"type":"object","properties":{"sceneRef":{"type":"string"},"chain":{"type":"string","enum":["solana","evm"]},"kind":{"type":"string","enum":["spl","collection","erc20","erc721"]},"address":{"type":"string"},"minBalance":{"type":"number"}},"required":["sceneRef","chain","kind","address"]}}}]',
+ true,
+ null
+)
+
+on conflict (slug) do nothing;
+
+commit;
diff --git a/api/_lib/onchain.js b/api/_lib/onchain.js
index 9894549e6..42da6a8c7 100644
--- a/api/_lib/onchain.js
+++ b/api/_lib/onchain.js
@@ -356,10 +356,14 @@ function _pickDescription(json) {
return null;
}
+function _isAbsoluteURI(uri) {
+ return /^(https?|ipfs|ar|data):/.test(uri);
+}
+
function _pickImage(json) {
const candidates = [json?.image, json?.thumbnail, json?.body?.thumbnail, json?.avatar];
for (const c of candidates) {
- if (typeof c === 'string' && c) return resolveURI(c);
+ if (typeof c === 'string' && c && _isAbsoluteURI(c)) return resolveURI(c);
}
return null;
}
@@ -374,7 +378,7 @@ function _pickBody(json) {
json?.image,
];
for (const c of candidates) {
- if (typeof c === 'string' && c) return resolveURI(c);
+ if (typeof c === 'string' && c && _isAbsoluteURI(c)) return resolveURI(c);
}
return null;
}
diff --git a/api/_lib/r2.js b/api/_lib/r2.js
index 6f5801e76..74a56e092 100644
--- a/api/_lib/r2.js
+++ b/api/_lib/r2.js
@@ -41,12 +41,16 @@ export const r2 = new Proxy(
);
// Short-lived signed URL for direct browser upload (PUT).
-export async function presignUpload({ key, contentType, contentLength, checksumSha256 }) {
+export async function presignUpload({ key, contentType, checksumSha256 }) {
+ // Do NOT include ContentLength in the command — that adds content-length to
+ // X-Amz-SignedHeaders, which browsers omit from CORS preflights (it is a
+ // "forbidden" request header). R2 would then reject the preflight, causing
+ // a network-level failure before the PUT response is ever checked.
+ // Size is validated server-side via headObject after upload.
const cmd = new PutObjectCommand({
Bucket: env.S3_BUCKET,
Key: key,
ContentType: contentType,
- ContentLength: contentLength,
ChecksumSHA256: checksumSha256,
});
return getSignedUrl(r2, cmd, { expiresIn: 300 });
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 029f18ef7..62b8d3b96 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -129,6 +129,8 @@ export const limits = {
agentDelegate: (key) => getLimiter('agent:delegate', { limit: 10, window: '1 m' }).limit(key),
// GitHub memory seeding: expensive (GitHub API + Claude). 1 seed per agent per 24 hours.
memorySeed: (agentId) => getLimiter('memory:seed', { limit: 1, window: '1 d' }).limit(agentId),
+ // Edge TTS: free upstream but cached in R2 — limit unique synthesis requests per user/min.
+ ttsEdge: (userId) => getLimiter('tts:edge', { limit: 20, window: '1 m' }).limit(userId),
};
// Trust only proxy headers that Vercel itself sets and signs. Naively reading
diff --git a/api/animations/presign.js b/api/animations/presign.js
index f2a1f80d3..939df9a2e 100644
--- a/api/animations/presign.js
+++ b/api/animations/presign.js
@@ -55,7 +55,6 @@ export default wrap(async (req, res) => {
const url = await presignUpload({
key,
contentType: body.content_type,
- contentLength: body.size_bytes,
...(body.checksum_sha256 ? { checksumSha256: body.checksum_sha256 } : {}),
});
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
index 52bbc7dfa..52e519954 100644
--- a/api/avatars/_actions.js
+++ b/api/avatars/_actions.js
@@ -38,7 +38,7 @@ const handlePresign = wrap(async (req, res) => {
const bodyAny = body;
const slug = bodyAny.slug ? slugSchema.parse(bodyAny.slug) : `draft-${Math.random().toString(36).slice(2, 8)}`;
const key = storageKeyFor({ userId, slug });
- const url = await presignUpload({ key, contentType: body.content_type, contentLength: body.size_bytes });
+ const url = await presignUpload({ key, contentType: body.content_type });
return json(res, 200, { storage_key: key, upload_url: url, method: 'PUT', headers: { 'content-type': body.content_type }, expires_in: 300 });
});
diff --git a/api/chat.js b/api/chat.js
index 9afaffa16..8514fc5f7 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -12,6 +12,7 @@ import { parse } from './_lib/validate.js';
import { recordEvent } from './_lib/usage.js';
import { captureException } from './_lib/sentry.js';
import { sql } from './_lib/db.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
import { z } from 'zod';
const ANTHROPIC_URL = 'https://api.anthropic.com/v1/messages';
@@ -160,6 +161,18 @@ export default wrap(async (req, res) => {
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in to chat with the agent');
+ const ip = clientIp(req);
+ const [rlUser, rlIp] = await Promise.all([
+ limits.chatUser(auth.userId ?? ip),
+ limits.chatIp(ip),
+ ]);
+ if (!rlUser.success || !rlIp.success) {
+ const rl = rlUser.success ? rlIp : rlUser;
+ const retryAfter = Math.max(1, Math.ceil((rl.reset - Date.now()) / 1000));
+ res.setHeader('retry-after', String(retryAfter));
+ return error(res, 429, 'rate_limited', 'Too many requests', { retry_after: retryAfter });
+ }
+
const body = parse(chatBody, await readJson(req));
const model = process.env.CHAT_MODEL || DEFAULT_MODEL;
const maxTokens = clampInt(
diff --git a/api/tts/edge.js b/api/tts/edge.js
new file mode 100644
index 000000000..06b9eebbc
--- /dev/null
+++ b/api/tts/edge.js
@@ -0,0 +1,205 @@
+/**
+ * POST /api/tts/edge
+ *
+ * Microsoft Edge TTS proxy using the same unofficial WebSocket protocol as
+ * the edge-tts Python package (pypi.org/project/edge-tts).
+ * No API key required — uses the public TrustedClientToken.
+ * Caches synthesized clips in R2 by sha256(voice + text + rate + pitch) for 30 days.
+ *
+ * Body: { voice: string, text: string, rate?: string, pitch?: string }
+ * voice — e.g. "en-US-AriaNeural". Defaults to "en-US-AriaNeural".
+ * rate — prosody rate, e.g. "+0%", "-10%", "+20%". Defaults to "+0%".
+ * pitch — prosody pitch, e.g. "+0Hz", "-5Hz". Defaults to "+0Hz".
+ * Response: audio/mpeg
+ */
+
+import WebSocket from 'ws';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, method, wrap, error, readJson } from '../_lib/http.js';
+import { limits } from '../_lib/rate-limit.js';
+import { sha256 } from '../_lib/crypto.js';
+import { headObject, getObjectBuffer, putObject } from '../_lib/r2.js';
+
+const TRUSTED_CLIENT_TOKEN = '6A5AA1D4EAFF4E9FB37E23D68491D6F4';
+const WSS_BASE = `wss://speech.microsoft.com/consumer/speech/synthesize/readaloud/edge/v1?TrustedClientToken=${TRUSTED_CLIENT_TOKEN}`;
+const AUDIO_FORMAT = 'audio-24khz-48kbitrate-mono-mp3';
+
+const WS_HEADERS = {
+ Pragma: 'no-cache',
+ 'Cache-Control': 'no-cache',
+ Origin: 'chrome-extension://jdiccldimpdaibmpdkjnbmckianbfold',
+ 'Accept-Encoding': 'gzip, deflate, br',
+ 'Accept-Language': 'en-US,en;q=0.9',
+ 'User-Agent':
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0',
+};
+
+// e.g. "en-US-AriaNeural", "zh-CN-XiaoxiaoNeural"
+const VOICE_RE = /^[a-zA-Z]{2,8}-[a-zA-Z]{2,8}-[a-zA-Z]{5,50}$/;
+const RATE_RE = /^[+-]\d+%$/;
+const PITCH_RE = /^[+-]\d+Hz$/;
+
+function isoTimestamp() {
+ return new Date().toISOString().replace(/\.\d+/, '.000');
+}
+
+function mkId() {
+ return crypto.randomUUID().replace(/-/g, '');
+}
+
+function buildSsml(voice, text, rate, pitch) {
+ const esc = text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
+ return (
+ `<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>` +
+ `<voice name='${voice}'>` +
+ `<prosody pitch='${pitch}' rate='${rate}' volume='+0%'>${esc}</prosody>` +
+ `</voice></speak>`
+ );
+}
+
+function synthesize(voice, text, rate, pitch) {
+ return new Promise((resolve, reject) => {
+ const connId = mkId();
+ const ws = new WebSocket(`${WSS_BASE}&ConnectionId=${connId}`, { headers: WS_HEADERS });
+
+ const chunks = [];
+ let finished = false;
+
+ const timeout = setTimeout(() => {
+ if (!finished) {
+ ws.terminate();
+ reject(new Error('edge-tts synthesis timed out'));
+ }
+ }, 30_000);
+
+ ws.on('open', () => {
+ const configMsg =
+ `X-Timestamp:${isoTimestamp()}\r\nContent-Type:application/json; charset=utf-8\r\nPath:speech.config\r\n\r\n` +
+ JSON.stringify({
+ context: {
+ synthesis: {
+ audio: {
+ metadataoptions: {
+ sentenceBoundaryEnabled: 'false',
+ wordBoundaryEnabled: 'false',
+ },
+ outputFormat: AUDIO_FORMAT,
+ },
+ },
+ },
+ });
+ ws.send(configMsg);
+
+ const requestId = mkId();
+ const ssmlMsg =
+ `X-RequestId:${requestId}\r\nContent-Type:application/ssml+xml\r\nX-Timestamp:${isoTimestamp()}\r\nPath:ssml\r\n\r\n` +
+ buildSsml(voice, text, rate, pitch);
+ ws.send(ssmlMsg);
+ });
+
+ ws.on('message', (data, isBinary) => {
+ if (!isBinary) {
+ const msg = data.toString();
+ if (msg.includes('Path:turn.end')) {
+ finished = true;
+ clearTimeout(timeout);
+ ws.close();
+ resolve(Buffer.concat(chunks));
+ }
+ return;
+ }
+ // Binary frame: first 2 bytes = big-endian header length, then header, then audio.
+ const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
+ const headerLen = buf.readUInt16BE(0);
+ const header = buf.subarray(2, 2 + headerLen).toString();
+ if (header.includes('Path:audio')) {
+ chunks.push(buf.subarray(2 + headerLen));
+ }
+ });
+
+ ws.on('error', (err) => {
+ clearTimeout(timeout);
+ reject(err);
+ });
+
+ ws.on('close', (code) => {
+ clearTimeout(timeout);
+ if (!finished) reject(new Error(`edge-tts WebSocket closed unexpectedly (${code})`));
+ });
+ });
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const userId = session?.id ?? bearer?.userId;
+ const rl = await limits.ttsEdge(String(userId));
+ if (!rl.success) {
+ const retryAfter = Math.max(1, Math.ceil((rl.reset - Date.now()) / 1000));
+ res.setHeader('retry-after', String(retryAfter));
+ return error(res, 429, 'rate_limited', 'Too many TTS requests', { retry_after: retryAfter });
+ }
+
+ const body = await readJson(req);
+ const voice = String(body.voice || 'en-US-AriaNeural').trim();
+ const text = String(body.text || '').trim();
+ const rate = String(body.rate || '+0%').trim();
+ const pitch = String(body.pitch || '+0Hz').trim();
+
+ if (!VOICE_RE.test(voice))
+ return error(res, 400, 'validation_error', 'invalid voice name');
+ if (!text) return error(res, 400, 'validation_error', 'text is required');
+ if (text.length > 500)
+ return error(res, 400, 'validation_error', 'text exceeds 500 chars per request');
+ if (!RATE_RE.test(rate))
+ return error(res, 400, 'validation_error', 'rate must be like +0% or -10%');
+ if (!PITCH_RE.test(pitch))
+ return error(res, 400, 'validation_error', 'pitch must be like +0Hz or -5Hz');
+
+ // ── R2 cache lookup ───────────────────────────────────────────────────────
+ const cacheHash = await sha256(`${voice}\x00${text}\x00${rate}\x00${pitch}`);
+ const cacheKey = `tts/edge/${cacheHash}.mp3`;
+
+ const cached = await headObject(cacheKey).catch(() => null);
+ if (cached) {
+ try {
+ const buf = await getObjectBuffer(cacheKey);
+ res.setHeader('content-type', 'audio/mpeg');
+ res.setHeader('content-length', String(buf.length));
+ res.setHeader('x-tts-cache', 'hit');
+ res.setHeader('cache-control', 'private, max-age=86400');
+ return res.end(buf);
+ } catch {
+ // Fall through to synthesize fresh on cache read failure.
+ }
+ }
+
+ // ── Synthesize via Microsoft Edge TTS ────────────────────────────────────
+ let audioBuffer;
+ try {
+ audioBuffer = await synthesize(voice, text, rate, pitch);
+ } catch (synthErr) {
+ console.error('[tts/edge] synthesis failed', synthErr);
+ return error(res, 502, 'upstream_error', 'Edge TTS synthesis failed');
+ }
+
+ if (!audioBuffer.length) return error(res, 502, 'upstream_error', 'Edge TTS returned empty audio');
+
+ putObject({
+ key: cacheKey,
+ body: audioBuffer,
+ contentType: 'audio/mpeg',
+ metadata: { 'created-at': new Date().toISOString() },
+ }).catch((e) => console.warn('[tts/edge] R2 cache write failed:', e.message));
+
+ res.setHeader('content-type', 'audio/mpeg');
+ res.setHeader('content-length', String(audioBuffer.length));
+ res.setHeader('x-tts-cache', 'miss');
+ res.setHeader('cache-control', 'private, max-age=86400');
+ return res.end(audioBuffer);
+});
diff --git a/chat/src/SkillsMarketplaceModal.svelte b/chat/src/SkillsMarketplaceModal.svelte
index d1f76de2d..c7df1d4a6 100644
--- a/chat/src/SkillsMarketplaceModal.svelte
+++ b/chat/src/SkillsMarketplaceModal.svelte
@@ -367,6 +367,7 @@
let loadingLibrary = false;
let libraryQuery = '';
let libraryInstalling = {};
+ let failedAvatars = new Set();
async function loadPluginLibrary() {
loadingLibrary = true;
@@ -804,16 +805,16 @@
<div class="flex flex-col gap-2 overflow-y-auto">
{#each filteredLibraryPlugins as plugin (plugin.identifier)}
<div class="flex items-center gap-x-3 rounded-lg border border-slate-200 px-3 py-3">
- {#if typeof plugin.avatar === 'string' && /^https?:\/\//.test(plugin.avatar)}
+ {#if typeof plugin.avatar === 'string' && /^https?:\/\//.test(plugin.avatar) && !failedAvatars.has(plugin.identifier)}
<img
src={plugin.avatar}
alt=""
class="h-8 w-8 shrink-0 rounded-md object-cover"
loading="lazy"
- on:error={(e) => { e.currentTarget.style.display = 'none'; }}
+ on:error={() => { failedAvatars = new Set([...failedAvatars, plugin.identifier]); }}
/>
{:else}
- <span class="shrink-0 text-2xl leading-none">{plugin.avatar}</span>
+ <span class="shrink-0 text-2xl leading-none">{/^https?:\/\//.test(plugin.avatar) ? '🔧' : plugin.avatar}</span>
{/if}
<div class="min-w-0 flex-1">
<div class="flex flex-wrap items-center gap-x-1.5 gap-y-1">
diff --git a/chat/src/manus/TopNav.svelte b/chat/src/manus/TopNav.svelte
index 620490baa..b10538c97 100644
--- a/chat/src/manus/TopNav.svelte
+++ b/chat/src/manus/TopNav.svelte
@@ -4,11 +4,34 @@
import { feMenu, feX } from '../feather.js';
import WalletConnect from '../WalletConnect.svelte';
import NotificationBell from '../NotificationBell.svelte';
+ import FeaturesDropdown from './dropdowns/FeaturesDropdown.svelte';
+ import ResourcesDropdown from './dropdowns/ResourcesDropdown.svelte';
- let mobileOpen = false;
+ let featuresOpen = false;
+ let resourcesOpen = false;
+ let mobileOpen = false;
+
+ const featOpen = { value: null }; const featClose = { value: null };
+ const resOpen = { value: null }; const resClose = { value: null };
+
+ function onFeatEnter() { clearTimeout(featClose.value); featOpen.value = setTimeout(() => (featuresOpen = true), 120); }
+ function onFeatLeave() { clearTimeout(featOpen.value); featClose.value = setTimeout(() => (featuresOpen = false), 200); }
+ function onResEnter() { clearTimeout(resClose.value); resOpen.value = setTimeout(() => (resourcesOpen = true), 120); }
+ function onResLeave() { clearTimeout(resOpen.value); resClose.value = setTimeout(() => (resourcesOpen = false), 200); }
+
+ function closeAll() {
+ featuresOpen = resourcesOpen = false;
+ }
+
+ let headerEl;
+ function handleWindowClick(e) {
+ if (headerEl && !headerEl.contains(e.target)) closeAll();
+ }
</script>
-<header class="sticky top-0 z-40 border-b border-rule bg-paper">
+<svelte:window on:click={handleWindowClick} />
+
+<header bind:this={headerEl} class="sticky top-0 z-40 border-b border-rule bg-paper">
<div class="mx-auto flex h-14 max-w-[1240px] items-center justify-between px-6">
<!-- LEFT: logo + wordmark -->
@@ -20,6 +43,50 @@
<span class="font-serif text-[22px] font-semibold lowercase tracking-tight">three.ws</span>
</button>
+ <!-- CENTER: desktop nav -->
+ <nav class="hidden items-center md:flex">
+
+ <!-- Features -->
+ <!-- svelte-ignore a11y-no-static-element-interactions -->
+ <div class="relative" on:mouseenter={onFeatEnter} on:mouseleave={onFeatLeave}>
+ <button
+ class="inline-flex h-14 items-center px-3 text-sm font-medium text-ink transition-colors hover:text-ink-soft"
+ aria-haspopup="true"
+ aria-expanded={featuresOpen}
+ >Features</button>
+ {#if featuresOpen}
+ <!-- svelte-ignore a11y-no-static-element-interactions -->
+ <div class="absolute left-0 top-full z-50 mt-2"
+ on:mouseenter={onFeatEnter} on:mouseleave={onFeatLeave}>
+ <FeaturesDropdown />
+ </div>
+ {/if}
+ </div>
+
+ <!-- Resources -->
+ <!-- svelte-ignore a11y-no-static-element-interactions -->
+ <div class="relative" on:mouseenter={onResEnter} on:mouseleave={onResLeave}>
+ <button
+ class="inline-flex h-14 items-center px-3 text-sm font-medium text-ink transition-colors hover:text-ink-soft"
+ aria-haspopup="true"
+ aria-expanded={resourcesOpen}
+ >Resources</button>
+ {#if resourcesOpen}
+ <!-- svelte-ignore a11y-no-static-element-interactions -->
+ <div class="absolute left-0 top-full z-50 mt-2"
+ on:mouseenter={onResEnter} on:mouseleave={onResLeave}>
+ <ResourcesDropdown />
+ </div>
+ {/if}
+ </div>
+
+ <!-- Pricing -->
+ <button
+ class="inline-flex h-14 items-center px-3 text-sm font-medium text-ink transition-colors hover:text-ink-soft"
+ on:click={() => route.set('pricing')}
+ >Pricing</button>
+ </nav>
+
<!-- RIGHT: auth buttons + hamburger -->
<div class="flex items-center gap-2">
<div class="hidden items-center gap-2 md:flex">
@@ -39,6 +106,12 @@
<!-- Mobile sheet -->
{#if mobileOpen}
<div class="border-t border-rule bg-paper md:hidden">
+ {#each ['Features','Resources','Pricing'] as label}
+ <button
+ class="block w-full px-6 py-3 text-left text-sm font-medium text-ink hover:bg-paper-deep"
+ on:click={() => { route.set(label.toLowerCase()); mobileOpen = false; }}
+ >{label}</button>
+ {/each}
<div class="flex gap-2 px-6 py-4">
<WalletConnect />
</div>
diff --git a/package-lock.json b/package-lock.json
index 4290c39cc..f946d7a02 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -52,6 +52,7 @@
"three": "^0.176.0",
"vhtml": "^2.2.0",
"viem": "^2.18.0",
+ "ws": "^8.20.0",
"zod": "^3.23.8"
},
"devDependencies": {
@@ -8249,27 +8250,6 @@
"node": ">=20"
}
},
- "node_modules/@solana/rpc-subscriptions-channel-websocket/node_modules/ws": {
- "version": "8.20.0",
- "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz",
- "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==",
- "license": "MIT",
- "engines": {
- "node": ">=10.0.0"
- },
- "peerDependencies": {
- "bufferutil": "^4.0.1",
- "utf-8-validate": ">=5.0.2"
- },
- "peerDependenciesMeta": {
- "bufferutil": {
- "optional": true
- },
- "utf-8-validate": {
- "optional": true
- }
- }
- },
"node_modules/@solana/rpc-subscriptions-spec": {
"version": "6.8.0",
"resolved": "https://registry.npmjs.org/@solana/rpc-subscriptions-spec/-/rpc-subscriptions-spec-6.8.0.tgz",
@@ -10771,27 +10751,6 @@
"node": ">=20"
}
},
- "node_modules/@zauthx402/sdk/node_modules/ws": {
- "version": "8.20.0",
- "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz",
- "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==",
- "license": "MIT",
- "engines": {
- "node": ">=10.0.0"
- },
- "peerDependencies": {
- "bufferutil": "^4.0.1",
- "utf-8-validate": ">=5.0.2"
- },
- "peerDependenciesMeta": {
- "bufferutil": {
- "optional": true
- },
- "utf-8-validate": {
- "optional": true
- }
- }
- },
"node_modules/abitype": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/abitype/-/abitype-1.2.3.tgz",
@@ -12480,6 +12439,27 @@
"integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==",
"license": "MIT"
},
+ "node_modules/ethers/node_modules/ws": {
+ "version": "8.17.1",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz",
+ "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ },
"node_modules/eventemitter3": {
"version": "5.0.4",
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",
@@ -14105,27 +14085,6 @@
"node": ">=20"
}
},
- "node_modules/helius-sdk/node_modules/ws": {
- "version": "8.20.0",
- "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz",
- "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==",
- "license": "MIT",
- "engines": {
- "node": ">=10.0.0"
- },
- "peerDependencies": {
- "bufferutil": "^4.0.1",
- "utf-8-validate": ">=5.0.2"
- },
- "peerDependenciesMeta": {
- "bufferutil": {
- "optional": true
- },
- "utf-8-validate": {
- "optional": true
- }
- }
- },
"node_modules/html-encoding-sniffer": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz",
@@ -16062,27 +16021,6 @@
"node": ">=18"
}
},
- "node_modules/puppeteer-core/node_modules/ws": {
- "version": "8.20.0",
- "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz",
- "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==",
- "license": "MIT",
- "engines": {
- "node": ">=10.0.0"
- },
- "peerDependencies": {
- "bufferutil": "^4.0.1",
- "utf-8-validate": ">=5.0.2"
- },
- "peerDependenciesMeta": {
- "bufferutil": {
- "optional": true
- },
- "utf-8-validate": {
- "optional": true
- }
- }
- },
"node_modules/puppeteer-extra": {
"version": "3.3.6",
"resolved": "https://registry.npmjs.org/puppeteer-extra/-/puppeteer-extra-3.3.6.tgz",
@@ -17615,27 +17553,6 @@
"node": ">=20"
}
},
- "node_modules/sas-lib/node_modules/ws": {
- "version": "8.20.0",
- "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz",
- "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==",
- "license": "MIT",
- "engines": {
- "node": ">=10.0.0"
- },
- "peerDependencies": {
- "bufferutil": "^4.0.1",
- "utf-8-validate": ">=5.0.2"
- },
- "peerDependenciesMeta": {
- "bufferutil": {
- "optional": true
- },
- "utf-8-validate": {
- "optional": true
- }
- }
- },
"node_modules/saxes": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
@@ -19666,9 +19583,9 @@
"license": "ISC"
},
"node_modules/ws": {
- "version": "8.17.1",
- "resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz",
- "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==",
+ "version": "8.20.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz",
+ "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
diff --git a/package.json b/package.json
index f661b4180..b36757b87 100644
--- a/package.json
+++ b/package.json
@@ -108,6 +108,7 @@
"three": "^0.176.0",
"vhtml": "^2.2.0",
"viem": "^2.18.0",
+ "ws": "^8.20.0",
"zod": "^3.23.8"
},
"devDependencies": {
diff --git a/public/login.html b/public/login.html
index d8efe4c13..a3186ce7c 100644
--- a/public/login.html
+++ b/public/login.html
@@ -892,7 +892,7 @@
}, { passive: true });
document.querySelectorAll('#f input').forEach((el) => {
el.addEventListener('keydown', (ev) => {
- if (ev.key.length === 1 || ev.key === 'Backspace') {
+ if (ev.key && (ev.key.length === 1 || ev.key === 'Backspace')) {
nod = (nod >= 0 ? -1 : 1) * 4;
}
});
diff --git a/scripts/gen-skills-seed.mjs b/scripts/gen-skills-seed.mjs
new file mode 100644
index 000000000..5f5889cb3
--- /dev/null
+++ b/scripts/gen-skills-seed.mjs
@@ -0,0 +1,101 @@
+// Generates api/_lib/migrations/2026-05-01-skills-chat-seed.sql
+// from the curatedToolPacks in chat/src/tools.js
+// Run: node scripts/gen-skills-seed.mjs
+
+import { readFileSync, writeFileSync } from 'fs';
+import { fileURLToPath } from 'url';
+import { dirname, join } from 'path';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const root = join(__dirname, '..');
+
+// Read and eval tools.js to extract curatedToolPacks.
+// We use a VM-like approach: strip the export keyword and eval.
+let src = readFileSync(join(root, 'chat/src/tools.js'), 'utf8');
+// Replace ES module exports so we can eval in a function
+src = src
+ .replace(/^export const /gm, 'const ')
+ .replace(/^export default /gm, 'const _default = ');
+
+// eslint-disable-next-line no-new-func
+const fn = new Function('window', src + '\nreturn { curatedToolPacks };');
+const { curatedToolPacks } = fn({});
+
+// Slugs/ids already in the existing seed (skip them)
+const existing = new Set(['tradingview-charts', 'web-search', 'tradingview']);
+
+const categoryMap = {
+ 'tradingview': 'finance',
+ 'price-chart-3d': 'finance',
+ 'token-price': 'finance',
+ 'token-ticker-3d': 'finance',
+ 'web-search': 'utility',
+ 'date-time': 'utility',
+ 'pump-launch': 'web3',
+ 'tx-explain': 'web3',
+ 'mint-scene-nft': 'web3',
+ 'nft-3d-import': 'web3',
+ 'wallet-balances': 'web3',
+ 'token-gate-scene': 'web3',
+};
+
+const tagsMap = {
+ 'price-chart-3d': ['3d','chart','crypto','finance'],
+ 'token-price': ['crypto','price','finance','coingecko'],
+ 'token-ticker-3d': ['3d','crypto','ticker','finance'],
+ 'date-time': ['time','date','utility'],
+ 'pump-launch': ['pump.fun','solana','token','web3'],
+ 'tx-explain': ['transaction','solana','evm','web3'],
+ 'mint-scene-nft': ['nft','solana','mint','3d'],
+ 'nft-3d-import': ['nft','3d','solana','evm'],
+ 'wallet-balances': ['wallet','solana','evm','web3'],
+ 'token-gate-scene': ['token-gate','nft','solana','web3'],
+};
+
+function sqlStr(s) {
+ // Escape single quotes for SQL
+ return s.replace(/'/g, "''");
+}
+
+function pgArray(arr) {
+ return `'{${arr.map(t => `"${t}"`).join(',')}}'`;
+}
+
+const rows = curatedToolPacks
+ .filter(p => !existing.has(p.id))
+ .map(p => {
+ const schemaJson = JSON.stringify(p.schema);
+ const category = categoryMap[p.id] || 'utility';
+ const tags = tagsMap[p.id] || [p.id];
+ return `(
+ '${sqlStr(p.name)}',
+ '${sqlStr(p.id)}',
+ '${sqlStr(p.description)}',
+ '${category}',
+ ${pgArray(tags)},
+ '${sqlStr(schemaJson)}',
+ true,
+ null
+)`;
+ });
+
+const sql = `-- Migration: seed curated chat skills into marketplace
+-- Generated from chat/src/tools.js curatedToolPacks (skips tradingview-charts and web-search which are already seeded)
+-- Idempotent via ON CONFLICT (slug) DO NOTHING.
+
+begin;
+
+insert into marketplace_skills (name, slug, description, category, tags, schema_json, is_public, author_id) values
+
+${rows.join(',\n\n')}
+
+on conflict (slug) do nothing;
+
+commit;
+`;
+
+const outPath = join(root, 'api/_lib/migrations/2026-05-01-skills-chat-seed.sql');
+writeFileSync(outPath, sql);
+console.log(`Written: ${outPath}`);
+console.log(`Skills seeded: ${rows.length}`);
+curatedToolPacks.filter(p => !existing.has(p.id)).forEach(p => console.log(' -', p.id));
diff --git a/src/animation-manager.js b/src/animation-manager.js
index 9f8c6ed65..dac5a47a5 100644
--- a/src/animation-manager.js
+++ b/src/animation-manager.js
@@ -184,7 +184,8 @@ export class AnimationManager {
async play(name) {
const ready = await this.ensureLoaded(name);
if (!ready) {
- console.warn(`[AnimationManager] "${name}" unavailable`);
+ if (this._failed.has(name) || this._animationDefs.some((d) => d.name === name))
+ console.warn(`[AnimationManager] "${name}" unavailable`);
return;
}
const action = this.actions.get(name);
@@ -210,7 +211,8 @@ export class AnimationManager {
if (name === this.currentName) return;
const ready = await this.ensureLoaded(name);
if (!ready) {
- console.warn(`[AnimationManager] "${name}" unavailable`);
+ if (this._failed.has(name) || this._animationDefs.some((d) => d.name === name))
+ console.warn(`[AnimationManager] "${name}" unavailable`);
return;
}
const next = this.actions.get(name);
diff --git a/src/app.js b/src/app.js
index 3eef8168a..351780e7e 100644
--- a/src/app.js
+++ b/src/app.js
@@ -265,10 +265,12 @@ class App {
this._maybePendingSave();
}
- // Boot the agent system once identity is ready. _loadAgentForEdit also
- // triggers _initAgentSystem at its tail; the AgentHome render is
- // idempotent so the second pass tears down and re-mounts cleanly.
- this._initAgentSystem();
+ // Boot the agent system once identity is ready. When agentEdit is set,
+ // _loadAgentForEdit calls _initAgentSystem itself after loading the
+ // correct identity, so skip the early call to avoid a double-mount.
+ if (!options.agentEdit) {
+ this._initAgentSystem();
+ }
// Studio preview iframes use postMessage to live-update brand config.
this._initWidgetBridge();
diff --git a/src/manifest.js b/src/manifest.js
index b3d4081e3..a0235b1a3 100644
--- a/src/manifest.js
+++ b/src/manifest.js
@@ -86,6 +86,10 @@ async function fetchManifestJSON(url) {
return res.json();
}
+function isAbsoluteURI(uri) {
+ return /^(https?|ipfs|ar|data):/.test(uri);
+}
+
// Convert either a full AGENT_MANIFEST or a bare ERC-8004 registration JSON
// into a uniform manifest object the runtime consumes.
export function normalize(json, { baseURI = '' } = {}) {
@@ -93,7 +97,7 @@ export function normalize(json, { baseURI = '' } = {}) {
if (json.spec && json.spec.startsWith('agent-manifest/')) {
const m = { ...json, _baseURI: baseURI };
m.body = m.body || {};
- if (!m.body.uri && m.image) m.body.uri = m.image;
+ if (!m.body.uri && m.image && isAbsoluteURI(m.image)) m.body.uri = m.image;
return m;
}
@@ -104,6 +108,7 @@ export function normalize(json, { baseURI = '' } = {}) {
// top-level `image` field is a 2D thumbnail (NFT-marketplace compat) —
// only fall back to it when no 3D body was declared.
const glbUri = findAvatar3D(json);
+ const imageUri = json.image && isAbsoluteURI(json.image) ? json.image : '';
return {
spec: 'agent-manifest/0.1',
_baseURI: baseURI,
@@ -111,8 +116,8 @@ export function normalize(json, { baseURI = '' } = {}) {
id: { agentId: registration.agentId?.toString() },
name: json.name,
description: json.description,
- image: json.image,
- body: { uri: resolveURI(glbUri || json.image || ''), format: 'gltf-binary' },
+ image: imageUri || null,
+ body: { uri: resolveURI(glbUri || imageUri), format: 'gltf-binary' },
brain: { provider: 'none' },
voice: { tts: { provider: 'browser' }, stt: { provider: 'browser' } },
skills: [],
@@ -132,7 +137,7 @@ export function normalize(json, { baseURI = '' } = {}) {
name: json.name || 'Unnamed agent',
description: json.description || '',
body: {
- uri: json.body?.uri || json.image || json.model || '',
+ uri: json.body?.uri || (json.image && isAbsoluteURI(json.image) ? json.image : '') || json.model || '',
format: json.body?.format || 'gltf-binary',
},
brain: json.brain || { provider: 'none' },
diff --git a/src/marketplace.js b/src/marketplace.js
index c84dc6336..2776bbb50 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -79,7 +79,7 @@ async function loadCategories() {
function renderCategories(data) {
const total = data?.total || 0;
- const counts = Object.fromEntries((data?.categories || []).map((c) => [c.slug, c.count]));
+ const counts = Object.fromEntries((data?.categories || []).map((cat) => [cat.slug, cat.count]));
const rows = [
{ slug: null, label: 'Discover', count: null, head: true },
{ slug: 'all', label: 'All', count: total },
@@ -311,8 +311,8 @@ function renderSimilar(items) {
return;
}
grid.innerHTML = items.map(renderCard).join('');
- grid.querySelectorAll('[data-id]').forEach((c) => {
- c.addEventListener('click', () => navTo(`/marketplace/agents/${c.dataset.id}`));
+ grid.querySelectorAll('[data-id]').forEach((card) => {
+ card.addEventListener('click', () => navTo(`/marketplace/agents/${card.dataset.id}`));
});
side.innerHTML =
@@ -329,8 +329,8 @@ function renderSimilar(items) {
</div>`,
)
.join('');
- side.querySelectorAll('[data-id]').forEach((c) => {
- c.addEventListener('click', () => navTo(`/marketplace/agents/${c.dataset.id}`));
+ side.querySelectorAll('[data-id]').forEach((card) => {
+ card.addEventListener('click', () => navTo(`/marketplace/agents/${card.dataset.id}`));
});
}
@@ -422,7 +422,7 @@ function bindEvents() {
function escapeHtml(s) {
return String(s || '').replace(
/[&<>"']/g,
- (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ (ch) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[ch],
);
}
@@ -475,8 +475,6 @@ function init() {
render();
}
-init();
-
// ── Plugin Marketplace ────────────────────────────────────────────────────────
const PLUGIN_API = '/api/plugins';
@@ -550,16 +548,16 @@ async function loadPluginCategories() {
function renderPluginCats(cats) {
const el = $('plugin-cats');
if (!el) return;
- const all = [{ slug: null, label: 'All', count: null }, ...cats.map((c) => ({
- slug: c.slug,
- label: c.slug.charAt(0).toUpperCase() + c.slug.slice(1),
- count: c.count,
+ const all = [{ slug: null, label: 'All', count: null }, ...cats.map((cat) => ({
+ slug: cat.slug,
+ label: cat.slug.charAt(0).toUpperCase() + cat.slug.slice(1),
+ count: cat.count,
}))];
- el.innerHTML = all.map((c) => {
- const active = pluginState.category === c.slug;
- return `<div class="cat-row${active ? ' active' : ''}" data-cat="${c.slug ?? ''}">
- <span>${escapeHtml(c.label)}</span>
- ${c.count != null ? `<span class="count">${c.count}</span>` : ''}
+ el.innerHTML = all.map((cat) => {
+ const active = pluginState.category === cat.slug;
+ return `<div class="cat-row${active ? ' active' : ''}" data-cat="${cat.slug ?? ''}">
+ <span>${escapeHtml(cat.label)}</span>
+ ${cat.count != null ? `<span class="count">${cat.count}</span>` : ''}
</div>`;
}).join('');
el.querySelectorAll('.cat-row').forEach((row) => {
@@ -784,3 +782,5 @@ function initPlugins() {
// Load categories (lazy — don't block initial page render)
loadPluginCategories();
}
+
+init();