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
chore: x402 replay guard, auto-rig sweep, and changelog refresh
nirholasbf9cf4c091c5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 31b9cc5a1..ead5e137a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -36,6 +36,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Build mode: place props in the 3D worlds** — The /play worlds now have a Build mode. Flip it on and a props palette opens: a set of hand-built pieces — crates, barrels, planters, lamps, benches, pillars, arches, ramps, signs, crystals, a stage and a pole — plus every public community model, which you can search and stream in. Pick a piece and a translucent preview follows your aim, snapped to a tidy grid so things line up; it glows green where it'll land and red where it won't. Press R (or the rotate button) to spin it a quarter-turn, then click to place. Whatever you place appears instantly for everyone else in the world and stays put when you leave and come back. Switch to remove mode to clear pieces you placed — you can only delete your own. It all works the same on desktop and on touch: tap to place, hold to remove, drag to look around. (`/play`) `[feature]`- **Buy live $THREE market intel over x402 — right on the IBM partnership page** — The IBM and three.ws partnership page now has a live $THREE Town Oracle: pay $0.01 in USDC from your own wallet and get back live $THREE market intel — price, 24-hour change, market cap, liquidity, 24-hour volume, and a bullish/bearish/neutral signal with a short rationale, formatted into a clean card right on the page. It's the same oracle the in-world paid kiosk in the $THREE town on /play buys from, settled over the x402 protocol, and it doubles as the live, working example for the eight-line drop-in paywall snippet. Data is live from DexScreener; nothing is mocked. (`/bazaar`) `[feature]`- **Check your plan usage and billing from any AI agent over MCP** — A new Model Context Protocol server, @three-ws/billing-mcp, lets an AI agent self-serve its own account economics — no need to pull in the human account owner. Agents can read their plan tier and how much of each quota is left (avatars and storage, agents, MCP tool calls in the last 24 hours, LLM calls this month), roll their metered usage into an invoice statement for any period with per-action line items and totals, export that statement as a CSV, and pull the itemized receipt behind any single charge — including its on-chain settlement and explorer link — or the signed receipt for a skill purchase. It also surfaces the income side: earnings for the agents you own, broken down by skill and over time, plus creator-subscription income. Every account read is private and scoped to your three.ws session; only the public platform fee rate needs no credential. The server is read-only — it never signs or moves funds. `[sdk, feature]`+- **Coin launches: stronger on-chain confirmation** — Launching a coin through three.ws now verifies that your confirmed transaction actually ran the pump.fun program before the launch is recorded — not just that it referenced your new mint address. This closes a gap where an unrelated transaction touching the mint could have been logged as a launch, keeping the launch directory and your agent's launch history accurate. `[security, fix]`- **Fixed the inline Pose Studio embed 404** — The lite Pose Studio that runs inline on demo pages now loads in production. The /pose-mini route was being built but had no production rewrite, so the embedded poser returned a 404 instead of letting you orbit and pose the mannequin in place. The route is now wired and the embed loads live. `[fix]`- **Fixed the live $THREE price, bonding-curve, and trade-safety reads** — The on-chain reads that power the live $THREE price and bonding-curve view, plus the pre-trade safety check that tells you whether a coin can actually be sold before you buy, were erroring out whenever the server's Solana RPC address was configured with a small formatting slip — a missing https://, a websocket address, or stray quotes. Those reads now repair the address automatically and always fall through to a healthy public node, so the price widget and the safety verdict load reliably instead of failing. No action needed on your end. `[fix]`- **Join Agora: post bounties, hire citizens, and vouch — as a real human** — Agora is no longer just for agents. Sign in and you become a citizen of the Commons yourself: your avatar appears in the world, and you can post a real bounty that escrows $THREE on-chain, hire a specific citizen for a job, claim and complete work yourself with a verifiable proof, and leave an on-chain vouch for someone whose deliverable you checked. Every action is the same real on-chain operation an agent runs — there's no fake 'human mode'. A 'you' panel shows your standing, balance, open bounties, and earnings live. Posting and escrow are server-side, spend-capped, and default to devnet; real-money mainnet $THREE stays gated behind explicit opt-in so nothing spends without you meaning it. Signed out, the world stays fully watchable with a clear prompt to join. (`/agora`) `[feature]`diff --git a/api/_lib/x402/payment-identifier-server.js b/api/_lib/x402/payment-identifier-server.jsindex eacbd6a53..e34dea832 100644--- a/api/_lib/x402/payment-identifier-server.js+++ b/api/_lib/x402/payment-identifier-server.js@@ -181,6 +181,49 @@ export async function releaseSlot({ route, paymentId }) {await cache.release(route, paymentId);}+// Always-on replay guard for endpoints that hand-roll the x402 dance (the MCP+// servers, launchpad/invoke) instead of using paidEndpoint(). paidEndpoint+// closes the verify→deliver→settle window with a proof-hash reservation; this is+// the same guard, packaged as a one-liner those endpoints can wrap their+// dispatch+settle in.+//+// It reserves a single-use lock keyed on the SHA-256 of the signed X-PAYMENT+// proof — only the original payer can reproduce it — so a captured or retried+// payment can't re-run the (often expensive: LLM / RPC / generation) work before+// the first settle lands. Double-CHARGE is already prevented downstream (the+// on-chain EIP-3009 nonce / Solana blockhash + the deterministic facilitator+// Idempotency-Key); this closes the remaining gap: free re-delivery / compute+// amplification from a concurrent replay in the narrow pre-settlement window.+// Once a payment settles, the consumed nonce makes any later /verify fail, so the+// lock only needs to span dispatch+settle and the caller releases it as soon as+// the request finishes — leaving a transient failure free to retry the same+// payment.+//+// Fails OPEN: a missing header, or a store with no Redis, degrades to the+// best-effort in-process claim in cache.reserve — it never blocks a legitimate+// payment, matching the paidEndpoint stance (a Redis blip must not 5xx a paid+// call when double-charge is already protected on-chain).+//+// Returns { ok, release }:+// ok=false → a concurrent request already holds the slot for this exact+// payment; the caller should reject (HTTP 409 / JSON-RPC error).+// release() → idempotent; call once the request finishes (use a finally block).+export async function reservePaymentProof(route, paymentHeader) {+ const hash = cache.hashPaymentProof(paymentHeader);+ if (!hash) return { ok: true, release: async () => {} };+ const paymentId = `proof:${hash}`;+ const owns = await reserveSlot({ route, paymentId });+ let released = false;+ return {+ ok: owns,+ release: async () => {+ if (!owns || released) return;+ released = true;+ await releaseSlot({ route, paymentId });+ },+ };+}+// Flush a cached entry back onto the wire. Mirrors the headers the live path// would have set (cache-control: no-store, x-payment-response, etc.) and// tags the response with `x-x402-idempotent: replay` so the caller can telldiff --git a/api/_mcp/payments.js b/api/_mcp/payments.jsindex 84b6d8dc2..e7caea4a1 100644--- a/api/_mcp/payments.js+++ b/api/_mcp/payments.js@@ -1,53 +1,11 @@import { X402Error, send402 } from '../_lib/x402-spec.js';import { reportServerError } from '../_lib/http.js';-import {- hashPaymentProof,- reserveSlot,- releaseSlot,-} from '../_lib/x402/payment-identifier-server.js';-// Always-on replay guard for the raw-verify MCP paid path.-//-// The paidEndpoint() wrapper closes the verify→deliver→settle window with a-// proof-hash reservation; the MCP servers hand-roll that dance, so they need the-// same guard. We reserve a single-use lock keyed on the SHA-256 of the signed-// X-PAYMENT proof — only the original payer can reproduce it — so a captured or-// retried payment can't re-run the (often expensive: LLM / RPC / generation) tool-// dispatch before the first settle lands.-//-// Double-CHARGE is already prevented downstream (the on-chain EIP-3009 nonce /-// Solana blockhash + the deterministic facilitator Idempotency-Key); this guard-// closes the remaining gap — free re-delivery / compute amplification from a-// concurrent replay in the narrow window before settlement broadcasts. Once a-// payment settles, the consumed nonce makes any later /verify fail, so the lock-// only needs to span dispatch+settle and the caller releases it as soon as the-// request finishes (success or failure) — leaving a transient failure free to be-// retried with the same payment.-//-// Fails OPEN: no header, or a store with no Redis, degrades to the best-effort-// in-process claim in idempotency-cache.reserve — it never blocks a legitimate-// payment, matching the paidEndpoint stance (a Redis blip must not 5xx a paid-// call when double-charge is already protected on-chain).-//-// Returns { ok, release }:-// ok=false → a concurrent request already holds the slot for this exact-// payment; reject with a JSON-RPC "payment_in_flight" error.-// release() → idempotent; call it once the request finishes (a finally block).-export async function reservePaymentProof(route, paymentHeader) {- const hash = hashPaymentProof(paymentHeader);- if (!hash) return { ok: true, release: async () => {} };- const paymentId = `proof:${hash}`;- const owns = await reserveSlot({ route, paymentId });- let released = false;- return {- ok: owns,- release: async () => {- if (!owns || released) return;- released = true;- await releaseSlot({ route, paymentId });- },- };-}+// Always-on replay guard for the raw-verify MCP paid path. Defined in the+// canonical idempotency module so every hand-rolled x402 endpoint shares one+// implementation; re-exported here because the MCP servers already import from+// this module. See payment-identifier-server.js for the full rationale.+export { reservePaymentProof } from '../_lib/x402/payment-identifier-server.js';export function sendX402Error(res, { resourceUrl, accepts }, err) {if (err instanceof X402Error) {@@ -63,5 +21,11 @@ export function sendX402Error(res, { resourceUrl, accepts }, err) {const ref = reportServerError(err, { code: 'mcp_x402_failed', context: { resourceUrl } });res.statusCode = 500;res.setHeader('content-type', 'application/json; charset=utf-8');- res.end(JSON.stringify({ error: 'internal', error_description: `x402 processing failed — quote ref ${ref} to support`, ref }));+ res.end(+ JSON.stringify({+ error: 'internal',+ error_description: `x402 processing failed — quote ref ${ref} to support`,+ ref,+ }),+ );}diff --git a/api/cron/auto-rig-sweep.js b/api/cron/auto-rig-sweep.jsindex c9c1012b8..695621c77 100644--- a/api/cron/auto-rig-sweep.js+++ b/api/cron/auto-rig-sweep.js@@ -23,6 +23,7 @@ import { constantTimeEquals } from '../_lib/crypto.js';import { sql } from '../_lib/db.js';import { getRegenProvider } from '../_lib/regen-provider.js';import { finalizeAutoRigStage } from '../_lib/auto-rig.js';+import { isAllowedProviderResultUrl } from '../_lib/provider-result-url.js';// Leave the webhook a clear runway before we touch a job: most rigs finish in// 60–90s, so a 3-minute quiet window means we only ever sweep genuinely stalled@@ -55,6 +56,11 @@ function requireCron(req, res) {return true;}+// Best-effort hostname for a log line — never throws on a malformed URL.+function hostOf(raw) {+ try { return new URL(raw).hostname; } catch { return 'unparseable'; }+}+async function failJob(jobId, userId, reason) {await sql`update avatar_regen_jobs@@ -150,6 +156,16 @@ export default wrap(async (req, res) => {// latency + an extra failure surface for a URL we already hold). The// finalize claim makes this safe even if a webhook retry races us.if (job.result_glb_url) {+ // SSRF gate: the webhook persists the extracted URL WITHOUT the host+ // allowlist, so a poisoned URL could be sitting in this column. Pin it to+ // an allowed provider host before fetching server-side; fail the job+ // cleanly on a miss instead of finalizing from it.+ if (!isAllowedProviderResultUrl(job.result_glb_url)) {+ console.warn('[auto-rig-sweep] blocked result url', { jobId: job.job_id, host: hostOf(job.result_glb_url) });+ await failJob(job.job_id, job.user_id, 'provider returned a disallowed result url');+ summary.failed++;+ continue;+ }await finalizeAutoRigStage({userId: job.user_id,jobId: job.job_id,@@ -179,13 +195,21 @@ export default wrap(async (req, res) => {const update = await prov.instance.status(job.ext_job_id);if (update.status === 'done' && update.resultGlbUrl) {- await finalizeAutoRigStage({- userId: job.user_id,- jobId: job.job_id,- job,- glbUrl: update.resultGlbUrl,- });- summary.finalized++;+ // SSRF gate (same as the fast path): pin the fresh provider URL to an+ // allowed host before the guarded fetch ever runs; fail on a miss.+ if (!isAllowedProviderResultUrl(update.resultGlbUrl)) {+ console.warn('[auto-rig-sweep] blocked result url', { jobId: job.job_id, host: hostOf(update.resultGlbUrl) });+ await failJob(job.job_id, job.user_id, 'provider returned a disallowed result url');+ summary.failed++;+ } else {+ await finalizeAutoRigStage({+ userId: job.user_id,+ jobId: job.job_id,+ job,+ glbUrl: update.resultGlbUrl,+ });+ summary.finalized++;+ }} else if (update.status === 'failed') {await failJob(job.job_id, job.user_id, update.error || 'provider reported rig failure');summary.failed++;diff --git a/api/launchpad/invoke.js b/api/launchpad/invoke.jsindex 3a8033be1..0abaae248 100644--- a/api/launchpad/invoke.js+++ b/api/launchpad/invoke.js@@ -36,6 +36,7 @@ import {settlePayment,verifyPayment,} from '../_lib/x402-spec.js';+import { reservePaymentProof } from '../_lib/x402/payment-identifier-server.js';const SLUG_RE = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/;const SOL_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;@@ -108,14 +109,17 @@ async function fulfillConcierge({ page, body }) {const system =`You are the concierge for "${headline}". ${tagline} ` +'Answer the visitor concisely and helpfully in plain language. ' +- "If the question is unrelated or something you cannot know, say so briefly rather than inventing an answer.";+ 'If the question is unrelated or something you cannot know, say so briefly rather than inventing an answer.';const result = await llmComplete({system,user: question.slice(0, 2000),maxTokens: 600,track: { surface: 'launchpad-concierge', slug: page.slug },});- return { answer: (result?.text || '').trim() || 'No answer was generated — please try again.', model: result?.model || null };+ return {+ answer: (result?.text || '').trim() || 'No answer was generated — please try again.',+ model: result?.model || null,+ };}function fulfillUnlock({ page }) {@@ -166,7 +170,12 @@ export default wrap(async (req, res) => {}const chain = CHAINS[String(monetize.chain || 'base').toLowerCase()];if (!chain) {- return error(res, 422, 'unsupported_chain', 'this page is configured for an unsupported chain');+ return error(+ res,+ 422,+ 'unsupported_chain',+ 'this page is configured for an unsupported chain',+ );}const priceAtomics = priceToAtomics(monetize.price);@@ -185,7 +194,10 @@ export default wrap(async (req, res) => {}const action = isUnlock ? 'unlock' : 'ask';- const resourceUrl = resolveResourceUrl(req, `/api/launchpad/invoke?slug=${slug}&action=${action}`);+ const resourceUrl = resolveResourceUrl(+ req,+ `/api/launchpad/invoke?slug=${slug}&action=${action}`,+ );const accept = buildAccept({ chain, priceAtomics, payTo, resourceUrl });const paymentHeader = (req.headers['x-payment'] || '').toString().trim();@@ -210,36 +222,70 @@ export default wrap(async (req, res) => {}// ── Paid: verify → fulfill → settle → respond ──────────────────────────────- let verified;- try {- verified = await verifyPayment({ paymentHeader, requirements: [accept] });- } catch (err) {- return error(res, err.status || 402, err.code || 'payment_invalid', err.message || 'payment verification failed');+ // Replay guard (parity with paidEndpoint): hold a single-use lock on the+ // signed payment proof across fulfill+settle so a captured/retried X-PAYMENT+ // can't re-run the concierge LLM call before the first settle lands. Released+ // in the finally; the consumed on-chain nonce blocks any replay thereafter.+ const proofGuard = await reservePaymentProof(+ `/api/launchpad/invoke:${slug}:${action}`,+ paymentHeader,+ );+ if (!proofGuard.ok) {+ return error(+ res,+ 409,+ 'payment_in_flight',+ 'a request with this payment is already being processed; retry shortly',+ );}- let result;try {- result = isUnlock- ? fulfillUnlock({ page })- : await fulfillConcierge({ page, body });- } catch (err) {- return error(res, err.status || 500, err.code || 'fulfillment_failed', err.message || 'could not fulfill request');- }+ let verified;+ try {+ verified = await verifyPayment({ paymentHeader, requirements: [accept] });+ } catch (err) {+ return error(+ res,+ err.status || 402,+ err.code || 'payment_invalid',+ err.message || 'payment verification failed',+ );+ }- let settled;- try {- settled = await settlePayment({ verified });- } catch (err) {- return error(res, err.status || 502, err.code || 'settle_failed', err.message || 'payment settlement failed');- }+ let result;+ try {+ result = isUnlock ? fulfillUnlock({ page }) : await fulfillConcierge({ page, body });+ } catch (err) {+ return error(+ res,+ err.status || 500,+ err.code || 'fulfillment_failed',+ err.message || 'could not fulfill request',+ );+ }- res.setHeader('X-PAYMENT-RESPONSE', encodePaymentResponseHeader(settled));- return json(res, 200, {- slug,- action,- payer: settled.payer || verified?.payer || null,- transaction: settled.transaction || null,- network: settled.network || accept.network,- ...result,- });+ let settled;+ try {+ settled = await settlePayment({ verified });+ } catch (err) {+ return error(+ res,+ err.status || 502,+ err.code || 'settle_failed',+ err.message || 'payment settlement failed',+ );+ }++ res.setHeader('X-PAYMENT-RESPONSE', encodePaymentResponseHeader(settled));+ return json(res, 200, {+ slug,+ action,+ payer: settled.payer || verified?.payer || null,+ transaction: settled.transaction || null,+ network: settled.network || accept.network,+ ...result,+ });+ } finally {+ await proofGuard.release();+ }});diff --git a/api/mcp-3d.js b/api/mcp-3d.jsindex 63dd56e71..c7f623cba 100644--- a/api/mcp-3d.js+++ b/api/mcp-3d.js@@ -98,7 +98,9 @@ export default wrap(async (req, res) => {// settling it here means the charge lands only after the work succeeded.// Only settle if a call succeeded — a wholesale failure is free.if (x402Ctx) {- const anySuccess = responses.some((r) => r && !r.error && !(r.result && r.result.isError));+ const anySuccess = responses.some(+ (r) => r && !r.error && !(r.result && r.result.isError),+ );if (anySuccess) {try {const settled = await settlePayment({ verified: x402Ctx.verified });diff --git a/api/mcp-agent.js b/api/mcp-agent.jsindex f6fa2391e..834035c50 100644--- a/api/mcp-agent.js+++ b/api/mcp-agent.js@@ -75,7 +75,9 @@ export default wrap(async (req, res) => {// advertised 402 price is only ever charged once useful work was delivered;// a wholesale failure leaves the payer's signed payload un-broadcast.if (x402Ctx) {- const anySuccess = responses.some((r) => r && !r.error && !(r.result && r.result.isError));+ const anySuccess = responses.some(+ (r) => r && !r.error && !(r.result && r.result.isError),+ );if (anySuccess) {try {const settled = await settlePayment({ verified: x402Ctx.verified });diff --git a/api/mcp-bazaar.js b/api/mcp-bazaar.jsindex 73dee13db..3c89e8309 100644--- a/api/mcp-bazaar.js+++ b/api/mcp-bazaar.js@@ -77,7 +77,9 @@ export default wrap(async (req, res) => {// advertised 402 price is only ever charged once useful work was delivered;// a wholesale failure leaves the payer's signed payload un-broadcast.if (x402Ctx) {- const anySuccess = responses.some((r) => r && !r.error && !(r.result && r.result.isError));+ const anySuccess = responses.some(+ (r) => r && !r.error && !(r.result && r.result.isError),+ );if (anySuccess) {try {const settled = await settlePayment({ verified: x402Ctx.verified });diff --git a/api/pump-fun-mcp.js b/api/pump-fun-mcp.jsindex 2ffa53e72..a50494e5a 100644--- a/api/pump-fun-mcp.js+++ b/api/pump-fun-mcp.js@@ -37,6 +37,7 @@ import {paymentRequirements,build402Body,} from './_lib/x402-spec.js';+import { reservePaymentProof } from './_lib/x402/payment-identifier-server.js';import { getPumpSdk, getConnection, solanaPubkey, getAmmPoolState } from './_lib/pump.js';import { pumpfunMcp, pumpfunBotEnabled } from './_lib/pumpfun-mcp.js';import { TOOLS, resolveToolName, rpcError, rpcEnvelope } from '../src/pump/mcp-tools.js';@@ -765,8 +766,14 @@ async function handleGetCoinIntel({ mint, network = 'mainnet' } = {}) {}const LAMPORTS_PER_SOL = 1_000_000_000;- const num = (v) => { const n = Number(v); return Number.isFinite(n) ? n : null; };- const sol = (v) => { const n = num(v); return n == null ? null : Math.round(n / LAMPORTS_PER_SOL * 10000) / 10000; };+ const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+ };+ const sol = (v) => {+ const n = num(v);+ return n == null ? null : Math.round((n / LAMPORTS_PER_SOL) * 10000) / 10000;+ };try {// Main intel row@@ -787,15 +794,19 @@ async function handleGetCoinIntel({ mint, network = 'mainnet' } = {}) {if (!row) return { found: false, mint: cleanMint, network };- const signals = (row.signals && typeof row.signals === 'object') ? row.signals : {};+ const signals = row.signals && typeof row.signals === 'object' ? row.signals : {};const riskFlags = Array.isArray(row.risk_flags) ? row.risk_flags : [];const q = num(row.quality_score) ?? 0;const hardFlags = ['bundle_launch', 'dev_dumped', 'single_whale'];const hard = riskFlags.some((f) => hardFlags.includes(f));- const verdict = hard || q < 25 ? { key: 'avoid', label: 'Avoid', tone: 'danger' }- : q < 50 || riskFlags.length ? { key: 'caution', label: 'Caution', tone: 'warn' }- : q < 72 ? { key: 'watch', label: 'Watch', tone: 'neutral' }- : { key: 'strong', label: 'Strong', tone: 'success' };+ const verdict =+ hard || q < 25+ ? { key: 'avoid', label: 'Avoid', tone: 'danger' }+ : q < 50 || riskFlags.length+ ? { key: 'caution', label: 'Caution', tone: 'warn' }+ : q < 72+ ? { key: 'watch', label: 'Watch', tone: 'neutral' }+ : { key: 'strong', label: 'Strong', tone: 'success' };// Outcome label (may not exist yet for fresh coins)let outcome = null;@@ -804,15 +815,18 @@ async function handleGetCoinIntel({ mint, network = 'mainnet' } = {}) {select outcome, graduated, rugged, ath_market_cap_usd, ath_multiple, labeled_atfrom pump_coin_outcomes where mint = ${cleanMint} limit 1`;- if (o) outcome = {- outcome: o.outcome,- graduated: o.graduated,- rugged: o.rugged,- ath_market_cap_usd: num(o.ath_market_cap_usd),- ath_multiple: num(o.ath_multiple),- labeled_at: o.labeled_at,- };- } catch { /* outcome table absent — fine */ }+ if (o)+ outcome = {+ outcome: o.outcome,+ graduated: o.graduated,+ rugged: o.rugged,+ ath_market_cap_usd: num(o.ath_market_cap_usd),+ ath_multiple: num(o.ath_multiple),+ labeled_at: o.labeled_at,+ };+ } catch {+ /* outcome table absent — fine */+ }// Top wallets (compact — notable ones only for the MCP response)let topWallets = [];@@ -828,10 +842,12 @@ async function handleGetCoinIntel({ mint, network = 'mainnet' } = {}) {is_creator: !!w.is_creator,buy_sol: sol(w.buy_lamports),sell_sol: sol(w.sell_lamports),- share: Math.round((num(w.buy_lamports) || 0) / totalBuy * 1000) / 1000,+ share: Math.round(((num(w.buy_lamports) || 0) / totalBuy) * 1000) / 1000,funder: w.funder || null,}));- } catch { /* wallets absent — fine */ }+ } catch {+ /* wallets absent — fine */+ }// Latest model conditional win-rates (so agents see the evidence behind each signal)let model = null;@@ -842,12 +858,15 @@ async function handleGetCoinIntel({ mint, network = 'mainnet' } = {}) {where network = ${network}order by trained_at desc limit 1`;- if (wrow) model = {- sample_size: wrow.sample_size,- trained_at: wrow.trained_at,- conditional_win_rates: wrow.conditional_win_rates || null,- };- } catch { /* weights table absent — training hasn't run yet */ }+ if (wrow)+ model = {+ sample_size: wrow.sample_size,+ trained_at: wrow.trained_at,+ conditional_win_rates: wrow.conditional_win_rates || null,+ };+ } catch {+ /* weights table absent — training hasn't run yet */+ }// Oracle conviction — fused 4-pillar score from the oracle engine (may not// exist for brand-new coins; the oracle-score cron sweeps ~every 5 min).@@ -860,21 +879,24 @@ async function handleGetCoinIntel({ mint, network = 'mainnet' } = {}) {where mint = ${cleanMint} and network = ${network}limit 1`;- if (oc) oracle = {- score: num(oc.score),- tier: oc.tier,- pillars: {- pedigree: num(oc.pedigree),- structure: num(oc.structure),- narrative: num(oc.narrative),- momentum: num(oc.momentum),- },- structure_cap: !!oc.structure_cap,- badges: Array.isArray(oc.badges) ? oc.badges : [],- reasons: Array.isArray(oc.reasons) ? oc.reasons : [],- scored_at: oc.scored_at,- };- } catch { /* oracle tables not yet migrated — fine */ }+ if (oc)+ oracle = {+ score: num(oc.score),+ tier: oc.tier,+ pillars: {+ pedigree: num(oc.pedigree),+ structure: num(oc.structure),+ narrative: num(oc.narrative),+ momentum: num(oc.momentum),+ },+ structure_cap: !!oc.structure_cap,+ badges: Array.isArray(oc.badges) ? oc.badges : [],+ reasons: Array.isArray(oc.reasons) ? oc.reasons : [],+ scored_at: oc.scored_at,+ };+ } catch {+ /* oracle tables not yet migrated — fine */+ }const smartNotable = Array.isArray(row.smart_money_notable) ? row.smart_money_notable : [];@@ -883,15 +905,21 @@ async function handleGetCoinIntel({ mint, network = 'mainnet' } = {}) {if (verdict.key === 'avoid') parts.push('⛔ AVOID.');else if (verdict.key === 'strong') parts.push('✅ Strong entry signal.');if (row.smart_money_count > 0)- parts.push(`${row.smart_money_count} proven smart-money wallet${row.smart_money_count > 1 ? 's' : ''} entered (win-rate avg ${smartNotable[0]?.win_rate != null ? (smartNotable[0].win_rate * 100).toFixed(0) + '%' : 'unknown'}).`);+ parts.push(+ `${row.smart_money_count} proven smart-money wallet${row.smart_money_count > 1 ? 's' : ''} entered (win-rate avg ${smartNotable[0]?.win_rate != null ? (smartNotable[0].win_rate * 100).toFixed(0) + '%' : 'unknown'}).`,+ );if (row.dev_sold) parts.push('Dev sold during observation window — high rug risk.');if (riskFlags.includes('bundle_launch')) parts.push('Coordinated bundle launch detected.');- if (row.is_news_meme && signals.news_headline) parts.push(`News-meme: "${signals.news_headline}".`);+ if (row.is_news_meme && signals.news_headline)+ parts.push(`News-meme: "${signals.news_headline}".`);if (row.category && row.category !== 'unknown') parts.push(`Category: ${row.category}.`);if (outcome?.graduated) parts.push('GRADUATED to Raydium.');else if (outcome?.rugged) parts.push('Rugged.');- else if (outcome?.ath_multiple) parts.push(`ATH ${outcome.ath_multiple.toFixed(1)}× from entry.`);- const summary = parts.join(' ') || `Quality ${q}/100. ${riskFlags.length ? 'Risk flags: ' + riskFlags.join(', ') + '.' : 'No hard risk flags.'}`;+ else if (outcome?.ath_multiple)+ parts.push(`ATH ${outcome.ath_multiple.toFixed(1)}× from entry.`);+ const summary =+ parts.join(' ') ||+ `Quality ${q}/100. ${riskFlags.length ? 'Risk flags: ' + riskFlags.join(', ') + '.' : 'No hard risk flags.'}`;return {found: true,@@ -1011,7 +1039,10 @@ async function _pinBuffer(buf, filename) {if (!r.ok) throw Object.assign(new Error(`Web3.Storage ${r.status}`), { rpcCode: -32004 });return { cid: (await r.json()).cid, provider: 'web3.storage' };}- throw rpcError(-32004, 'no IPFS pinning provider configured (PINATA_JWT or WEB3_STORAGE_TOKEN)');+ throw rpcError(+ -32004,+ 'no IPFS pinning provider configured (PINATA_JWT or WEB3_STORAGE_TOKEN)',+ );}async function _fetchImgBuf(imageUrl) {@@ -1034,9 +1065,14 @@ async function _fetchImgBuf(imageUrl) {// cloud metadata) before fetching. Pinned variant closes the DNS-rebind window.let r;try {- r = await fetchSafePublicUrlPinned(imageUrl, { signal: ctrl.signal }, { allowHttp: true });+ r = await fetchSafePublicUrlPinned(+ imageUrl,+ { signal: ctrl.signal },+ { allowHttp: true },+ );} catch (err) {- if (err instanceof SsrfBlockedError) throw rpcError(-32602, 'image_url is not an allowed public URL');+ if (err instanceof SsrfBlockedError)+ throw rpcError(-32602, 'image_url is not an allowed public URL');throw err;}if (!r.ok) throw rpcError(-32004, `image fetch failed: HTTP ${r.status}`);@@ -1046,10 +1082,20 @@ async function _fetchImgBuf(imageUrl) {const ext = ct.split('/')[1]?.split(';')[0] || 'png';const fname = new URL(imageUrl, 'https://x').pathname.split('/').pop() || `image.${ext}`;return { buf, filename: fname };- } finally { clearTimeout(tid); }+ } finally {+ clearTimeout(tid);+ }}-async function handleUploadMetadata({ name, symbol, description, image_url, twitter, telegram, website } = {}) {+async function handleUploadMetadata({+ name,+ symbol,+ description,+ image_url,+ twitter,+ telegram,+ website,+} = {}) {if (!name || !symbol || !description || !image_url)throw rpcError(-32602, 'name, symbol, description, and image_url are required');if (String(name).length > 32) throw rpcError(-32602, 'name exceeds 32 chars');@@ -1117,13 +1163,21 @@ async function handlePumpfunBotStatus() {if (!r.ok) return { configured: true, healthy: false, latencyMs, error: `bot ${r.status}` };const j = await r.json().catch(() => null);if (j?.error)- return { configured: true, healthy: false, latencyMs, error: j.error.message || 'rpc error' };+ return {+ configured: true,+ healthy: false,+ latencyMs,+ error: j.error.message || 'rpc error',+ };return { configured: true, healthy: true, latencyMs };} catch (err) {return {configured: true,healthy: false,- error: err?.name === 'AbortError' ? 'timeout after 3000ms' : err?.message || 'fetch failed',+ error:+ err?.name === 'AbortError'+ ? 'timeout after 3000ms'+ : err?.message || 'fetch failed',};} finally {clearTimeout(timer);@@ -1146,7 +1200,10 @@ async function handleGetOracleConviction({ mint, network = 'mainnet' } = {}) {return { found: false, reason: 'database_unavailable' };}- const num = (v) => { const n = Number(v); return Number.isFinite(n) ? n : null; };+ const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+ };try {// 1. Conviction verdict from oracle_conviction cache@@ -1205,21 +1262,26 @@ async function handleGetOracleConviction({ mint, network = 'mainnet' } = {}) {select outcome, graduated, rugged, ath_market_cap_usd, ath_multiple, labeled_atfrom pump_coin_outcomes where mint = ${cleanMint} limit 1`;- if (o) outcome = {- outcome: o.outcome,- graduated: o.graduated,- rugged: o.rugged,- ath_market_cap_usd: num(o.ath_market_cap_usd),- ath_multiple: num(o.ath_multiple),- labeled_at: o.labeled_at,- };- } catch { /* fine — table may not exist yet */ }+ if (o)+ outcome = {+ outcome: o.outcome,+ graduated: o.graduated,+ rugged: o.rugged,+ ath_market_cap_usd: num(o.ath_market_cap_usd),+ ath_multiple: num(o.ath_multiple),+ labeled_at: o.labeled_at,+ };+ } catch {+ /* fine — table may not exist yet */+ }// Resolve wallet labels: brain reputation wins; knownWallet() seed fills the gap.let knownWallet;try {knownWallet = (await import('./_lib/oracle/known-wallets.js')).knownWallet;- } catch { knownWallet = () => null; }+ } catch {+ knownWallet = () => null;+ }const whosIn = walletRows.map((w) => {const brainLabel = w.label && w.label !== 'unproven' ? w.label : null;@@ -1227,10 +1289,11 @@ async function handleGetOracleConviction({ mint, network = 'mainnet' } = {}) {return {wallet: w.wallet,label: brainLabel || known?.label || 'unproven',- score: w.smart_money_score != null ? num(w.smart_money_score) : (known?.score ?? null),+ score:+ w.smart_money_score != null ? num(w.smart_money_score) : (known?.score ?? null),win_rate: w.win_rate != null ? num(w.win_rate) : null,early_win_rate: w.early_win_rate != null ? num(w.early_win_rate) : null,- source: brainLabel ? 'brain' : (known ? 'gmgn' : null),+ source: brainLabel ? 'brain' : known ? 'gmgn' : null,tag: w.tag || known?.tag || null,buy_sol: Number(w.buy_lamports || 0) / 1e9,sell_sol: Number(w.sell_lamports || 0) / 1e9,@@ -1240,13 +1303,14 @@ async function handleGetOracleConviction({ mint, network = 'mainnet' } = {}) {});// Tier summary for agent quick-read- const tierLabel = {- prime: 'PRIME — highest conviction. Top-grade entry signal.',- strong: 'STRONG — solid conviction. Enter with normal position size.',- lean: 'LEAN — mild positive lean. Size small or wait for confirmation.',- watch: 'WATCH — insufficient signal. Observe only.',- avoid: 'AVOID — negative signal. Do not enter.',- }[conv.tier] || conv.tier;+ const tierLabel =+ {+ prime: 'PRIME — highest conviction. Top-grade entry signal.',+ strong: 'STRONG — solid conviction. Enter with normal position size.',+ lean: 'LEAN — mild positive lean. Size small or wait for confirmation.',+ watch: 'WATCH — insufficient signal. Observe only.',+ avoid: 'AVOID — negative signal. Do not enter.',+ }[conv.tier] || conv.tier;return {found: true,@@ -1273,14 +1337,16 @@ async function handleGetOracleConviction({ mint, network = 'mainnet' } = {}) {scored_at: conv.scored_at,},- narrative: narr ? {- category: narr.category,- narrative: narr.narrative,- virality: num(narr.virality),- confidence: num(narr.confidence),- tags: Array.isArray(narr.tags) ? narr.tags : [],- source: narr.source,- } : null,+ narrative: narr+ ? {+ category: narr.category,+ narrative: narr.narrative,+ virality: num(narr.virality),+ confidence: num(narr.confidence),+ tags: Array.isArray(narr.tags) ? narr.tags : [],+ source: narr.source,+ }+ : null,whos_in: whosIn,outcome,@@ -1357,7 +1423,7 @@ const INSTRUCTIONS ='LAUNCH A COIN: to deploy a new pump.fun coin as an agent, call pumpfun_upload_metadata ' +'(bearer required) to pin name/symbol/description/image to IPFS and get a uri, then POST ' +'to /api/pump/launch-agent with agent_id + uri to build, sign, and submit the launch ' +- 'transaction using the agent\'s custodial wallet. All data is live; most tools need no key.';+ "transaction using the agent's custodial wallet. All data is live; most tools need no key.";const MAX_BATCH = 16;// Tools that are expensive (CPU grind or long-lived RPC subscriptions) or that@@ -1529,9 +1595,7 @@ async function dispatchRpc(msg, ctx) {// Advertise indexer-backed tools only when the bot is configured, so MCP// clients never see a tool that would just return -32004 on call. The// always-on pumpfun_bot_status (not in INDEXER_TOOLS) reports capability.- const tools = pumpfunBotEnabled()- ? TOOLS- : TOOLS.filter((t) => !INDEXER_TOOLS.has(t.name));+ const tools = pumpfunBotEnabled() ? TOOLS : TOOLS.filter((t) => !INDEXER_TOOLS.has(t.name));return rpcEnvelope(id, { tools });}if (rpcMethod === 'resources/list') return rpcEnvelope(id, { resources: [] });@@ -1548,7 +1612,10 @@ async function dispatchRpc(msg, ctx) {const handler =typeof name === 'string' && Object.hasOwn(HANDLERS, name) ? HANDLERS[name] : null;if (!handler) {- return rpcEnvelope(id, null, { code: -32601, message: `unknown tool: ${requestedName}` });+ return rpcEnvelope(id, null, {+ code: -32601,+ message: `unknown tool: ${requestedName}`,+ });}// Auth gate: expensive (vanity grind, long-lived RPC watch) and sensitive// (returns a secret key) tools require a bearer or verified x402 payment.@@ -1569,11 +1636,18 @@ async function dispatchRpc(msg, ctx) {if (!ctx.batch) {ctx.gateDenied = {id,- failure: { kind: 'rate_limited', code: -32029, message: 'rate limit exceeded for gated tools' },+ failure: {+ kind: 'rate_limited',+ code: -32029,+ message: 'rate limit exceeded for gated tools',+ },};return null;}- return rpcEnvelope(id, null, { code: -32029, message: 'rate limit exceeded for gated tools' });+ return rpcEnvelope(id, null, {+ code: -32029,+ message: 'rate limit exceeded for gated tools',+ });}try {const data = await handler(params?.arguments || {});@@ -1642,7 +1716,10 @@ export default wrap(async (req, res) => {return json(res,200,- rpcEnvelope(null, null, { code: -32600, message: `batch too large (max ${MAX_BATCH})` }),+ rpcEnvelope(null, null, {+ code: -32600,+ message: `batch too large (max ${MAX_BATCH})`,+ }),{ 'mcp-protocol-version': PROTOCOL_VERSION },);}@@ -1663,72 +1740,102 @@ export default wrap(async (req, res) => {400,rpcEnvelope(null, null, {code: -32600,- message: 'one X-PAYMENT settles a single gated call — send at most one paid tool per request',+ message:+ 'one X-PAYMENT settles a single gated call — send at most one paid tool per request',}),{ 'mcp-protocol-version': PROTOCOL_VERSION },);}}- // Per-request dispatch context. Gate credentials resolve at most once.- let gateAuthPromise = null;- const ctx = {- req,- res,- batch: isBatch,- x402Ctx: null,- gatedSuccess: false,- gatedId: null,- gateDenied: null,- ensureGateAuth() {- if (!gateAuthPromise) gateAuthPromise = resolveGatedAuth(req);- return gateAuthPromise;- },- };-- const responses = [];- for (const msg of messages) {- const envelope = await dispatchRpc(msg, ctx);- // Single-request gate denial keeps the legacy 401/402 HTTP semantics.- if (ctx.gateDenied) return writeGatedAuthFailure(res, ctx.gateDenied.id, ctx.gateDenied.failure);- if (envelope !== null) responses.push(envelope);- }-- // Settle the verified x402 payment AFTER gated work succeeded — atomic from- // the payer's perspective (verify → work → settle, mirroring /api/mcp): a- // failed tool never broadcasts the payment, and a successful one is always- // captured so the gated work can't be delivered free or the same signed- // payload replayed. One settlement covers the whole request.- if (ctx.x402Ctx && ctx.gatedSuccess) {- try {- const settled = await settlePayment({ verified: ctx.x402Ctx.verified });- res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));- } catch (settleErr) {+ // Replay guard (parity with paidEndpoint): a paid request holds a single-use+ // lock on its signed payment proof across dispatch+settle so a captured/retried+ // X-PAYMENT can't re-run the gated (often on-chain or LLM-backed) tool before+ // the first settle lands. Scoped to genuine paid requests (X-PAYMENT, no+ // bearer) — the same condition as the pay-once-run-many guard above. Released+ // in the finally; the consumed on-chain nonce blocks any replay thereafter.+ let releaseProof = async () => {};+ if (req.headers['x-payment'] && !extractBearer(req)) {+ const guard = await reservePaymentProof('/api/pump-fun-mcp', req.headers['x-payment']);+ if (!guard.ok) {return json(res,- 402,- rpcEnvelope(ctx.gatedId, null, {+ 409,+ rpcEnvelope(null, null, {code: -32402,- message: `payment settlement failed: ${settleErr?.message || 'settle error'}`,- data: build402Body({- resourceUrl: ctx.x402Ctx.resourceUrl,- accepts: ctx.x402Ctx.requirements,- error: settleErr?.message || 'settle error',- }),+ message:+ 'a request with this payment is already being processed; retry shortly',}),{ 'mcp-protocol-version': PROTOCOL_VERSION },);}+ releaseProof = guard.release;}- // All-notification requests owe no body — 202 Accepted per Streamable HTTP.- if (responses.length === 0) {- res.statusCode = 202;- res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);- return res.end();- }+ try {+ // Per-request dispatch context. Gate credentials resolve at most once.+ let gateAuthPromise = null;+ const ctx = {+ req,+ res,+ batch: isBatch,+ x402Ctx: null,+ gatedSuccess: false,+ gatedId: null,+ gateDenied: null,+ ensureGateAuth() {+ if (!gateAuthPromise) gateAuthPromise = resolveGatedAuth(req);+ return gateAuthPromise;+ },+ };- return json(res, 200, isBatch ? responses : responses[0], {- 'mcp-protocol-version': PROTOCOL_VERSION,- });+ const responses = [];+ for (const msg of messages) {+ const envelope = await dispatchRpc(msg, ctx);+ // Single-request gate denial keeps the legacy 401/402 HTTP semantics.+ if (ctx.gateDenied)+ return writeGatedAuthFailure(res, ctx.gateDenied.id, ctx.gateDenied.failure);+ if (envelope !== null) responses.push(envelope);+ }++ // Settle the verified x402 payment AFTER gated work succeeded — atomic from+ // the payer's perspective (verify → work → settle, mirroring /api/mcp): a+ // failed tool never broadcasts the payment, and a successful one is always+ // captured so the gated work can't be delivered free or the same signed+ // payload replayed. One settlement covers the whole request.+ if (ctx.x402Ctx && ctx.gatedSuccess) {+ try {+ const settled = await settlePayment({ verified: ctx.x402Ctx.verified });+ res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));+ } catch (settleErr) {+ return json(+ res,+ 402,+ rpcEnvelope(ctx.gatedId, null, {+ code: -32402,+ message: `payment settlement failed: ${settleErr?.message || 'settle error'}`,+ data: build402Body({+ resourceUrl: ctx.x402Ctx.resourceUrl,+ accepts: ctx.x402Ctx.requirements,+ error: settleErr?.message || 'settle error',+ }),+ }),+ { 'mcp-protocol-version': PROTOCOL_VERSION },+ );+ }+ }++ // All-notification requests owe no body — 202 Accepted per Streamable HTTP.+ if (responses.length === 0) {+ res.statusCode = 202;+ res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);+ return res.end();+ }++ return json(res, 200, isBatch ? responses : responses[0], {+ 'mcp-protocol-version': PROTOCOL_VERSION,+ });+ } finally {+ await releaseProof();+ }});diff --git a/data/changelog.json b/data/changelog.jsonindex 9ada5201b..107ce568b 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-24",+ "title": "Coin launches: stronger on-chain confirmation",+ "summary": "Launching a coin through three.ws now verifies that your confirmed transaction actually ran the pump.fun program before the launch is recorded — not just that it referenced your new mint address. This closes a gap where an unrelated transaction touching the mint could have been logged as a launch, keeping the launch directory and your agent's launch history accurate.",+ "tags": [+ "security",+ "fix"+ ]+ },{"date": "2026-06-24","title": "Reliability fixes: marketplace cards, avatar build status, and on-chain indexing",diff --git a/deploy/sniper/README.md b/deploy/sniper/README.mdindex 2c9a96efe..dc581456a 100644--- a/deploy/sniper/README.md+++ b/deploy/sniper/README.md@@ -95,7 +95,7 @@ loop instead of silently mis-trading) when:- `SNIPER_MODE` / `SNIPER_NETWORK` is not one of the allowed values,- `SNIPER_MODE=live` with neither `SOLANA_RPC_URL` nor `HELIUS_API_KEY`.-This is unit-verified in `tests/agent-sniper-ops.test.mjs`.+This is unit-verified in `tests/agent-sniper-ops.test.js`.## Deploy (simulate)diff --git a/package-lock.json b/package-lock.jsonindex 3f4a1e394..ffaad9926 100644--- a/package-lock.json+++ b/package-lock.json@@ -34,6 +34,23 @@"packages/marketplace-mcp","packages/x402-mcp","packages/provenance-mcp",+ "packages/autopilot-mcp",+ "packages/portfolio-mcp",+ "packages/copy-mcp",+ "packages/signals-mcp",+ "packages/alerts-mcp",+ "packages/notifications-mcp",+ "packages/billing-mcp",+ "packages/activity-mcp",+ "packages/agenc-mcp",+ "packages/agora-mcp",+ "packages/vision-mcp",+ "packages/brain-mcp",+ "packages/audio-mcp",+ "packages/kol-mcp",+ "packages/clash-mcp",+ "packages/tutor-mcp",+ "packages/loom-mcp","walk-sdk","tour-sdk"],@@ -22969,6 +22986,14 @@"url": "https://github.com/chalk/strip-ansi?sponsor=1"}},+ "node_modules/@three-ws/activity-mcp": {+ "resolved": "packages/activity-mcp",+ "link": true+ },+ "node_modules/@three-ws/agenc-mcp": {+ "resolved": "packages/agenc-mcp",+ "link": true+ },"node_modules/@three-ws/agent-payments": {"resolved": "agent-payments-sdk","link": true@@ -22977,6 +23002,22 @@"resolved": "agent-ui-sdk","link": true},+ "node_modules/@three-ws/agora-mcp": {+ "resolved": "packages/agora-mcp",+ "link": true+ },+ "node_modules/@three-ws/alerts-mcp": {+ "resolved": "packages/alerts-mcp",+ "link": true+ },+ "node_modules/@three-ws/audio-mcp": {+ "resolved": "packages/audio-mcp",+ "link": true+ },+ "node_modules/@three-ws/autopilot-mcp": {+ "resolved": "packages/autopilot-mcp",+ "link": true+ },"node_modules/@three-ws/avatar": {"resolved": "avatar-sdk","link": true@@ -22997,6 +23038,22 @@"resolved": "packages/avatar-schema","link": true},+ "node_modules/@three-ws/billing-mcp": {+ "resolved": "packages/billing-mcp",+ "link": true+ },+ "node_modules/@three-ws/brain-mcp": {+ "resolved": "packages/brain-mcp",+ "link": true+ },+ "node_modules/@three-ws/clash-mcp": {+ "resolved": "packages/clash-mcp",+ "link": true+ },+ "node_modules/@three-ws/copy-mcp": {+ "resolved": "packages/copy-mcp",+ "link": true+ },"node_modules/@three-ws/ibm-watsonx-mcp": {"resolved": "packages/ibm-watsonx-mcp","link": true@@ -23009,6 +23066,14 @@"resolved": "packages/intel-mcp","link": true},+ "node_modules/@three-ws/kol-mcp": {+ "resolved": "packages/kol-mcp",+ "link": true+ },+ "node_modules/@three-ws/loom-mcp": {+ "resolved": "packages/loom-mcp",+ "link": true+ },"node_modules/@three-ws/marketplace-mcp": {"resolved": "packages/marketplace-mcp","link": true@@ -23029,10 +23094,18 @@"resolved": "packages/naming-mcp","link": true},+ "node_modules/@three-ws/notifications-mcp": {+ "resolved": "packages/notifications-mcp",+ "link": true+ },"node_modules/@three-ws/page-agent": {"resolved": "page-agent-sdk","link": true},+ "node_modules/@three-ws/portfolio-mcp": {+ "resolved": "packages/portfolio-mcp",+ "link": true+ },"node_modules/@three-ws/provenance-mcp": {"resolved": "packages/provenance-mcp","link": true@@ -23045,6 +23118,10 @@"resolved": "packages/scene-mcp","link": true},+ "node_modules/@three-ws/signals-mcp": {+ "resolved": "packages/signals-mcp",+ "link": true+ },"node_modules/@three-ws/solana-agent": {"resolved": "solana-agent-sdk","link": true@@ -23057,6 +23134,10 @@"resolved": "tour-sdk","link": true},+ "node_modules/@three-ws/tutor-mcp": {+ "resolved": "packages/tutor-mcp",+ "link": true+ },"node_modules/@three-ws/vanity-mcp": {"resolved": "packages/vanity-mcp","link": true@@ -23065,6 +23146,10 @@"resolved": "packages/viewer-presets","link": true},+ "node_modules/@three-ws/vision-mcp": {+ "resolved": "packages/vision-mcp",+ "link": true+ },"node_modules/@three-ws/walk": {"resolved": "walk-sdk","link": true@@ -54118,6 +54203,98 @@}}},+ "packages/activity-mcp": {+ "name": "@three-ws/activity-mcp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "zod": "^3.23.8"+ },+ "bin": {+ "activity-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "packages/agenc-mcp": {+ "name": "@three-ws/agenc-mcp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "zod": "^3.23.8"+ },+ "bin": {+ "agenc-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "packages/agora-mcp": {+ "name": "@three-ws/agora-mcp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "@three-ws/solana-agent": "^0.2.0",+ "bs58": "^6.0.0",+ "zod": "^3.23.8"+ },+ "bin": {+ "agora-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "packages/alerts-mcp": {+ "name": "@three-ws/alerts-mcp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "zod": "^3.23.8"+ },+ "bin": {+ "alerts-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "packages/audio-mcp": {+ "name": "@three-ws/audio-mcp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "zod": "^3.23.8"+ },+ "bin": {+ "audio-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "packages/autopilot-mcp": {+ "name": "@three-ws/autopilot-mcp",+ "version": "0.2.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "zod": "^3.23.8"+ },+ "bin": {+ "autopilot-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },"packages/avatar-agent-mcp": {"name": "@three-ws/avatar-agent","version": "1.2.0",@@ -54173,6 +54350,68 @@"node": ">=18"}},+ "packages/billing-mcp": {+ "name": "@three-ws/billing-mcp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "zod": "^3.23.8"+ },+ "bin": {+ "billing-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "packages/brain-mcp": {+ "name": "@three-ws/brain-mcp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "zod": "^3.23.8"+ },+ "bin": {+ "brain-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "packages/clash-mcp": {+ "name": "@three-ws/clash-mcp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "bs58": "^6.0.0",+ "tweetnacl": "^1.0.3",+ "zod": "^3.23.8"+ },+ "bin": {+ "clash-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "packages/copy-mcp": {+ "name": "@three-ws/copy-mcp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "zod": "^3.23.8"+ },+ "bin": {+ "copy-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },"packages/ibm-watsonx-mcp": {"name": "@three-ws/ibm-watsonx-mcp","version": "0.2.0",@@ -54222,6 +54461,36 @@"node": ">=20"}},+ "packages/kol-mcp": {+ "name": "@three-ws/kol-mcp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "zod": "^3.23.8"+ },+ "bin": {+ "kol-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "packages/loom-mcp": {+ "name": "@three-ws/loom-mcp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "zod": "^3.23.8"+ },+ "bin": {+ "loom-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },"packages/marketplace-mcp": {"name": "@three-ws/marketplace-mcp","version": "0.1.0",@@ -54252,6 +54521,39 @@"node": ">=20"}},+ "packages/notifications-mcp": {+ "name": "@three-ws/notifications-mcp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "zod": "^3.23.8"+ },+ "bin": {+ "notifications-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "packages/portfolio-mcp": {+ "name": "@three-ws/portfolio-mcp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "@solana/spl-token": "^0.4.14",+ "@solana/web3.js": "^1.98.4",+ "bs58": "^6.0.0",+ "zod": "^3.23.8"+ },+ "bin": {+ "portfolio-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },"packages/provenance-mcp": {"name": "@three-ws/provenance-mcp","version": "0.1.0",@@ -54297,6 +54599,21 @@"node": ">=20"}},+ "packages/signals-mcp": {+ "name": "@three-ws/signals-mcp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "zod": "^3.23.8"+ },+ "bin": {+ "signals-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },"packages/three-token-mcp": {"name": "@three-ws/three-token-mcp","version": "1.1.0",@@ -54817,6 +55134,21 @@"@esbuild/win32-x64": "0.28.0"}},+ "packages/tutor-mcp": {+ "name": "@three-ws/tutor-mcp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "zod": "^3.23.8"+ },+ "bin": {+ "tutor-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },"packages/vanity-mcp": {"name": "@three-ws/vanity-mcp","version": "0.1.0",@@ -54848,9 +55180,24 @@}}},+ "packages/vision-mcp": {+ "name": "@three-ws/vision-mcp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "zod": "^3.23.8"+ },+ "bin": {+ "vision-mcp": "src/index.js"+ },+ "engines": {+ "node": ">=20"+ }+ },"packages/x402-mcp": {"name": "@three-ws/x402-mcp",- "version": "0.1.0",+ "version": "0.2.0","license": "Apache-2.0","dependencies": {"@modelcontextprotocol/sdk": "^1.29.0",diff --git a/package.json b/package.jsonindex afb3cdfcf..6d23bc778 100644--- a/package.json+++ b/package.json@@ -94,7 +94,7 @@]},"scripts": {- "postinstall": "(node scripts/build-cache.mjs check agent-payments-sdk agent-payments-sdk/src agent-payments-sdk/package.json || (npm run build --prefix agent-payments-sdk && node scripts/build-cache.mjs stamp agent-payments-sdk agent-payments-sdk/src agent-payments-sdk/package.json)) && (node scripts/fix-pump-sdk-esm.mjs & node scripts/fix-x402-extensions-esm.mjs & node scripts/fix-zauth-sdk-solana-esm.mjs & node scripts/fix-colyseus-storage.mjs & node scripts/copy-three-decoders.mjs & node scripts/setup-claude-skills.mjs & wait)",+ "postinstall": "(node scripts/build-cache.mjs check agent-payments-sdk agent-payments-sdk/src agent-payments-sdk/package.json || (npm run build --prefix agent-payments-sdk && node scripts/build-cache.mjs stamp agent-payments-sdk agent-payments-sdk/src agent-payments-sdk/package.json)) && (node scripts/fix-pump-sdk-esm.mjs & node scripts/fix-x402-extensions-esm.mjs & node scripts/fix-buffer-layout-utils-esm.mjs & node scripts/fix-zauth-sdk-solana-esm.mjs & node scripts/fix-colyseus-storage.mjs & node scripts/copy-three-decoders.mjs & node scripts/setup-claude-skills.mjs & wait)","setup": "node scripts/setup-dev.mjs","dev": "vite --port 3000","dev:multi": "npm run dev --prefix multiplayer",diff --git a/pages/home.html b/pages/home.htmlindex c4f164c28..fa01a3ea2 100644--- a/pages/home.html+++ b/pages/home.html@@ -570,6 +570,17 @@transition: opacity 0.5s ease;}.walk-preview-loading.is-done { opacity: 0; pointer-events: none; }+ .walk-preview-retry {+ margin-top: 4px; padding: 7px 16px;+ font-family: var(--font-mono); font-size: 10px; letter-spacing: 0.1em;+ text-transform: uppercase; color: var(--text-1);+ background: transparent; border: 1px solid var(--hairline-strong);+ border-radius: 6px; cursor: pointer;+ transition: border-color 0.15s ease, background 0.15s ease, transform 0.05s ease;+ }+ .walk-preview-retry:hover { border-color: var(--text-2); background: rgba(255,255,255,0.04); }+ .walk-preview-retry:active { transform: translateY(1px); }+ .walk-preview-retry:focus-visible { outline: 2px solid var(--text-2); outline-offset: 2px; }.walk-preview-spinner {width: 24px; height: 24px; border: 2px solid var(--hairline-strong);border-top-color: var(--text-2); border-radius: 50%;diff --git a/public/changelog.json b/public/changelog.jsonindex 94bbc18b3..0277dfda0 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-24T15:43:34.031Z",+ "generated_at": "2026-06-24T15:52:47.901Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -295,6 +295,17 @@"feature"]},+ {+ "date": "2026-06-24",+ "type": "update",+ "title": "Coin launches: stronger on-chain confirmation",+ "summary": "Launching a coin through three.ws now verifies that your confirmed transaction actually ran the pump.fun program before the launch is recorded — not just that it referenced your new mint address. This closes a gap where an unrelated transaction touching the mint could have been logged as a launch, keeping the launch directory and your agent's launch history accurate.",+ "link": null,+ "tags": [+ "security",+ "fix"+ ]+ },{"date": "2026-06-24","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 187d0346b..7a56392f2 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -222,6 +222,14 @@<category>sdk</category><description>A new Model Context Protocol server, @three-ws/billing-mcp, lets an AI agent self-serve its own account economics — no need to pull in the human account owner. Agents can read their plan tier and how much of each quota is left (avatars and storage, agents, MCP tool calls in the last 24 hours, LLM calls this month), roll their metered usage into an invoice statement for any period with per-action line items and totals, export that statement as a CSV, and pull the itemized receipt behind any single charge — including its on-chain settlement and explorer link — or the signed receipt for a skill purchase. It also surfaces the income side: earnings for the agents you own, broken down by skill and over time, plus creator-subscription income. Every account read is private and scoped to your three.ws session; only the public platform fee rate needs no credential. The server is read-only — it never signs or moves funds.</description></item>+ <item>+ <title>Coin launches: stronger on-chain confirmation</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-24:Coin launches: stronger on-chain confirmation</guid>+ <pubDate>Wed, 24 Jun 2026 12:00:00 GMT</pubDate>+ <category>security</category>+ <description>Launching a coin through three.ws now verifies that your confirmed transaction actually ran the pump.fun program before the launch is recorded — not just that it referenced your new mint address. This closes a gap where an unrelated transaction touching the mint could have been logged as a launch, keeping the launch directory and your agent's launch history accurate.</description>+ </item><item><title>Fixed the inline Pose Studio embed 404</title><link>https://three.ws/changelog</link>diff --git a/public/features.json b/public/features.jsonindex c0aeefc61..5b2b6907d 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-24T15:43:34.011Z",+ "generated_at": "2026-06-24T15:52:47.794Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/fix-buffer-layout-utils-esm.mjs b/scripts/fix-buffer-layout-utils-esm.mjsnew file mode 100644index 000000000..ab5903fbc--- /dev/null+++ b/scripts/fix-buffer-layout-utils-esm.mjs@@ -0,0 +1,67 @@+// Patches @solana/buffer-layout-utils after install to repair its broken ESM build.+//+// 0.2.0 ships an INCOMPLETE `lib/esm/` directory: `base.mjs`, `bigint.mjs`, and+// `decimal.mjs` are present, but `index.mjs`, `native.mjs`, and `web3.mjs` never+// made it into the tarball (only their `.js.map` files did). The package's+// `exports.import` condition and `module` field still advertise the missing+// `./lib/esm/index.mjs`, so any ESM consumer fails with:+//+// Error [ERR_MODULE_NOT_FOUND]: Cannot find module '.../lib/esm/index.mjs'+// imported from .../@solana/spl-token/lib/esm/instructions/amountToUiAmount.js+//+// @solana/spl-token is imported all over the agent-wallet / pump trade paths+// (and exercised by `npm run smoke:agent-wallet`), so this breaks the whole ESM+// graph that touches SPL token instructions.+//+// Fix: redirect the `import` condition (and drop the dangling `module` field) to+// the complete CJS build. `lib/cjs/index.js` re-exports everything via the TS+// `__exportStar` pattern, which both Node's cjs-module-lexer and Vite/esbuild+// interop statically resolve into named exports (`u64`, `publicKey`, `bool`, …),+// so `import { u64 } from '@solana/buffer-layout-utils'` works under raw Node and+// in the bundler. Same approach as fix-x402-extensions-esm.mjs.+//+// Idempotent (re-points only when still aimed at the missing .mjs); survives+// `npm ci` via postinstall.++import { existsSync, readFileSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';++const root = dirname(fileURLToPath(import.meta.url));+const repo = dirname(root);+const pkgPath = join(repo, 'node_modules/@solana/buffer-layout-utils/package.json');++if (!existsSync(pkgPath)) {+ console.log('[fix-buffer-layout-utils-esm] package not installed, skipping');+ process.exit(0);+}++const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));+const cjsEntry = './lib/cjs/index.js';++// The complete build is CJS; only repoint if the package still has it.+if (!existsSync(join(dirname(pkgPath), 'lib/cjs/index.js'))) {+ console.log('[fix-buffer-layout-utils-esm] cjs build missing, cannot repoint — skipping');+ process.exit(0);+}++let mutated = false;++if (pkg.exports && typeof pkg.exports === 'object' && pkg.exports.import !== cjsEntry) {+ pkg.exports.import = cjsEntry;+ mutated = true;+}++// `module` points at the missing ESM entry; bundlers that prefer it over+// `exports` would re-introduce the same broken resolution. Drop it.+if (pkg.module) {+ delete pkg.module;+ mutated = true;+}++if (mutated) {+ writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n');+ console.log('[fix-buffer-layout-utils-esm] redirected import→cjs (esm build is incomplete)');+} else {+ console.log('[fix-buffer-layout-utils-esm] already patched');+}diff --git a/src/shared/agent-wallet-chip.js b/src/shared/agent-wallet-chip.jsindex c47a60422..c75c1e3b2 100644--- a/src/shared/agent-wallet-chip.js+++ b/src/shared/agent-wallet-chip.js@@ -174,22 +174,38 @@ function formatTokenAmount(n) {return n.toPrecision(2);}-/** Render the short, vanity-aware address label (prefix/suffix highlighted). */-function addressLabelHTML(status) {- const { address, prefix, suffix } = status;- const head = prefix && address.startsWith(prefix) ? prefix : address.slice(0, 4);- const tail = suffix && address.endsWith(suffix) ? suffix : address.slice(-4);- const headHi = !!(prefix && address.startsWith(prefix));- const tailHi = !!(suffix && address.endsWith(suffix));+/**+ * The single vanity-aware address highlighter for the whole wallet program. When+ * the address really begins with `prefix` / ends with `suffix`, that segment is+ * shown verbatim and emphasized (`twc-hi`); otherwise the head/tail fall back to a+ * plain `head`/`tail`-length slice. Returns the inner spans only (no wrapper), so+ * the chip, the popover, and the living-avatar nameplate all render the same+ * "license plate" — reuse this, never reimplement the head/tail/highlight logic.+ *+ * @param {string} address base58 Solana address+ * @param {string|null} prefix claimed vanity prefix (highlighted only if it matches)+ * @param {string|null} suffix claimed vanity suffix (highlighted only if it matches)+ * @param {{head?:number, tail?:number}} [opts]+ * @returns {string} HTML: `<span[ class="twc-hi"]>head</span><span class="twc-dots">…</span><span[…]>tail</span>`+ */+export function highlightAddress(address, prefix, suffix, { head = 4, tail = 4 } = {}) {+ const a = String(address || '');+ const headHi = !!(prefix && a.startsWith(prefix));+ const tailHi = !!(suffix && a.endsWith(suffix));+ const headTxt = headHi ? prefix : a.slice(0, head);+ const tailTxt = tailHi ? suffix : a.slice(-tail);return (- `<span class="twc-addr">` +- `<span class="${headHi ? 'twc-hi' : ''}">${esc(head)}</span>` ++ `<span class="${headHi ? 'twc-hi' : ''}">${esc(headTxt)}</span>` +`<span class="twc-dots">…</span>` +- `<span class="${tailHi ? 'twc-hi' : ''}">${esc(tail)}</span>` +- `</span>`+ `<span class="${tailHi ? 'twc-hi' : ''}">${esc(tailTxt)}</span>`);}+/** Render the short, vanity-aware address label (prefix/suffix highlighted). */+function addressLabelHTML(status) {+ return `<span class="twc-addr">${highlightAddress(status.address, status.prefix, status.suffix, { head: 4, tail: 4 })}</span>`;+}+/** Build a tiny sparkline SVG from a real value series (empty state when sparse). */function sparklineSVG(points, { up = true, w = 56, h = 16, cls = '' } = {}) {const stroke = up ? 'var(--success,#4ade80)' : 'var(--danger,#f87171)';@@ -854,12 +870,7 @@ function positionPopover(el, trigger) {}function vanityAddrHTML(meta) {- const a = meta.address;- const head = meta.prefix && a.startsWith(meta.prefix) ? meta.prefix : a.slice(0, 6);- const tail = meta.suffix && a.endsWith(meta.suffix) ? meta.suffix : a.slice(-6);- const hH = meta.prefix && a.startsWith(meta.prefix);- const tH = meta.suffix && a.endsWith(meta.suffix);- return `<span class="${hH ? 'twc-hi' : ''}">${esc(head)}</span>…<span class="${tH ? 'twc-hi' : ''}">${esc(tail)}</span>`;+ return highlightAddress(meta.address, meta.prefix, meta.suffix, { head: 6, tail: 6 });}function renderPopoverBody(el, entry, meta) {@@ -1035,6 +1046,6 @@ function wirePopoverActions(el, meta) {if (typeof window !== 'undefined') {window.twsAgentWalletChip = {getWalletStatus, getWalletIdentity, hasWallet, walletChipHTML, walletChipEl,- wireWalletChips, ensureWalletChipStyles, formatWalletUsd,+ wireWalletChips, ensureWalletChipStyles, formatWalletUsd, highlightAddress,};}diff --git a/src/shared/agent-wealth-state.js b/src/shared/agent-wealth-state.jsindex b08c87658..b76985bf5 100644--- a/src/shared/agent-wealth-state.js+++ b/src/shared/agent-wealth-state.js@@ -46,6 +46,7 @@ function neutralState(agentId, network) {balanceSol: 0, balanceUsd: 0,momentum: 0, momentumUsd24h: 0, inflowUsd24h: 0, outflowUsd24h: 0,streamingNow: 0, lastTipAt: null,+ holdsThree: false, prefs: null,isOwner: false, ok: false,};}@@ -53,8 +54,9 @@ function neutralState(agentId, network) {/*** Fetch + normalize an agent's live wealth state into the canonical contract* the task defines: { tier, balanceSol, balanceUsd, momentum, streamingNow,- * lastTipAt } (plus the raw USD figures for the owner's "why" breakdown and an- * `ok` flag the caller can use to decide whether to keep its last real state).+ * lastTipAt, holdsThree, prefs, isOwner } (plus the raw USD figures for the+ * owner's "why" breakdown and an `ok` flag the caller can use to decide whether+ * to keep its last real state).** @param {string|object} agent an agent id or any record holding one* @param {object} [opts]@@ -108,6 +110,11 @@ function normalizeWealth(agentId, network, data, flow) {const balanceUsd = Number(flow.balance_usd ?? data?.portfolio?.usd) || 0;const balanceSol = Number(flow.balance_sol ?? data?.portfolio?.sol) || 0;const t = data?.tier?.key ? data.tier : tierForUsd(balanceUsd);+ // $THREE is the only coin the platform names; holding it earns the brand accent+ // on the avatar and nameplate. Real holding from the same canonical read — the+ // `portfolio.three` block is present only when the agent actually holds $THREE.+ const three = data?.portfolio?.three;+ const holdsThree = !!(three && (Number(three.amount) > 0 || Number(three.usd) > 0));return {agentId, network,tier: t.key || flow.tier || 'dormant',@@ -121,6 +128,11 @@ function normalizeWealth(agentId, network, data, flow) {outflowUsd24h: Number(flow.outflow_usd_24h) || 0,streamingNow: Math.max(0, Number(flow.streaming_now) || 0),lastTipAt: flow.last_tip_at || null,+ holdsThree,+ // The owner's saved presentation prefs travel with the state so a surface that+ // reads the wealth state (the living-avatar nameplate) honours how the owner+ // configured the agent without a second request. Raw here; consumers normalize.+ prefs: data?.prefs || null,isOwner: !!data?.is_owner,ok: true,};diff --git a/src/shared/living-avatar.js b/src/shared/living-avatar.jsnew file mode 100644index 000000000..ff2b33229--- /dev/null+++ b/src/shared/living-avatar.js@@ -0,0 +1,501 @@+/**+ * The Living Avatar — the agent's wallet-reactive IDENTITY layer (the nameplate).+ *+ * Where wallet-aura.js (the glow) answers "how funded does this agent LOOK," this+ * module answers "WHO is this agent, on chain." It renders the avatar's license+ * plate: the agent name, its vanity-highlighted public address, and a tier glyph+ * that reads the SAME wealth bucket the aura paints — anchored to the avatar so you+ * can look at a character and read its financial life at a glance.+ *+ * One source of truth, composed not reinvented:+ * • identity (address, vanity prefix/suffix, rarity, owner, deep links) comes from+ * getWalletStatus() in agent-wallet-chip.js — the platform's one normalizer;+ * • the vanity-highlighted address uses that module's one highlightAddress();+ * • the tier + accent come from wallet-networth.js (tierForUsd/computeWalletVisual),+ * the same tier math the 2D and 3D auras use;+ * • live tier + the pulse-on-earn ride agent-wealth-state.js's cached custody read,+ * so the nameplate and the aura share ONE request per agent and never disagree.+ *+ * Three fidelities, same data:+ * • mountNameplate() — a DOM overlay plate anchored to a hero / card avatar;+ * • applyWorldNameplate() — a cheap, pooled enrichment of a world's floating name+ * label (tier dot + vanity mark via CSS, survives the+ * renderer's per-frame textContent updates);+ * • resolveLivingAvatar() — the pure descriptor both renderers (and Tasks 04/05)+ * consume: { tier, holdsThree, vanity, address, … }.+ *+ * Honest by construction: a real $0 wallet shows a clean plate with no tier glyph+ * (an owner sees a "fund to light it up" nudge); an RPC failure silently falls back+ * to the identity-only plate, never a broken effect. No precise dollar value is ever+ * floated over an avatar — only the bucketed tier. $THREE is the only coin named.+ */++import { getWalletStatus, highlightAddress, ensureWalletChipStyles } from './agent-wallet-chip.js';+import { tierForUsd, computeWalletVisual } from './wallet-networth.js';+import { fetchWealthState, computeWealthDynamics } from './agent-wealth-state.js';+import { normalizePrefs } from './agent-networth.js';++const STYLE_ID = 'tws-living-avatar-styles';+const REDUCED_MOTION =+ typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;++function esc(s) {+ return String(s == null ? '' : s).replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++function agentIdOf(agent) {+ if (!agent) return null;+ if (typeof agent === 'string') return agent;+ return agent.agent_id || agent.agentId || agent.id || null;+}++// ── pure descriptor ───────────────────────────────────────────────────────────++/**+ * Resolve an agent record (+ optional real wallet figures) into the normalized+ * Living-Avatar descriptor every renderer consumes. Pure and synchronous — pass a+ * known `usd`/`holdsThree` to get the tier filled in, omit them for the loading+ * (identity-only) descriptor. Tier math and identity are NOT reimplemented here:+ * they compose getWalletStatus + tierForUsd/computeWalletVisual.+ *+ * @param {object|string} agent any supported agent/avatar record (or just an id)+ * @param {object} [opts]+ * @param {number} [opts.usd] real total portfolio USD (undefined → tier unknown)+ * @param {boolean} [opts.holdsThree] real $THREE holding (drives the brand accent)+ * @param {boolean} [opts.isOwner] server-resolved ownership for the viewer+ * @returns {{+ * agentId, address, name, avatarUrl, prefix, suffix, isVanity, rarity,+ * explorerUrl, hubUrl, ownerName, isOwner, hasWallet,+ * tier, tierLabel, level, accent, glow, dormant, holdsThree, hasTier+ * }}+ */+export function resolveLivingAvatar(agent, opts = {}) {+ const status = typeof agent === 'string' ? null : getWalletStatus(agent);+ const usd = opts.usd;+ const hasTier = Number.isFinite(usd);+ const holdsThree = !!opts.holdsThree;+ const visual = hasTier+ ? computeWalletVisual({ usdTotal: usd, mix: holdsThree ? { three: 1 } : { sol: 1 }, hasThree: holdsThree })+ : null;+ const tier = hasTier ? tierForUsd(usd) : null;++ if (!status) {+ const id = agentIdOf(agent);+ const name = typeof agent === 'object'+ ? agent?.name || agent?.display_name || agent?.agent_name || null+ : null;+ return {+ agentId: id, address: null, name, avatarUrl: null,+ prefix: null, suffix: null, isVanity: false, rarity: null,+ explorerUrl: null, hubUrl: id ? `/agent/${id}/wallet` : null,+ ownerName: null, isOwner: !!opts.isOwner, hasWallet: false,+ tier: tier?.key || null, tierLabel: tier?.label || null, level: tier?.level ?? null,+ accent: visual?.accent || 'var(--wallet-accent,#c4b5fd)',+ glow: visual?.glow || 'var(--wallet-glow,rgba(139,92,246,.45))',+ dormant: hasTier ? !!visual?.dormant : true,+ holdsThree, hasTier,+ };+ }++ return {+ agentId: status.agentId, address: status.address, name: status.name, avatarUrl: status.avatarUrl,+ prefix: status.prefix, suffix: status.suffix, isVanity: status.isVanity, rarity: status.rarity,+ explorerUrl: status.explorerUrl, hubUrl: status.hubUrl, ownerName: status.ownerName,+ isOwner: !!opts.isOwner, hasWallet: true,+ tier: tier?.key || null, tierLabel: tier?.label || null, level: tier?.level ?? null,+ accent: visual?.accent || 'var(--wallet-accent,#c4b5fd)',+ glow: visual?.glow || 'var(--wallet-glow,rgba(139,92,246,.45))',+ dormant: hasTier ? !!visual?.dormant : false,+ holdsThree, hasTier,+ };+}++// ── styles ──────────────────────────────────────────────────────────────────++function ensureStyles() {+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;+ const s = document.createElement('style');+ s.id = STYLE_ID;+ s.textContent = `+.la-plate{position:absolute;z-index:6;left:50%;bottom:10px;transform:translateX(-50%);+ display:inline-flex;align-items:center;gap:7px;max-width:calc(100% - 16px);+ padding:5px 9px;border-radius:999px;pointer-events:auto;+ font:600 12px/1 var(--font-body,Inter,system-ui,-apple-system,"Segoe UI",sans-serif);+ color:var(--ink,#e8e8e8);background:var(--surface-2,rgba(18,18,22,.82));+ border:1px solid var(--wallet-stroke,rgba(139,92,246,.3));+ box-shadow:0 6px 22px rgba(0,0,0,.4);backdrop-filter:blur(var(--blur-md,12px));+ --la-accent:var(--wallet-accent,#c4b5fd);--la-glow:var(--wallet-glow,rgba(139,92,246,.45));+ opacity:0;transition:opacity .35s var(--ease-standard,ease),transform .25s var(--ease-standard,ease),border-color .25s ease,box-shadow .3s ease;}+.la-plate[data-pos="top"]{bottom:auto;top:10px;}+.la-plate[data-ready="1"]{opacity:1;}+.la-plate[data-vanity="1"]{border-color:var(--wallet-stroke-strong,rgba(139,92,246,.5));}+.la-plate[data-three="1"]{border-color:color-mix(in srgb,var(--la-accent) 60%,#f0c46e 40%);}+.la-plate:hover,.la-plate:focus-within{border-color:var(--wallet-stroke-strong,rgba(139,92,246,.55));box-shadow:0 8px 28px rgba(0,0,0,.5),0 0 0 1px var(--la-glow);}+.la-plate:focus-visible{outline:2px solid var(--la-glow);outline-offset:2px;}+.la-glyph{width:9px;height:9px;border-radius:50%;flex:none;position:relative;+ background:var(--la-accent);box-shadow:0 0 7px var(--la-glow);transition:background .4s ease,box-shadow .4s ease;}+.la-plate[data-tier="dormant"] .la-glyph,.la-plate[data-tierless="1"] .la-glyph{background:var(--ink-faint,rgba(255,255,255,.32));box-shadow:none;}+.la-glyph-sk{background:linear-gradient(90deg,rgba(255,255,255,.1),rgba(255,255,255,.28),rgba(255,255,255,.1));+ background-size:200% 100%;animation:la-sk 1.1s ease-in-out infinite;box-shadow:none;}+@keyframes la-sk{0%{background-position:200% 0}100%{background-position:-200% 0}}+.la-name{font-weight:700;color:var(--ink-bright,#fff);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:140px;}+.la-addr{font-family:var(--font-mono,ui-monospace,SFMono-Regular,Menlo,monospace);font-size:11px;letter-spacing:.01em;+ color:var(--wallet-accent,#c4b5fd);display:inline-flex;gap:1px;align-items:center;border-left:1px solid var(--wallet-stroke,rgba(139,92,246,.28));padding-left:7px;}+.la-addr .twc-hi{color:var(--ink-bright,#fff);font-weight:700;}+.la-addr .twc-dots{opacity:.5;}+.la-three{font-size:9px;font-weight:800;letter-spacing:.03em;text-transform:uppercase;flex:none;+ color:#1a1206;background:linear-gradient(135deg,#f0c46e,#e0a94a);padding:2px 6px;border-radius:999px;line-height:1.3;}+.la-expand{display:inline-flex;align-items:center;gap:5px;max-width:0;overflow:hidden;opacity:0;+ transition:max-width .28s var(--ease-standard,ease),opacity .2s ease;}+.la-plate:hover .la-expand,.la-plate:focus-within .la-expand{max-width:120px;opacity:1;}+.la-act{appearance:none;background:none;border:none;padding:0 2px;margin:0;cursor:pointer;color:inherit;opacity:.7;+ display:inline-flex;align-items:center;transition:opacity .15s ease,transform .12s ease;}+.la-act:hover{opacity:1;}+.la-act:active{transform:scale(.9);}+.la-act:focus-visible{outline:2px solid var(--la-glow);outline-offset:2px;border-radius:4px;}+.la-act svg{width:13px;height:13px;}+.la-copied{color:var(--success,#4ade80)!important;}+.la-tip{font:700 10px/1 var(--font-body,Inter,system-ui);color:var(--wallet-accent-strong,#a78bfa);+ border-left:1px solid var(--wallet-stroke,rgba(139,92,246,.28));padding-left:7px;white-space:nowrap;+ appearance:none;background:none;border-top:none;border-right:none;border-bottom:none;cursor:pointer;transition:color .15s ease;}+.la-tip:hover{color:var(--ink-bright,#fff);}+.la-tip:focus-visible{outline:2px solid var(--la-glow);outline-offset:2px;border-radius:4px;}+.la-fund{font:700 10px/1 var(--font-body,Inter,system-ui);color:var(--wallet-accent-strong,#a78bfa);+ border-left:1px solid var(--wallet-stroke,rgba(139,92,246,.28));padding-left:7px;white-space:nowrap;text-decoration:none;transition:color .15s ease;}+.la-fund:hover{color:var(--ink-bright,#fff);}+.la-plate.la-pulse{animation:la-pulse 1.2s var(--ease-standard,ease-out);}+@keyframes la-pulse{0%{box-shadow:0 6px 22px rgba(0,0,0,.4),0 0 0 0 var(--la-glow);}+ 30%{box-shadow:0 6px 22px rgba(0,0,0,.4),0 0 0 8px color-mix(in srgb,var(--la-glow) 0%,transparent);}+ 100%{box-shadow:0 6px 22px rgba(0,0,0,.4),0 0 0 0 transparent;}}+.la-plate[data-lod="card"]{padding:3px 7px;gap:5px;font-size:11px;bottom:6px;}+.la-plate[data-lod="card"] .la-name{max-width:90px;}+.la-plate[data-lod="card"] .la-addr,.la-plate[data-lod="card"] .la-expand{display:none;}++/* ── world label enrichment (CSS-only, survives renderer textContent updates) ── */+.walk-remote-label.la-world-label{--la-tier:var(--ink-faint,rgba(255,255,255,.4));}+.walk-remote-label.la-world-label::before{content:"";display:inline-block;width:7px;height:7px;border-radius:50%;+ margin-right:6px;vertical-align:middle;background:var(--la-tier);box-shadow:0 0 6px var(--la-tier);}+.walk-remote-label[data-la-tier="dormant"]::before,.walk-remote-label.la-world-label:not([data-la-tier])::before{box-shadow:none;opacity:.6;}+.walk-remote-label[data-la-vanity]::after{content:"✦";margin-left:5px;color:var(--wallet-accent,#c4b5fd);font-weight:700;vertical-align:middle;}+.walk-remote-label.la-world-three{border-color:color-mix(in srgb,var(--wallet-accent,#c4b5fd) 55%,#f0c46e 45%)!important;}+@media (prefers-reduced-motion: reduce){+ .la-plate,.la-glyph,.la-expand{transition:none;}+ .la-glyph-sk{animation:none;}+ .la-plate.la-pulse{animation:none;}+}`;+ (document.head || document.documentElement).appendChild(s);+}++const COPY_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';+const LINK_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>';+const GEAR_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1Z"/></svg>';++async function copyToClipboard(addr, btn) {+ if (!addr || typeof navigator === 'undefined' || !navigator.clipboard) return;+ try {+ await navigator.clipboard.writeText(addr);+ if (!btn) return;+ const prev = btn.innerHTML;+ btn.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg>';+ btn.classList.add('la-copied');+ setTimeout(() => { btn.innerHTML = prev; btn.classList.remove('la-copied'); }, 1400);+ } catch { /* clipboard denied — address still legible on the plate */ }+}++// ── overlay nameplate (hero / card) ───────────────────────────────────────────++/**+ * Mount the Living-Avatar nameplate as a DOM overlay anchored to a container that+ * holds an avatar (a <model-viewer> stage, a portrait wrap, a card thumb). Renders+ * identity (name + vanity address) immediately from the record, then hydrates the+ * tier glyph + role-appropriate actions from the real wallet — never blocking the+ * avatar's first paint on wallet data.+ *+ * @param {HTMLElement} container+ * @param {object} agent any supported agent/avatar record+ * @param {object} [opts]+ * @param {'mainnet'|'devnet'} [opts.network='mainnet']+ * @param {'top'|'bottom'} [opts.position='bottom']+ * @param {'full'|'card'} [opts.lod='full'] card LOD hides the address/expand for dense thumbs+ * @param {boolean} [opts.isOwner=false] initial owner hint (reconciled with the server read)+ * @param {boolean} [opts.live=true] keep the tier glyph current + pulse on real earnings+ * @returns {{ el, update(state), setTier(usd,holdsThree), setPrefs(prefs), pulse(), destroy() }|null}+ */+export function mountNameplate(container, agent, opts = {}) {+ if (!container || typeof document === 'undefined') return null;+ ensureWalletChipStyles();+ ensureStyles();++ const network = opts.network === 'devnet' ? 'devnet' : 'mainnet';+ const lod = opts.lod === 'card' ? 'card' : 'full';+ const position = opts.position === 'top' ? 'top' : 'bottom';+ const agentId = agentIdOf(agent);++ const cs = getComputedStyle(container);+ if (cs.position === 'static') container.style.position = 'relative';++ let descriptor = resolveLivingAvatar(agent, { isOwner: !!opts.isOwner });+ // No wallet at all and no name → nothing meaningful to anchor; bail cleanly.+ if (!descriptor.hasWallet && !descriptor.name) return null;++ const plate = document.createElement('div');+ plate.className = 'la-plate';+ plate.dataset.pos = position;+ plate.dataset.lod = lod;+ plate.dataset.tierless = '1';+ plate.setAttribute('tabindex', '0');+ plate.setAttribute('role', 'group');++ let prefs = null;+ let isOwner = !!opts.isOwner;+ let lastTipAt = null;+ let lastUsd = null;+ let primed = false;++ function render() {+ const showAddr = descriptor.hasWallet && lod === 'full' && !(prefs && prefs.nameplate?.address === false);+ const showTier = !(prefs && (prefs.reactivity === 'off' || prefs.signals?.aura === false || prefs.nameplate?.tier === false));+ const vanity = descriptor.isVanity;+ const three = descriptor.holdsThree && showTier;++ plate.style.setProperty('--la-accent', descriptor.accent);+ plate.style.setProperty('--la-glow', descriptor.glow);+ plate.dataset.tier = descriptor.tier || 'dormant';+ plate.dataset.vanity = vanity ? '1' : '0';+ plate.dataset.three = three ? '1' : '0';+ // Tier glyph: a skeleton dot until the first read, then the real bucket (or+ // removed when the wallet is honestly empty). Never a precise dollar value.+ const tierState = !descriptor.hasTier ? 'sk' : descriptor.dormant || !showTier ? 'off' : 'on';+ plate.dataset.tierless = tierState === 'on' ? '0' : '1';+ const glyphCls = tierState === 'sk' ? 'la-glyph la-glyph-sk' : 'la-glyph';+ const glyphTitle = tierState === 'sk'+ ? 'Reading wallet…'+ : tierState === 'off'+ ? (descriptor.hasWallet ? 'Dormant wallet' : 'Wallet provisioning')+ : `${descriptor.tierLabel} tier · funded`;++ const addrHTML = showAddr+ ? `<span class="la-addr" aria-label="Wallet address ${esc(descriptor.address)}">${highlightAddress(descriptor.address, descriptor.prefix, descriptor.suffix, { head: 4, tail: 4 })}</span>`+ : '';+ const threeTag = three+ ? '<span class="la-three" title="Holds $THREE — the platform coin">$THREE</span>'+ : '';++ // Expand-on-hover: full-address copy + explorer (visitor-safe, read-only).+ const expand = descriptor.hasWallet && lod === 'full'+ ? `<span class="la-expand">` ++ `<button type="button" class="la-act" data-la-copy title="Copy address" aria-label="Copy wallet address">${COPY_SVG}</button>` ++ `<a class="la-act" href="${esc(descriptor.explorerUrl)}" target="_blank" rel="noopener noreferrer" title="View on Solscan" aria-label="View wallet on Solscan">${LINK_SVG}</a>` ++ `</span>`+ : '';++ // Role action: owner → tune how the agent presents (opens the presence panel);+ // non-owner → tip the agent; a fresh empty wallet nudges its owner to fund it.+ let action = '';+ if (isOwner) {+ if (descriptor.hasWallet && descriptor.dormant && descriptor.hasTier) {+ action = descriptor.hubUrl+ ? `<a class="la-fund" href="${esc(descriptor.hubUrl)}#deposit" title="Fund this agent to light it up">⚡ Fund</a>`+ : '';+ } else if (lod === 'full') {+ action = `<button type="button" class="la-act" data-la-settings title="Tune how your agent presents" aria-label="Nameplate display settings">${GEAR_SVG}</button>`;+ }+ } else if (descriptor.hasWallet) {+ action = `<button type="button" class="la-tip" data-la-tip title="Tip ${esc(descriptor.name || 'this agent')}">◎ Tip</button>`;+ }++ plate.innerHTML =+ `<span class="${glyphCls}" aria-hidden="true" title="${esc(glyphTitle)}"></span>` ++ `<span class="la-name">${esc(descriptor.name || 'Agent')}</span>` ++ threeTag + addrHTML + expand + action;+ plate.setAttribute('aria-label',+ `${descriptor.name || 'Agent'}${descriptor.hasWallet ? `, wallet ${descriptor.address}` : ''}` ++ `${tierState === 'on' ? `, ${descriptor.tierLabel} tier` : ''}${three ? ', holds $THREE' : ''}`);+ wire();+ }++ function wire() {+ const copyBtn = plate.querySelector('[data-la-copy]');+ if (copyBtn) copyBtn.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); copyToClipboard(descriptor.address, copyBtn); });+ const tip = plate.querySelector('[data-la-tip]');+ if (tip) tip.addEventListener('click', async (e) => {+ e.preventDefault(); e.stopPropagation();+ try {+ const { openTipModal } = await import('./agent-tip-modal.js');+ openTipModal({+ id: descriptor.agentId, solana_address: descriptor.address,+ name: descriptor.name || 'this agent', avatar_thumbnail_url: descriptor.avatarUrl || '',+ meta: { payments: { accepted_tokens: (agent?.meta?.payments?.accepted_tokens || agent?.payments?.accepted_tokens || []) } },+ });+ } catch { /* address still copyable from the expanded plate */ }+ });+ const gear = plate.querySelector('[data-la-settings]');+ if (gear) gear.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); openOwnerSettings(); });+ }++ // Owner settings affordance: reveal the presence panel (the owner's control+ // centre for how the agent presents itself). Scroll the nearest one into view+ // and flash it; broadcast an event so a page can open a collapsed panel; fall+ // back to the wallet hub so the affordance is never a dead end.+ function openOwnerSettings() {+ if (agentId) window.dispatchEvent(new CustomEvent('tws:open-presence', { detail: { agentId } }));+ const panel = document.querySelector('.nwp');+ if (panel) {+ panel.scrollIntoView({ behavior: REDUCED_MOTION ? 'auto' : 'smooth', block: 'center' });+ panel.animate?.(+ [{ boxShadow: '0 0 0 0 rgba(139,92,246,.6)' }, { boxShadow: '0 0 0 6px rgba(139,92,246,0)' }],+ { duration: 1000, easing: 'ease-out' },+ );+ return;+ }+ if (descriptor.hubUrl) window.location.href = `${descriptor.hubUrl}#presence`;+ }++ function setTier(usd, holdsThree) {+ descriptor = resolveLivingAvatar(agent, { usd, holdsThree, isOwner });+ render();+ }++ function setPrefs(p) {+ prefs = p ? normalizePrefs(p) : null;+ render();+ }++ function pulse() {+ if (REDUCED_MOTION || !plate.isConnected) return;+ if (prefs && (prefs.reactivity === 'off' || prefs.signals?.events === false)) return;+ plate.classList.remove('la-pulse');+ void plate.offsetWidth; // restart the animation+ plate.classList.add('la-pulse');+ setTimeout(() => plate.classList.remove('la-pulse'), 1300);+ }++ function update(state) {+ if (!state || !state.ok) return;+ if (typeof state.isOwner === 'boolean') isOwner = state.isOwner;+ if (state.prefs) prefs = normalizePrefs(state.prefs);+ descriptor = resolveLivingAvatar(agent, { usd: state.balanceUsd, holdsThree: state.holdsThree, isOwner });+ render();+ // A real new tip or a real balance increase fires one tasteful glint — only+ // after the first (priming) read so landing on the page never replays an old+ // event. The dynamics gate keeps a flat wallet from ever pulsing.+ const dyn = computeWealthDynamics(state);+ const tipAdvanced = state.lastTipAt && state.lastTipAt !== lastTipAt;+ const grew = lastUsd != null && state.balanceUsd > lastUsd + 1e-6;+ if (primed && (tipAdvanced || (grew && dyn.trend !== 'down'))) pulse();+ lastTipAt = state.lastTipAt;+ lastUsd = state.balanceUsd;+ primed = true;+ }++ container.appendChild(plate);+ render();+ requestAnimationFrame(() => { plate.dataset.ready = '1'; });++ // Live tier + pulse: a visibility-gated poll of the cached custody read. Uses the+ // shared 60s client cache (fresh:false) so on a hero page it rides the aura's+ // poll for zero extra requests, and self-hydrates anywhere the aura isn't mounted.+ let stop = () => {};+ if (opts.live !== false && agentId) {+ let timer = 0;+ let stopped = false;+ let visible = true;+ const io = typeof IntersectionObserver === 'function'+ ? new IntersectionObserver((es) => { visible = es.some((e) => e.isIntersecting); }, { threshold: 0.01 })+ : null;+ if (io) io.observe(container);+ const tick = async () => {+ if (stopped) return;+ if (visible && (typeof document === 'undefined' || document.visibilityState === 'visible')) {+ try { update(await fetchWealthState(agentId, { network })); } catch { /* hold last real look */ }+ }+ if (!stopped) timer = setTimeout(tick, 30_000);+ };+ tick();+ stop = () => { stopped = true; if (timer) clearTimeout(timer); try { io?.disconnect(); } catch { /* noop */ } };+ }++ return {+ el: plate,+ update, setTier, setPrefs, pulse,+ destroy() { stop(); plate.remove(); },+ };+}++// ── world label enrichment (pooled, CSS-only) ─────────────────────────────────++const _embedCache = new Map(); // agentId -> Promise<embed|null> (dedupes across all labels)++function fetchEmbed(agentId, network) {+ const key = `${agentId}:${network}`;+ if (_embedCache.has(key)) return _embedCache.get(key);+ const p = fetch(`/api/agents/wallet-embed?id=${encodeURIComponent(agentId)}&network=${encodeURIComponent(network)}`, {+ headers: { accept: 'application/json' },+ })+ .then((r) => (r.ok ? r.json() : null))+ .then((j) => j?.data || null)+ .catch(() => null);+ _embedCache.set(key, p);+ return p;+}++/**+ * Enrich a world's floating name label (e.g. walk.js's `.walk-remote-label`) with+ * the agent's wealth tier + vanity, so a crowded plaza is instantly legible — you+ * can see who's funded and who's vanity without walking up to each one. Drives the+ * label's tier dot + vanity mark through CSS pseudo-elements and data attributes,+ * which SURVIVE the renderer's per-frame `textContent = name` updates (no child+ * nodes to clobber). One cached, deduped wallet-embed read per agent across all+ * labels — no per-frame work, no per-label request storm. Visitor view only: it+ * reads the public embed and shows the bucketed tier, never a dollar value.+ *+ * @param {HTMLElement} label the floating label element+ * @param {string} agentId the piloted agent's UUID+ * @param {object} [opts] { network }+ * @returns {{ destroy: () => void }}+ */+export function applyWorldNameplate(label, agentId, opts = {}) {+ if (!label || !agentId || typeof document === 'undefined') return { destroy() {} };+ ensureStyles();+ const network = opts.network === 'devnet' ? 'devnet' : 'mainnet';+ let destroyed = false;++ fetchEmbed(agentId, network).then((embed) => {+ if (destroyed || !embed || !embed.address) return;+ label.classList.add('la-world-label');+ const usd = Number(embed.balanceUsd);+ if (Number.isFinite(usd)) {+ const tier = tierForUsd(usd);+ const vis = computeWalletVisual({ usdTotal: usd, mix: Number(embed.three) > 0 ? { three: 1 } : { sol: 1 }, hasThree: Number(embed.three) > 0 });+ label.dataset.laTier = tier.key;+ label.style.setProperty('--la-tier', tier.level > 0 ? vis.accent : 'var(--ink-faint,rgba(255,255,255,.4))');+ }+ if (Number(embed.three) > 0) label.classList.add('la-world-three');+ const v = embed.vanity;+ if (v && (v.prefix || v.suffix)) label.dataset.laVanity = String(v.prefix || v.suffix);+ // Accessible, non-doxxing hover summary (tier bucket + vanity, never a $ value).+ const bucket = Number.isFinite(usd) ? tierForUsd(usd) : null;+ const bits = [embed.name || ''];+ if (bucket && bucket.level > 0) bits.push(`${bucket.label} tier`);+ if (Number(embed.three) > 0) bits.push('holds $THREE');+ if (v && (v.prefix || v.suffix)) bits.push('vanity address');+ label.title = bits.filter(Boolean).join(' · ');+ });++ return {+ destroy() {+ destroyed = true;+ label.classList.remove('la-world-label', 'la-world-three');+ delete label.dataset.laTier;+ delete label.dataset.laVanity;+ label.style.removeProperty('--la-tier');+ },+ };+}++if (typeof window !== 'undefined') {+ window.twsLivingAvatar = { resolveLivingAvatar, mountNameplate, applyWorldNameplate };+}diff --git a/src/walk-embed-preview.js b/src/walk-embed-preview.jsindex 689a2a348..acf86e9cc 100644--- a/src/walk-embed-preview.js+++ b/src/walk-embed-preview.js@@ -277,6 +277,12 @@ export function initWalkPreview(container) {let currentMotion = 'idle';async function loadAvatar() {+ // A retry after a partial failure (GLB added, then the clip manifest fetch+ // threw) must not stack a second avatar in the rig — drop the prior one first.+ if (avatar) {+ avatarRig.remove(avatar);+ avatar = null;+ }const loader = new GLTFLoader();const gltf = await loader.loadAsync(AVATAR_URL);const model = gltf.scene;@@ -317,6 +323,38 @@ export function initWalkPreview(container) {}}+ // Drive the load and, on failure, swap the perpetual spinner for a designed,+ // retryable error state. A loading overlay that never resolves — what the+ // avatar/manifest/clip fetch left behind when it threw — is exactly the frozen+ // UI this surface must not ship.+ function startLoad() {+ const loadingEl = container.querySelector('[data-walk-loading]');+ if (loadingEl) {+ loadingEl.classList.remove('is-done');+ loadingEl.innerHTML =+ '<div class="walk-preview-spinner"></div><span>Loading 3D scene…</span>';+ }+ loadAvatar().catch((err) => {+ log.warn('[walk-preview] load failed', err);+ showLoadError();+ });+ }++ function showLoadError() {+ const loadingEl = container.querySelector('[data-walk-loading]');+ if (!loadingEl) return;+ loadingEl.classList.remove('is-done');+ loadingEl.innerHTML = '';+ const msg = document.createElement('span');+ msg.textContent = 'Couldn’t load the 3D preview.';+ const retry = document.createElement('button');+ retry.type = 'button';+ retry.className = 'walk-preview-retry';+ retry.textContent = 'Retry';+ retry.addEventListener('click', startLoad, { once: true });+ loadingEl.append(msg, retry);+ }+// ── Resize ──────────────────────────────────────────────────────function resize() {const r = container.getBoundingClientRect();@@ -483,7 +521,7 @@ export function initWalkPreview(container) {for (const entry of entries) {if (entry.isIntersecting && !started) {started = true;- loadAvatar().catch((err) => log.warn('[walk-preview] load failed', err));+ startLoad();syncRunning();observer.disconnect();}diff --git a/tests/api/auto-rig-finalize.test.js b/tests/api/auto-rig-finalize.test.jsindex 37e8be76c..71405c80a 100644--- a/tests/api/auto-rig-finalize.test.js+++ b/tests/api/auto-rig-finalize.test.js@@ -109,18 +109,26 @@ vi.mock('../../api/_lib/glb-inspect.js', () => ({vi.mock('../../api/_lib/webhook-dispatch.js', () => ({ dispatchWebhooks: vi.fn(async () => {}) }));vi.mock('../../api/_lib/regen-provider.js', () => ({ getRegenProvider: async () => ({ name: 'replicate', instance: null }) }));+// The rigged-GLB fetch now flows through the shared provider-result-url guard+// (host allowlist + IP-pinned SSRF connect), which uses raw node http — not the+// global fetch — so stubbing global.fetch no longer intercepts it. Mock the one+// guarded helper instead; the real allowlist/extract logic stays intact for the+// SSRF specs. RIGGED_BYTES are the exact 4 bytes the checksum assertions expect.+const RIGGED_BYTES = new Uint8Array([0x67, 0x6c, 0x54, 0x46]);+let fetchGlbImpl = async () => Buffer.from(RIGGED_BYTES);+const fetchProviderGlbBufferMock = vi.fn((...a) => fetchGlbImpl(...a));+vi.mock('../../api/_lib/provider-result-url.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, fetchProviderGlbBuffer: (...a) => fetchProviderGlbBufferMock(...a) };+});+const { finalizeAutoRigStage } = await import('../../api/_lib/auto-rig.js');const { dispatchWebhooks } = await import('../../api/_lib/webhook-dispatch.js');function mockFetchGlb(ok = true) {- global.fetch = vi.fn(async () => {- if (!ok) return { ok: false, status: 502, headers: { get: () => '0' }, arrayBuffer: async () => new ArrayBuffer(0) };- return {- ok: true,- headers: { get: () => '4' },- arrayBuffer: async () => new Uint8Array([0x67, 0x6c, 0x54, 0x46]).buffer,- };- });+ fetchGlbImpl = ok+ ? async () => Buffer.from(RIGGED_BYTES)+ : async () => { throw new Error('fetch glb: 502'); };}const job = { source_avatar_id: 'src-1', mode: 'rerig', params: { auto_rig: true } };diff --git a/tests/api/reconstruct-finalize.test.js b/tests/api/reconstruct-finalize.test.jsindex 36a6be4ec..f23bf9434 100644--- a/tests/api/reconstruct-finalize.test.js+++ b/tests/api/reconstruct-finalize.test.js@@ -34,24 +34,25 @@ vi.mock('../../api/_lib/regen-provider.js', () => ({getRegenProvider: async () => providerMock,}));+// Provider/result GLBs (the reconstruct output, the rigged result, and the bare+// unrigged mesh) are now fetched through the shared guard, which uses raw node+// http rather than the global fetch — so we mock the guarded helper. The real+// host-allowlist + extract logic is covered by tests/provider-result-url.test.js.+const fetchProviderGlbBufferMock = vi.fn(async () => Buffer.from(new Uint8Array([0x67, 0x6c, 0x54, 0x46])));+vi.mock('../../api/_lib/provider-result-url.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, fetchProviderGlbBuffer: (...a) => fetchProviderGlbBufferMock(...a) };+});+const { finalizeReconstructStage, pollRiggingStage } = await import('../../api/_lib/reconstruct-finalize.js');const RIGGED = { isRigged: true, skinCount: 1, skeletonJointCount: 30, nodeCount: 40, meshCount: 1, animationCount: 0, generator: 'test' };const UNRIGGED = { isRigged: false, skinCount: 0, skeletonJointCount: 0, nodeCount: 2, meshCount: 1, animationCount: 0, generator: 'test' };-function mockFetchGlb() {- global.fetch = vi.fn(async () => ({- ok: true,- headers: { get: () => '1024' },- arrayBuffer: async () => new Uint8Array([0x67, 0x6c, 0x54, 0x46]).buffer,- }));-}-const baseJob = { provider: 'replicate', params: { name: 'Me', visibility: 'private' } };beforeEach(() => {vi.clearAllMocks();- mockFetchGlb();providerMock.instance = null;});diff --git a/tests/api/webhooks-replicate.test.js b/tests/api/webhooks-replicate.test.jsindex 1b57a336c..c7ac8b24f 100644--- a/tests/api/webhooks-replicate.test.js+++ b/tests/api/webhooks-replicate.test.js@@ -55,6 +55,16 @@ vi.mock('../../api/_lib/avatars.js', () => ({createAvatar: createAvatarMock,}));+// The finalize stage fetches the result GLB through the shared guard (raw node+// http, not global fetch), so stub just that helper — and keep extractGlbUrl /+// isAllowedProviderResultUrl REAL so the webhook's actual host-allowlist gating+// is exercised here, not mocked away.+const fetchProviderGlbBufferMock = vi.fn(async () => Buffer.from(Buffer.alloc(256)));+vi.mock('../../api/_lib/provider-result-url.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, fetchProviderGlbBuffer: (...a) => fetchProviderGlbBufferMock(...a) };+});+// Don't actually fetch the result GLB URL — return a tiny fake buffer.// Snapshot fetch eagerly so each test file's tearDown restores its own// baseline regardless of cross-file worker ordering.diff --git a/tests/api/x402-mcp-replay-guard.test.js b/tests/api/x402-mcp-replay-guard.test.jsnew file mode 100644index 000000000..33c2033ba--- /dev/null+++ b/tests/api/x402-mcp-replay-guard.test.js@@ -0,0 +1,106 @@+// Replay guard for hand-rolled x402 endpoints (MCP servers + launchpad/invoke).+//+// The paidEndpoint() wrapper closes the verify→deliver→settle re-delivery window+// with a proof-hash reservation; the MCP servers and launchpad/invoke hand-roll+// that dance, so they share reservePaymentProof() from payment-identifier-server.+//+// Double-CHARGE is already prevented downstream (on-chain EIP-3009 nonce / Solana+// blockhash + the deterministic facilitator Idempotency-Key). These tests pin the+// remaining property: a captured/retried X-PAYMENT can't acquire the lock twice+// in the pre-settlement window, so it can't re-run the (often expensive) work for+// free — while a transient failure (release on any finish) stays retryable.+//+// Exercises the helper directly against the in-process Map fallback in+// idempotency-cache.js (no Redis in CI), matching x402-payment-identifier.test.js.++import { describe, it, expect, beforeEach } from 'vitest';++import * as cache from '../../api/_lib/x402/idempotency-cache.js';+import {+ reservePaymentProof,+ hashPaymentProof,+} from '../../api/_lib/x402/payment-identifier-server.js';++// A realistic base64 X-PAYMENT header — the helper hashes the exact header bytes.+function header(nonce) {+ return Buffer.from(+ JSON.stringify({+ x402Version: 2,+ scheme: 'exact',+ network: 'eip155:8453',+ payload: { authorization: { value: '1000', nonce } },+ }),+ 'utf8',+ ).toString('base64');+}++beforeEach(() => {+ cache._resetMemoryStore();+});++describe('reservePaymentProof', () => {+ it('no header → ok with a no-op release (free/bearer calls are never blocked)', async () => {+ const g = await reservePaymentProof('/api/mcp', undefined);+ expect(g.ok).toBe(true);+ await expect(g.release()).resolves.toBeUndefined();+ });++ it('first reservation wins; a concurrent duplicate of the same proof is blocked', async () => {+ const h = header('0xaaa');+ const first = await reservePaymentProof('/api/mcp', h);+ expect(first.ok).toBe(true);++ const dup = await reservePaymentProof('/api/mcp', h);+ expect(dup.ok).toBe(false);++ await first.release();+ });++ it('release frees the slot so the same payment can be retried (transient-failure path)', async () => {+ const h = header('0xretry');+ const first = await reservePaymentProof('/api/mcp', h);+ expect(first.ok).toBe(true);+ await first.release();++ const retry = await reservePaymentProof('/api/mcp', h);+ expect(retry.ok).toBe(true);+ await retry.release();+ });++ it('distinct payments do not collide', async () => {+ const a = await reservePaymentProof('/api/mcp', header('0x1'));+ const b = await reservePaymentProof('/api/mcp', header('0x2'));+ expect(a.ok).toBe(true);+ expect(b.ok).toBe(true);+ });++ it('same proof under different routes does not collide (route-namespaced key)', async () => {+ const h = header('0xroute');+ const a = await reservePaymentProof('/api/mcp', h);+ const b = await reservePaymentProof('/api/mcp-3d', h);+ expect(a.ok).toBe(true);+ expect(b.ok).toBe(true);+ });++ it('release is idempotent — a double release never re-deletes another claim', async () => {+ const h = header('0xidem');+ const g = await reservePaymentProof('/api/mcp', h);+ expect(g.ok).toBe(true);+ await g.release();+ await g.release(); // no-op, must not throw or free a future claim++ // A new claim taken after the double-release stays held.+ const next = await reservePaymentProof('/api/mcp', h);+ expect(next.ok).toBe(true);+ const dup = await reservePaymentProof('/api/mcp', h);+ expect(dup.ok).toBe(false);+ await next.release();+ });++ it('the reservation key is bound to the exact signed payment bytes', () => {+ const h = header('0xbind');+ expect(hashPaymentProof(h)).toBe(hashPaymentProof(h));+ expect(hashPaymentProof(h)).not.toBe(hashPaymentProof(header('0xother')));+ expect(hashPaymentProof(undefined)).toBeNull();+ });+});diff --git a/tests/auto-rig-ssrf.test.js b/tests/auto-rig-ssrf.test.jsnew file mode 100644index 000000000..bb2759731--- /dev/null+++ b/tests/auto-rig-ssrf.test.js@@ -0,0 +1,241 @@+// End-to-end SSRF guard on the two completion paths that fetch a provider URL+// without a webhook signature behind them: the browser regenerate-status poll and+// the cron sweep. A forged/compromised provider status() that returns a loopback+// or cloud-metadata resultGlbUrl must terminate the job cleanly — never persist+// the URL, never hand it to a finalize stage that would fetch it server-side.+//+// The provider is fully stubbed; no test ever touches a real network host. The+// real provider-result-url allowlist runs (not mocked) so this exercises the+// actual gate, while db/auth/finalize are mocked to observe the side effects.++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));+vi.mock('../api/_lib/sentry.js', () => ({ captureException: () => {} }));++// ── shared mutable state, set per-case ───────────────────────────────────────+const state = {+ pollJob: null,+ cronCandidates: [],+ statusReturn: null,+ pollUpdates: [],+ failJobCalls: [],+};++function resetState() {+ state.pollJob = null;+ state.cronCandidates = [];+ state.statusReturn = null;+ state.pollUpdates = [];+ state.failJobCalls = [];+}++// One sql mock serving both handlers, branching on the query text.+const sqlMock = vi.fn(async (strings, ...values) => {+ const text = (Array.isArray(strings) ? strings.join('?') : String(strings)).toLowerCase();+ if (text.includes('returning job_id')) return []; // cron reap — no zombies in these tests+ if (text.includes('update avatar_regen_jobs')) {+ if (text.includes('result_glb_url =')) {+ // Poll persist: set status, result_glb_url, error.+ state.pollUpdates.push({ status: values[0], result_glb_url: values[1], error: values[2] });+ return [];+ }+ if (text.includes("status = 'failed'")) {+ // Cron failJob: error, jobId, userId.+ state.failJobCalls.push({ error: values[0], jobId: values[1], userId: values[2] });+ return [];+ }+ return [];+ }+ if (text.includes('select') && text.includes('from avatar_regen_jobs')) {+ if (text.includes("mode = 'rerig'")) return state.cronCandidates; // cron candidate scan+ return state.pollJob ? [state.pollJob] : []; // poll single-job lookup+ }+ return [];+});+vi.mock('../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));++// Auth: an authenticated session user for the poll handler.+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: async () => ({ id: 'u1' }),+ authenticateBearer: async () => null,+ extractBearer: () => null,+ hasScope: () => true,+}));++// Provider: status() returns whatever the case configured.+const providerInstance = { status: vi.fn(async () => state.statusReturn) };+vi.mock('../api/_lib/regen-provider.js', () => ({+ getRegenProvider: async () => ({ name: 'replicate', instance: providerInstance }),+ getRegenProviderForJob: async () => ({ name: 'replicate', instance: providerInstance }),+ getRegenProviderByName: async () => ({ name: 'replicate', instance: providerInstance }),+ BYOK_REGEN_PROVIDERS: [],+}));++// Finalize stages: spies we assert are NOT called on a blocked URL.+const finalizeAutoRigStageMock = vi.fn(async () => ({ status: 'done', resultAvatarId: 'sib-1' }));+vi.mock('../api/_lib/auto-rig.js', () => ({+ finalizeAutoRigStage: (...a) => finalizeAutoRigStageMock(...a),+ rigInfoIsRigged: () => false,+}));+const finalizeReconstructStageMock = vi.fn(async () => ({ status: 'done', resultAvatarId: 'rec-1' }));+const pollRiggingStageMock = vi.fn(async () => ({ status: 'rigging' }));+vi.mock('../api/_lib/reconstruct-finalize.js', () => ({+ finalizeReconstructStage: (...a) => finalizeReconstructStageMock(...a),+ pollRiggingStage: (...a) => pollRiggingStageMock(...a),+}));++const { dispatch } = await import('../api/avatars/_actions.js');+const cronHandler = (await import('../api/cron/auto-rig-sweep.js')).default;++function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ headersSent: false,+ writableEnded: false,+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },+ getHeader(k) { return this._h[k.toLowerCase()]; },+ end(body) { this._body = body; this.writableEnded = true; },+ };+}++function pollReq(jobId) {+ return { method: 'GET', url: `/api/avatars/regenerate-status?jobId=${jobId}`, headers: {} };+}++const LOOPBACK = 'http://127.0.0.1/x.glb';+const METADATA = 'http://169.254.169.254/latest/meta-data/x.glb';+const VALID = 'https://pbxt.replicate.delivery/abc/x.glb';++beforeEach(() => {+ vi.clearAllMocks();+ resetState();+ process.env.CRON_SECRET = 'test-cron-secret';+});++describe('(a) browser-poll path — regenerate-status', () => {+ function baseJob() {+ return {+ job_id: 'poll-1',+ status: 'running',+ result_avatar_id: null,+ result_glb_url: null,+ error: null,+ provider: 'replicate',+ ext_job_id: 'ext-1',+ created_at: new Date().toISOString(),+ mode: 'rerig',+ params: { auto_rig: true },+ source_avatar_id: 'src-1',+ };+ }++ it('fails the job and persists NO url when the provider returns a loopback host', async () => {+ state.pollJob = baseJob();+ state.statusReturn = { status: 'done', resultGlbUrl: LOOPBACK };++ const res = makeRes();+ await dispatch('regenerate-status', pollReq('poll-1'), res);++ expect(res.statusCode).toBe(200);+ expect(state.pollUpdates).toHaveLength(1);+ expect(state.pollUpdates[0]).toEqual({+ status: 'failed',+ result_glb_url: null,+ error: 'provider returned a disallowed result url',+ });+ // The poisoned URL never reaches a finalize stage.+ expect(finalizeAutoRigStageMock).not.toHaveBeenCalled();+ expect(finalizeReconstructStageMock).not.toHaveBeenCalled();+ expect(pollRiggingStageMock).not.toHaveBeenCalled();+ });++ it('also blocks a cloud-metadata host', async () => {+ state.pollJob = baseJob();+ state.statusReturn = { status: 'done', resultGlbUrl: METADATA };++ await dispatch('regenerate-status', pollReq('poll-1'), makeRes());++ expect(state.pollUpdates[0].status).toBe('failed');+ expect(state.pollUpdates[0].result_glb_url).toBeNull();+ expect(finalizeAutoRigStageMock).not.toHaveBeenCalled();+ });++ it('lets a valid Replicate delivery URL through to finalize', async () => {+ state.pollJob = baseJob();+ state.statusReturn = { status: 'done', resultGlbUrl: VALID };++ await dispatch('regenerate-status', pollReq('poll-1'), makeRes());++ // Persisted with the real URL (auto-rig keeps it non-terminal: 'running').+ expect(state.pollUpdates).toHaveLength(1);+ expect(state.pollUpdates[0].result_glb_url).toBe(VALID);+ expect(state.pollUpdates[0].status).toBe('running');+ expect(finalizeAutoRigStageMock).toHaveBeenCalledOnce();+ expect(finalizeAutoRigStageMock.mock.calls[0][0]).toMatchObject({ glbUrl: VALID });+ });+});++describe('(b) cron sweep path — auto-rig-sweep', () => {+ function cronReq() {+ return { method: 'GET', url: '/api/cron/auto-rig-sweep', headers: { authorization: 'Bearer test-cron-secret' } };+ }+ function candidate() {+ return {+ job_id: 'cron-1',+ user_id: 'u1',+ source_avatar_id: 'src-1',+ ext_job_id: 'ext-1',+ status: 'running',+ result_glb_url: null,+ created_at: new Date().toISOString(),+ };+ }++ it('fails the job without finalizing when the provider returns a metadata host', async () => {+ state.cronCandidates = [candidate()];+ state.statusReturn = { status: 'done', resultGlbUrl: METADATA };++ const res = makeRes();+ await cronHandler(cronReq(), res);++ expect(res.statusCode).toBe(200);+ const summary = JSON.parse(res._body);+ expect(summary.failed).toBe(1);+ expect(state.failJobCalls).toHaveLength(1);+ expect(state.failJobCalls[0]).toMatchObject({+ jobId: 'cron-1',+ error: 'provider returned a disallowed result url',+ });+ expect(finalizeAutoRigStageMock).not.toHaveBeenCalled();+ });++ it('blocks a poisoned URL already stored on the row (fast path)', async () => {+ state.cronCandidates = [{ ...candidate(), result_glb_url: LOOPBACK }];+ // No status() needed — the row already carries the (poisoned) URL.++ const res = makeRes();+ await cronHandler(cronReq(), res);++ const summary = JSON.parse(res._body);+ expect(summary.failed).toBe(1);+ expect(state.failJobCalls[0]).toMatchObject({ error: 'provider returned a disallowed result url' });+ expect(finalizeAutoRigStageMock).not.toHaveBeenCalled();+ expect(providerInstance.status).not.toHaveBeenCalled();+ });++ it('still finalizes a valid Replicate delivery URL', async () => {+ state.cronCandidates = [candidate()];+ state.statusReturn = { status: 'done', resultGlbUrl: VALID };++ const res = makeRes();+ await cronHandler(cronReq(), res);++ const summary = JSON.parse(res._body);+ expect(summary.finalized).toBe(1);+ expect(state.failJobCalls).toHaveLength(0);+ expect(finalizeAutoRigStageMock).toHaveBeenCalledOnce();+ expect(finalizeAutoRigStageMock.mock.calls[0][0]).toMatchObject({ glbUrl: VALID });+ });+});diff --git a/tests/provider-result-url.test.js b/tests/provider-result-url.test.jsnew file mode 100644index 000000000..5f4cfe84e--- /dev/null+++ b/tests/provider-result-url.test.js@@ -0,0 +1,186 @@+// SSRF host-pinning for provider-returned GLB URLs. The auto-rig / reconstruct+// completion paths fetch a URL the provider hands back; a forged or compromised+// payload could point that fetch at cloud metadata, loopback, or an RFC1918+// address. These tests cover the two positive gates this module adds on top of+// ssrf-guard.js's IP/DNS checks: the scheme-validating extractor and the+// provider-host allowlist.++import { describe, it, expect, vi, beforeEach } from 'vitest';++// fetchProviderGlbBuffer delegates to ssrf-guard's pinned fetch (raw node http).+// Stub just that transport so the size-ceiling path can be exercised without a+// real socket; keep SsrfBlockedError real so `code === 'ssrf_blocked'` holds.+const pinnedFetchMock = vi.fn();+vi.mock('../api/_lib/ssrf-guard.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, fetchSafePublicUrlPinned: (...a) => pinnedFetchMock(...a) };+});++const {+ extractGlbUrl,+ isAllowedProviderResultUrl,+ assertProviderResultUrl,+ fetchProviderGlbBuffer,+ PROVIDER_RESULT_HOSTS,+ MAX_GLB_BYTES,+ SsrfBlockedError,+} = await import('../api/_lib/provider-result-url.js');++beforeEach(() => {+ vi.clearAllMocks();+});++describe('extractGlbUrl — only ever returns an http(s) string', () => {+ it('rejects non-http(s) string schemes', () => {+ expect(extractGlbUrl('file:///etc/passwd')).toBeNull();+ expect(extractGlbUrl('javascript:alert(1)')).toBeNull();+ expect(extractGlbUrl('gopher://x/1')).toBeNull();+ expect(extractGlbUrl('data:model/gltf-binary;base64,AAAA')).toBeNull();+ });++ it('rejects non-string / empty / numeric input', () => {+ expect(extractGlbUrl(42)).toBeNull();+ expect(extractGlbUrl(null)).toBeNull();+ expect(extractGlbUrl(undefined)).toBeNull();+ expect(extractGlbUrl('')).toBeNull();+ expect(extractGlbUrl({})).toBeNull();+ });++ it('rejects object/array members whose scheme is unsafe or non-string', () => {+ expect(extractGlbUrl({ url: 'gopher://x' })).toBeNull();+ expect(extractGlbUrl({ url: 169 })).toBeNull();+ expect(extractGlbUrl({ glb: 'file:///x.glb' })).toBeNull();+ expect(extractGlbUrl(['file:///a.glb', 'gopher://b'])).toBeNull();+ });++ it('returns a valid https string verbatim', () => {+ expect(extractGlbUrl('https://pbxt.replicate.delivery/x.glb')).toBe(+ 'https://pbxt.replicate.delivery/x.glb',+ );+ });++ it('prefers the .glb entry from an array, only among http(s) entries', () => {+ expect(extractGlbUrl(['https://a/x.glb', 'https://b/y.png'])).toBe('https://a/x.glb');+ // Non-glb http entries still resolve to the first http(s) member.+ expect(extractGlbUrl(['https://b/y.png', 'https://a/z.bin'])).toBe('https://b/y.png');+ });++ it('reads the conventional object keys (http(s) only)', () => {+ expect(extractGlbUrl({ mesh_url: 'https://pbxt.replicate.delivery/m.glb' })).toBe(+ 'https://pbxt.replicate.delivery/m.glb',+ );+ expect(extractGlbUrl({ model: 'https://replicate.delivery/out.glb' })).toBe(+ 'https://replicate.delivery/out.glb',+ );+ });+});++describe('isAllowedProviderResultUrl — host allowlist (webhook semantics)', () => {+ it('seeds the allowlist from the Replicate delivery hosts', () => {+ expect(PROVIDER_RESULT_HOSTS).toEqual(+ expect.arrayContaining(['replicate.delivery', 'replicate.com', 'pbxt.replicate.delivery']),+ );+ });++ it('allows exact and dot-suffix matches over https', () => {+ expect(isAllowedProviderResultUrl('https://replicate.delivery/x.glb')).toBe(true);+ expect(isAllowedProviderResultUrl('https://pbxt.replicate.delivery/a/b/x.glb')).toBe(true);+ // dot-suffix: a sub-subdomain of an allowed host.+ expect(isAllowedProviderResultUrl('https://edge.pbxt.replicate.delivery/x.glb')).toBe(true);+ expect(isAllowedProviderResultUrl('https://cdn.replicate.com/x.glb')).toBe(true);+ });++ it('rejects http:// even on an allowed host', () => {+ expect(isAllowedProviderResultUrl('http://replicate.delivery/x.glb')).toBe(false);+ expect(isAllowedProviderResultUrl('http://pbxt.replicate.delivery/x.glb')).toBe(false);+ });++ it('rejects look-alike and unrelated hosts', () => {+ expect(isAllowedProviderResultUrl('https://replicate.delivery.evil.com/x.glb')).toBe(false);+ expect(isAllowedProviderResultUrl('https://notreplicate.delivery/x.glb')).toBe(false);+ expect(isAllowedProviderResultUrl('https://evil.com/x.glb')).toBe(false);+ });++ it('rejects private / loopback / metadata hosts', () => {+ expect(isAllowedProviderResultUrl('http://127.0.0.1/x.glb')).toBe(false);+ expect(isAllowedProviderResultUrl('https://127.0.0.1/x.glb')).toBe(false);+ expect(isAllowedProviderResultUrl('http://169.254.169.254/latest/meta-data')).toBe(false);+ expect(isAllowedProviderResultUrl('http://10.0.0.5/x.glb')).toBe(false);+ expect(isAllowedProviderResultUrl('http://192.168.1.10/x.glb')).toBe(false);+ });++ it('never throws on malformed input', () => {+ expect(isAllowedProviderResultUrl('not a url')).toBe(false);+ expect(isAllowedProviderResultUrl('')).toBe(false);+ expect(isAllowedProviderResultUrl(null)).toBe(false);+ });+});++describe('assertProviderResultUrl', () => {+ it('returns the url on an allowed host', () => {+ const u = 'https://pbxt.replicate.delivery/x.glb';+ expect(assertProviderResultUrl(u)).toBe(u);+ });++ it('throws SsrfBlockedError (code ssrf_blocked, status 400) on a disallowed host', () => {+ for (const u of ['http://169.254.169.254/x.glb', 'https://evil.com/x.glb', 'http://127.0.0.1/x.glb']) {+ let thrown;+ try {+ assertProviderResultUrl(u);+ } catch (err) {+ thrown = err;+ }+ expect(thrown).toBeInstanceOf(SsrfBlockedError);+ expect(thrown.code).toBe('ssrf_blocked');+ expect(thrown.status).toBe(400);+ }+ });+});++describe('fetchProviderGlbBuffer — allowlist gate + size ceiling', () => {+ it('blocks a metadata/loopback/non-allowlisted host BEFORE opening any socket', async () => {+ for (const u of ['http://169.254.169.254/x.glb', 'https://localhost/x.glb', 'https://evil.com/x.glb']) {+ await expect(fetchProviderGlbBuffer(u)).rejects.toMatchObject({ code: 'ssrf_blocked' });+ }+ // The host gate runs first, so the pinned transport is never reached.+ expect(pinnedFetchMock).not.toHaveBeenCalled();+ });++ it('rejects an oversized content-length with the size error', async () => {+ pinnedFetchMock.mockResolvedValueOnce({+ ok: true,+ headers: { get: (k) => (k === 'content-length' ? String(MAX_GLB_BYTES + 1) : null) },+ arrayBuffer: async () => new ArrayBuffer(0),+ });+ await expect(+ fetchProviderGlbBuffer('https://pbxt.replicate.delivery/big.glb'),+ ).rejects.toThrow(/glb too large/);+ });++ it('rejects a non-ok response with the status error', async () => {+ pinnedFetchMock.mockResolvedValueOnce({+ ok: false,+ status: 502,+ headers: { get: () => null },+ arrayBuffer: async () => new ArrayBuffer(0),+ });+ await expect(+ fetchProviderGlbBuffer('https://pbxt.replicate.delivery/x.glb'),+ ).rejects.toThrow(/fetch glb: 502/);+ });++ it('returns the buffer for an allowed host within the size ceiling', async () => {+ const bytes = new Uint8Array([0x67, 0x6c, 0x54, 0x46]);+ pinnedFetchMock.mockResolvedValueOnce({+ ok: true,+ headers: { get: () => '4' },+ arrayBuffer: async () => bytes.buffer,+ });+ const buf = await fetchProviderGlbBuffer('https://pbxt.replicate.delivery/x.glb');+ expect(Buffer.isBuffer(buf)).toBe(true);+ expect(buf.equals(Buffer.from(bytes))).toBe(true);+ expect(pinnedFetchMock).toHaveBeenCalledOnce();+ // The pinned variant is used with allowHttp:false (forwarded/stored response).+ expect(pinnedFetchMock.mock.calls[0][2]).toMatchObject({ allowHttp: false });+ });+});diff --git a/workers/pump-fun-mcp/worker.js b/workers/pump-fun-mcp/worker.jsindex c3b24c712..a1c2a17ac 100644--- a/workers/pump-fun-mcp/worker.js+++ b/workers/pump-fun-mcp/worker.js@@ -510,9 +510,25 @@ export default {}const responses = [];- for (const msg of messages) {- const envelope = await dispatchRpc(msg, env);- if (envelope !== null) responses.push(envelope);+ try {+ for (const msg of messages) {+ const envelope = await dispatchRpc(msg, env);+ if (envelope !== null) responses.push(envelope);+ }+ } catch (err) {+ // dispatchRpc guards each tool call, but an unexpected throw before that+ // guard (a malformed message, a handler-builder failure) would otherwise+ // escape as an opaque Cloudflare 1101 — breaking the JSON-RPC contract.+ // Log the real cause to the worker log; hand the client a sanitized+ // -32603 envelope echoing the request id when it's unambiguous.+ console.error('[pump-fun-mcp] dispatch failed', err?.stack || err);+ return respond(+ rpcEnvelope(isBatch ? null : messages[0]?.id ?? null, null, {+ code: -32603,+ message: 'internal error',+ }),+ 500,+ );}// All-notification requests owe no body — 202 Accepted per Streamable HTTP.