Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: smart-money intel APIs and panel, walk pilot endpoint, home/tour cleanup, SDK zip
nirholasdd723d44aa08
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dda2d4fb3..2df1d835c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-06-20- **Grind-Bounty Market** (`/vanity/bounties`) — A decentralized x402 bounty market for hard Solana vanity addresses — escrow a USDC bounty and a fleet of independent workers grinds it in parallel. The first verified match wins, but the found key is sealed to you so the worker never sees your wallet. Earn USDC by grinding open bounties.+- **Guided Tour** (`/tour`) — A 3D guide walks across the live site, points at every feature, and narrates what each one does and how to use it — voice plus an on-screen chat bubble, paced by you.- **Proof-of-Grind Gallery** (`/vanity/gallery`) — A public gallery and leaderboard of the rarest Solana vanity addresses ground on three.ws — each provably-fair, verified, and shareable. Appraise any address to see its honest rarity tier and grind cost.- **Choose where you walk — six environments for the Walk page** — Your avatar no longer strolls in one fixed studio. A new environment picker lets you drop into six distinct worlds: a sunlit Park with shade trees and benches, a neon Cyberpunk street, a bright Beach with palm trees and a turquoise sea, a white-walled Gallery with pedestals and hung art, an abstract Void grid for pure focus, and the three.ws Office with desks and plants. Open the picker from the environment button in the Walk HUD to see a preview of each scene, or press V to cycle through them. Switching fades smoothly to the new sky and back — the ground, lighting, reflections, and props all change to match, and the avatar walks and collides correctly in every world. Link straight to a scene with ?env=beach (or park, cyberpunk, gallery, void, office), and your last choice is remembered next time you visit. Every scene is a real 3D model with its own HDR lighting, authored and owned by three.ws. (`/features/walk`) `[feature]`- **Express yourself in Walk — wave, dance, sit, point, cheer and more** — Your avatar can now emote while you stroll. Hold G on desktop — or long-press the action button on mobile — to pop a radial gesture wheel, aim, and release to play one of eight gestures: wave, dance, sit, point, cheer, agree, disagree, and a talking idle. Keys 1–8 fire them instantly, and a quick-access tray sits in the corner. Upper-body gestures like wave and cheer blend over your walk so you keep moving while you gesture; sit and dance take over the whole body, and a single step rises you back up. Everything crossfades — no stiff T-pose flashes between moves — and gestures replicate to other players in the same world. Chat messages now animate the avatar as it 'talks', and developers can trigger any gesture programmatically with window.walk.playGesture('wave'). (`/features/walk`) `[feature]`@@ -17,6 +18,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Proof-of-grind: a public gallery of the rarest wallets ground here** — A vanity address is a flex — but until now the flex was unverifiable. Proof-of-grind turns it into provenance. Every provably-fair grind can now carry an honest rarity score and tier (Common → Mythic) computed straight from the real grind difficulty: longer patterns rank higher, with documented, capped bonuses for real dictionary words, palindromes, and repeated-character runs — no inflated numbers. Publish a wallet (opt-in, secret-free; we re-verify your signed receipt against the live three.ws service key before it appears) and it joins a public gallery and leaderboard of the rarest addresses ground on three.ws, sortable and filterable by tier and pattern, each with a verified badge and a beautiful share card for X. New tools: paste any address to appraise its tier and estimated grind cost, and every agent's wallet chip now shows its rarity tier wherever it appears. No secret, seed, or sealed key is ever stored or shown. (`/vanity/gallery`) `[feature, security, sdk]`- **Real product analytics + the $THREE conversion funnel** — We now measure the journeys that matter so we can find and fix where people drop off. Every key step is captured as a real, privacy-respecting event: landing on the homepage and which call-to-action you click, connecting a wallet (started, succeeded, or failed), creating an agent, and copying an embed snippet. The $THREE holder funnel is fully instrumented end to end — token page view → buy clicked → swap quote shown → swap confirmed → swap settled on-chain — so we can see exactly how far buyers get. Marketplace searches, agent profile views, and dashboard/visualizer opens are tracked too, alongside failed API calls so reliability is visible. Wallet addresses are always truncated, events are queued so they never slow the page, and analytics can never break the app. `[improvement, infra]`- **Solana cover-charge and x402 payments fixed when the primary RPC misbehaves** — Paying the Pole Club cover charge — and any Solana payment authorized through the checkout — could fail at the "Authorize payment" step with an internal-error reference. The cause was a misconfigured upstream Solana node answering with a "not found" status that our automatic failover didn't treat as a reason to switch providers, so the payment stalled instead of routing to a healthy node. Failover now rotates off a dead or misrouted node the same way it already handled rate-limits and outages, so the wallet falls through to a working node and the payment goes through. (`/club`) `[fix]`+- **Take the guided tour — a 3D guide walks you through every feature** — New to three.ws, or never sure what half the menus do? Press play on the new Guided Tour and a 3D avatar steps onto the page, walks across the real live site, and points at each feature in turn — a beam connects the guide to exactly what it's describing, a spotlight dims everything else, and it tells you what the feature does and how to use it. Every stop is narrated out loud and shown in a chat bubble above the guide's head, so you can listen, read along, or mute the voice. The tour runs as chapters — getting started, building an agent and giving it a body and voice, taking it on-chain with wallets and payments, the live showcases, and where to learn more — about half an hour end to end, and entirely paced by you: pause, skip ahead, step back, or scrub the progress bar anytime. Wander off to try something and the guide waits; press play and it walks you back to where you left off. Start it from the new Tour page or the Discover menu. (`/tour`) `[feature]`- **The homepage hero now reacts to live $THREE market data** — The 3D agent on the home page now stands inside a living $THREE energy field — a faceted crystal in a particle cloud that breathes with the market in real time. Price momentum speeds its spin and warms or cools its color, 24-hour volume sets how brightly the field glows, every on-chain buy sends a green ripple and every sell a red one, and each deploy burn flares the whole field in burn-orange. A small live readout in the corner shows the current $THREE price, 24h change, and holder count. It loads only when the hero is on screen, drops to a calm static version if you prefer reduced motion, and quietly shows a "reconnecting" hint instead of ever inventing a number when the feed blips. (`/`) `[feature, improvement]`- **The pricing page now reveals as you scroll** — The lower sections of the pricing page — the full feature comparison, the FAQ, and the closing call-to-action — now fade and rise gently into view as you scroll to them instead of sitting flat on the page, matching the staggered entrance the plan cards already had. The motion is purely cosmetic and gracefully turns itself off if you've asked your system to reduce motion, and the content always appears even on browsers that don't support scroll detection. (`/pricing`) `[improvement]`- **Walk Avatar extension gets a full settings page** — The three.ws Walk Avatar browser extension now has a dedicated settings page (open it from the popup's "All settings" link or chrome://extensions → Details → Extension options). Choose your default avatar, where it appears on a page (including a new follow-the-cursor mode), its size, walk speed, and a light/dark/auto theme that reads each page's background. Turn on read-aloud narration and pick from real synthesis voices, and set per-site allow and block lists so the avatar only shows up where you want it. Every change saves instantly and roams across your signed-in Chrome installs, with a one-click reset to defaults and a diagnostics panel showing your session and extension version. `[feature]`diff --git a/api/_lib/trade-firewall.js b/api/_lib/trade-firewall.jsindex 077b1696d..f231e89fd 100644--- a/api/_lib/trade-firewall.js+++ b/api/_lib/trade-firewall.js@@ -23,6 +23,7 @@ import { unpackMint, NATIVE_MINT } from '@solana/spl-token';import { sql } from './db.js';import { getPumpTradeClient, getAmmPoolState, getConnection } from './pump.js';import { checkPriceImpact } from './agent-trade-guards.js';+import { getSmartMoneyForMint } from './smart-money.js';const WSOL_MINT = NATIVE_MINT.toBase58();@@ -46,6 +47,7 @@ const PENALTY = Object.freeze({dev_dumped: 14, // dev sold inside the observation windowbundle: 12, // coordinated-launch likelihoodprice_impact: 10, // this size moves the market a lot+ sybil_cluster: 14, // buyers dominated by one funder cluster (manufactured demand)});const BLOCK_SCORE = 45; // at/under this composite → block on warnings alone@@ -331,6 +333,30 @@ function checkImpact(priceImpactPct) {return result('price_impact', 'pass', 'impact_ok', { impact_pct: Number(priceImpactPct) });}+// ── check 5: smart-money sybil dominance (task 03 graph) ──────────────────────+// The buyers "in" this coin are scored against the wallet-reputation graph: when+// the net-buy flow is dominated by a single shared-funder cluster, the demand is+// likely manufactured (one entity across many wallets), so WARN. Pure additive+// signal — if the graph has no data or the DB is unreachable, this degrades to a+// silent skip and never blocks the trade.+async function checkSybil(mint, network) {+ try {+ const sm = await getSmartMoneyForMint(mint, network);+ if (!sm || sm.sybil_flag !== true) {+ return result('smart_money', sm && sm.count > 0 ? 'pass' : 'skip',+ sm && sm.count > 0 ? 'smart_money_clean' : 'no_smart_money_data',+ { count: sm?.count ?? 0, smart_money_score: sm?.smart_money_score ?? null });+ }+ return result('smart_money', 'warn', 'sybil_cluster_dominant', {+ count: sm.count ?? 0,+ smart_money_score: sm.smart_money_score ?? null,+ dominant_cluster: sm.dominant_cluster ?? null,+ });+ } catch {+ return result('smart_money', 'skip', 'smart_money_unavailable', {});+ }+}+// ── verdict composition ───────────────────────────────────────────────────────function compose(checks, simulated) {let score = 100;@@ -376,6 +402,10 @@ function compose(checks, simulated) {score -= PENALTY.price_impact;reasons.push(`Price impact is high (${Number(c.detail.impact_pct).toFixed(1)}%) — you may receive far less than market.`);break;+ case 'sybil_cluster_dominant':+ score -= PENALTY.sybil_cluster;+ reasons.push('Buying is dominated by one funder cluster — the demand looks manufactured by a single entity, not organic.');+ break;case 'venue_read_failed':case 'authority_read_failed':case 'mint_not_found':@@ -475,18 +505,19 @@ export async function assessTradeSafety({// Run the independent checks concurrently — the kernel adds a few hundred ms,// not seconds, even on the hot snipe path.- const [authorityRes, venueRes, roundTrip, intelRes] = await Promise.all([+ const [authorityRes, venueRes, roundTrip, intelRes, sybilRes] = await Promise.all([checkMintAuthority(conn, mintPk, cacheKey),checkVenue(net, mintPk, cacheKey),lamports > 0n? checkRoundTrip({ network: net, mintPk, payer, quoteAmount: lamports, connection: conn }): Promise.resolve({ res: result('round_trip', 'skip', 'no_quote_amount', {}), simulated: false }),checkIntel(mintPk.toBase58(), net),+ checkSybil(mintPk.toBase58(), net),]);const impactRes = checkImpact(priceImpactPct);- const checks = [authorityRes, venueRes, roundTrip.res, intelRes, impactRes];+ const checks = [authorityRes, venueRes, roundTrip.res, intelRes, impactRes, sybilRes];const { verdict, score, reasons } = compose(checks, roundTrip.simulated);return { verdict, score, simulated: roundTrip.simulated, reasons, checks };diff --git a/api/cron/smart-money-graph.js b/api/cron/smart-money-graph.jsnew file mode 100644index 000000000..ce0d76fe8--- /dev/null+++ b/api/cron/smart-money-graph.js@@ -0,0 +1,48 @@+// GET/POST /api/cron/smart-money-graph — maintain the Smart-Money wallet graph.+//+// Recomputes smart_wallet_reputation + smart_wallet_clusters from the coin-intel+// ground truth: every observed buyer (pump_coin_wallets) joined to what the coin+// actually did (pump_coin_outcomes). Each wallet earns a realized 0..100 score+// (ATH-weighted, confidence-regressed), and wallets sharing a funder are clustered+// (sybil/insider detection). The live lookup (api/_lib/smart-money.js) that the+// firewall, sniper scorer, oracle gate, and the public Smart-Money API all share+// reads from these tables.+//+// Idempotent + bounded so a frequent cron can never run away. Mainnet-only+// (pump_coin_* live on mainnet). Reads/writes only the graph's own tables.++import { error, json, method, wrap } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { recomputeWalletGraph } from '../../workers/agent-sniper/recompute-wallet-graph.js';++const NETWORK = 'mainnet';++function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }+ const auth = req.headers['authorization'] || '';+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ if (!constantTimeEquals(presented, secret)) {+ error(res, 401, 'unauthorized', 'invalid cron secret');+ return false;+ }+ return true;+}++export default wrap(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;++ const started = Date.now();+ const result = await recomputeWalletGraph({ network: NETWORK });++ return json(res, 200, {+ ok: result.ok,+ wallets: result.wallets,+ clusters: result.clusters,+ coins: result.coins,+ reason: result.reason || null,+ ms: Date.now() - started,+ });+});diff --git a/api/intel/smart-money.js b/api/intel/smart-money.jsnew file mode 100644index 000000000..1ba7fe432--- /dev/null+++ b/api/intel/smart-money.js@@ -0,0 +1,55 @@+/**+ * Smart-Money intel — public read API.+ *+ * GET /api/intel/smart-money?mint=<addr>&network=mainnet+ * → who reputable is net-buying this coin right now, a 0..100+ * smart_money_score, the funder clusters in the book, and a sybil_flag+ * when one cluster dominates.+ * GET /api/intel/smart-money?wallet=<addr>&network=mainnet+ * → one wallet's realized reputation card (also served by /api/intel/wallet/:addr)+ *+ * The edge: judge a coin by WHO is buying it, computed from real observed buys ⋈+ * real outcomes (graduated/pumped/rugged + ATH) — not a vanity list. The recompute+ * job (api/cron/smart-money-graph) maintains the graph; this serves it. Public ++ * IP rate-limited, briefly cached. Honest zero-data: `computed:false` means the+ * graph doesn't have enough on-chain history for this coin yet.+ *+ * $THREE is the only coin three.ws promotes — this assesses whatever runtime mint+ * the caller hands it and never names or recommends any token.+ */++import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getSmartMoneyForMint, getWalletReputation } from '../_lib/smart-money.js';++function normNetwork(v) {+ return v === 'devnet' ? 'devnet' : 'mainnet';+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;+ const rl = await limits.mcpIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://x');+ const network = normNetwork(url.searchParams.get('network'));+ const wallet = url.searchParams.get('wallet');+ const mint = url.searchParams.get('mint');++ if (wallet) {+ const rep = await getWalletReputation(wallet.trim(), network);+ return json(res, 200, rep, {+ 'cache-control': 'public, max-age=30, stale-while-revalidate=60',+ });+ }++ if (!mint) {+ return json(res, 400, { error: 'bad_request', message: 'mint or wallet query param required' });+ }++ const result = await getSmartMoneyForMint(mint.trim(), network);+ return json(res, 200, result, {+ 'cache-control': 'public, max-age=15, stale-while-revalidate=30',+ });+});diff --git a/api/intel/wallet/[address].js b/api/intel/wallet/[address].jsnew file mode 100644index 000000000..4afe49e20--- /dev/null+++ b/api/intel/wallet/[address].js@@ -0,0 +1,55 @@+/**+ * Wallet reputation — public read API.+ *+ * GET /api/intel/wallet/<address>?network=mainnet+ * → one wallet's realized track record from the Smart-Money graph:+ * realized_score (0..100), win_rate, avg ATH multiple, winners/losers,+ * labels (smart_money / sybil / fresh / …), and its funder cluster.+ *+ * Computed from real observed buys ⋈ real outcomes by the recompute job+ * (api/cron/smart-money-graph). Public + IP rate-limited, briefly cached. Honest+ * zero-data: `computed:false` means we have no track record for this address yet.+ *+ * Public on-chain address analytics only — never exposes or stores private keys.+ */++import { cors, json, method, wrap, rateLimited } from '../../_lib/http.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';+import { getWalletReputation } from '../../_lib/smart-money.js';++function normNetwork(v) {+ return v === 'devnet' ? 'devnet' : 'mainnet';+}++// A base58 Solana address is 32–44 chars from the base58 alphabet. We don't need a+// full decode here (the lookup degrades to zero-data on a miss anyway) — this just+// rejects obvious garbage before a DB round-trip.+const BASE58 = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;+ const rl = await limits.mcpIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://x');+ const network = normNetwork(url.searchParams.get('network'));++ // Vercel injects the [address] segment as a query param; fall back to parsing+ // the path so the endpoint also works when invoked directly in dev.+ let address = url.searchParams.get('address');+ if (!address) {+ const parts = url.pathname.split('/').filter(Boolean);+ address = parts[parts.length - 1];+ }+ address = (address || '').trim();++ if (!BASE58.test(address)) {+ return json(res, 400, { error: 'bad_request', message: 'a valid Solana address is required' });+ }++ const rep = await getWalletReputation(address, network);+ return json(res, 200, rep, {+ 'cache-control': 'public, max-age=30, stale-while-revalidate=60',+ });+});diff --git a/api/walk/pilot.js b/api/walk/pilot.jsnew file mode 100644index 000000000..90ccde4ea--- /dev/null+++ b/api/walk/pilot.js@@ -0,0 +1,261 @@+// POST /api/walk/pilot — the "brain" for the Walk Avatar's page-piloting mode.+//+// The Chrome extension's content script captures a compact snapshot of the+// interactive elements on the page the user is looking at, plus the user's+// natural-language task and the history of steps taken so far. This endpoint+// asks an LLM for the SINGLE next action to take, returned as strict JSON, and+// the content script executes it on the real page — then calls again with the+// updated snapshot. A ReAct-style observe→plan→act loop, with the model on the+// server (our keys, free-tier fallback) and the hands in the browser.+//+// Body:+// {+// instruction: string, // the user's task+// url: string, title: string, // current page+// elements: [{ ref, tag, role, name, value, type, placeholder, href,+// checked, editable, inViewport }],+// history: [{ action, result }],+// step: number,+// answer?: string // user's reply to a prior `ask`+// }+// Response: { thought, say, action: {...}, done }+//+// No mocks: planning runs through api/_lib/llm.js (llmComplete), which uses the+// platform's provider chain (free NVIDIA/OpenRouter tiers ahead of paid keys).++import { z } from 'zod';+import { cors, method, readJson, error, json, wrap, rateLimited } from '../_lib/http.js';+import { parse } from '../_lib/validate.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { llmComplete, llmConfigured, LlmUnavailableError } from '../_lib/llm.js';+import { getSessionUser, extractBearer, authenticateBearer } from '../_lib/auth.js';++export const maxDuration = 60;++const elementSchema = z.object({+ ref: z.number().int(),+ tag: z.string().max(20).optional(),+ role: z.string().max(40).optional().nullable(),+ name: z.string().max(400).optional().nullable(),+ value: z.string().max(400).optional().nullable(),+ type: z.string().max(40).optional().nullable(),+ placeholder: z.string().max(200).optional().nullable(),+ href: z.string().max(400).optional().nullable(),+ checked: z.boolean().optional(),+ editable: z.boolean().optional(),+ inViewport: z.boolean().optional(),+});++const bodySchema = z.object({+ instruction: z.string().min(1).max(2000),+ url: z.string().max(2048).optional().default(''),+ title: z.string().max(500).optional().default(''),+ elements: z.array(elementSchema).max(200).optional().default([]),+ history: z+ .array(+ z.object({+ action: z.string().max(600),+ result: z.string().max(600).optional().default(''),+ }),+ )+ .max(60)+ .optional()+ .default([]),+ step: z.number().int().min(0).max(100).optional().default(0),+ answer: z.string().max(2000).optional().nullable(),+ model: z.string().max(80).optional().nullable(),+});++const SYSTEM = `You are the navigator for a friendly 3D avatar that pilots a web page on the user's behalf, inside their own browser tab. You see a compact list of the interactive elements currently on the page and must choose the SINGLE best next action to progress the user's task. The user watches the avatar act in real time.++You reply with ONE JSON object and nothing else. Shape:+{+ "thought": "one short private sentence of reasoning",+ "say": "a short, friendly first-person line the avatar speaks aloud about what it's about to do (e.g. 'Searching for that now…')",+ "done": false,+ "action": {+ "type": "click" | "type" | "scroll" | "navigate" | "wait" | "ask" | "finish",+ "ref": <element ref number, for click/type/scroll-to-element>,+ "text": "<text to type, for type>",+ "clear": <true to clear the field first, for type>,+ "submit": <true to press Enter after typing, for type>,+ "direction": "down" | "up" | "top" | "bottom", // for scroll without a ref+ "url": "<absolute https URL>", // for navigate+ "ms": <milliseconds, for wait>,+ "question": "<a question for the user>", // for ask+ "summary": "<what was accomplished>" // for finish+ }+}++Rules:+- Choose exactly ONE action per reply. Reference elements only by the "ref" numbers given.+- Prefer interacting with on-page elements (click/type) over navigate. Use navigate only for a clearly-known destination URL or when the page offers no usable path.+- If the element you need is not in the list, "scroll" (direction "down"/"up") to reveal more, then look again next turn.+- To search, "type" into the search box with "submit": true.+- NEVER type into password fields or enter credentials, payment card numbers, or secrets. If the task requires signing in or paying, use "ask" to hand control back to the user.+- Use "ask" when you genuinely need a decision or information only the user has (which of several results, confirmation of a risky/destructive/irreversible step, a value you don't know).+- Set "done": true with action "finish" and a "summary" when the task is complete, OR when it cannot be completed — explain why in the summary.+- Keep "say" under ~12 words, warm and concise. The avatar is a companion, not a robot.+- Be decisive and efficient. Avoid repeating an action that already appears in the history with the same result.`;++function buildUserPrompt(b) {+ const lines = [];+ lines.push(`TASK: ${b.instruction}`);+ lines.push(`PAGE: ${b.title || '(untitled)'} — ${b.url || '(unknown url)'}`);+ lines.push(`STEP: ${b.step}`);+ if (b.answer) lines.push(`USER JUST ANSWERED: ${b.answer}`);+ if (b.history.length) {+ lines.push('\nHISTORY (most recent last):');+ for (const h of b.history.slice(-12)) {+ lines.push(`- ${h.action}${h.result ? ` → ${h.result}` : ''}`);+ }+ }+ lines.push('\nINTERACTIVE ELEMENTS ON THE PAGE:');+ if (!b.elements.length) {+ lines.push('(none captured — consider scrolling or waiting)');+ } else {+ for (const e of b.elements) {+ const bits = [`[${e.ref}] <${e.tag || '?'}`];+ if (e.role) bits.push(`role=${e.role}`);+ if (e.type) bits.push(`type=${e.type}`);+ bits[bits.length - 1] += '>';+ let label = (e.name || '').replace(/\s+/g, ' ').trim();+ if (!label && e.placeholder) label = `placeholder: ${e.placeholder}`;+ if (!label && e.value) label = `value: ${e.value}`;+ let line = `${bits.join(' ')} ${label}`.trim();+ if (e.editable) line += ' (editable)';+ if (e.checked != null) line += e.checked ? ' (checked)' : ' (unchecked)';+ if (e.inViewport === false) line += ' (off-screen)';+ lines.push(line.slice(0, 300));+ }+ }+ lines.push('\nReturn the single next action as one JSON object.');+ return lines.join('\n');+}++// Tolerant JSON extraction: models occasionally wrap the object in prose or a+// ```json fence. Pull the first balanced top-level object.+function extractJson(text) {+ if (!text) return null;+ const fence = text.match(/```(?:json)?\s*([\s\S]*?)```/i);+ const candidate = fence ? fence[1] : text;+ const start = candidate.indexOf('{');+ if (start === -1) return null;+ let depth = 0;+ let inStr = false;+ let esc = false;+ for (let i = start; i < candidate.length; i++) {+ const c = candidate[i];+ if (inStr) {+ if (esc) esc = false;+ else if (c === '\\') esc = true;+ else if (c === '"') inStr = false;+ continue;+ }+ if (c === '"') inStr = true;+ else if (c === '{') depth++;+ else if (c === '}') {+ depth--;+ if (depth === 0) {+ try {+ return JSON.parse(candidate.slice(start, i + 1));+ } catch {+ return null;+ }+ }+ }+ }+ return null;+}++const ACTION_TYPES = new Set(['click', 'type', 'scroll', 'navigate', 'wait', 'ask', 'finish']);++function normalizePlan(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const a = raw.action && typeof raw.action === 'object' ? raw.action : {};+ let type = String(a.type || '').toLowerCase().trim();+ if (!ACTION_TYPES.has(type)) {+ // A bare "done" with a summary but no/!valid action means finish.+ if (raw.done) type = 'finish';+ else return null;+ }+ const action = { type };+ if (a.ref != null && Number.isFinite(Number(a.ref))) action.ref = Number(a.ref);+ if (typeof a.text === 'string') action.text = a.text.slice(0, 2000);+ if (a.clear != null) action.clear = Boolean(a.clear);+ if (a.submit != null) action.submit = Boolean(a.submit);+ if (typeof a.direction === 'string') action.direction = a.direction.toLowerCase();+ if (typeof a.url === 'string') action.url = a.url.slice(0, 2048);+ if (a.ms != null && Number.isFinite(Number(a.ms))) action.ms = Math.min(15000, Math.max(0, Number(a.ms)));+ if (typeof a.question === 'string') action.question = a.question.slice(0, 1000);+ if (typeof a.summary === 'string') action.summary = a.summary.slice(0, 1000);+ return {+ thought: typeof raw.thought === 'string' ? raw.thought.slice(0, 500) : '',+ say: typeof raw.say === 'string' ? raw.say.slice(0, 280) : '',+ done: Boolean(raw.done) || type === 'finish',+ action,+ };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { origins: '*', methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ // Optional identity — only used for spend attribution + a higher rate bucket.+ let userId = null;+ try {+ const bearer = extractBearer(req);+ const user = bearer ? await authenticateBearer(bearer) : await getSessionUser(req);+ userId = user?.id || user?.sub || null;+ } catch {+ userId = null;+ }++ const ip = clientIp(req);+ const ipRl = await limits.chatIp(ip);+ if (!ipRl.success) return rateLimited(res, ipRl, 'too many requests from this IP');+ if (userId) {+ const userRl = await limits.chatUser(userId);+ if (!userRl.success) return rateLimited(res, userRl, 'rate limit exceeded');+ }++ if (!llmConfigured()) {+ return error(res, 503, 'llm_unavailable', 'No LLM provider is configured to plan actions.');+ }++ const raw = await readJson(req);+ const body = parse(bodySchema, raw);++ let completion;+ try {+ completion = await llmComplete({+ system: SYSTEM,+ user: buildUserPrompt(body),+ maxTokens: 700,+ timeoutMs: 45000,+ track: { userId, tool: 'walk-pilot' },+ });+ } catch (err) {+ if (err instanceof LlmUnavailableError) {+ return error(res, 503, 'llm_unavailable', 'No LLM provider is configured to plan actions.');+ }+ if (err?.code === 'daily_spend_cap_exceeded') {+ return error(res, 429, 'spend_cap', err.message);+ }+ return error(res, 502, 'planner_failed', `Planner upstream error: ${err?.message || err}`);+ }++ const plan = normalizePlan(extractJson(completion.text));+ if (!plan) {+ // Never strand the loop: fall back to handing control to the user.+ return json(res, 200, {+ thought: 'planner returned an unparseable response',+ say: "I'm not sure how to proceed — could you guide me?",+ done: false,+ action: { type: 'ask', question: 'I had trouble reading the page. What should I do next?' },+ model: completion.model,+ });+ }++ return json(res, 200, { ...plan, model: completion.model });+});diff --git a/data/changelog.json b/data/changelog.jsonindex fc91c5ce9..f7a663847 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-20",+ "title": "Take the guided tour — a 3D guide walks you through every feature",+ "summary": "New to three.ws, or never sure what half the menus do? Press play on the new Guided Tour and a 3D avatar steps onto the page, walks across the real live site, and points at each feature in turn — a beam connects the guide to exactly what it's describing, a spotlight dims everything else, and it tells you what the feature does and how to use it. Every stop is narrated out loud and shown in a chat bubble above the guide's head, so you can listen, read along, or mute the voice. The tour runs as chapters — getting started, building an agent and giving it a body and voice, taking it on-chain with wallets and payments, the live showcases, and where to learn more — about half an hour end to end, and entirely paced by you: pause, skip ahead, step back, or scrub the progress bar anytime. Wander off to try something and the guide waits; press play and it walks you back to where you left off. Start it from the new Tour page or the Discover menu.",+ "tags": [+ "feature"+ ],+ "link": "/tour"+ },{"date": "2026-06-20","title": "Choose where you walk — six environments for the Walk page",diff --git a/extensions/walk-avatar/store-assets/icon-128.png b/extensions/walk-avatar/store-assets/icon-128.pngdeleted file mode 100644index a6c0a632c..000000000Binary files a/extensions/walk-avatar/store-assets/icon-128.png and /dev/null differdiff --git a/extensions/walk-avatar/store-assets/marquee-1280x800.png b/extensions/walk-avatar/store-assets/marquee-1280x800.pngdeleted file mode 100644index 89ed54749..000000000Binary files a/extensions/walk-avatar/store-assets/marquee-1280x800.png and /dev/null differdiff --git a/extensions/walk-avatar/store-assets/promo-tile-440x280.png b/extensions/walk-avatar/store-assets/promo-tile-440x280.pngdeleted file mode 100644index d336435ce..000000000Binary files a/extensions/walk-avatar/store-assets/promo-tile-440x280.png and /dev/null differdiff --git a/extensions/walk-avatar/store-assets/screenshot-1.png b/extensions/walk-avatar/store-assets/screenshot-1.pngindex df954e384..bcb988aea 100644Binary files a/extensions/walk-avatar/store-assets/screenshot-1.png and b/extensions/walk-avatar/store-assets/screenshot-1.png differdiff --git a/extensions/walk-avatar/store-assets/screenshot-2.png b/extensions/walk-avatar/store-assets/screenshot-2.pngdeleted file mode 100644index aec7c7d9c..000000000Binary files a/extensions/walk-avatar/store-assets/screenshot-2.png and /dev/null differdiff --git a/extensions/walk-avatar/store-assets/screenshot-3.png b/extensions/walk-avatar/store-assets/screenshot-3.pngdeleted file mode 100644index c29f85e87..000000000Binary files a/extensions/walk-avatar/store-assets/screenshot-3.png and /dev/null differdiff --git a/extensions/walk-avatar/store-assets/screenshot-4.png b/extensions/walk-avatar/store-assets/screenshot-4.pngindex 2fbe4fb68..e309b7b96 100644Binary files a/extensions/walk-avatar/store-assets/screenshot-4.png and b/extensions/walk-avatar/store-assets/screenshot-4.png differdiff --git a/extensions/walk-avatar/store-assets/screenshot-5.png b/extensions/walk-avatar/store-assets/screenshot-5.pngindex 1ae069836..4c384a801 100644Binary files a/extensions/walk-avatar/store-assets/screenshot-5.png and b/extensions/walk-avatar/store-assets/screenshot-5.png differdiff --git a/pages/home.html b/pages/home.htmlindex 59b46353b..deeefdbbe 100644--- a/pages/home.html+++ b/pages/home.html@@ -231,117 +231,6 @@margin: 0; color: var(--text-3); font-size: 13.5px; max-width: 240px;}- /* ── Reactive $THREE hero ──────────────────────────────────────── */- /* Live-data canvas sits behind the avatar; the avatar's transparent- stage lets the crystal + particle field bleed around it. */- .rhero-canvas {- position: absolute; inset: 0;- width: 100%; height: 100%;- display: block; z-index: 0;- opacity: 0;- transition: opacity 1.1s ease;- pointer-events: none;- }- .rhero-canvas.rhero-canvas--ready { opacity: 1; }- /* Calm static fallback (reduced motion / canvas unavailable): a faint- faceted glow, no animation. Hidden once the live canvas paints. */- .rhero-static {- position: absolute; inset: 0; z-index: 0; pointer-events: none;- background:- radial-gradient(42% 38% at 50% 46%, rgba(170,200,255,0.16) 0%, rgba(140,170,230,0.05) 45%, transparent 70%),- conic-gradient(from 30deg at 50% 46%, rgba(255,255,255,0.05), transparent 25%, rgba(255,255,255,0.04) 50%, transparent 75%, rgba(255,255,255,0.05));- opacity: 0;- transition: opacity 0.6s ease;- }- .hero-stage[data-rhero-reduced="true"] .rhero-static { opacity: 1; }- .hero-stage-inner { z-index: 1; }-- /* Live data readout — small, elegant, anchored top-left of the stage. */- .rhero-overlay {- position: absolute; top: 16px; left: 16px; z-index: 6;- display: flex; flex-direction: column; gap: 4px;- padding: 11px 14px;- border-radius: 14px;- background: rgba(8,8,9,0.55);- border: 1px solid var(--hairline-strong);- backdrop-filter: blur(14px) saturate(1.1);- -webkit-backdrop-filter: blur(14px) saturate(1.1);- pointer-events: none;- min-width: 132px;- box-shadow: 0 10px 30px rgba(0,0,0,0.35);- animation: rhero-overlay-in 0.7s 0.2s both cubic-bezier(.2,.7,.3,1);- }- @keyframes rhero-overlay-in {- from { opacity: 0; transform: translateY(-6px); }- to { opacity: 1; transform: none; }- }- .rhero-overlay-head {- display: flex; align-items: center; justify-content: space-between; gap: 10px;- }- .rhero-mint {- font: 600 10px/1 var(--font-mono);- letter-spacing: 0.16em; color: var(--text-3);- }- .rhero-status {- display: inline-flex; align-items: center; gap: 5px;- font: 500 9.5px/1 var(--font-mono);- letter-spacing: 0.1em; text-transform: uppercase; color: var(--text-3);- }- .rhero-dot {- width: 5px; height: 5px; border-radius: 50%;- background: var(--buy); box-shadow: 0 0 6px var(--buy);- animation: rhero-pulse 2.2s ease-in-out infinite;- }- .rhero-overlay[data-connection="reconnecting"] .rhero-dot {- background: #f5a623; box-shadow: 0 0 6px #f5a623;- }- .rhero-overlay[data-connection="reconnecting"] .rhero-status { color: #f5a623; }- @keyframes rhero-pulse {- 0%, 100% { opacity: 1; transform: scale(1); }- 50% { opacity: 0.45; transform: scale(0.7); }- }- .rhero-price-row { display: flex; align-items: baseline; gap: 8px; }- .rhero-price {- font: 600 19px/1 var(--font-display);- color: var(--text); letter-spacing: -0.01em;- font-variant-numeric: tabular-nums;- }- .rhero-change {- font: 600 11.5px/1 var(--font-mono);- font-variant-numeric: tabular-nums;- }- .rhero-change[data-dir="up"] { color: var(--buy); }- .rhero-change[data-dir="down"] { color: var(--sell); }- .rhero-change[data-dir="flat"] { color: var(--text-3); }- .rhero-holders {- font: 500 10.5px/1 var(--font-mono);- color: var(--text-4); letter-spacing: 0.04em;- }- .rhero-holders [data-rhero="holders"] { color: var(--text-3); }- /* Loading shimmer for the values until first stats land. */- .rhero-overlay[data-loading] .rhero-price,- .rhero-overlay[data-loading] .rhero-change,- .rhero-overlay[data-loading] [data-rhero="holders"] {- color: transparent; border-radius: 5px;- background: linear-gradient(90deg, var(--surface-2) 25%, var(--surface-3) 50%, var(--surface-2) 75%);- background-size: 200% 100%;- animation: rhero-shimmer 1.3s ease-in-out infinite;- }- @keyframes rhero-shimmer {- from { background-position: 200% 0; }- to { background-position: -200% 0; }- }- @media (max-width: 980px) {- .rhero-overlay { top: 12px; left: 12px; padding: 9px 12px; min-width: 116px; }- .rhero-price { font-size: 16.5px; }- }- @media (prefers-reduced-motion: reduce) {- .rhero-dot, .rhero-overlay { animation: none !important; }- .rhero-overlay[data-loading] .rhero-price,- .rhero-overlay[data-loading] .rhero-change,- .rhero-overlay[data-loading] [data-rhero="holders"] { animation: none !important; }- }-/* ── CAPABILITY STRIP ──────────────────────────────────── */.capability-strip {position: relative;@@ -1467,8 +1356,18 @@background: var(--text-3); border-radius: 2px;border: none; cursor: pointer;opacity: 0.5; transition: opacity 0.15s;+ position: relative;}.wyg-anim-stop:hover { opacity: 1; }+ /* Touch: extend the hit area to 44px around the 14px glyph without+ altering its visual size or the header layout (WCAG 2.5.8). */+ @media (hover: none) and (pointer: coarse) {+ .wyg-anim-stop::after {+ content: ''; position: absolute;+ top: 50%; left: 50%; transform: translate(-50%, -50%);+ width: 44px; height: 44px;+ }+ }.wyg-anim-scroll {display: flex; gap: 6px;overflow-x: auto; overflow-y: hidden;@@ -2579,19 +2478,6 @@</div></div><div class="hero-stage" id="hero-stage">- <canvas class="rhero-canvas" id="rhero-canvas" aria-hidden="true"></canvas>- <div class="rhero-static" aria-hidden="true"></div>- <div class="rhero-overlay" id="rhero-overlay" data-loading data-connection="live" role="group" aria-label="Live $THREE market data">- <div class="rhero-overlay-head">- <span class="rhero-mint">$THREE</span>- <span class="rhero-status"><span class="rhero-dot"></span><span data-rhero="status">Live</span></span>- </div>- <div class="rhero-price-row">- <span class="rhero-price" data-rhero="price">—</span>- <span class="rhero-change" data-rhero="change" data-dir="flat">—</span>- </div>- <div class="rhero-holders"><span data-rhero="holders">—</span> holders</div>- </div><div class="hero-stage-inner" id="hero-stage-inner"></div><div class="hero-chips-wrap" id="hero-chips-wrap"><div class="hero-chips-label">@@ -4924,21 +4810,9 @@// Live pump.fun token card + real "Launch yours" flow.import { initHomeLiveToken } from '/src/home-live-token.js';import { initHomepageLauncher } from '/src/pump/homepage-launcher.js';- import { initReactiveHero } from '/src/home-three-reactive-hero.js';const hltCard = document.getElementById('hlt-card');if (hltCard) initHomeLiveToken(hltCard);initHomepageLauncher(document.getElementById('hlt-launch'));-- // Signature reactive $THREE hero — crystal + particle field that breathes- // with live market data, mounted behind the hero avatar.- const rheroStage = document.getElementById('hero-stage');- if (rheroStage) {- initReactiveHero({- stage: rheroStage,- canvas: document.getElementById('rhero-canvas'),- overlay: document.getElementById('rhero-overlay'),- });- }</script><script type="module">diff --git a/public/agents/index.html b/public/agents/index.htmlindex 660f9adf1..d4b8245e0 100644--- a/public/agents/index.html+++ b/public/agents/index.html@@ -120,7 +120,11 @@.hero h1 { font-size: 26px; }}</style>-+ <!-- Site-wide mobile polish: horizontal-scroll guard, iOS focus-zoom+ fix, and the 44px tap-target floor. Loaded last so it wins on+ equal specificity over this page's inline styles. -->+ <link rel="stylesheet" href="/mobile.css" />+<meta name="twitter:title" content="Agents Index · three.ws"><meta name="twitter:description" content="Browse every registered agent on three.ws."><meta name="twitter:image" content="https://three.ws/api/page-og?s=agent-tools&t=Agents+Index&d=Browse+every+registered+agent+on+three.ws.&p=%2Fagents">diff --git a/public/changelog.json b/public/changelog.jsonindex dcafaf9d1..2ffc924a3 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-20T05:23:20.566Z",+ "generated_at": "2026-06-20T05:35:12.277Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -16,6 +16,16 @@"launch"]},+ {+ "date": "2026-06-20",+ "type": "launch",+ "title": "Guided Tour",+ "summary": "A 3D guide walks across the live site, points at every feature, and narrates what each one does and how to use it — voice plus an on-screen chat bubble, paced by you.",+ "link": "/tour",+ "tags": [+ "launch"+ ]+ },{"date": "2026-06-20","type": "launch",@@ -122,6 +132,16 @@"fix"]},+ {+ "date": "2026-06-20",+ "type": "update",+ "title": "Take the guided tour — a 3D guide walks you through every feature",+ "summary": "New to three.ws, or never sure what half the menus do? Press play on the new Guided Tour and a 3D avatar steps onto the page, walks across the real live site, and points at each feature in turn — a beam connects the guide to exactly what it's describing, a spotlight dims everything else, and it tells you what the feature does and how to use it. Every stop is narrated out loud and shown in a chat bubble above the guide's head, so you can listen, read along, or mute the voice. The tour runs as chapters — getting started, building an agent and giving it a body and voice, taking it on-chain with wallets and payments, the live showcases, and where to learn more — about half an hour end to end, and entirely paced by you: pause, skip ahead, step back, or scrub the progress bar anytime. Wander off to try something and the guide waits; press play and it walks you back to where you left off. Start it from the new Tour page or the Discover menu.",+ "link": "/tour",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-20","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex e7a162f35..2301fa60e 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -14,6 +14,14 @@<category>launch</category><description>A decentralized x402 bounty market for hard Solana vanity addresses — escrow a USDC bounty and a fleet of independent workers grinds it in parallel. The first verified match wins, but the found key is sealed to you so the worker never sees your wallet. Earn USDC by grinding open bounties.</description></item>+ <item>+ <title>Guided Tour</title>+ <link>https://three.ws/tour</link>+ <guid isPermaLink="false">2026-06-20:Guided Tour</guid>+ <pubDate>Sat, 20 Jun 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>A 3D guide walks across the live site, points at every feature, and narrates what each one does and how to use it — voice plus an on-screen chat bubble, paced by you.</description>+ </item><item><title>Proof-of-Grind Gallery</title><link>https://three.ws/vanity/gallery</link>@@ -94,6 +102,14 @@<category>fix</category><description>Paying the Pole Club cover charge — and any Solana payment authorized through the checkout — could fail at the "Authorize payment" step with an internal-error reference. The cause was a misconfigured upstream Solana node answering with a "not found" status that our automatic failover didn't treat as a reason to switch providers, so the payment stalled instead of routing to a healthy node. Failover now rotates off a dead or misrouted node the same way it already handled rate-limits and outages, so the wallet falls through to a working node and the payment goes through.</description></item>+ <item>+ <title>Take the guided tour — a 3D guide walks you through every feature</title>+ <link>https://three.ws/tour</link>+ <guid isPermaLink="false">2026-06-20:Take the guided tour — a 3D guide walks you through every feature</guid>+ <pubDate>Sat, 20 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>New to three.ws, or never sure what half the menus do? Press play on the new Guided Tour and a 3D avatar steps onto the page, walks across the real live site, and points at each feature in turn — a beam connects the guide to exactly what it's describing, a spotlight dims everything else, and it tells you what the feature does and how to use it. Every stop is narrated out loud and shown in a chat bubble above the guide's head, so you can listen, read along, or mute the voice. The tour runs as chapters — getting started, building an agent and giving it a body and voice, taking it on-chain with wallets and payments, the live showcases, and where to learn more — about half an hour end to end, and entirely paced by you: pause, skip ahead, step back, or scrub the progress bar anytime. Wander off to try something and the guide waits; press play and it walks you back to where you left off. Start it from the new Tour page or the Discover menu.</description>+ </item><item><title>The homepage hero now reacts to live $THREE market data</title><link>https://three.ws/</link>diff --git a/public/features.json b/public/features.jsonindex c051ef7f9..b69b0d199 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-20T05:23:20.537Z",+ "generated_at": "2026-06-20T05:35:12.182Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -164,6 +164,16 @@"indexable": true,"tags": [],"showcase": false+ },+ {+ "path": "/tour",+ "title": "Guided Tour",+ "description": "A 3D guide walks across the live site, points at every feature, and narrates what each one does and how to use it — voice plus an on-screen chat bubble, paced by you.",+ "added": "2026-06-20",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false}]},diff --git a/public/footer.css b/public/footer.cssindex fcc4a3564..2549716f3 100644--- a/public/footer.css+++ b/public/footer.css@@ -545,6 +545,9 @@width: 44px;height: 44px;}+ .h-footer-newsletter-input {+ min-height: 44px;+ }.h-footer-newsletter-btn svg,.h-footer-social svg {width: 16px;diff --git a/public/llms-full.txt b/public/llms-full.txtindex b14f50e6f..5542b7c4f 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -103,6 +103,12 @@ URL: https://three.ws/what-isPlain-English introduction to three.ws — what a 3D AI agent is, real use-cases, and where to begin.+### Guided Tour++URL: https://three.ws/tour++A 3D guide walks across the live site, points at every feature, and narrates what each one does and how to use it — voice plus an on-screen chat bubble, paced by you.+## BuildCreate and customize an agent.diff --git a/public/llms.txt b/public/llms.txtindex 4185b2e8e..fcbc9d41d 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -26,6 +26,7 @@ Entry points into the product.- [Sitemap](https://three.ws/sitemap): Human-readable index of every page on three.ws.- [Characters](https://three.ws/characters): Discover AI characters on three.ws. Chat, trade, and create.- [What is three.ws?](https://three.ws/what-is): Plain-English introduction to three.ws — what a 3D AI agent is, real use-cases, and where to begin.+- [Guided Tour](https://three.ws/tour): A 3D guide walks across the live site, points at every feature, and narrates what each one does and how to use it — voice plus an on-screen chat bubble, paced by you.## Builddiff --git a/public/mobile.css b/public/mobile.cssindex cf2e4eb3d..803ad8e96 100644--- a/public/mobile.css+++ b/public/mobile.css@@ -414,13 +414,12 @@min-height: 44px;}- /* Filter chips/segments: 40px keeps dense rows from ballooning while- still clearing the comfortable-touch threshold, with breathing room- between neighbours. */+ /* Filter chips/segments: full 44px hit height with breathing room+ between neighbours so dense rows stay easy to tap. */.market-chip,.market-cat-chip,.market-filter-chip {- min-height: 40px;+ min-height: 44px;display: inline-flex;align-items: center;}diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex bb8762ac6..311903272 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -65,7 +65,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 287 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 288 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -77,7 +77,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 287 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 288 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -96,7 +96,7 @@</nav><section class="sm-section" id="main"><header>- <h2>Main<span class="sm-count" data-count>15</span></h2>+ <h2>Main<span class="sm-count" data-count>16</span></h2><p class="sm-section-desc">Entry points into the product.</p></header><ul class="sm-list">@@ -205,6 +205,13 @@<span class="sm-desc">Plain-English introduction to three.ws — what a 3D AI agent is, real use-cases, and where to begin.</span></a></li>+ <li>+ <a href="/tour">+ <span class="sm-title">Guided Tour</span>+ <span class="sm-path">/tour</span>+ <span class="sm-desc">A 3D guide walks across the live site, points at every feature, and narrates what each one does and how to use it — voice plus an on-screen chat bubble, paced by you.</span>+ </a>+ </li></ul></section>diff --git a/scripts/build-extension.mjs b/scripts/build-extension.mjsindex 485cbb17a..6b00e76d3 100644--- a/scripts/build-extension.mjs+++ b/scripts/build-extension.mjs@@ -38,6 +38,33 @@ await Promise.all([target: 'chrome109',external: ['chrome'],}),+ // Classic content scripts injected (in order) via chrome.scripting before+ // content.js — each is a self-contained IIFE that publishes a window global.+ // They are NOT imported by content.js, so esbuild must emit them separately+ // or chrome.scripting.executeScript fails on a missing file and the whole+ // avatar injection aborts.+ build({+ entryPoints: [join(src, 'content-narrator.js')],+ outfile: join(out, 'content-narrator.js'),+ bundle: true,+ format: 'iife',+ platform: 'browser',+ minify: isProd,+ sourcemap: !isProd,+ target: 'chrome109',+ external: ['chrome'],+ }),+ build({+ entryPoints: [join(src, 'content-pilot.js')],+ outfile: join(out, 'content-pilot.js'),+ bundle: true,+ format: 'iife',+ platform: 'browser',+ minify: isProd,+ sourcemap: !isProd,+ target: 'chrome109',+ external: ['chrome'],+ }),build({entryPoints: [join(src, 'popup.js')],outfile: join(out, 'popup.js'),@@ -67,6 +94,9 @@ cpSync(join(src, 'manifest.json'), join(out, 'manifest.json'));cpSync(join(src, 'popup.html'), join(out, 'popup.html'));cpSync(join(src, 'options.html'), join(out, 'options.html'));cpSync(join(src, 'icons'), join(out, 'icons'), { recursive: true });+// Vendored third-party readability lib is injected as-is (large, pre-minified);+// copy it verbatim rather than re-bundling.+cpSync(join(src, 'vendor'), join(out, 'vendor'), { recursive: true });// Write injected CSS (empty placeholder — content.js injects styles programmatically)writeFileSync(join(out, 'styles', 'inject.css'), '/* reserved for injected styles */\n');diff --git a/scripts/extension-screenshots.mjs b/scripts/extension-screenshots.mjsindex ea3a90a3a..ee00864d1 100644--- a/scripts/extension-screenshots.mjs+++ b/scripts/extension-screenshots.mjs@@ -236,10 +236,17 @@ async function routeApi(context, avatars) {// Compose a small extension surface onto a branded 1280×800 frame.async function composeSurface(shotBuf, outName, caption) {const bg = await sharp(tileSvg(W, H, { title: '', sub: '' })).png().toBuffer();- const meta = await sharp(shotBuf).metadata();+ // Scale the surface to comfortably fit inside the frame (room for caption).+ const maxW = W - 200, maxH = H - 170;+ let shot = shotBuf;+ const m0 = await sharp(shotBuf).metadata();+ if (m0.width > maxW || m0.height > maxH) {+ shot = await sharp(shotBuf).resize({ width: maxW, height: maxH, fit: 'inside' }).png().toBuffer();+ }+ const meta = await sharp(shot).metadata();const sw = meta.width, sh = meta.height;const mask = Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${sw}" height="${sh}"><rect width="${sw}" height="${sh}" rx="16" ry="16"/></svg>`);- const rounded = await sharp(shotBuf).composite([{ input: mask, blend: 'dest-in' }]).png().toBuffer();+ const rounded = await sharp(shot).composite([{ input: mask, blend: 'dest-in' }]).png().toBuffer();const left = Math.round((W - sw) / 2);const top = Math.round((H - sh) / 2) - 20;const shadow = Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}"><rect x="${left - 6}" y="${top + 12}" width="${sw + 12}" height="${sh + 12}" rx="22" fill="#000" opacity="0.5"/></svg>`);diff --git a/src/feature-tour/guide-avatar.js b/src/feature-tour/guide-avatar.jsindex 380f02852..816014aef 100644--- a/src/feature-tour/guide-avatar.js+++ b/src/feature-tour/guide-avatar.js@@ -55,9 +55,19 @@ export class GuideAvatar {async mount() {ensureStyles();this._buildDom();- await this._buildScene();- this.clock = new Timer();- this._raf = requestAnimationFrame(this._tick);+ // The DOM host (and its speech bubble) is built first, so even if WebGL or+ // the avatar GLB fail to load the tour degrades gracefully: captions still+ // show above the moving host, and the spotlight + pointer beam still work.+ // The guide just loses its rendered body rather than breaking the tour.+ try {+ await this._buildScene();+ this.clock = new Timer();+ this._raf = requestAnimationFrame(this._tick);+ } catch (err) {+ console.warn('[tour] guide avatar failed to load — continuing without a rendered body:', err?.message || err);+ this._headless = true;+ this.canvas?.remove();+ }// Park bottom-right until the first stop moves it.const start = { x: window.innerWidth - CANVAS_W - MARGIN, y: window.innerHeight - CANVAS_H - MARGIN };this._setPos(start, false);diff --git a/src/game/coin-buy.js b/src/game/coin-buy.jsindex e85fb4427..78e48393e 100644--- a/src/game/coin-buy.js+++ b/src/game/coin-buy.js@@ -21,6 +21,7 @@import './coin-buy.css';import { detectSolanaWallet, SOLANA_RPC, solanaTxExplorerUrl } from '../erc8004/solana-deploy.js';import { createSafetyPanel } from '../shared/safety-panel.js';+import { createSmartMoneyPanel } from '../shared/smart-money-panel.js';const WSOL = 'So11111111111111111111111111111111111111112';const USDC_MINT = {@@ -203,6 +204,12 @@ class TradeModal {this.safetyHost = el('div', { class: 'cc-buy-safety-host' });this.safetyHost.appendChild(this.safety.el);+ // Who is buying this coin — the smart-money wallet-reputation read. Coin-level+ // intel (independent of buy amount/denomination), shown for any selected coin.+ this.smartMoney = createSmartMoneyPanel();+ this.smartMoneyHost = el('div', { class: 'cc-buy-smartmoney-host' });+ this.smartMoneyHost.appendChild(this.smartMoney.el);+this.cta = el('button', { class: 'cc-buy-cta', type: 'button', onclick: () => this._onCta() });this.ctaLabel = 'buy';@@ -241,6 +248,7 @@ class TradeModal {this.feeLine,this.slipRow,this.walletLine,+ this.smartMoneyHost,this.safetyHost,this.cta,this.statusLine,@@ -256,6 +264,7 @@ class TradeModal {document.body.appendChild(this.overlay);requestAnimationFrame(() => this.overlay.classList.add('cc-on'));this._syncMode();+ this.smartMoney?.loadForMint({ mint: this.coin.mint, network: NETWORK });setTimeout(() => this.amountInput.focus(), 30);}@@ -265,6 +274,7 @@ class TradeModal {this.overlay.classList.remove('cc-on');setTimeout(() => this.overlay.remove(), 180);this.safety?.destroy();+ this.smartMoney?.destroy();if (_open === this) _open = null;}diff --git a/src/home-three-reactive-hero.js b/src/home-three-reactive-hero.jsdeleted file mode 100644index b3cbc7328..000000000--- a/src/home-three-reactive-hero.js+++ /dev/null@@ -1,704 +0,0 @@-/**- * Reactive $THREE hero — the homepage centerpiece that breathes with the market.- *- * A faceted $THREE crystal floating in a particle field, mounted behind the hero- * avatar. Every visual is driven by *real* live data — no simulated numbers:- *- * • Price momentum (24h change) → spin speed + warm/cool color temperature- * • 24h volume → particle brightness/density + crystal glow- * • Each on-chain trade → a ripple pulse, green for buy / red for sell- * • Each deploy burn → a warm ember burst + crystal flare- *- * Data sources (all live, polled, diffed against last value):- * /api/three-token/stats price · 24h change · volume · holders- * /api/pump/coin-trades?mint=… real buy/sell trades for $THREE- * /api/three-token/burns deploy-to-burn ledger- *- * Three.js is dynamic-imported only once the hero scrolls into view; on- * prefers-reduced-motion we skip the canvas entirely and keep just the live data- * readout. Fetch failures freeze the last-known state and surface a subtle- * "reconnecting" hint — the canvas never crashes and we never invent a number.- */--const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';--const STATS_URL = '/api/three-token/stats';-const TRADES_URL = `/api/pump/coin-trades?mint=${THREE_MINT}&limit=20`;-const BURNS_URL = '/api/three-token/burns';--const STATS_POLL_MS = 20_000; // price/volume/holders move slowly; 20s is plenty-const TRADES_POLL_MS = 6_000; // trades are the heartbeat — poll tighter-const BURNS_POLL_MS = 45_000; // deploy burns are rare; gentle cadence--const isMobile = () => window.matchMedia('(max-width: 768px)').matches;-const prefersReducedMotion = () =>- window.matchMedia('(prefers-reduced-motion: reduce)').matches;--const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));-const lerp = (a, b, t) => a + (b - a) * t;--function fmtPrice(p) {- const v = Number(p);- if (!isFinite(v) || v <= 0) return '—';- if (v >= 1) return `$${v.toFixed(3)}`;- if (v >= 0.001) return `$${v.toFixed(5)}`;- // Sub-thousandth: show the first significant digits without a wall of zeros.- return `$${v.toPrecision(3)}`;-}--function fmtCount(n) {- const v = Number(n);- if (!isFinite(v) || v < 0) return '—';- if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(2)}M`;- if (v >= 1_000) return `${(v / 1_000).toFixed(1)}K`;- return `${Math.round(v)}`;-}--// ─────────────────────────────────────────────────────────────────────────────-// Live market feed — polls three real endpoints, diffs, and emits events.-// ─────────────────────────────────────────────────────────────────────────────--class MarketFeed {- constructor({ onStats, onTrade, onBurn, onConnection }) {- this.onStats = onStats || (() => {});- this.onTrade = onTrade || (() => {});- this.onBurn = onBurn || (() => {});- this.onConnection = onConnection || (() => {});-- this.lastStats = null;- this.seenTrades = new Set();- this.seenBurns = new Set();- this.tradesSeeded = false;- this.burnsSeeded = false;-- this.timers = {};- this.fetching = {};- this.failStreak = 0;- this.connected = null; // null = unknown until first result- this.running = false;- this.destroyed = false;- }-- start() {- if (this.running || this.destroyed) return;- this.running = true;- // Kick all three immediately, then settle into their own cadences.- this._loop('stats', () => this._pollStats(), STATS_POLL_MS);- this._loop('trades', () => this._pollTrades(), TRADES_POLL_MS);- this._loop('burns', () => this._pollBurns(), BURNS_POLL_MS);- }-- stop() {- this.running = false;- for (const t of Object.values(this.timers)) clearTimeout(t);- this.timers = {};- }-- destroy() {- this.destroyed = true;- this.stop();- }-- _loop(key, fn, interval) {- const tick = async () => {- if (!this.running || this.destroyed) return;- if (this.fetching[key]) return;- this.fetching[key] = true;- try {- await fn();- } finally {- this.fetching[key] = false;- if (this.running && !this.destroyed) {- this.timers[key] = setTimeout(tick, interval);- }- }- };- tick();- }-- async _getJSON(url) {- const r = await fetch(url, { headers: { accept: 'application/json' } });- if (!r.ok) throw new Error(`HTTP ${r.status}`);- return r.json();- }-- _markOk() {- this.failStreak = 0;- if (this.connected !== true) {- this.connected = true;- this.onConnection(true);- }- }-- _markFail() {- this.failStreak += 1;- // Only declare a real outage after repeated failures so a single blip- // doesn't flicker the readout into an error state.- if (this.failStreak >= 3 && this.connected !== false) {- this.connected = false;- this.onConnection(false);- }- }-- async _pollStats() {- try {- const data = await this._getJSON(STATS_URL);- const t = data?.token || {};- const stats = {- price: t.price_usd != null ? Number(t.price_usd) : null,- change24h: t.price_change_24h != null ? Number(t.price_change_24h) : null,- volume24h: t.volume_24h != null ? Number(t.volume_24h) : null,- holders: t.holders != null ? Number(t.holders) : null,- };- const prev = this.lastStats;- this.lastStats = stats;- this._markOk();- this.onStats(stats, prev);- } catch {- this._markFail();- }- }-- async _pollTrades() {- try {- const data = await this._getJSON(TRADES_URL);- const trades = Array.isArray(data?.trades) ? data.trades : [];- this._markOk();- // First successful fetch only seeds the seen-set — we don't want to- // fire 20 ripples at once on page load. Subsequent fetches emit only- // genuinely new trades.- for (const tr of trades) {- const id = tr.tx || tr.signature;- if (!id || this.seenTrades.has(id)) continue;- this.seenTrades.add(id);- if (!this.tradesSeeded) continue;- this.onTrade({- isBuy: tr.is_buy === true,- usd: tr.usd_amount != null ? Number(tr.usd_amount) : null,- sol: tr.sol_amount != null ? Number(tr.sol_amount) : null,- });- }- this.tradesSeeded = true;- if (this.seenTrades.size > 600) {- this.seenTrades = new Set(- trades.map((t) => t.tx || t.signature).filter(Boolean),- );- }- } catch {- this._markFail();- }- }-- async _pollBurns() {- try {- const data = await this._getJSON(BURNS_URL);- const burns = Array.isArray(data?.burns) ? data.burns : [];- this._markOk();- for (const b of burns) {- const id = b.id != null ? String(b.id) : null;- if (!id || this.seenBurns.has(id)) continue;- this.seenBurns.add(id);- if (!this.burnsSeeded) continue;- this.onBurn({ amount: Number(b.amount) || 0, agent: b.agent_name });- }- this.burnsSeeded = true;- if (this.seenBurns.size > 400) {- this.seenBurns = new Set(burns.map((b) => String(b.id)).filter(Boolean));- }- } catch {- this._markFail();- }- }-}--// ─────────────────────────────────────────────────────────────────────────────-// Reactive Three.js scene — crystal + particle field + trade ripples + burns.-// ─────────────────────────────────────────────────────────────────────────────--class ReactiveScene {- constructor(THREE, canvas) {- this.THREE = THREE;- this.canvas = canvas;-- const renderer = new THREE.WebGLRenderer({- canvas,- antialias: !isMobile(),- alpha: true,- powerPreference: 'high-performance',- });- renderer.setClearColor(0x000000, 0);- this.renderer = renderer;-- this.scene = new THREE.Scene();- this.camera = new THREE.PerspectiveCamera(34, 1, 0.1, 100);- this.camera.position.set(0, 0, 7.2);-- // Lighting — a cool key + warm rim so facets read with depth even before- // the emissive glow kicks in.- const key = new THREE.DirectionalLight(0xffffff, 1.6);- key.position.set(3, 4, 5);- this.scene.add(key);- const rim = new THREE.DirectionalLight(0x88aaff, 0.7);- rim.position.set(-4, -2, -3);- this.scene.add(rim);- this.scene.add(new THREE.AmbientLight(0x404050, 1.0));-- // Color targets for momentum tint (subtle — premium, not a disco ball).- this.colWarm = new THREE.Color(0xfff0d8);- this.colCool = new THREE.Color(0xcfe0ff);- this.colNeutral = new THREE.Color(0xf2f4f8);-- this._buildCrystal();- this._buildParticles();- this._buildRipplePool();-- // Smoothed visual state — data sets targets, the render loop lerps toward.- this.spin = 0.12;- this.targetSpin = 0.12;- this.glow = 0.35;- this.targetGlow = 0.35;- this.hue = 0; // -1 cool … +1 warm- this.targetHue = 0;- this.burnFlash = 0; // decays each frame- this.crystalRot = { x: 0, y: 0 };-- this.disposed = false;- this.running = false;- this._lastT = 0;- this._tick = this._tick.bind(this);-- this._ro = new ResizeObserver(() => this._resize());- this._ro.observe(canvas);- this._resize();- }-- _buildCrystal() {- const T = this.THREE;- const geo = new T.IcosahedronGeometry(1.18, 0); // 0 detail = sharp facets- const mat = new T.MeshStandardMaterial({- color: 0xf2f4f8,- emissive: 0x223044,- emissiveIntensity: 0.4,- metalness: 0.35,- roughness: 0.18,- flatShading: true,- transparent: true,- opacity: 0.92,- });- this.crystalMat = mat;- this.crystal = new T.Mesh(geo, mat);- this.scene.add(this.crystal);-- // Crisp facet edges over the shaded body — reads as a cut gem, not a blob.- const edges = new T.EdgesGeometry(geo);- this.edgeMat = new T.LineBasicMaterial({- color: 0xffffff,- transparent: true,- opacity: 0.5,- });- this.crystalEdges = new T.LineSegments(edges, this.edgeMat);- this.crystal.add(this.crystalEdges);-- // Additive halo sprite behind the crystal — the "energy" that brightens- // with volume and flares on a burn. Generated, not loaded.- const halo = this._radialSprite(0xbcdcff);- halo.scale.set(7, 7, 1);- halo.position.z = -1.2;- this.haloMat = halo.material;- this.scene.add(halo);- this.halo = halo;- }-- _radialSprite(color) {- const T = this.THREE;- const size = 128;- const cnv = document.createElement('canvas');- cnv.width = cnv.height = size;- const ctx = cnv.getContext('2d');- const g = ctx.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);- g.addColorStop(0, 'rgba(255,255,255,1)');- g.addColorStop(0.25, 'rgba(255,255,255,0.55)');- g.addColorStop(1, 'rgba(255,255,255,0)');- ctx.fillStyle = g;- ctx.fillRect(0, 0, size, size);- const tex = new T.CanvasTexture(cnv);- tex.colorSpace = T.SRGBColorSpace;- const mat = new T.SpriteMaterial({- map: tex,- color,- transparent: true,- opacity: 0.4,- blending: T.AdditiveBlending,- depthWrite: false,- });- return new T.Sprite(mat);- }-- _buildParticles() {- const T = this.THREE;- const count = isMobile() ? 1100 : 2600;- const positions = new Float32Array(count * 3);- const phases = new Float32Array(count);- for (let i = 0; i < count; i++) {- // Spherical shell around the crystal so particles fill the stage and- // frame the avatar rather than clumping at the centre.- const r = 2.3 + Math.pow(Math.random(), 0.6) * 3.4;- const theta = Math.random() * Math.PI * 2;- const phi = Math.acos(2 * Math.random() - 1);- positions[i * 3] = r * Math.sin(phi) * Math.cos(theta);- positions[i * 3 + 1] = r * Math.sin(phi) * Math.sin(theta) * 0.8;- positions[i * 3 + 2] = r * Math.cos(phi);- phases[i] = Math.random() * Math.PI * 2;- }- const geo = new T.BufferGeometry();- geo.setAttribute('position', new T.BufferAttribute(positions, 3));- this._particlePhases = phases;- this._particleBase = positions.slice();-- const mat = new T.PointsMaterial({- color: 0x9fb4d8,- size: isMobile() ? 0.045 : 0.038,- sizeAttenuation: true,- transparent: true,- opacity: 0.5,- blending: T.AdditiveBlending,- depthWrite: false,- });- this.particleMat = mat;- this.particles = new T.Points(geo, mat);- this.scene.add(this.particles);- }-- _buildRipplePool() {- const T = this.THREE;- this.ripples = [];- for (let i = 0; i < 14; i++) {- const geo = new T.RingGeometry(1, 1.06, 48);- const mat = new T.MeshBasicMaterial({- color: 0xffffff,- transparent: true,- opacity: 0,- side: T.DoubleSide,- blending: T.AdditiveBlending,- depthWrite: false,- });- const mesh = new T.Mesh(geo, mat);- mesh.visible = false;- this.scene.add(mesh);- this.ripples.push({ mesh, mat, active: false, age: 0, life: 1, scale: 1, speed: 1 });- }- }-- // ── Data → visuals ────────────────────────────────────────────────────────-- applyStats(stats) {- if (!stats) return;- // Momentum → spin + tint. Normalise 24h change into a -1…1 band.- const m = stats.change24h != null ? clamp(stats.change24h / 15, -1, 1) : 0;- this.targetSpin = 0.1 + Math.abs(m) * 0.55 + (m > 0 ? m * 0.25 : 0);- this.targetHue = m;-- // Volume → glow/brightness. Log scale so it's responsive across orders of- // magnitude without a tiny float pinning it to zero.- if (stats.volume24h != null && stats.volume24h > 0) {- const v = clamp(Math.log10(stats.volume24h + 1) / 6.2, 0, 1);- this.targetGlow = 0.3 + v * 0.85;- }- }-- pulseTrade(trade) {- const T = this.THREE;- const slot = this.ripples.find((r) => !r.active) || this.ripples[0];- const usd = trade.usd != null && trade.usd > 0 ? trade.usd : 0;- // Bigger trades throw bigger, brighter rings.- const mag = usd > 0 ? clamp(Math.log10(usd + 1) / 3, 0.3, 1) : 0.45;- slot.active = true;- slot.age = 0;- slot.life = 1.4 + mag * 0.6;- slot.scale = 1;- slot.endScale = 2.4 + mag * 3.2;- slot.speed = 1;- slot.mesh.visible = true;- slot.mesh.scale.setScalar(0.6);- slot.mesh.rotation.set(0, 0, Math.random() * Math.PI);- slot.mat.color.set(trade.isBuy ? 0x2ecc71 : 0xff5c5c);- slot.startOpacity = 0.55 + mag * 0.35;- // A buy nudges the crystal brighter, a sell dims it momentarily.- this.targetGlow = clamp(this.targetGlow + (trade.isBuy ? 0.08 : -0.05), 0.3, 1.3);- }-- flashBurn() {- // Warm flare: spike the halo + crystal emissive and warm the particles for- // a beat. burnFlash decays in the render loop.- this.burnFlash = 1;- // A burn ring in $THREE's burn-orange.- const slot = this.ripples.find((r) => !r.active) || this.ripples[0];- slot.active = true;- slot.age = 0;- slot.life = 2.2;- slot.scale = 1;- slot.endScale = 6.5;- slot.mesh.visible = true;- slot.mesh.scale.setScalar(0.5);- slot.mat.color.set(0xff8a2b);- slot.startOpacity = 0.85;- }-- // ── Loop ────────────────────────────────────────────────────────────────-- start() {- if (this.running || this.disposed) return;- this.running = true;- this._lastT = 0;- this._raf = requestAnimationFrame(this._tick);- }-- pause() {- this.running = false;- if (this._raf) cancelAnimationFrame(this._raf);- this._raf = null;- }-- _tick(now) {- if (this.disposed) return;- this._raf = requestAnimationFrame(this._tick);- const t = now / 1000;- let dt = this._lastT ? t - this._lastT : 0.016;- this._lastT = t;- dt = Math.min(dt, 0.05); // clamp after a tab-switch so nothing jumps-- // Ease visual state toward data-driven targets.- this.spin = lerp(this.spin, this.targetSpin, 1 - Math.pow(0.001, dt));- this.glow = lerp(this.glow, this.targetGlow, 1 - Math.pow(0.01, dt));- this.hue = lerp(this.hue, this.targetHue, 1 - Math.pow(0.05, dt));- this.burnFlash = Math.max(0, this.burnFlash - dt * 1.6);-- // Crystal spin + gentle wobble + market "breathing".- this.crystalRot.y += dt * this.spin;- this.crystalRot.x += dt * this.spin * 0.35;- this.crystal.rotation.set(this.crystalRot.x, this.crystalRot.y, 0);- const breathe = 1 + Math.sin(t * 0.9) * 0.025;- this.crystal.scale.setScalar(breathe * (1 + this.burnFlash * 0.18));-- // Momentum tint blends neutral→warm/cool.- const tint = this.colNeutral.clone();- if (this.hue > 0) tint.lerp(this.colWarm, this.hue);- else if (this.hue < 0) tint.lerp(this.colCool, -this.hue);- this.crystalMat.color.copy(tint);- this.crystalMat.emissiveIntensity = 0.35 + this.glow * 0.9 + this.burnFlash * 1.5;- if (this.burnFlash > 0) {- this.crystalMat.emissive.setRGB(- 0.13 + this.burnFlash * 0.7,- 0.18 + this.burnFlash * 0.35,- 0.27,- );- } else {- this.crystalMat.emissive.setHex(0x223044);- }- this.edgeMat.opacity = 0.4 + this.glow * 0.35;-- // Halo brightness from glow + burn flare.- this.haloMat.opacity = 0.22 + this.glow * 0.3 + this.burnFlash * 0.5;- const haloScale = 6.4 + this.glow * 1.4 + this.burnFlash * 3;- this.halo.scale.set(haloScale, haloScale, 1);- if (this.burnFlash > 0.01) this.haloMat.color.setRGB(1, 0.6 + 0.2, 0.35);- else this.haloMat.color.setHex(0xbcdcff);-- // Particle field: slow counter-rotation, subtle breathing, brightness from- // volume; warmed during a burn.- this.particles.rotation.y += dt * (0.04 + this.spin * 0.15);- this.particles.rotation.x = Math.sin(t * 0.1) * 0.08;- this.particleMat.opacity = 0.32 + this.glow * 0.4;- this.particleMat.size = (isMobile() ? 0.045 : 0.038) * (1 + this.glow * 0.4);- if (this.burnFlash > 0.01) this.particleMat.color.setRGB(1, 0.72, 0.45);- else this.particleMat.color.setHex(0x9fb4d8);-- this._updateRipples(dt);- this.renderer.render(this.scene, this.camera);- }-- _updateRipples(dt) {- for (const r of this.ripples) {- if (!r.active) continue;- r.age += dt;- const p = r.age / r.life;- if (p >= 1) {- r.active = false;- r.mesh.visible = false;- r.mat.opacity = 0;- continue;- }- // Ease-out expansion, opacity fades on a curve.- const e = 1 - Math.pow(1 - p, 2);- const s = lerp(0.6, r.endScale, e);- r.mesh.scale.setScalar(s);- r.mat.opacity = (r.startOpacity || 0.6) * (1 - p) * (1 - p);- }- }-- _resize() {- const w = this.canvas.clientWidth;- const h = this.canvas.clientHeight;- if (!w || !h) return;- const dpr = Math.min(window.devicePixelRatio || 1, isMobile() ? 1.5 : 2);- this.renderer.setPixelRatio(dpr);- this.renderer.setSize(w, h, false);- this.camera.aspect = w / h;- this.camera.updateProjectionMatrix();- }-- dispose() {- if (this.disposed) return;- this.disposed = true;- this.pause();- this._ro?.disconnect();- this.scene.traverse((o) => {- o.geometry?.dispose?.();- const m = o.material;- if (Array.isArray(m)) m.forEach((x) => x.dispose?.());- else m?.dispose?.();- o.material?.map?.dispose?.();- });- this.renderer.dispose();- this.renderer.forceContextLoss?.();- }-}--// ─────────────────────────────────────────────────────────────────────────────-// Live data overlay — the small, elegant readout anchored to the hero.-// ─────────────────────────────────────────────────────────────────────────────--class DataOverlay {- constructor(root) {- this.root = root;- this.el = {- price: root.querySelector('[data-rhero="price"]'),- change: root.querySelector('[data-rhero="change"]'),- holders: root.querySelector('[data-rhero="holders"]'),- status: root.querySelector('[data-rhero="status"]'),- };- }-- setStats(stats) {- this.root.removeAttribute('data-loading');- if (this.el.price) this.el.price.textContent = fmtPrice(stats.price);- if (this.el.holders) this.el.holders.textContent = fmtCount(stats.holders);- if (this.el.change) {- const c = stats.change24h;- if (c == null || !isFinite(c)) {- this.el.change.textContent = '—';- this.el.change.dataset.dir = 'flat';- } else {- const up = c >= 0;- this.el.change.textContent = `${up ? '+' : ''}${c.toFixed(2)}%`;- this.el.change.dataset.dir = up ? 'up' : 'down';- }- }- }-- setConnection(ok) {- if (!this.el.status) return;- this.root.dataset.connection = ok ? 'live' : 'reconnecting';- this.el.status.textContent = ok ? 'Live' : 'Reconnecting…';- }-}--// ─────────────────────────────────────────────────────────────────────────────-// Public entry point.-// ─────────────────────────────────────────────────────────────────────────────--/**- * @param {Object} opts- * @param {HTMLElement} opts.stage The hero-stage container (drives in-view loading).- * @param {HTMLCanvasElement} opts.canvas The reactive canvas (behind the avatar).- * @param {HTMLElement} opts.overlay The live data readout element.- */-export function initReactiveHero({ stage, canvas, overlay }) {- if (!stage || !overlay) return null;-- const data = new DataOverlay(overlay);- const reduced = prefersReducedMotion();-- let scene = null;- let booted = false;- let booting = false;-- const feed = new MarketFeed({- onStats: (stats) => {- data.setStats(stats);- scene?.applyStats(stats);- },- onTrade: (trade) => scene?.pulseTrade(trade),- onBurn: () => scene?.flashBurn(),- onConnection: (ok) => data.setConnection(ok),- });-- async function bootScene() {- if (booted || booting || reduced || !canvas) return;- booting = true;- try {- const THREE = await import('three');- if (destroyed) return;- scene = new ReactiveScene(THREE, canvas);- // Re-apply the latest stats so the scene opens already tuned to the market.- if (feed.lastStats) scene.applyStats(feed.lastStats);- scene.start();- booted = true;- canvas.classList.add('rhero-canvas--ready');- } catch (e) {- // Three failed to load (offline, blocked) — the static gradient stage and- // the live readout still stand on their own. Don't crash the page.- console.warn('[reactive-hero] scene unavailable', e);- } finally {- booting = false;- }- }-- let destroyed = false;- let visible = false;-- // Lazy: only spin up Three + the data loop once the hero is actually on screen.- const io = new IntersectionObserver(- (entries) => {- const onScreen = entries.some((e) => e.isIntersecting);- if (onScreen === visible) return;- visible = onScreen;- if (onScreen) {- feed.start();- bootScene();- scene?.start();- } else {- feed.stop();- scene?.pause();- }- },- { rootMargin: '120px' },- );- io.observe(stage);-- // Honour tab visibility too — no point rendering/polling a hidden tab.- const onVis = () => {- if (document.hidden) {- feed.stop();- scene?.pause();- } else if (visible) {- feed.start();- scene?.start();- }- };- document.addEventListener('visibilitychange', onVis);-- function destroy() {- if (destroyed) return;- destroyed = true;- io.disconnect();- document.removeEventListener('visibilitychange', onVis);- feed.destroy();- scene?.dispose();- }- window.addEventListener('pagehide', destroy, { once: true });-- if (reduced) stage.dataset.rheroReduced = 'true';-- return { destroy };-}diff --git a/src/shared/smart-money-panel.js b/src/shared/smart-money-panel.jsnew file mode 100644index 000000000..88f8061f0--- /dev/null+++ b/src/shared/smart-money-panel.js@@ -0,0 +1,265 @@+/**+ * Smart-Money panel — the reusable, accessible "who is buying this coin" graph.+ *+ * Renders the wallet-reputation read for a coin: a 0–100 smart-money score, the+ * reputable wallets currently net-buying it (each with a realized track record and+ * a Solscan link), the funder clusters in the book, and a sybil flag when one+ * cluster dominates the demand. Every number traces to real observed buys ⋈ real+ * outcomes — there are no vanity lists or invented trader names.+ *+ * Usage mirrors the Safety panel:+ * const panel = createSmartMoneyPanel(); // a controller+ * panel.el // root element to mount+ * panel.loadForMint({ mint, network }); // fetch + render+ * panel.setState('idle' | 'loading'); // explicit empty/loading+ * panel.applyData(result); // render data you already have+ *+ * Every state is designed: idle (no coin yet), loading (skeleton), error+ * (actionable retry), zero-data ("not enough on-chain history yet"), and+ * populated. Uses the platform design tokens (CSS vars) with sane fallbacks so it+ * themes correctly inside the wallet hub, the in-world coin modal, and Mission+ * Control alike.+ *+ * $THREE is the only coin three.ws promotes — this assesses whatever runtime mint+ * the host hands it and never names or recommends any token.+ */++const STYLE_ID = 'tw-smartmoney-style';+const STYLE = `+.tw-sm { border: 1px solid var(--stroke, rgba(255,255,255,.1)); border-radius: var(--radius-md, 10px); background: var(--surface-1, rgba(255,255,255,.03)); padding: 12px 13px; display: flex; flex-direction: column; gap: 10px; font-size: var(--text-sm, .8125rem); animation: tw-sm-in var(--duration-base, 220ms) var(--ease-out, ease); }+@keyframes tw-sm-in { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }+@media (prefers-reduced-motion: reduce) { .tw-sm, .tw-sm-skel { animation: none !important; } }+.tw-sm-head { display: flex; align-items: center; gap: 9px; }+.tw-sm-title { font-weight: 600; color: var(--ink-bright, #fff); }+.tw-sm-score { margin-left: auto; font-variant-numeric: tabular-nums; font-weight: 600; color: var(--ink, #e8e8e8); }+.tw-sm-score small { color: var(--ink-dim, #888); font-weight: 400; }+.tw-sm--strong .tw-sm-score { color: var(--success, #4ade80); }+.tw-sm--mid .tw-sm-score { color: var(--warn, #fbbf24); }+.tw-sm-info { appearance: none; border: none; background: none; cursor: help; color: var(--ink-dim, #888); padding: 0 2px; font-size: .85em; line-height: 1; }+.tw-sm-info:hover, .tw-sm-info:focus-visible { color: var(--ink, #e8e8e8); }+.tw-sm-sybil { display: flex; gap: 7px; align-items: flex-start; font-size: var(--text-2xs, .72rem); color: var(--warn, #fbbf24); line-height: 1.4; }+.tw-sm-sybil::before { content: "⚠"; flex: none; }+.tw-sm-summary { color: var(--ink, #e8e8e8); line-height: 1.4; }+.tw-sm-wallets { list-style: none; margin: 0; padding: 0; display: grid; gap: 5px; }+.tw-sm-wallet { display: flex; align-items: center; gap: 8px; font-size: var(--text-2xs, .72rem); }+.tw-sm-rank { width: 18px; height: 18px; border-radius: 50%; flex: none; display: grid; place-items: center; font-weight: 700; font-size: .62rem; background: var(--surface-2, rgba(255,255,255,.06)); color: var(--ink, #e8e8e8); }+.tw-sm-wallet--proven .tw-sm-rank { background: color-mix(in srgb, var(--success,#4ade80) 22%, transparent); color: var(--success, #4ade80); }+.tw-sm-addr { font-family: var(--font-mono, ui-monospace, monospace); color: var(--accent, #7dd3fc); text-decoration: none; }+.tw-sm-addr:hover, .tw-sm-addr:focus-visible { text-decoration: underline; }+.tw-sm-meta { margin-left: auto; display: flex; gap: 9px; align-items: center; color: var(--ink-dim, #999); font-variant-numeric: tabular-nums; }+.tw-sm-rep { font-weight: 600; color: var(--ink, #e8e8e8); }+.tw-sm-sybtag { font-size: .62rem; padding: 1px 5px; border-radius: 4px; background: color-mix(in srgb, var(--warn,#fbbf24) 18%, transparent); color: var(--warn, #fbbf24); }+.tw-sm-toggle { appearance: none; border: none; background: none; color: var(--ink-dim, #888); cursor: pointer; font: inherit; font-size: var(--text-2xs, .72rem); padding: 2px 0; text-align: left; text-decoration: underline; text-underline-offset: 2px; }+.tw-sm-toggle:hover, .tw-sm-toggle:focus-visible { color: var(--ink, #e8e8e8); }+.tw-sm-clusters { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; }+.tw-sm-cluster { display: flex; align-items: center; gap: 8px; font-size: var(--text-2xs, .72rem); color: var(--ink-dim, #999); }+.tw-sm-bar { flex: 1; height: 5px; border-radius: 3px; background: var(--surface-2, rgba(255,255,255,.06)); overflow: hidden; }+.tw-sm-bar > span { display: block; height: 100%; background: var(--accent, #7dd3fc); border-radius: 3px; }+.tw-sm-cluster--dominant .tw-sm-bar > span { background: var(--warn, #fbbf24); }+.tw-sm-skel { height: 12px; border-radius: 5px; background: var(--surface-2, rgba(255,255,255,.06)); animation: tw-sm-skel 1.3s ease-in-out infinite; }+.tw-sm-skel:nth-child(2) { width: 80%; } .tw-sm-skel:nth-child(3) { width: 55%; }+@keyframes tw-sm-skel { 0%,100% { opacity: .5; } 50% { opacity: 1; } }+.tw-sm-err { color: var(--danger, #f87171); display: flex; gap: 8px; align-items: center; flex-wrap: wrap; font-size: var(--text-2xs, .72rem); }+.tw-sm-err button { appearance: none; border: 1px solid currentColor; background: none; color: inherit; font: inherit; font-size: var(--text-2xs,.72rem); border-radius: var(--radius-sm,6px); padding: 2px 9px; cursor: pointer; }+.tw-sm-idle, .tw-sm-empty { color: var(--ink-dim, #888); font-size: var(--text-sm, .8125rem); line-height: 1.4; }+`;++const WHAT_THIS_MEANS =+ 'three.ws scores every wallet by its realized track record across launches it bought — its hit-rate and how high those coins ran. The smart-money score (0–100) is the net-buy-weighted reputation of the proven wallets currently holding this coin. A “sybil” warning means one funder cluster controls most of the buying, so the demand may be one entity across many wallets rather than independent traders. Every number is computed from real on-chain buys and real outcomes, not a curated list.';++function injectStyle() {+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;+ const tag = document.createElement('style');+ tag.id = STYLE_ID;+ tag.textContent = STYLE;+ document.head.appendChild(tag);+}++function shortAddr(a) {+ const s = String(a || '');+ return s.length > 10 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s;+}++function solscanUrl(address, network) {+ const cluster = network === 'devnet' ? '?cluster=devnet' : '';+ return `https://solscan.io/account/${encodeURIComponent(address)}${cluster}`;+}++/**+ * Create a Smart-Money panel controller.+ * @param {object} [opts]+ * @param {(data: object|null) => void} [opts.onData] called whenever the data changes.+ * @param {boolean} [opts.startExpanded] show the cluster breakdown by default.+ */+export function createSmartMoneyPanel({ onData = () => {}, startExpanded = false } = {}) {+ injectStyle();+ const root = document.createElement('div');+ root.className = 'tw-sm';+ root.setAttribute('role', 'region');+ root.setAttribute('aria-label', 'Smart money');++ let expanded = startExpanded;+ let lastReq = 0;+ let current = null;+ let lastArgs = null;++ function setIdle(message) {+ current = null;+ root.className = 'tw-sm';+ root.removeAttribute('aria-busy');+ root.innerHTML = `<div class="tw-sm-idle">${escapeHtml(message || 'Select a coin to see who is buying it.')}</div>`;+ onData(null);+ }++ function setLoading() {+ root.className = 'tw-sm';+ root.setAttribute('aria-busy', 'true');+ root.innerHTML = `+ <div class="tw-sm-head"><span class="tw-sm-title">Reading smart money…</span></div>+ <div class="tw-sm-skel"></div><div class="tw-sm-skel"></div><div class="tw-sm-skel"></div>`;+ }++ function setError(retryFn) {+ root.removeAttribute('aria-busy');+ root.className = 'tw-sm';+ root.innerHTML = '';+ const wrap = document.createElement('div');+ wrap.className = 'tw-sm-err';+ wrap.setAttribute('role', 'alert');+ wrap.append(document.createTextNode('Couldn’t read smart money.'));+ if (retryFn) {+ const b = document.createElement('button');+ b.type = 'button';+ b.textContent = 'Retry';+ b.addEventListener('click', retryFn);+ wrap.appendChild(b);+ }+ root.appendChild(wrap);+ onData(null);+ }++ function applyData(d) {+ if (!d || typeof d !== 'object') { setIdle(); return; }+ current = d;+ root.removeAttribute('aria-busy');++ // Honest zero-data state: the graph hasn't observed enough history for this coin.+ if (d.computed === false || (d.count === 0 && (!d.clusters || d.clusters.length === 0))) {+ root.className = 'tw-sm';+ root.innerHTML = `+ <div class="tw-sm-head">+ <span class="tw-sm-title">Smart money</span>+ <button type="button" class="tw-sm-info" aria-label="What this means" title="${escapeHtml(WHAT_THIS_MEANS)}">ⓘ</button>+ </div>+ <div class="tw-sm-empty">Not enough on-chain history yet — no proven wallets have a track record in this coin. The graph keeps learning as buys and outcomes accrue.</div>`;+ onData(d);+ return;+ }++ const score = Number.isFinite(Number(d.smart_money_score)) ? Math.round(Number(d.smart_money_score)) : 0;+ const tier = score >= 65 ? 'strong' : score >= 35 ? 'mid' : 'low';+ const wallets = Array.isArray(d.wallets) ? d.wallets : [];+ const clusters = Array.isArray(d.clusters) ? d.clusters : [];+ const count = Number(d.count) || wallets.length;+ const network = d.network === 'devnet' ? 'devnet' : 'mainnet';++ const summary = count > 0+ ? `${count} proven wallet${count === 1 ? '' : 's'} net-buying${Number(d.total_buyers) > count ? ` of ${d.total_buyers} total` : ''}.`+ : 'No proven wallets are net-buying right now.';++ root.className = `tw-sm tw-sm--${tier}`;+ root.innerHTML = `+ <div class="tw-sm-head">+ <span class="tw-sm-title">Smart money</span>+ <button type="button" class="tw-sm-info" aria-label="What this means" title="${escapeHtml(WHAT_THIS_MEANS)}">ⓘ</button>+ <span class="tw-sm-score">${score}<small>/100</small></span>+ </div>+ ${d.sybil_flag ? `<div class="tw-sm-sybil">Demand is dominated by one funder cluster (${Math.round((Number(d.sybil_share) || 0) * 100)}% of net buys) — likely one entity across many wallets, not organic.</div>` : ''}+ <div class="tw-sm-summary">${escapeHtml(summary)}</div>+ ${wallets.length ? `<ul class="tw-sm-wallets">${wallets.slice(0, 6).map((w, i) => {+ const rep = Math.round(Number(w.realized_score) || 0);+ const proven = rep >= 70;+ const wr = Number(w.win_rate);+ const wrTxt = Number.isFinite(wr) ? `${Math.round(wr * 100)}% win` : '';+ return `<li class="tw-sm-wallet ${proven ? 'tw-sm-wallet--proven' : ''}">+ <span class="tw-sm-rank" aria-hidden="true">${i + 1}</span>+ <a class="tw-sm-addr" href="${escapeHtml(solscanUrl(w.address, network))}" target="_blank" rel="noopener noreferrer" title="${escapeHtml(w.address || '')}">${escapeHtml(shortAddr(w.address))}</a>+ ${w.sybil ? '<span class="tw-sm-sybtag">cluster</span>' : ''}+ <span class="tw-sm-meta">${wrTxt ? `<span>${escapeHtml(wrTxt)}</span>` : ''}<span class="tw-sm-rep">${rep}</span></span>+ </li>`;+ }).join('')}</ul>` : ''}+ ${clusters.length ? `<button type="button" class="tw-sm-toggle" aria-expanded="${expanded}">${expanded ? 'Hide' : 'Show'} ${clusters.length} funder cluster${clusters.length === 1 ? '' : 's'}</button>` : ''}+ <ul class="tw-sm-clusters" ${expanded ? '' : 'hidden'}>+ ${clusters.map((c) => {+ const pct = Math.round((Number(c.share) || 0) * 100);+ const dominant = d.sybil_flag && pct >= 50;+ return `<li class="tw-sm-cluster ${dominant ? 'tw-sm-cluster--dominant' : ''}">+ <span>${c.buyers || 0} wallet${(c.buyers || 0) === 1 ? '' : 's'}</span>+ <span class="tw-sm-bar"><span style="width:${pct}%"></span></span>+ <span>${pct}%</span>+ </li>`;+ }).join('')}+ </ul>`;++ const info = root.querySelector('.tw-sm-info');+ if (info) info.addEventListener('click', () => info.focus());+ const toggle = root.querySelector('.tw-sm-toggle');+ if (toggle) {+ toggle.addEventListener('click', () => {+ expanded = !expanded;+ const list = root.querySelector('.tw-sm-clusters');+ if (list) list.hidden = !expanded;+ toggle.textContent = `${expanded ? 'Hide' : 'Show'} ${clusters.length} funder cluster${clusters.length === 1 ? '' : 's'}`;+ toggle.setAttribute('aria-expanded', String(expanded));+ });+ }+ onData(d);+ }++ /**+ * Fetch the smart-money read for a mint and render it.+ * @param {{ mint: string, network?: string }} args+ */+ async function loadForMint(args) {+ lastArgs = args;+ const mint = args?.mint;+ if (!mint) { setIdle(); return; }+ const seq = ++lastReq;+ setLoading();+ try {+ const u = new URLSearchParams({ mint, network: args.network || 'mainnet' });+ const r = await fetch(`/api/intel/smart-money?${u.toString()}`, { headers: { accept: 'application/json' } });+ if (seq !== lastReq) return;+ if (!r.ok) { setError(() => loadForMint(lastArgs)); return; }+ const data = await r.json();+ if (seq !== lastReq) return;+ applyData(data);+ } catch {+ if (seq !== lastReq) return;+ setError(() => loadForMint(lastArgs));+ }+ }++ function setState(s) {+ if (s === 'idle') setIdle();+ else if (s === 'loading') setLoading();+ }++ setIdle();++ return {+ el: root,+ loadForMint,+ applyData,+ setState,+ getData: () => current,+ destroy() { lastReq = -1; root.remove(); },+ };+}++// Minimal HTML escape — the panel never injects untrusted markup.+function escapeHtml(s) {+ return String(s == null ? '' : s)+ .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')+ .replace(/"/g, '"').replace(/'/g, ''');+}diff --git a/tasks/walk/18-walk-environment-selector.md b/tasks/walk/18-walk-environment-selector.mddeleted file mode 100644index e4dc91edd..000000000--- a/tasks/walk/18-walk-environment-selector.md+++ /dev/null@@ -1,49 +0,0 @@-# Task 18 — Walk Page: Environment / Scene Selector--## Priority: HIGH--## Objective-Let users choose the environment their avatar walks in: park, cyberpunk street, beach, gallery, abstract void, three.ws office. Each environment is a real GLB scene with appropriate lighting, skybox, and ground.--## Scope-- New module: `src/walk-environments.js`-- Source environments — use real CC0 / properly licensed assets:- - `park` — green grass, trees, simple bench (Poly Pizza / Quaternius CC0 packs)- - `cyberpunk` — neon street scene- - `beach` — sand, water shader, palm trees- - `gallery` — white-walled art space (good for showcase)- - `void` — minimal grid floor, gradient sky (procedural, no GLB needed)- - `office` — three.ws virtual office (start with a simple room, can be replaced later)-- Store at `public/environments/<name>/scene.glb` + `preview.jpg` (256×256)-- Each environment includes:- - GLB scene- - HDR environment map (`public/environments/<name>/env.hdr`) for IBL- - Recommended directional light direction/intensity (stored in `public/environments/index.json` metadata)- - Walkable ground plane (avatar collides with `y=0` plus the GLB ground mesh raycast)-- URL param: `?env=park` — environment loads on page open-- HUD: environment picker dropdown showing previews; swap is smooth (fade to black 300ms, swap, fade in)-- Persists last selection in `localStorage`--## Definition of Done-- All six environments load and look visually distinct-- Avatar collides correctly with each ground (no clipping, no floating)-- Lighting matches environment (cyberpunk is dim with neon; beach is bright)-- `?env=beach` loads beach on first paint-- No console errors--## Rules-Complete 100%. No stubs. No fake data. Real GLBs, real HDRs, real licenses. No "coming soon" environments. Wire end-to-end.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/walk/18-walk-environment-selector.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/vercel.json b/vercel.jsonindex 67514736f..d9414a1ab 100644--- a/vercel.json+++ b/vercel.json@@ -1926,6 +1926,14 @@"src": "/api/pump/smart-money","dest": "/api/pump/smart-money.js"},+ {+ "src": "/api/intel/smart-money",+ "dest": "/api/intel/smart-money.js"+ },+ {+ "src": "/api/intel/wallet/([^/]+)",+ "dest": "/api/intel/wallet/[address].js?address=$1"+ },{"src": "/api/pump/safety","dest": "/api/pump/safety.js"@@ -3684,6 +3692,10 @@"path": "/api/cron/smart-money-rollup","schedule": "*/5 * * * *"},+ {+ "path": "/api/cron/smart-money-graph",+ "schedule": "*/10 * * * *"+ },{"path": "/api/cron/intel-learn","schedule": "*/15 * * * *"diff --git a/walk-sdk.zip b/walk-sdk.zipnew file mode 100644index 000000000..1051872f5Binary files /dev/null and b/walk-sdk.zip differdiff --git a/workers/agent-sniper/index.js b/workers/agent-sniper/index.jsindex eb93c547c..8935bf690 100644--- a/workers/agent-sniper/index.js+++ b/workers/agent-sniper/index.js@@ -20,6 +20,7 @@ import { runPositionSweep } from './positions.js';import { startFirstClaimWatch } from './first-claim-watch.js';import { startIntelWatcher } from './intel/watcher.js';import { getLearnedWeights } from './intel/store.js';+import { getSmartMoneyForMint } from '../../api/_lib/smart-money.js';import { startHeartbeat } from './heartbeat.js';import { makeErrorTracker } from './error-tracker.js';import {@@ -128,11 +129,23 @@ async function main() {const onIntel = (rec) => {if (draining || cfg.globalKill) return;const strategies = cachedStrategies();+ const wantsIntel = strategies.some(+ (strat) => (strat.trigger || 'new_mint') === 'intel_confirmed' && strat.network === cfg.network,+ );+ if (!wantsIntel) return;++ // Attach the live smart-money graph read once per finished intel record so+ // scoreIntel's gate + score see who reputable is in. Degrades silently to a+ // zero-data result (computed:false) — never blocks the snipe path.+ const smartReady = getSmartMoneyForMint(rec.mint, cfg.network)+ .then((sm) => { rec.smart_money = sm; })+ .catch(() => { rec.smart_money = null; });+for (const strat of strategies) {if ((strat.trigger || 'new_mint') !== 'intel_confirmed') continue;if (strat.network !== cfg.network) continue;- getLearnedWeights(cfg.network)- .then((weights) => {+ Promise.all([getLearnedWeights(cfg.network), smartReady])+ .then(([weights]) => {const { pass, score, reasons } = scoreIntel(rec, strat, weights);if (!pass) return;log.info('intel candidate', { agent: strat.agent_id, mint: rec.mint, symbol: rec.symbol, score, reasons });diff --git a/workers/agent-sniper/recompute-wallet-graph.js b/workers/agent-sniper/recompute-wallet-graph.jsnew file mode 100644index 000000000..766378624--- /dev/null+++ b/workers/agent-sniper/recompute-wallet-graph.js@@ -0,0 +1,276 @@+// Smart-Money Wallet Graph — the recompute job.+//+// Joins pump_coin_wallets ⋈ pump_coin_outcomes to give every wallet a realized+// track record, and clusters wallets by shared funder (union-find) into sybil+// groups. Maintains smart_wallet_reputation + smart_wallet_clusters. Read by the+// live lookup (api/_lib/smart-money.js) that the firewall, sniper scorer, oracle+// gate, and public API share.+//+// Design constraints (all enforced below):+// - Idempotent + re-runnable: a coin's wallets fold into reputation exactly once+// (smart_wallet_folded cursor). cluster_id is the deterministic min-address, so+// a full rerun produces identical rows.+// - Batched: respects Neon HTTP limits — bounded SELECTs, chunked multi-row+// upserts, no statement that scans the whole history at once.+// - Fire-and-forget vs the live feed: this is a separate process / cron. It never+// touches the trade path; a failure here degrades the graph's freshness, never+// a buy.+//+// Run standalone: SMART_GRAPH=1 node workers/agent-sniper/recompute-wallet-graph.js+// Or from the cron: api/cron/smart-money-graph.js calls recomputeWalletGraph().+//+// Derived ONLY from real observed buys + real outcomes — no curated lists.++import { scoreWallet, clusterByFunder } from './intel/wallet-graph.js';++let _sqlPromise = null;+async function getSql() {+ if (_sqlPromise) return _sqlPromise;+ _sqlPromise = import('../../api/_lib/db.js')+ .then((m) => m.sql)+ .catch((err) => { console.warn('[wallet-graph] db import failed:', err?.message); return null; });+ return _sqlPromise;+}++const UPSERT_CHUNK = 200; // rows per multi-statement upsert batch+const MIN_NET_BUY_LAMPORTS = 0; // a wallet must be a net buyer to be "in" a coin+const ms = (d) => (d ? new Date(d).getTime() : null);++/**+ * Recompute the whole graph for a network.+ *+ * @param {object} [opts]+ * @param {'mainnet'|'devnet'} [opts.network='mainnet']+ * @param {number} [opts.maxCoins=4000] cap coins folded per run (Neon-friendly).+ * @returns {Promise<{ ok:boolean, wallets:number, clusters:number, coins:number, ms:number, reason?:string }>}+ */+export async function recomputeWalletGraph({ network = 'mainnet', maxCoins = 4000 } = {}) {+ const started = Date.now();+ const sql = await getSql();+ if (!sql) return { ok: false, wallets: 0, clusters: 0, coins: 0, ms: 0, reason: 'no_db' };+ const net = network === 'devnet' ? 'devnet' : 'mainnet';++ // 1) Pull every wallet that net-bought a coin with a FINAL outcome, joined to+ // that outcome. Only judged coins (outcome <> 'unknown') count toward a track+ // record. Bounded by maxCoins-worth of distinct mints via the outcome table.+ let rows;+ try {+ rows = await sql`+ select+ w.wallet as address,+ w.mint,+ (w.buy_lamports - w.sell_lamports) as net_buy_lamports,+ w.first_seen_at, w.last_seen_at, w.funder,+ o.outcome, o.ath_multiple+ from pump_coin_outcomes o+ join pump_coin_wallets w on w.mint = o.mint+ where o.outcome is not null and o.outcome <> 'unknown'+ and w.buy_lamports > w.sell_lamports+ and o.mint in (+ select mint from pump_coin_outcomes+ where outcome is not null and outcome <> 'unknown'+ order by labeled_at desc+ limit ${Math.max(1, Math.min(20000, maxCoins | 0))}+ )+ `;+ } catch (err) {+ console.warn('[wallet-graph] join read failed:', err?.message);+ return { ok: false, wallets: 0, clusters: 0, coins: 0, ms: Date.now() - started, reason: 'read_failed' };+ }++ if (!rows.length) {+ return { ok: true, wallets: 0, clusters: 0, coins: 0, ms: Date.now() - started, reason: 'no_judged_coins' };+ }++ // 2) Group rows per wallet → judged-launch list, and collect funder edges ++ // co-occurrence (which mints each wallet bought) for clustering.+ const perWallet = new Map(); // address → judged[]+ const funderOf = new Map(); // address → funder (last non-null wins)+ const coOccurrence = new Map(); // address → Set(mint)+ const coins = new Set();++ for (const r of rows) {+ const address = r.address;+ if (!address) continue;+ coins.add(r.mint);++ if (!perWallet.has(address)) perWallet.set(address, []);+ perWallet.get(address).push({+ outcome: r.outcome,+ ath_multiple: r.ath_multiple != null ? Number(r.ath_multiple) : null,+ net_buy_lamports: Number(r.net_buy_lamports) || 0,+ first_seen: ms(r.first_seen_at),+ last_seen: ms(r.last_seen_at),+ });++ if (r.funder && !funderOf.has(address)) funderOf.set(address, r.funder);+ if (!coOccurrence.has(address)) coOccurrence.set(address, new Set());+ coOccurrence.get(address).add(r.mint);+ }++ // 3) Score every wallet (pure).+ const repRows = [];+ for (const [address, judged] of perWallet) {+ const s = scoreWallet(judged);+ repRows.push({+ address,+ network: net,+ trades_seen: s.trades_seen,+ winners: s.winners,+ losers: s.losers,+ win_rate: s.win_rate,+ avg_ath_multiple: s.avg_ath_multiple,+ realized_score: s.realized_score,+ labels: s.labels,+ first_seen: s.first_seen != null ? new Date(s.first_seen).toISOString() : null,+ last_seen: s.last_seen != null ? new Date(s.last_seen).toISOString() : null,+ });+ }++ // 4) Cluster by shared funder (pure union-find + co-occurrence confidence).+ const walletFunders = [...perWallet.keys()].map((address) => ({ address, funder: funderOf.get(address) || null }));+ const clusterRows = clusterByFunder(walletFunders, coOccurrence).map((c) => ({ ...c, network: net }));++ // 5) Fold sybil labels back into the reputation rows — a wallet in a+ // high-confidence cluster is tagged so the live lookup + UI show it.+ const clusterByAddr = new Map(clusterRows.map((c) => [c.address, c]));+ for (const r of repRows) {+ const c = clusterByAddr.get(r.address);+ if (c && c.confidence >= 0.5 && c.size >= 3 && !r.labels.includes('sybil')) {+ r.labels = [...r.labels, 'sybil'];+ }+ }++ // 6) Persist — chunked multi-row upserts (Neon HTTP friendly).+ let wroteWallets = 0;+ let wroteClusters = 0;+ try {+ wroteWallets = await upsertReputation(sql, repRows);+ // Replace this network's clusters wholesale: clustering is global over the+ // judged set, so a stale membership must be cleared, not left behind.+ await sql`delete from smart_wallet_clusters where network = ${net}`;+ wroteClusters = await upsertClusters(sql, clusterRows);+ await markFolded(sql, net, rows);+ } catch (err) {+ console.warn('[wallet-graph] persist failed:', err?.message);+ return { ok: false, wallets: wroteWallets, clusters: wroteClusters, coins: coins.size, ms: Date.now() - started, reason: 'persist_failed' };+ }++ return { ok: true, wallets: wroteWallets, clusters: wroteClusters, coins: coins.size, ms: Date.now() - started };+}++async function upsertReputation(sql, repRows) {+ let written = 0;+ for (let i = 0; i < repRows.length; i += UPSERT_CHUNK) {+ const chunk = repRows.slice(i, i + UPSERT_CHUNK);+ for (const r of chunk) {+ await sql`+ insert into smart_wallet_reputation (+ address, network, trades_seen, winners, losers, win_rate,+ avg_ath_multiple, realized_score, labels, first_seen, last_seen, scored_at+ ) values (+ ${r.address}, ${r.network}, ${r.trades_seen}, ${r.winners}, ${r.losers},+ ${r.win_rate}, ${r.avg_ath_multiple}, ${r.realized_score}, ${r.labels},+ ${r.first_seen}, ${r.last_seen}, now()+ )+ on conflict (address, network) do update set+ trades_seen = excluded.trades_seen, winners = excluded.winners,+ losers = excluded.losers, win_rate = excluded.win_rate,+ avg_ath_multiple = excluded.avg_ath_multiple,+ realized_score = excluded.realized_score, labels = excluded.labels,+ first_seen = least(smart_wallet_reputation.first_seen, excluded.first_seen),+ last_seen = greatest(smart_wallet_reputation.last_seen, excluded.last_seen),+ scored_at = now()+ `;+ written++;+ }+ }+ return written;+}++async function upsertClusters(sql, clusterRows) {+ let written = 0;+ for (let i = 0; i < clusterRows.length; i += UPSERT_CHUNK) {+ const chunk = clusterRows.slice(i, i + UPSERT_CHUNK);+ for (const c of chunk) {+ await sql`+ insert into smart_wallet_clusters (+ address, network, cluster_id, funder_root, size, confidence, scored_at+ ) values (+ ${c.address}, ${c.network}, ${c.cluster_id}, ${c.funder_root},+ ${c.size}, ${c.confidence}, now()+ )+ on conflict (address, network) do update set+ cluster_id = excluded.cluster_id, funder_root = excluded.funder_root,+ size = excluded.size, confidence = excluded.confidence, scored_at = now()+ `;+ written++;+ }+ }+ return written;+}++// Record the idempotency cursor: every coin folded this run, with the outcome it+// was folded at. Lets an incremental variant skip already-folded coins; the full+// recompute above is itself idempotent regardless.+async function markFolded(sql, net, rows) {+ const seen = new Map(); // mint → outcome+ for (const r of rows) if (!seen.has(r.mint)) seen.set(r.mint, r.outcome);+ const entries = [...seen.entries()];+ for (let i = 0; i < entries.length; i += UPSERT_CHUNK) {+ const chunk = entries.slice(i, i + UPSERT_CHUNK);+ for (const [mint, outcome] of chunk) {+ await sql`+ insert into smart_wallet_folded (mint, network, outcome, folded_at)+ values (${mint}, ${net}, ${outcome}, now())+ on conflict (mint, network) do update set+ outcome = excluded.outcome, folded_at = now()+ `;+ }+ }+}++// ── standalone entrypoint ─────────────────────────────────────────────────────+// Env-gated: SMART_GRAPH=1 enables the loop; SMART_GRAPH_INTERVAL_MS sets cadence+// (default 5 min). Mirrors the worker style — long-lived, batched, never blocks.+function isMain() {+ try {+ return import.meta.url === `file://${process.argv[1]}`;+ } catch {+ return false;+ }+}++async function runLoop() {+ const network = (process.env.SNIPER_NETWORK || 'mainnet').trim() === 'devnet' ? 'devnet' : 'mainnet';+ const intervalMs = Math.max(60_000, Number(process.env.SMART_GRAPH_INTERVAL_MS) || 300_000);+ console.log(`[wallet-graph] starting recompute loop (network=${network}, every ${Math.round(intervalMs / 1000)}s)`);++ let running = true;+ const stop = (sig) => { console.log(`[wallet-graph] ${sig} — stopping`); running = false; };+ process.on('SIGINT', () => stop('SIGINT'));+ process.on('SIGTERM', () => stop('SIGTERM'));++ while (running) {+ try {+ const r = await recomputeWalletGraph({ network });+ console.log('[wallet-graph] recompute', r);+ } catch (err) {+ console.warn('[wallet-graph] recompute crashed:', err?.message);+ }+ // Sleep in short slices so a SIGTERM mid-interval exits promptly.+ const wakeAt = Date.now() + intervalMs;+ while (running && Date.now() < wakeAt) {+ await new Promise((res) => setTimeout(res, Math.min(1000, wakeAt - Date.now())));+ }+ }+ process.exit(0);+}++if (isMain()) {+ if (!/^(1|true|yes|on)$/i.test(String(process.env.SMART_GRAPH || ''))) {+ console.error('[wallet-graph] refusing to start: set SMART_GRAPH=1 to enable the recompute loop');+ process.exit(1);+ }+ runLoop().catch((err) => { console.error('[wallet-graph] fatal:', err?.message); process.exit(1); });+}diff --git a/workers/agent-sniper/scorer.js b/workers/agent-sniper/scorer.jsindex 01d766f47..9beef829c 100644--- a/workers/agent-sniper/scorer.js+++ b/workers/agent-sniper/scorer.js@@ -107,6 +107,24 @@ export function scoreIntel(rec, strat, weights = null) {return { pass: false, score: 0, reasons: ['no_socials'] };}+ // Smart-money gate (task 03). `rec.smart_money` is the live graph read attached+ // by the worker (getSmartMoneyForMint). It honours two optional strategy knobs:+ // require_smart_money — demand at least one reputable, non-sybil buyer.+ // min_smart_money_score — demand the coin's 0..100 pedigree score clears a bar.+ // Both skip silently when the graph hasn't scored this coin yet (computed:false)+ // — a brand-new coin lacks history; the other gates still protect the snipe.+ const sm = rec.smart_money || null;+ const smComputed = !!(sm && sm.computed);+ if (smComputed) {+ if (strat.require_smart_money === true && (sm.count ?? 0) < 1) {+ return { pass: false, score: 0, reasons: ['no_smart_money'] };+ }+ const minSm = n(strat.min_smart_money_score);+ if (minSm != null && (n(sm.smart_money_score) ?? 0) < minSm) {+ return { pass: false, score: 0, reasons: [`smart_money_below_min:${sm.smart_money_score}<${minSm}`] };+ }+ }+// ── score: baseline quality + learned model + organic, minus risk ─────────let score = (rec.quality_score ?? 0) / 100;reasons.push(`quality:${rec.quality_score}`);@@ -116,6 +134,15 @@ export function scoreIntel(rec, strat, weights = null) {const learned = learnedScore(s, weights);if (learned != null) { score += learned; reasons.push(`learned:${learned}`); }+ // Smart-money lifts the score (proven money in) and a dominant sybil cluster+ // drags it (a manufactured "wide base"). Pure contribution — no I/O here.+ if (smComputed) {+ const smScore = n(sm.smart_money_score) ?? 0;+ const smCount = sm.count ?? 0;+ if (smCount > 0) { score += Math.min(0.5, (smScore / 100) * 0.5); reasons.push(`smart_money:${smScore}/${smCount}`); }+ if (sm.sybil_flag) { score -= 0.4; reasons.push('sybil_cluster'); }+ }+if (rec.category) reasons.push(`cat:${rec.category}`);for (const flag of rec.risk_flags || []) reasons.push(`flag:${flag}`);