Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: provider health checks, pump quote mint, x402 pay core

nirholas4b2e268f528e
diff --git a/api/_lib/chat-models.js b/api/_lib/chat-models.js
index 85bce2fe3..f0af1a09b 100644
--- a/api/_lib/chat-models.js
+++ b/api/_lib/chat-models.js
@@ -109,17 +109,21 @@ export const PROVIDER_MODEL_DEFAULTS = {
/**
* Provider order to try when none is explicitly requested ("auto"), ranked by
* first-attempt reliability under current operating conditions:
- * 1. groq — fast free tier that answers on the first attempt; the
- * common-case primary. Per-minute caps only.
- * 2. openrouter — free fallback (reliable Llama 3.3 70B; see DEFAULT_FREE_MODEL).
- * 3. anthropic — paid, highly reliable, but only present when a key is
- * configured (BYOK / host we-pay); skipped otherwise.
+ * 1. anthropic — paid, highly reliable, keyed in prod (host we-pay / BYOK).
+ * Leads the ladder so the common path resolves on attempt 0
+ * instead of burning the free tiers' rate limits first. Only
+ * present when a key is configured; skipped otherwise, which
+ * transparently falls back to the free-tier ordering below.
+ * 2. groq — fast free tier that answers on the first attempt. Per-minute
+ * caps only; the primary for anonymous/free traffic.
+ * 3. openrouter — free fallback (reliable Llama 3.3 70B; see DEFAULT_FREE_MODEL).
* 4. openai — LAST. Account is over quota (see operational note); only
* reached after everything else is exhausted.
* Providers without a configured key are skipped, so the effective ladder is
- * short in the common case.
+ * short in the common case. A provider in a health cooldown (see
+ * api/_lib/provider-health.js) is also skipped for the cooldown window.
*/
-export const DEFAULT_PROVIDER_ORDER = ['groq', 'openrouter', 'anthropic', 'openai'];
+export const DEFAULT_PROVIDER_ORDER = ['anthropic', 'groq', 'openrouter', 'openai'];
/**
* OpenRouter sibling models for per-model rate-limit failover. OpenRouter's
diff --git a/api/_lib/llm.js b/api/_lib/llm.js
index 4dae25f7b..149abbe20 100644
--- a/api/_lib/llm.js
+++ b/api/_lib/llm.js
@@ -5,10 +5,12 @@
// • Groq and OpenRouter are PLATFORM-FUNDED. The server holds those keys and
// callers use them for free. They are the default providers, tried in order.
//
-// • Anthropic is BYOK (bring-your-own-key). It is used ONLY when the caller
-// passes an explicit `anthropicKey` (e.g. an agent owner's own key). The
-// platform never depends on a server-side ANTHROPIC_API_KEY and never
-// hard-fails when it is absent — every flow degrades to the free providers.
+// • Anthropic is used when the caller passes an explicit BYOK `anthropicKey`
+// (e.g. an agent owner's own key), OR when the caller opts in with
+// `serverAnthropic: true` and a server `ANTHROPIC_API_KEY` is configured.
+// Both are OFF by default: a caller that passes neither never touches
+// Anthropic, and no flow hard-fails when the key is absent — every flow
+// still degrades to the free providers.
//
// Consolidated from the multi-provider fallback that already lived in
// api/persona/extract.js and api/persona/preview.js.
@@ -71,11 +73,19 @@ function openaiCompatProvider({ name, key, url, model, extraHeaders = {} }) {
};
}
-// Build the ordered provider chain for a request. BYOK Anthropic (when the
-// caller brings a key) is preferred, then the free platform providers.
-function providerChain({ anthropicKey, anthropicModel } = {}) {
+// Build the ordered provider chain for a request. Anthropic leads when keyed —
+// a caller-supplied BYOK key always, or the server `ANTHROPIC_API_KEY` when the
+// caller opts in with `serverAnthropic: true`. After that come the free platform
+// providers (Groq, then OpenRouter).
+//
+// `serverAnthropic` is opt-in (default off) so the historical BYOK-only policy
+// is unchanged for existing callers: the platform never *depends* on a server
+// Anthropic key and still degrades to the free providers when it's absent. The
+// persona endpoints opt in to get Anthropic-first ordered failover.
+function providerChain({ anthropicKey, anthropicModel, serverAnthropic = false } = {}) {
const chain = [];
if (anthropicKey) chain.push(anthropicProvider(anthropicKey, anthropicModel));
+ else if (serverAnthropic && env.ANTHROPIC_API_KEY) chain.push(anthropicProvider(env.ANTHROPIC_API_KEY, anthropicModel));
if (env.GROQ_API_KEY) {
chain.push(openaiCompatProvider({
name: 'groq',
@@ -112,8 +122,8 @@ export function llmConfigured(opts = {}) {
// Returns { text, provider, model, usage:{input,output}, raw }.
// Throws LlmUnavailableError when no provider is configured, or the last
// upstream error (with .status = 502) when every provider failed.
-export async function llmComplete({ system, user, maxTokens = 1024, anthropicKey = null, anthropicModel = null, timeoutMs = 30_000 }) {
- const chain = providerChain({ anthropicKey, anthropicModel });
+export async function llmComplete({ system, user, maxTokens = 1024, anthropicKey = null, anthropicModel = null, serverAnthropic = false, timeoutMs = 30_000 }) {
+ const chain = providerChain({ anthropicKey, anthropicModel, serverAnthropic });
if (!chain.length) throw new LlmUnavailableError();
let lastErr;
diff --git a/api/_lib/migrations/20260608000000_pump_quote_mint.sql b/api/_lib/migrations/20260608000000_pump_quote_mint.sql
new file mode 100644
index 000000000..996c3de28
--- /dev/null
+++ b/api/_lib/migrations/20260608000000_pump_quote_mint.sql
@@ -0,0 +1,19 @@
+-- Migration: record the quote (pairing) mint for each launched agent token.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260608000000_pump_quote_mint.sql
+-- Idempotent.
+--
+-- Agent tokens can now be launched USDC-paired (pump.fun v2 stable pairs) so the
+-- agent's USDC earnings → buyback → burn loop swaps in the same currency it
+-- earns. `quote_mint` stores that pairing:
+-- NULL → SOL-paired (native SOL / wrapped SOL) — the historical default.
+-- <mint>→ stable-paired; the quote SPL mint (e.g. the USDC mint).
+-- The buyback cron still derives the live quote from the on-chain bonding curve,
+-- so this column is for display, filtering, and analytics — existing rows stay
+-- NULL (SOL-paired) and are unaffected.
+
+begin;
+
+alter table pump_agent_mints
+ add column if not exists quote_mint text;
+
+commit;
diff --git a/api/_lib/provider-health.js b/api/_lib/provider-health.js
new file mode 100644
index 000000000..69be27cad
--- /dev/null
+++ b/api/_lib/provider-health.js
@@ -0,0 +1,54 @@
+// Provider-health circuit breaker for the LLM fallback chains.
+//
+// When an upstream LLM provider rate-limits (429) or errors (5xx / "Provider
+// returned error"), one throttle window otherwise turns into dozens of failed
+// requests: every incoming request re-picks the same throttled provider as its
+// primary, fails, fails over, and re-hits it again on the next request. This
+// records a short per-provider cooldown in the shared cache (Upstash Redis when
+// configured, in-memory otherwise) so subsequent requests skip a provider that
+// is currently throttling and go straight to a healthy one.
+//
+// Best-effort by design: a cache read/write failure never blocks a chat — the
+// helpers swallow errors and degrade to "no cooldown known", which is exactly
+// the pre-breaker behaviour.
+
+import { cacheGet, cacheSet } from './cache.js';
+
+const COOLDOWN_PREFIX = 'llm-cooldown:';
+// Long enough to ride out a typical per-minute rate-limit window, short enough
+// that a provider that has recovered is retried promptly.
+const DEFAULT_COOLDOWN_SECONDS = 45;
+
+/**
+ * Record that `provider` is unhealthy, so it is skipped for `seconds`. The
+ * cache TTL is the cooldown — presence of the key means "in cooldown", and it
+ * expires on its own. Fire-and-forget friendly; never throws.
+ */
+export async function markProviderCooldown(provider, seconds = DEFAULT_COOLDOWN_SECONDS) {
+ if (!provider) return;
+ try {
+ await cacheSet(`${COOLDOWN_PREFIX}${provider}`, { until: Date.now() + seconds * 1000 }, seconds);
+ } catch {
+ // Cache unavailable — degrade silently to no-cooldown.
+ }
+}
+
+/**
+ * Given a list of provider names, return the Set of those currently in a
+ * cooldown window. Reads are coalesced/memoized by the cache layer, so the
+ * handful of GETs collapse to roughly one cache round-trip. Never throws.
+ */
+export async function providersInCooldown(providers) {
+ const cooling = new Set();
+ await Promise.all(
+ providers.map(async (name) => {
+ try {
+ const hit = await cacheGet(`${COOLDOWN_PREFIX}${name}`);
+ if (hit) cooling.add(name);
+ } catch {
+ // Treat an unreadable key as "not in cooldown".
+ }
+ }),
+ );
+ return cooling;
+}
diff --git a/api/_lib/pump-quote.js b/api/_lib/pump-quote.js
new file mode 100644
index 000000000..302175038
--- /dev/null
+++ b/api/_lib/pump-quote.js
@@ -0,0 +1,43 @@
+// Quote-currency resolution for pump.fun agent-token launches.
+//
+// Agent tokens earn USDC (x402 payments → buyback vault) and burn via the
+// USDC-funded buyback. For that buyback to swap USDC → the agent's token, the
+// coin's bonding curve must be USDC-paired (quote mint = USDC). This module is
+// the single place that classifies a requested launch quote into SOL- vs
+// USDC-paired so the launch handlers, persistence, and UI stay consistent.
+//
+// Pure + dependency-light so it is unit-testable without the chain.
+
+import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET } from '../payments/_config.js';
+
+// Wrapped SOL — the canonical quote mint for SOL-paired coins under the v2
+// unified interface. On-chain SOL curves store `bonding_curve.quote_mint` as the
+// system default pubkey (all-zeros); both mean "SOL-paired".
+export const WSOL_MINT = 'So11111111111111111111111111111111111111112';
+const SYSTEM_DEFAULT_PUBKEY = '11111111111111111111111111111111';
+
+/** The USDC mint for a network ('mainnet' | 'devnet'). */
+export function usdcMintFor(network) {
+ return network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT;
+}
+
+/**
+ * Classify a requested launch quote mint.
+ *
+ * @param {object} args
+ * @param {string|null|undefined} args.quoteMint Requested quote mint (base58),
+ * or null/omitted for SOL-paired.
+ * @param {'mainnet'|'devnet'} [args.network='mainnet']
+ * @returns {{ isUsdc: boolean, quoteMint: string|null, label: 'SOL'|'USDC'|'TOKEN' }}
+ * - `quoteMint`: canonical value to persist — `null` for SOL-paired (so the
+ * SDK/curve uses native SOL), or the explicit mint for a stable pair.
+ * - `isUsdc`: true for any non-SOL quote (stable-paired).
+ * - `label`: display label; 'USDC' when it matches the network USDC mint.
+ */
+export function classifyLaunchQuote({ quoteMint, network = 'mainnet' } = {}) {
+ const q = typeof quoteMint === 'string' ? quoteMint.trim() : '';
+ if (!q || q === WSOL_MINT || q === SYSTEM_DEFAULT_PUBKEY) {
+ return { isUsdc: false, quoteMint: null, label: 'SOL' };
+ }
+ return { isUsdc: true, quoteMint: q, label: q === usdcMintFor(network) ? 'USDC' : 'TOKEN' };
+}
diff --git a/api/brain/chat.js b/api/brain/chat.js
index e282bb75e..827c4ce04 100644
--- a/api/brain/chat.js
+++ b/api/brain/chat.js
@@ -348,6 +348,18 @@ export default wrap(async function handler(req, res) {
tier: spec.tier,
})}\n\n`);
+ // Per-attempt abort budget. A hung native provider must not silently consume
+ // the whole maxDuration; cap each streamText attempt at the smaller of
+ // PER_ATTEMPT_MS or the remaining wall-clock so it aborts fast and hands off
+ // to the OpenRouter fallback while time remains. Mirrors the timeout-budget
+ // pattern in api/chat.js. TOTAL_BUDGET_MS leaves headroom under maxDuration=120
+ // so a primary-then-fallback pair both fit; PER_ATTEMPT_MS stays under the
+ // ~30s hang that previously near-timed-out the function.
+ const TOTAL_BUDGET_MS = 110_000;
+ const PER_ATTEMPT_MS = 25_000;
+ const deadline = t0 + TOTAL_BUDGET_MS;
+ const attemptBudgetMs = () => Math.max(1_000, Math.min(PER_ATTEMPT_MS, deadline - Date.now()));
+
let firstTokenMs = null;
// Drains one streamText attempt to the SSE response. firstTokenMs is set on
@@ -369,6 +381,10 @@ export default wrap(async function handler(req, res) {
// default of 2 means a quota-exhausted or credits-depleted key burns
// ~10–20s retrying before surfacing the error we already know to route around.
maxRetries: 0,
+ // Bound this attempt by the remaining wall-clock so a hung provider
+ // aborts fast and the outer chain can fall back while time remains. The
+ // abort surfaces as a thrown error (or via onError) handled below.
+ abortSignal: AbortSignal.timeout(attemptBudgetMs()),
onError: ({ error }) => {
streamErr = error;
},
@@ -472,8 +488,13 @@ function affordableBudget(err) {
function isProviderOutage(err) {
const status = Number(err?.statusCode || err?.cause?.statusCode || 0);
if (status === 429 || status === 402 || status >= 500) return true;
+ // An aborted attempt — our per-attempt timeout budget firing on a hung
+ // provider — is route-around-able: hand off to the OpenRouter fallback rather
+ // than surfacing a dead-air error to the user.
+ const name = err?.name || err?.cause?.name || '';
+ if (name === 'AbortError' || name === 'TimeoutError') return true;
const msg = `${err?.message || ''} ${err?.cause?.message || ''}`;
- return /quota|insufficient_quota|rate.?limit|too many requests|billing|exceeded your current|requires more credits|overloaded|temporarily unavailable|maxRetriesExceeded/i.test(msg);
+ return /quota|insufficient_quota|rate.?limit|too many requests|billing|exceeded your current|requires more credits|overloaded|temporarily unavailable|maxRetriesExceeded|abort|timed out|timeout/i.test(msg);
}
// One-line, length-capped error summary for server logs.
diff --git a/api/chat.js b/api/chat.js
index 85ef1a550..63c543fae 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -31,6 +31,7 @@ import { loadUserProviderKeys } from './_lib/provider-keys.js';
import { watsonxConfig, watsonxAuthHeaders } from './_lib/watsonx.js';
import { orchestrateConfig } from './_lib/orchestrate.js';
import { guardianConfig, governSend, sendCapUsd } from './_lib/granite-guardian.js';
+import { markProviderCooldown, providersInCooldown } from './_lib/provider-health.js';
import {
DEFAULT_FREE_MODEL,
PROVIDER_MODEL_DEFAULTS,
@@ -350,7 +351,13 @@ export default wrap(async (req, res) => {
userProviderKeys = await loadUserProviderKeys(urow?.provider_keys);
}
- let route = pickProvider(body.provider, body.model, userProviderKeys);
+ // Health cooldowns: a provider that recently 429'd / 5xx'd is skipped while it
+ // recovers, so a single throttle window doesn't cascade into request after
+ // request re-hitting the same dead provider. Best-effort — an unreadable
+ // cache yields an empty set (pre-breaker behaviour).
+ const cooldown = await providersInCooldown(Object.keys(PROVIDERS));
+
+ let route = pickProvider(body.provider, body.model, userProviderKeys, cooldown);
if (!route) {
return error(res, 503, 'chat_unavailable', 'no chat provider is configured');
}
@@ -382,7 +389,7 @@ export default wrap(async (req, res) => {
// Provider/model failover chain. The first entry is the picked route; if it
// returns 429 (rate-limit) or 5xx (provider down) we cycle through a
// pre-built fallback list before surfacing an error.
- let fallbackRoutes = buildFallbackChain(route, userProviderKeys);
+ let fallbackRoutes = buildFallbackChain(route, userProviderKeys, cooldown);
// Anonymous traffic must never fail over onto paid providers (OpenAI/
// Anthropic). Clamp the whole chain to the free-tier anon providers so a
// rate-limited free model degrades to another free model, never paid keys.
@@ -435,6 +442,9 @@ export default wrap(async (req, res) => {
captureException(err, { route: 'chat', stage: 'fetch', provider: route.name });
const reason = err?.name === 'AbortError' ? 'timed out' : err.message;
console.error(`[chat:${route.name}] upstream fetch failed:`, reason);
+ // An unreachable/timed-out provider is unhealthy — cool it down so the
+ // next request skips it instead of waiting on the same dead socket.
+ void markProviderCooldown(route.name);
// Network blip — try next route if one exists and time remains.
routeIdx++;
if (routeIdx < fallbackRoutes.length && Date.now() < deadline) {
@@ -443,8 +453,13 @@ export default wrap(async (req, res) => {
retriedTransient = false;
continue;
}
- return error(res, 502, 'upstream_unavailable', 'chat backend unreachable', {
+ // Every route was unreachable/timed out — that's transient capacity, not a
+ // permanent breakage. 503 + Retry-After so the client backs off and retries
+ // (the same contract as the rate-limit terminal below), never a hard 502.
+ res.setHeader('Retry-After', '20');
+ return error(res, 503, 'rate_limited', 'The AI chat is at capacity right now. Please try again in a few seconds.', {
providers_tried: providersTried(attempted),
+ retry_after: 20,
});
}
@@ -516,6 +531,8 @@ export default wrap(async (req, res) => {
if ((upstream.status === 429 || upstream.status >= 500) && canFailOver()) {
const text = await upstream.text().catch(() => '');
console.warn(`[chat:${route.name}] ${upstream.status} — falling over to ${fallbackRoutes[routeIdx + 1].name}/${fallbackRoutes[routeIdx + 1].model}: ${text.slice(0, 120)}`);
+ // Rate-limited or erroring upstream — cool it down for subsequent requests.
+ void markProviderCooldown(route.name);
routeIdx++;
route = fallbackRoutes[routeIdx];
includeTools = true;
@@ -569,20 +586,30 @@ export default wrap(async (req, res) => {
// surface the (provider-name-only) list of what was tried so the client can
// show "tried groq, openrouter…" without leaking upstream internals.
//
- // Status semantics: when the chain gave up because every route was
- // *rate-limited* (429 — the common free-tier exhaustion in prod), that's
- // capacity, not breakage. Return 503 with Retry-After so the client backs
- // off and retries instead of treating it as a hard upstream failure (502).
- const rateLimited = upstream.status === 429;
- if (rateLimited) res.setHeader('Retry-After', '20');
+ // Status semantics: an exhausted chain almost always means *capacity*, not
+ // a caller error. Broaden beyond a bare 429 — treat any all-routes-exhausted
+ // outcome that reads as throttling or an upstream outage (429, any 5xx, or a
+ // "Provider returned error" / overloaded / quota body) as capacity and return
+ // 503 + Retry-After so the client backs off and retries, never a hard 502.
+ // Only a genuine non-429 4xx (a request the next provider would also reject)
+ // stays a 502.
+ const atCapacity =
+ upstream.status === 429 ||
+ upstream.status >= 500 ||
+ /provider returned error|rate.?limit|over.?loaded|capacity|temporarily unavailable|quota|exceeded your current/i.test(
+ `${upstreamMessage} ${text}`,
+ );
+ // The final route failed too — cool it down so the next request skips it.
+ if (atCapacity) void markProviderCooldown(route.name);
+ if (atCapacity) res.setHeader('Retry-After', '20');
return error(
res,
- rateLimited ? 503 : 502,
- rateLimited ? 'rate_limited' : 'upstream_error',
- rateLimited
+ atCapacity ? 503 : 502,
+ atCapacity ? 'rate_limited' : 'upstream_error',
+ atCapacity
? 'The AI chat is at capacity right now. Please try again in a few seconds.'
: 'The AI chat provider is temporarily unavailable. Please try again in a moment.',
- { providers_tried: providersTried(attempted), ...(rateLimited ? { retry_after: 20 } : {}) },
+ { providers_tried: providersTried(attempted), ...(atCapacity ? { retry_after: 20 } : {}) },
);
}
@@ -708,30 +735,38 @@ async function governActions(actions, userMessage) {
// ── Provider selection ───────────────────────────────────────────────────────
-function pickProvider(requested, model, userKeys = {}) {
+function pickProvider(requested, model, userKeys = {}, cooldown = new Set()) {
const order = requested
? [requested, ...Object.keys(PROVIDERS).filter((p) => p !== requested)]
: DEFAULT_PROVIDER_ORDER;
- for (const name of order) {
- const cfg = PROVIDERS[name];
- const apiKey = userKeys[name] || process.env[cfg.envKey];
- if (!apiKey) continue;
- // watsonx needs both a key and a project/space scope to serve a model;
- // Orchestrate needs both a key and its endpoint URL.
- if (name === 'watsonx' && !watsonxConfig().configured) continue;
- if (name === 'orchestrate' && !orchestrateConfig().configured) continue;
- // CHAT_MODEL is an Anthropic-style id; it must not leak into a watsonx or
- // Orchestrate request (which expect their own model/agent ids). Those
- // providers use the client-named value or their own default.
- const chosenModel =
- (requested === name && model) ||
- (name === 'watsonx' || name === 'orchestrate'
- ? cfg.defaultModel
- : process.env.CHAT_MODEL || cfg.defaultModel);
- return makeRoute(name, cfg, apiKey, chosenModel);
- }
- return null;
+ // Two passes: first skip providers in a health cooldown, then — only if that
+ // leaves nothing configured — ignore cooldowns so a request never 503s purely
+ // because every healthy provider happens to be cooling down. An explicitly
+ // requested provider is never cooldown-skipped (the caller asked for it).
+ const resolve = (skipCooldown) => {
+ for (const name of order) {
+ const cfg = PROVIDERS[name];
+ const apiKey = userKeys[name] || process.env[cfg.envKey];
+ if (!apiKey) continue;
+ if (skipCooldown && name !== requested && cooldown.has(name)) continue;
+ // watsonx needs both a key and a project/space scope to serve a model;
+ // Orchestrate needs both a key and its endpoint URL.
+ if (name === 'watsonx' && !watsonxConfig().configured) continue;
+ if (name === 'orchestrate' && !orchestrateConfig().configured) continue;
+ // CHAT_MODEL is an Anthropic-style id; it must not leak into a watsonx or
+ // Orchestrate request (which expect their own model/agent ids). Those
+ // providers use the client-named value or their own default.
+ const chosenModel =
+ (requested === name && model) ||
+ (name === 'watsonx' || name === 'orchestrate'
+ ? cfg.defaultModel
+ : process.env.CHAT_MODEL || cfg.defaultModel);
+ return makeRoute(name, cfg, apiKey, chosenModel);
+ }
+ return null;
+ };
+ return resolve(true) || resolve(false);
}
// Build an ordered failover list starting with the primary route. Cycles
@@ -744,9 +779,14 @@ function pickProvider(requested, model, userKeys = {}) {
// model. Falling over from llama-3.3-70b:free → mistral-7b:free recovers
// from a single upstream burst without paying. Last resort is paid Anthropic
// so the user still gets a response.
+// Note: Groq deliberately has NO sibling beyond its own default. A second Groq
+// model is the *same account*, so when Groq throttles (the common prod failure)
+// a sibling slot is wasted re-hitting the throttled account instead of giving
+// the fallback slot to a different provider. Anthropic/OpenRouter siblings are
+// kept — those are per-model rate limits where a sibling model genuinely helps.
const FALLBACK_SIBLINGS = {
openrouter: OPENROUTER_SIBLINGS,
- groq: ['llama-3.3-70b-versatile', 'llama-3.1-8b-instant'],
+ groq: ['llama-3.3-70b-versatile'],
anthropic: ['claude-sonnet-4-6', 'claude-haiku-4-5-20251001'],
openai: ['gpt-4o-mini'],
};
@@ -767,7 +807,7 @@ function eligibleAsFallback(modelId) {
return meta.tools === true && !meta.moderationGated;
}
-function buildFallbackChain(primary, userKeys = {}) {
+function buildFallbackChain(primary, userKeys = {}, cooldown = new Set()) {
const chain = [primary];
const seen = new Set([`${primary.name}:${primary.model}`]);
@@ -790,8 +830,12 @@ function buildFallbackChain(primary, userKeys = {}) {
for (const m of FALLBACK_SIBLINGS[primary.name] || []) tryAdd(primary.name, m);
// (b) Other providers, in reliability order, at their configured default.
+ // Skip providers in a health cooldown so a globally-throttling provider isn't
+ // re-hit on every request — that's the mechanism that turns one throttle
+ // window into dozens of failures. The primary is always kept (position 0).
for (const name of DEFAULT_PROVIDER_ORDER) {
if (name === primary.name) continue;
+ if (cooldown.has(name)) continue;
tryAdd(name, PROVIDERS[name].defaultModel);
}
diff --git a/api/marketplace/[action].js b/api/marketplace/[action].js
index b6fa99d6f..04272bd29 100644
--- a/api/marketplace/[action].js
+++ b/api/marketplace/[action].js
@@ -836,13 +836,16 @@ async function handlePreview(req, res, id) {
res.end();
}
-// Build an ordered list of all configured preview routes. Priority:
-// 1. groq — free, fast, first-attempt reliable (per-minute caps only)
-// 2. openrouter — free Llama fallback
-// 3. anthropic — paid server key; reliable but costs money
+// Build an ordered list of all configured preview routes. Priority mirrors the
+// chat ladder (api/_lib/chat-models.js → DEFAULT_PROVIDER_ORDER): Anthropic-first
+// so the common path resolves on attempt 0 instead of burning the rate-limited
+// free tiers, then the free fallbacks, with the over-quota OpenAI account last.
+// 1. anthropic — paid server key; keyed in prod, most reliable first attempt
+// 2. groq — free, fast, first-attempt reliable (per-minute caps only)
+// 3. openrouter — free Llama fallback
// 4. openai — paid; last resort (account may be over quota)
function buildPreviewRoutes() {
- const order = ['groq', 'openrouter', 'anthropic', 'openai'];
+ const order = ['anthropic', 'groq', 'openrouter', 'openai'];
const routes = [];
for (const name of order) {
const cfg = PREVIEW_PROVIDERS[name];
diff --git a/api/persona/extract.js b/api/persona/extract.js
index 7902e95fa..9c8b7161d 100644
--- a/api/persona/extract.js
+++ b/api/persona/extract.js
@@ -1,94 +1,16 @@
// POST /api/persona/extract
// Synthesizes a structured persona JSON from a short onboarding interview.
-// Prefers Anthropic direct, falls back to OpenRouter then Groq so the
-// feature works regardless of which API keys are configured.
+// Runs through the shared LLM helper (api/_lib/llm.js) for Anthropic-first
+// ordered failover: server Anthropic → Groq → OpenRouter, so a single upstream
+// 429/5xx fails over to the next provider instead of returning a hard 502.
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { llmComplete, LlmUnavailableError } from '../_lib/llm.js';
const MAX_ANSWERS = 12;
const MAX_QA_CHARS = 1200;
-function resolveProvider() {
- const anthropicKey = process.env.ANTHROPIC_API_KEY;
- if (anthropicKey) {
- return {
- name: 'anthropic',
- model: 'claude-haiku-4-5-20251001',
- url: 'https://api.anthropic.com/v1/messages',
- headers: {
- 'content-type': 'application/json',
- 'x-api-key': anthropicKey,
- 'anthropic-version': '2023-06-01',
- },
- buildBody: (system, userMessage) => ({
- model: 'claude-haiku-4-5-20251001',
- max_tokens: 800,
- system,
- messages: [{ role: 'user', content: userMessage }],
- }),
- extractText: (r) => r.content?.[0]?.text || '',
- extractUsage: (r) => ({
- input: r.usage?.input_tokens ?? 0,
- output: r.usage?.output_tokens ?? 0,
- }),
- };
- }
- const orKey = process.env.OPENROUTER_API_KEY;
- if (orKey) {
- return {
- name: 'openrouter',
- model: 'anthropic/claude-3.5-haiku',
- url: 'https://openrouter.ai/api/v1/chat/completions',
- headers: {
- 'content-type': 'application/json',
- authorization: `Bearer ${orKey}`,
- 'HTTP-Referer': 'https://three.ws',
- 'X-Title': 'three.ws persona',
- },
- buildBody: (system, userMessage) => ({
- model: 'anthropic/claude-3.5-haiku',
- max_tokens: 800,
- messages: [
- { role: 'system', content: system },
- { role: 'user', content: userMessage },
- ],
- }),
- extractText: (r) => r.choices?.[0]?.message?.content || '',
- extractUsage: (r) => ({
- input: r.usage?.prompt_tokens ?? 0,
- output: r.usage?.completion_tokens ?? 0,
- }),
- };
- }
- const groqKey = process.env.GROQ_API_KEY;
- if (groqKey) {
- return {
- name: 'groq',
- model: 'llama-3.3-70b-versatile',
- url: 'https://api.groq.com/openai/v1/chat/completions',
- headers: {
- 'content-type': 'application/json',
- authorization: `Bearer ${groqKey}`,
- },
- buildBody: (system, userMessage) => ({
- model: 'llama-3.3-70b-versatile',
- max_tokens: 800,
- messages: [
- { role: 'system', content: system },
- { role: 'user', content: userMessage },
- ],
- }),
- extractText: (r) => r.choices?.[0]?.message?.content || '',
- extractUsage: (r) => ({
- input: r.usage?.prompt_tokens ?? 0,
- output: r.usage?.completion_tokens ?? 0,
- }),
- };
- }
- return null;
-}
-
async function resolveUser(req) {
const session = await getSessionUser(req);
if (session) return session.id;
@@ -167,16 +89,6 @@ const handler = wrap(async (req, res) => {
const body = await readJson(req);
const input = validateInput(body);
- const provider = resolveProvider();
- if (!provider) {
- return error(
- res,
- 503,
- 'config_missing',
- 'Persona extraction is not available right now. Please try again later.',
- );
- }
-
let userMessage;
if (input.mode === 'freeform') {
userMessage = `Analyze the following text and synthesize a persona JSON that captures the voice, personality, and communication patterns present in it.\n\n---\n${input.text}\n---`;
@@ -188,20 +100,24 @@ const handler = wrap(async (req, res) => {
}
const t0 = Date.now();
- const llmRes = await fetch(provider.url, {
- method: 'POST',
- headers: provider.headers,
- body: JSON.stringify(provider.buildBody(SYSTEM_PROMPT, userMessage)),
- });
-
- if (!llmRes.ok) {
- const detail = await llmRes.text();
- console.error(`[persona/extract] ${provider.name} error`, llmRes.status, detail);
- return error(res, 502, 'upstream_error', `${provider.name} API ${llmRes.status}`);
+ let completion;
+ try {
+ completion = await llmComplete({
+ system: SYSTEM_PROMPT,
+ user: userMessage,
+ maxTokens: 800,
+ serverAnthropic: true,
+ });
+ } catch (err) {
+ if (err instanceof LlmUnavailableError) {
+ return error(res, 503, 'config_missing',
+ 'Persona extraction is not available right now. Please try again later.');
+ }
+ console.error('[persona/extract] all providers failed', err?.status, err?.message);
+ return error(res, err?.status || 502, 'upstream_error', 'Persona extraction is briefly unavailable. Please try again.');
}
- const result = await llmRes.json();
- const raw = provider.extractText(result);
+ const raw = completion.text;
let persona;
try {
const stripped = raw
@@ -245,11 +161,11 @@ const handler = wrap(async (req, res) => {
: '',
};
- const usage = provider.extractUsage(result);
+ const usage = completion.usage;
return json(res, 200, {
persona: normalized,
- model: provider.model,
+ model: completion.model,
tokens_used: usage.input + usage.output,
tokens_in: usage.input,
tokens_out: usage.output,
diff --git a/api/persona/preview.js b/api/persona/preview.js
index e25dc833b..2cfedbe11 100644
--- a/api/persona/preview.js
+++ b/api/persona/preview.js
@@ -1,75 +1,15 @@
// POST /api/persona/preview
// Replies to a user message in the voice of a supplied persona JSON.
-// Prefers Anthropic direct, falls back to OpenRouter then Groq.
+// Runs through the shared LLM helper (api/_lib/llm.js) for Anthropic-first
+// ordered failover: server Anthropic → Groq → OpenRouter, so a single upstream
+// 429/5xx fails over to the next provider instead of returning a hard 502.
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
-import { env } from '../_lib/env.js';
+import { llmComplete, LlmUnavailableError } from '../_lib/llm.js';
const MAX_MSG_CHARS = 1500;
-function resolveProvider() {
- if (env.ANTHROPIC_API_KEY) {
- return {
- name: 'anthropic',
- model: 'claude-haiku-4-5-20251001',
- url: 'https://api.anthropic.com/v1/messages',
- headers: {
- 'content-type': 'application/json',
- 'x-api-key': env.ANTHROPIC_API_KEY,
- 'anthropic-version': '2023-06-01',
- },
- buildBody: (system, userMessage, maxTokens) => ({
- model: 'claude-haiku-4-5-20251001',
- max_tokens: maxTokens,
- system,
- messages: [{ role: 'user', content: userMessage }],
- }),
- extractText: (r) => (r.content?.[0]?.text || '').trim(),
- extractUsage: (r) => ({ input: r.usage?.input_tokens ?? 0, output: r.usage?.output_tokens ?? 0 }),
- };
- }
- if (env.OPENROUTER_API_KEY) {
- return {
- name: 'openrouter',
- model: 'anthropic/claude-3.5-haiku',
- url: 'https://openrouter.ai/api/v1/chat/completions',
- headers: {
- 'content-type': 'application/json',
- 'authorization': `Bearer ${env.OPENROUTER_API_KEY}`,
- 'HTTP-Referer': 'https://three.ws',
- 'X-Title': 'three.ws persona',
- },
- buildBody: (system, userMessage, maxTokens) => ({
- model: 'anthropic/claude-3.5-haiku',
- max_tokens: maxTokens,
- messages: [{ role: 'system', content: system }, { role: 'user', content: userMessage }],
- }),
- extractText: (r) => (r.choices?.[0]?.message?.content || '').trim(),
- extractUsage: (r) => ({ input: r.usage?.prompt_tokens ?? 0, output: r.usage?.completion_tokens ?? 0 }),
- };
- }
- if (env.GROQ_API_KEY) {
- return {
- name: 'groq',
- model: 'llama-3.3-70b-versatile',
- url: 'https://api.groq.com/openai/v1/chat/completions',
- headers: {
- 'content-type': 'application/json',
- 'authorization': `Bearer ${env.GROQ_API_KEY}`,
- },
- buildBody: (system, userMessage, maxTokens) => ({
- model: 'llama-3.3-70b-versatile',
- max_tokens: maxTokens,
- messages: [{ role: 'system', content: system }, { role: 'user', content: userMessage }],
- }),
- extractText: (r) => (r.choices?.[0]?.message?.content || '').trim(),
- extractUsage: (r) => ({ input: r.usage?.prompt_tokens ?? 0, output: r.usage?.completion_tokens ?? 0 }),
- };
- }
- return null;
-}
-
async function resolveUser(req) {
const session = await getSessionUser(req);
if (session) return session.id;
@@ -126,33 +66,30 @@ const handler = wrap(async (req, res) => {
const body = validateBody(await readJson(req));
- const provider = resolveProvider();
- if (!provider) {
- return error(res, 503, 'config_missing',
- 'No LLM provider configured. Set OPENROUTER_API_KEY, GROQ_API_KEY, or ANTHROPIC_API_KEY.');
- }
-
const system = buildSystemPrompt(body.persona);
const t0 = Date.now();
- const llmRes = await fetch(provider.url, {
- method: 'POST',
- headers: provider.headers,
- body: JSON.stringify(provider.buildBody(system, body.user_message, 220)),
- });
-
- if (!llmRes.ok) {
- const detail = await llmRes.text();
- console.error(`[persona/preview] ${provider.name} error`, llmRes.status, detail);
- return error(res, 502, 'upstream_error', `${provider.name} API ${llmRes.status}`);
+ let completion;
+ try {
+ completion = await llmComplete({
+ system,
+ user: body.user_message,
+ maxTokens: 220,
+ serverAnthropic: true,
+ });
+ } catch (err) {
+ if (err instanceof LlmUnavailableError) {
+ return error(res, 503, 'config_missing',
+ 'No LLM provider configured. Set ANTHROPIC_API_KEY, GROQ_API_KEY, or OPENROUTER_API_KEY.');
+ }
+ console.error('[persona/preview] all providers failed', err?.status, err?.message);
+ return error(res, err?.status || 502, 'upstream_error', 'Persona preview is briefly unavailable. Please try again.');
}
- const result = await llmRes.json();
- const reply = provider.extractText(result);
- const usage = provider.extractUsage(result);
+ const usage = completion.usage;
return json(res, 200, {
- reply,
- model: provider.model,
+ reply: completion.text,
+ model: completion.model,
tokens_used: usage.input + usage.output,
tokens_in: usage.input,
tokens_out: usage.output,
diff --git a/api/pump/[action].js b/api/pump/[action].js
index 83c7204c1..69b07059e 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -93,6 +93,7 @@ import {
SOLANA_USDC_MINT_DEVNET,
toUsdcAtomics,
} from '../payments/_config.js';
+import { classifyLaunchQuote, usdcMintFor } from '../_lib/pump-quote.js';
const TOKEN_PROGRAM_ID = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
@@ -893,9 +894,12 @@ const launchPrepSchema = z
buyback_bps: z.number().int().min(0).max(10_000).default(0),
sol_buy_in: z.number().nonnegative().max(50).default(0), // SOL-paired initial buy, capped 50 SOL
usdc_buy_in: z.number().nonnegative().max(1_000_000).default(0), // USDC-paired initial buy
- // Optional quote mint — when provided and non-WSOL (e.g. USDC), the coin
- // is created as a USDC-paired V2 coin using createV2AndBuyV2Instructions.
- // When omitted, the coin is SOL-paired (existing behaviour).
+ // Quote currency for the coin. `quote_currency: 'usdc'` is the friendly
+ // form — the server resolves the network-correct USDC mint. `quote_mint`
+ // is the explicit form (any non-WSOL mint → stable-paired v2 coin via
+ // createV2AndBuyV2Instructions). When neither is set, the coin is
+ // SOL-paired (existing behaviour). quote_currency wins when both appear.
+ quote_currency: z.enum(['sol', 'usdc']).optional(),
quote_mint: z.string().min(32).max(44).optional(),
// Optional client-ground vanity mint address. When provided, the client
// already holds the secret key locally and will co-sign in the wallet —
@@ -1067,7 +1071,18 @@ async function handleLaunchPrep(req, res) {
const isAgent = body.coin_type === 'agent';
const effBuyback = isAgent ? body.buyback_bps : 0;
- const launchQuoteMint = body.quote_mint ? solanaPubkey(body.quote_mint) : null;
+ // Resolve the quote pairing: null → SOL-paired; an explicit mint (e.g. USDC)
+ // → stable-paired so the agent's USDC buyback can swap+burn natively. The
+ // friendly `quote_currency` ('sol'|'usdc') wins and resolves the
+ // network-correct USDC mint; otherwise an explicit `quote_mint` is used.
+ const requestedQuoteMint =
+ body.quote_currency === 'usdc'
+ ? usdcMintFor(body.network)
+ : body.quote_currency === 'sol'
+ ? null
+ : body.quote_mint;
+ const quote = classifyLaunchQuote({ quoteMint: requestedQuoteMint, network: body.network });
+ const launchQuoteMint = quote.quoteMint ? solanaPubkey(quote.quoteMint) : null;
const instructions = await buildLaunchInstructions({
sdk, BN, mint, creator, signer,
name: body.name, symbol: body.symbol, uri: body.uri,
@@ -1116,6 +1131,7 @@ async function handleLaunchPrep(req, res) {
network: body.network,
buyback_bps: effBuyback,
coin_type: body.coin_type,
+ quote_mint: quote.quoteMint, // null = SOL-paired; else the stable quote mint
prep_id: prepId,
})}::jsonb,
${expiresAt}
@@ -1135,6 +1151,8 @@ async function handleLaunchPrep(req, res) {
network: body.network,
buyback_bps: effBuyback,
coin_type: body.coin_type,
+ quote_mint: quote.quoteMint,
+ quote_currency: quote.label,
expires_at: expiresAt.toISOString(),
instructions: mintKeypair
? 'Decode tx_base64 as VersionedTransaction. Sign with the mint keypair (mint_secret_key_b64) AND the user wallet, submit, then POST /api/pump/launch-confirm with the tx_signature.'
@@ -1199,11 +1217,11 @@ async function handleLaunchConfirm(req, res) {
const agentAuthority = p.creator_address || p.wallet_address;
const [row] = await sql`
insert into pump_agent_mints
- (agent_id, user_id, network, mint, name, symbol, metadata_uri, agent_authority, buyback_bps)
+ (agent_id, user_id, network, mint, name, symbol, metadata_uri, agent_authority, buyback_bps, quote_mint)
values
(${p.agent_id}, ${user.id}, ${p.network}, ${p.mint},
- ${p.name}, ${p.symbol}, ${metadataUri}, ${agentAuthority}, ${p.buyback_bps})
- returning id, mint, network, buyback_bps, created_at
+ ${p.name}, ${p.symbol}, ${metadataUri}, ${agentAuthority}, ${p.buyback_bps}, ${p.quote_mint ?? null})
+ returning id, mint, network, buyback_bps, quote_mint, created_at
`;
await sql`delete from agent_registrations_pending where id=${pending.id}`;
@@ -1307,6 +1325,12 @@ const launchAgentSchema = z
network: z.enum(['mainnet', 'devnet']).default('mainnet'),
buyback_bps: z.number().int().min(0).max(10_000).default(0),
sol_buy_in: z.number().nonnegative().max(50).default(0),
+ // USDC-paired agent coins: pass `quote_mint` (the USDC mint) to create a
+ // stable-paired curve, and `usdc_buy_in` for an optional USDC dev buy. The
+ // agent custodial wallet must hold that USDC (checked in the preflight).
+ usdc_buy_in: z.number().nonnegative().max(1_000_000).default(0),
+ quote_currency: z.enum(['sol', 'usdc']).optional(),
+ quote_mint: z.string().min(32).max(44).optional(),
mint_address: z.string().min(32).max(44).optional(),
mint_secret_key_b64: z.string().min(20).optional(),
coin_type: z.enum(['regular', 'mayhem', 'agent']).default('agent'),
@@ -1390,10 +1414,27 @@ async function handleLaunchAgent(req, res) {
`;
if (existing) return error(res, 409, 'conflict', 'mint already registered');
+ // Resolve the quote pairing. Agent coins are SOL-paired by default; pass
+ // `quote_currency: 'usdc'` (or an explicit `quote_mint`) to launch a
+ // stable-paired coin whose USDC buyback swaps natively.
+ const requestedQuoteMint =
+ body.quote_currency === 'usdc'
+ ? usdcMintFor(body.network)
+ : body.quote_currency === 'sol'
+ ? null
+ : body.quote_mint;
+ const quote = classifyLaunchQuote({ quoteMint: requestedQuoteMint, network: body.network });
+ const launchQuoteMint = quote.quoteMint ? solanaPubkey(quote.quoteMint) : null;
+
// Pre-flight: make sure the agent wallet can afford the launch.
const conn = solanaConnection(body.network);
const PUMP_BASE_LAMPORTS = Math.floor(0.022 * LAMPORTS_PER_SOL);
- const initialBuyLamports = Math.floor((body.sol_buy_in || 0) * LAMPORTS_PER_SOL);
+ // SOL always covers rent + fees. A SOL dev buy adds to the requirement; a USDC
+ // dev buy is funded from the wallet's USDC balance (checked separately), so it
+ // does not add to the SOL requirement.
+ const initialBuyLamports = quote.isUsdc
+ ? 0
+ : Math.floor((body.sol_buy_in || 0) * LAMPORTS_PER_SOL);
const requiredLamports = PUMP_BASE_LAMPORTS + initialBuyLamports;
let balanceLamports = 0;
try {
@@ -1410,6 +1451,29 @@ async function handleLaunchAgent(req, res) {
);
}
+ // USDC dev buy: the custodial wallet must hold the USDC it will spend, or the
+ // create+buy reverts on-chain. Verify up front so it fails cleanly here.
+ if (quote.isUsdc && body.usdc_buy_in > 0) {
+ const needAtomics = BigInt(Math.round(body.usdc_buy_in * 1_000_000));
+ let haveAtomics = 0n;
+ try {
+ const { getAssociatedTokenAddressSync } = await import('@solana/spl-token');
+ const usdcAta = getAssociatedTokenAddressSync(launchQuoteMint, creator, true);
+ const bal = await conn.getTokenAccountBalance(usdcAta);
+ haveAtomics = BigInt(bal?.value?.amount ?? 0);
+ } catch {
+ haveAtomics = 0n; // missing/closed ATA → treat as zero balance
+ }
+ if (haveAtomics < needAtomics) {
+ return error(
+ res,
+ 402,
+ 'insufficient_usdc',
+ `agent wallet holds ${(Number(haveAtomics) / 1e6).toFixed(2)} USDC, needs ${body.usdc_buy_in.toFixed(2)} USDC for the dev buy — deposit USDC to ${creator.toBase58()} or set usdc_buy_in to 0`,
+ );
+ }
+ }
+
const { sdk, BN } = await getPumpSdk({ network: body.network });
const isMayhem = body.coin_type === 'mayhem';
@@ -1420,6 +1484,8 @@ async function handleLaunchAgent(req, res) {
sdk, BN, mint, creator,
name: body.name, symbol: body.symbol, uri: body.uri,
solBuyIn: body.sol_buy_in,
+ usdcBuyIn: body.usdc_buy_in,
+ quoteMint: launchQuoteMint,
isMayhem,
});
@@ -1475,12 +1541,12 @@ async function handleLaunchAgent(req, res) {
const mintAddr = mint.toBase58();
const [row] = await sql`
insert into pump_agent_mints
- (agent_id, user_id, network, mint, name, symbol, metadata_uri, agent_authority, buyback_bps)
+ (agent_id, user_id, network, mint, name, symbol, metadata_uri, agent_authority, buyback_bps, quote_mint)
values
(${resolvedAgentId}, ${user.id}, ${body.network}, ${mintAddr},
- ${body.name}, ${body.symbol}, ${body.uri}, ${creator.toBase58()}, ${effBuyback})
+ ${body.name}, ${body.symbol}, ${body.uri}, ${creator.toBase58()}, ${effBuyback}, ${quote.quoteMint ?? null})
on conflict (mint, network) do nothing
- returning id, mint, network, buyback_bps, created_at
+ returning id, mint, network, buyback_bps, quote_mint, created_at
`;
await sql`
@@ -1496,6 +1562,9 @@ async function handleLaunchAgent(req, res) {
signature,
network: body.network,
sol_buy_in: body.sol_buy_in || 0,
+ usdc_buy_in: body.usdc_buy_in || 0,
+ quote_mint: quote.quoteMint,
+ quote_currency: quote.label,
buyback_bps: effBuyback,
coin_type: body.coin_type,
source: 'studio_agent_wallet',
@@ -1523,6 +1592,8 @@ async function handleLaunchAgent(req, res) {
network: body.network,
buyback_bps: effBuyback,
coin_type: body.coin_type,
+ quote_mint: quote.quoteMint,
+ quote_currency: quote.label,
pump_agent_mint: row || null,
explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,
pumpfun_url: `https://pump.fun/coin/${mintAddr}`,
diff --git a/data/rss/items.json b/data/rss/items.json
index df8acce37..ef8c93bda 100644
--- a/data/rss/items.json
+++ b/data/rss/items.json
@@ -1,6 +1,25 @@
{
"_readme": "Curated RSS items for https://three.ws/rss/announcements.xml. Edit this file to control exactly what HackerNoon (and any RSS reader) sees. Each entry needs: id (stable slug), title, date (ISO 8601), body_html. Optional: link, author, summary, tags. Items are served newest-first by date; cap is 80. Last merged from data/archives/trythreews_tweets_2026-06-03.json on 2026-06-05 (102 total items, merged June 2026 posts).",
"items": [
+ {
+ "id": "three-ws-first-month-retrospective",
+ "slug": "three-ws-first-month-3d-agent-layer",
+ "title": "One Month In: How three.ws Built the 3D Agent Layer of the Internet",
+ "date": "2026-06-08T12:00:00.000Z",
+ "author": "three.ws",
+ "summary": "In one month, three.ws went from launch to global coverage: browser-native 3D AI agents listed across major exchanges and data platforms, deployed on four hyperscale clouds, live in Anthropic's MCP Registry, and covered from CoinMarketCap to Vogue. A look back at 30 days of shipping.",
+ "body_html": "<p><strong>One month.</strong> On May 1, 2026, three.ws went live with a simple conviction: AI agents should not be trapped in a text box. They should have a body, a wallet, memory, and an identity that lives on-chain. Thirty days later, that conviction is listed across the world's largest exchanges and data platforms, deployed on four hyperscale clouds, published in Anthropic's official MCP Registry, and written up everywhere from CoinMarketCap to Vogue. Here is what one month of relentless shipping looks like.</p>\n<h2>The build never stopped</h2>\n<p>The team shipped in public, nearly every day. The core product landed first: a single <code>&lt;agent-3d&gt;</code> web component that drops a browser-native 3D AI agent onto any page, complete with an LLM brain, memory, real-time emotion blending, physical DOM awareness, and a verifiable Solana identity.</p>\n<p>From there the surface area only grew:</p>\n<ul>\n<li><strong>Solana wallets and x402 payments.</strong> Agents got real wallets and a pay-per-call endpoint. Every tool call can trigger a signed USDC payment, settled on-chain.</li>\n<li><strong>pump.fun skills.</strong> Swap, create coins, collect fees, and trade, all as skills an agent calls autonomously. The team even reverse-engineered the agent-payments SDK so agents can fund their own buybacks.</li>\n<li><strong>Real-time voice.</strong> Cloned voice, accurate lip-sync, and live voice chat where agents listen, reason, and respond out loud.</li>\n<li><strong>The Animations and Poses Studio.</strong> Body language and movement in a few clicks instead of tedious frame-by-frame animation.</li>\n<li><strong>The embed editor.</strong> Live preview against your real site, device frames, voice, chat, AR, and a transparent background, all from one screen.</li>\n</ul>\n<h2>Partnerships most teams take years to earn</h2>\n<p>In a single month, three.ws became an official partner of the companies that define enterprise computing:</p>\n<ul>\n<li><strong>IBM</strong> Business Partner, powering text and image to 3D model generation.</li>\n<li><strong>AWS</strong> Technology Partner, live on AWS Marketplace, with a contribution published on the AWS Builder Center blog.</li>\n<li><strong>Google Cloud</strong> for expanded 3D rendering compute and the Google Cloud for Web3 Startups program.</li>\n<li><strong>Alibaba Cloud</strong> partner, live on the International Marketplace across 200+ countries.</li>\n<li><strong>Coinbase</strong> verified x402 Bazaar service provider, letting agents discover, pay for, and call any x402 service in USDC.</li>\n<li><strong>Anthropic</strong>, with multiple MCP servers live in the official MCP Registry, usable in Claude and any MCP client.</li>\n</ul>\n<h2>Where you can find three.ws now</h2>\n<p>The result of all that work is a footprint that already spans the internet. In one month, three.ws and the <strong>$three</strong> coin have appeared across:</p>\n<p><strong>Exchanges and market data:</strong> <a href=\"https://jup.ag/tokens/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump\" rel=\"noopener\">Jupiter</a>, <a href=\"https://web3.binance.com/en/token/sol/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump\" rel=\"noopener\">Binance Wallet</a>, and <a href=\"https://www.coingecko.com/en/coins/three-ws\" rel=\"noopener\">CoinGecko</a>.</p>\n<p><strong>Developer registries and packages:</strong> the <a href=\"https://registry.modelcontextprotocol.io/?q=threews\" rel=\"noopener\">Anthropic MCP Registry</a>, <a href=\"https://www.npmjs.com/package/three.ws\" rel=\"noopener\">npm</a>, and PulseMCP.</p>\n<p><strong>Press and media:</strong> <a href=\"https://coinmarketcap.com/community/articles/6a226647c17eac2629024fc8/\" rel=\"noopener\">CoinMarketCap</a>, <a href=\"https://www.mexc.com/news/1115820\" rel=\"noopener\">MEXC News</a>, <a href=\"https://hackernoon.com/threews-earns-a-781-proof-of-usefulness-score-by-building-embeddable-3d-ai-agents\" rel=\"noopener\">HackerNoon</a> with a 781 Proof of Usefulness score, Vogue's Photo Vogue, the Wall Street Journal, and a podcast on Spotify.</p>\n<h2>Recognition from the people who watch closely</h2>\n<p>The market intelligence agent <a href=\"https://x.com/aixbt_agent\" rel=\"noopener\">aixbt</a> put it plainly: three's recent moves with IBM, the Anthropic MCP Registry, and Coinbase rails put real distance between it and other Solana AI plays. three.ws also earned W3C membership and contributed to the Agent Identity Registry Protocol, then entered both the Solana Frontier Hackathon via Colosseum and the MeDo Hackathon.</p>\n<h2>Built by a team that ships</h2>\n<p>None of this came from a roadmap deck. It came from shipping, in public, every single day, and wiring every feature end to end. The team committed to a public stats page covering x402 volume, unique users, animations, and memory, because the open nature of on-chain data means the numbers can speak for themselves.</p>\n<p>One month in, three.ws is the 3D agent layer of the internet. The only coin is <strong>$three</strong>. Contract address: <code>FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump</code>.</p>\n<p>And this was just the warm up. <a href=\"https://three.ws\" rel=\"noopener\">three.ws</a></p>",
+ "tags": [
+ "retrospective",
+ "milestones",
+ "press",
+ "partnerships",
+ "mcp",
+ "x402",
+ "solana",
+ "three"
+ ]
+ },
{
"id": "cmc-mcp-registry-article",
"title": "three.ws Brings Autonomous Payments and 3D Generation to Anthropic's Official MCP Registry",
diff --git a/docs/demo-routes.md b/docs/demo-routes.md
index fb77e398b..daae68bc3 100644
--- a/docs/demo-routes.md
+++ b/docs/demo-routes.md
@@ -1,24 +1,31 @@
# Demo routes
The canonical map of every `/demo/*` and `/demos/*` route as of
-2026-05-27. Update whenever a route is added, removed, or moved.
+2026-06-08. Update whenever a route is added, removed, or moved.
The demo namespace splits in two:
-- `/demo/<slug>/` — full standalone demos that own their URL space
- (multiple sub-pages, dynamic segments). Each lives in
+- `/demo` and `/demo/<slug>/` — full standalone demos that own their URL
+ space (multiple sub-pages, dynamic segments). `/demo` (no slug) is the
+ agent-economy demo (`pages/demo-economy.html`); the rest live in
`public/demo/<slug>/`.
-- `/demos/<slug>` — single-page lab demos. Index hub is
- `/demos/`. Each lives in `public/demos/<slug>.html`.
+- `/demos/<slug>` — single-page lab demos. Index hub is `/demos/`; the
+ agent-interaction sub-lab is `/demos/agents/`. Each lives in
+ `public/demos/<slug>.html`.
Production routing is in [vercel.json](../vercel.json); the matching
Vite dev-server middleware is in [vite.config.js](../vite.config.js).
Both must be kept in sync.
+Every row below was verified against the live Vite dev server
+(`npm run dev`, port 3000) with `curl -sIL`, not read from config alone.
+See [Verification notes](#verification-notes-2026-06-08) at the end.
+
## Routes
| Route | Page file | What it does |
|---|---|---|
+| `/demo` | `pages/demo-economy.html` | Agent Economy demo — two AI agents pay each other on-chain. |
| `/demo/coin` | `public/demo/coin/index.html` | Lottery + reflection demo on a single Pump.fun coin (real-time holder feed, payout history). |
| `/demo/coin/<mint>` | `public/demo/coin/index.html` | Same page hydrated for a specific base58 mint address (32–44 chars). |
| `/demo/avatar-os/` | `public/demo/avatar-os/index.html` | OSS avatar pipeline hub linking to the four sub-pages below. |
@@ -54,10 +61,55 @@ Both must be kept in sync.
| `/demos/voice-clone` | `public/demos/voice-clone.html` | Voice cloning demo. |
| `/demos/walk-embed-sdk` | `public/demos/walk-embed-sdk.html` | Walk animation embed via SDK. |
-The legacy `/brain`, `/lipsync`, `/lipsync/mic`
-shortcuts in `vercel.json` still resolve to the `/demos/*.html` files
-above. They predate the `/demos/` namespace and are kept for backward
-compatibility — prefer the `/demos/<slug>` form for new links.
+`public/demos/404.html` (`/demos/404`) is the lab's designed not-found
+page, not a content demo — the `/demos/` index also embeds it as a
+hidden empty-state. It is intentionally omitted from the table above.
+
+The legacy `/lipsync`, `/lipsync/mic` shortcuts in `vercel.json` still
+resolve to the `/demos/lipsync-*.html` files above. They predate the
+`/demos/` namespace and are kept for backward compatibility — prefer the
+`/demos/<slug>` form for new links.
+
+### Agent interaction lab — `/demos/agents/*`
+
+Single-purpose demos of an avatar reacting to the page. Index hub is
+`/demos/agents/` (`public/demos/agents/index.html`), linked from the main
+`/demos/` index. Each page lives at `public/demos/agents/<slug>.html` and
+is served by the `/demos/agents/<slug>` rewrite.
+
+| Route | Page file | What it does |
+|---|---|---|
+| `/demos/agents/auto-rig` | `public/demos/agents/auto-rig.html` | Auto-rigging an imported mesh. |
+| `/demos/agents/builds-button` | `public/demos/agents/builds-button.html` | Agent assembles a CTA button. |
+| `/demos/agents/climb-title` | `public/demos/agents/climb-title.html` | Agent climbs the page title. |
+| `/demos/agents/cursor-follower` | `public/demos/agents/cursor-follower.html` | Agent tracks the cursor. |
+| `/demos/agents/face-mocap` | `public/demos/agents/face-mocap.html` | Webcam face mocap drives the avatar. |
+| `/demos/agents/fall-from-top` | `public/demos/agents/fall-from-top.html` | Agent drops in from the top of the viewport. |
+| `/demos/agents/falls-asleep` | `public/demos/agents/falls-asleep.html` | Idle agent falls asleep. |
+| `/demos/agents/gemini-live` | `public/demos/agents/gemini-live.html` | Live conversation via Gemini. |
+| `/demos/agents/high-five` | `public/demos/agents/high-five.html` | Agent high-fives on click. |
+| `/demos/agents/holds-cta` | `public/demos/agents/holds-cta.html` | Agent holds up the call-to-action. |
+| `/demos/agents/pickup-drop` | `public/demos/agents/pickup-drop.html` | Pick up and drop the agent. |
+| `/demos/agents/scroll-inertia` | `public/demos/agents/scroll-inertia.html` | Agent reacts to scroll inertia. |
+| `/demos/agents/sit-in-body` | `public/demos/agents/sit-in-body.html` | Agent sits inside body copy. |
+| `/demos/agents/skateboard` | `public/demos/agents/skateboard.html` | Agent skateboards across the page. |
+| `/demos/agents/trampoline` | `public/demos/agents/trampoline.html` | Agent bounces on a trampoline. |
+| `/demos/agents/walks-gutter` | `public/demos/agents/walks-gutter.html` | Agent walks the page gutter. |
+| `/demos/agents/wrecking-ball` | `public/demos/agents/wrecking-ball.html` | Wrecking-ball physics demo. |
+
+## Related demo pages (outside `/demo` and `/demos`)
+
+Page files that carry a `demo-`/`coin` name or alias into the lab but
+live at their own top-level URLs:
+
+| Route | Page file | What it does |
+|---|---|---|
+| `/coin3d` | `pages/coin3d.html` | Token-in-3D visualizer. |
+| `/app-demo` | `pages/app-demo.html` | Viewer with the studio skin (studio-skin demo). |
+| `/embed-demo` | `pages/embed-demo.html` | Avatar embed demo. |
+| `/avatar-studio-demo` | `pages/avatar-studio-demo.html` | Avatar Studio demo. |
+| `/lipsync` | `public/demos/lipsync-tts.html` | Alias into the lab — TTS-driven lipsync. |
+| `/lipsync/mic` | `public/demos/lipsync-mic.html` | Alias into the lab — mic/audio-driven lipsync. |
## Legacy redirects
@@ -66,10 +118,9 @@ compatibility — prefer the `/demos/<slug>` form for new links.
| `/coin` | `/demo/coin` | `vercel.json` (301), mirrored in `vite.config.js` middleware for dev. |
| `/coin/` | `/demo/coin` | `vercel.json` (301), mirrored in `vite.config.js` middleware for dev. |
-`pages/pump-coin-page.html` predates the `/demo/coin` rewrite and is
-not wired into the canonical demo nav. It still resolves at
-`/pump-coin-page` via the generic `pages/<slug>.html` fallback in the
-Vite middleware, but new links should point at `/demo/coin`.
+Both redirects land on a `200` (`/demo/coin/`) after following the
+30x. The legacy `pages/pump-coin-page.html` has been removed —
+`/pump-coin-page` now `404`s and `/demo/coin` is the only coin demo URL.
## Adding a new demo
@@ -102,3 +153,24 @@ Vite middleware, but new links should point at `/demo/coin`.
The route must return `200` (or `301` → 200 for a documented
legacy redirect).
+
+## Verification notes (2026-06-08)
+
+Verified on the live Vite dev server (`npm run dev`, port 3000):
+
+- Every route in the tables above returns **200**. `/coin` and `/coin/`
+ return **301 → `/demo/coin/` → 200**.
+- All 27 `/demos/<slug>` pages and all 17 `/demos/agents/<slug>` pages
+ return 200 (extensionless and `.html` forms both resolve; in-page links
+ use `.html`).
+- Each page renders a real, non-placeholder `<title>` and loads its JS
+ modules with **200** responses.
+- `/_vercel/insights/script.js` 404s on the dev server on every page —
+ that is Vercel Web Analytics, injected by the Vercel platform only in
+ production. It is not a route regression.
+- `/demo/avatar-os/studio` (no `.html`) 404s in dev and is **not** a
+ supported URL — the avatar-os hub links its sub-pages with the `.html`
+ extension, which is the canonical form. Same for the other avatar-os
+ sub-pages.
+- No `vercel.json` or `vite.config.js` changes were needed; all routes
+ were already wired correctly.
diff --git a/docs/persona-hub.md b/docs/persona-hub.md
index 7d8fb8e52..f407e4f3f 100644
--- a/docs/persona-hub.md
+++ b/docs/persona-hub.md
@@ -152,7 +152,7 @@ A successful response looks like:
```json
{
- "token": "eyJhbGciOiJIUzI1NiIsImtpZCI6ImsxIiwidHlwIjoiSldUIn0…",
+ "token": "eyJhbGciOiJFUzI1NiIsImtpZCI6InBlcnNvbmEtMjAyNi0wNS0yMCIsInR5cCI6IkpXVCJ9…",
"expires_in": 86400,
"avatar": {
"id": "a-1",
diff --git a/docs/pumpfun-program/AUDIT-2026-06-08.md b/docs/pumpfun-program/AUDIT-2026-06-08.md
new file mode 100644
index 000000000..93d470e26
--- /dev/null
+++ b/docs/pumpfun-program/AUDIT-2026-06-08.md
@@ -0,0 +1,208 @@
+# pump.fun v2 trade-interface audit — three.ws
+
+**Date:** 2026-06-08
+**Scope:** every place three.ws builds a bonding-curve buy/sell, the AMM swap path,
+the buyback inner instruction, and the launch (create + initial buy) path — audited
+against the vendored v2 docs and IDLs in `docs/pumpfun-program/`.
+**SDKs in use:** `@pump-fun/[email protected]` (resolves the `^1.36.0` range we depend on),
+`@pump-fun/pump-swap-sdk`, `@pump-fun/agent-payments-sdk`.
+
+## Method
+
+For each instruction we build, the v2 account list, account order, writable/signer
+masks, discriminator, and argument encoding were checked against
+`docs/pumpfun-program/idl/pump.json` (extracted programmatically) and the
+prose in `docs/instructions/{BUY,SELL,COIN_CREATION}.md` +
+`docs/FEE_RECIPIENTS.md`. SDK builder internals were read from
+`node_modules/@pump-fun/pump-sdk/dist/esm/index.js` to confirm that the params we
+pass (and omit) produce correct accounts.
+
+Two facts drive several verdicts:
+
+- `isLegacyQuoteMint(q)` ≡ `q.equals(NATIVE_MINT) || q.equals(PublicKey.default)`.
+ On-chain SOL curves store `bonding_curve.quote_mint = PublicKey.default`; both the
+ default and wSOL are "legacy" (SOL-paired). USDC (or any other quote) is non-legacy.
+- The SDK's `buyV2Instructions` / `sellV2Instructions` derive the quote mint from
+ `bondingCurve.quoteMint` internally and default `quoteTokenProgram` to the legacy
+ SPL Token program (correct for USDC, which is an SPL-Token mint) and base
+ `tokenProgram` to Token-2022 (correct for `create_v2` coins).
+
+## Per-path verdicts
+
+| # | Path | Builder | Verdict | Evidence |
+|---|------|---------|---------|----------|
+| 1 | Buyback full-swap inner ix (`buy_exact_quote_in_v2`, CPI'd by `agent_buyback_trigger`) | **hand-rolled** account list | **PASS** | [pump-swap-ix.js:135](../../api/_lib/pump-swap-ix.js#L135), consumed at [cron/[name].js:1507](../../api/cron/%5Bname%5D.js#L1507) |
+| 2 | Bonding-curve buy — USDC-paired | SDK `buyV2Instructions` | **PASS** | [[action].js:285](../../api/pump/%5Baction%5D.js#L285) |
+| 3 | Bonding-curve buy — SOL-paired | SDK `buyInstructions` (legacy `buy`) | **PASS (legacy, supported)** | [[action].js:315](../../api/pump/%5Baction%5D.js#L315) |
+| 4 | Bonding-curve sell — USDC-paired | SDK `sellV2Instructions` | **PASS** | [[action].js:527](../../api/pump/%5Baction%5D.js#L527) |
+| 5 | Bonding-curve sell — SOL-paired | SDK `sellInstructions` (legacy `sell`) | **PASS (legacy, supported)** | [[action].js:539](../../api/pump/%5Baction%5D.js#L539) |
+| 6 | AMM buy (post-graduation) | SDK `buyQuoteInput(swapState,…)` | **PASS** | [[action].js:355](../../api/pump/%5Baction%5D.js#L355) |
+| 7 | AMM sell (post-graduation) | SDK `sellBaseInput(swapState,…)` | **PASS** | [[action].js:571](../../api/pump/%5Baction%5D.js#L571) |
+| 8 | Quote endpoint (curve + AMM, SOL + USDC) | SDK pricing helpers | **PASS** | [[action].js:2018](../../api/pump/%5Baction%5D.js#L2018) |
+| 9 | Launch create+buy — USDC-paired | SDK `createV2AndBuyV2Instructions` | **GAP-B (fixed)** | [[action].js:827](../../api/pump/%5Baction%5D.js#L827) |
+| 10 | Buy-confirm recording | handler | **GAP-A (fixed)** | [[action].js:400](../../api/pump/%5Baction%5D.js#L400) |
+| 11 | Buyback fee-recipient selection | hand-rolled | **GAP-C (fixed)** | [pump-swap-ix.js:104](../../api/_lib/pump-swap-ix.js#L104) |
+
+### 1 — Buyback inner ix `buy_exact_quote_in_v2` — PASS
+
+The only place we hand-roll a full v2 account list (the SDK has no offline builder
+for the inner-CPI variant consumed by `agent_buyback_trigger`). Verified **bit-for-bit**
+against the IDL:
+
+- 27 accounts, exact order matching `idl/pump.json → buy_exact_quote_in_v2.accounts`.
+- Writable mask `{6,7,8,9,10,11,12,13,14,15,16,17,20,21}` (0-based) matches the IDL.
+- `user` (index 13, the buyback-authority PDA) is the sole signer — `invoke_signed`
+ by the outer ix supplies the signature. Matches IDL `user: writable+signer`.
+- Discriminator `[194,171,28,70,104,77,91,47]` matches the IDL.
+- Data = `disc ‖ spendable_quote_in:u64 LE ‖ min_tokens_out:u64 LE` — matches the IDL
+ arg order.
+- `quote_mint` resolved from `bonding_curve.quote_mint` (default → wSOL); base/quote
+ token programs read from each mint's on-chain owner; ATAs derived with the matching
+ program. Correct for SOL, USDC, and Token-2022 base mints.
+
+This path already has exhaustive offline coverage in
+[tests/pump-swap-ix.test.js](../../tests/pump-swap-ix.test.js) (account order, writable
+mask, signer set, discriminator, data encoding, graduation guard, currency-mismatch
+guard, default-quote normalization). **No change needed to the account list.**
+
+### 2–7 — SDK-built buy/sell (curve + AMM) — PASS
+
+These delegate to the official SDK v2/AMM builders, which is exactly the
+"prefer the SDK's v2 builders over hand-rolled lists" guidance. Confirmed from SDK
+internals:
+
+- `buyV2Instructions` / `sellV2Instructions` compute
+ `quoteMint = isLegacyQuoteMint(bondingCurve.quoteMint) ? NATIVE_MINT : bondingCurve.quoteMint`
+ and emit `buy_v2` / `sell_v2` with the full 27/26-account v2 layout. The explicit
+ `quoteMint` we pass at [[action].js:291](../../api/pump/%5Baction%5D.js#L291) is
+ ignored by the SDK (its signature has no such param) — the **on-chain curve is the
+ source of truth**, which is the safe behavior. Harmless but noted.
+- AMM `buyQuoteInput(swapState,…)` / `sellBaseInput(swapState,…)` derive every account
+ (pool, quote mint, token programs, creator vault) from `swapSolanaState`, so they are
+ quote-asset-agnostic. The USDC pool is resolved correctly because
+ `getAmmPoolState` keys the canonical pool PDA with the explicit quote mint
+ (`canonicalPumpPoolPda(mint, quoteMint)`, [pump.js:236](../../api/_lib/pump.js#L236));
+ `canonicalPumpPoolPda(mint, quoteMint = NATIVE_MINT)` incorporates the quote mint into
+ the PDA seeds.
+
+**SOL-paired buy/sell (rows 3, 5)** still use the legacy `buy`/`sell` builders. The
+upstream announcement explicitly supports this ("All existing trade instructions will
+continue to work… no changes needed") and guarantees identical quotes/costs. Migrating
+the live SOL path to `buy_v2`/`sell_v2` is a **future-proofing recommendation, not a
+bug** — see Recommendations. Left unchanged to avoid risk to the in-production SOL flow.
+
+## Gaps found and fixed
+
+### GAP-A (medium, reachable) — `buy-confirm` rejected USDC buys
+
+`buyConfirmSchema.sol` was `z.number().positive()` (strictly > 0). The USDC buy flow is
+already wired end-to-end (`buy-prep` accepts `usdc_amount`; the MCP skill
+`pumpfun-buy` accepts `usdcAmount`), but the skill's confirm step sent `sol: 0` for USDC
+buys ([src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js)), which the
+`.positive()` schema 400'd — a dead end on a wired path.
+
+**Fix:** `sol` and a new `usdc_amount` are both optional with a refine requiring one of
+them ([[action].js:381](../../api/pump/%5Baction%5D.js#L381)). The handler stores the
+`sol_amount` lamports column only for SOL buys (USDC leaves it null — see follow-up on a
+quote-amount column) and emits a quote-aware `coin-buy` feed event. The MCP skill now
+sends `usdc_amount` for USDC buys instead of `sol: 0`.
+
+### GAP-B (low, forward-looking) — USDC launch initial-buy mis-estimated base tokens
+
+`buildLaunchInstructions` (USDC branch) called
+`getBuyTokenAmountFromSolAmount({ …, bondingCurve: null })` **without** `quoteMint`. For a
+fresh curve the SDK seeds reserves via `newBondingCurve(global, quoteMint)`; with
+`quoteMint` undefined it uses `initial_virtual_sol_reserves` instead of
+`initial_virtual_quote_reserves`, so the base-token estimate is priced against the wrong
+pool. Passed to `createV2AndBuyV2Instructions` as the `amount` (with `quoteAmount` as the
+1%-padded max cost), a wrong estimate can over/under-spend or revert on `max_quote_cost`.
+
+**Fix:** pass `quoteMint` ([[action].js:824](../../api/pump/%5Baction%5D.js#L824)). The
+SOL path was already correct (it intends SOL reserves). Note: `handleQuote`'s USDC curve
+quote was **already correct** — it passes a real fetched `bondingCurve`, so the SDK uses
+the curve's own reserves and the `quoteMint` param is moot there.
+
+### GAP-C (low, robustness; affects the live buyback path) — hardcoded buyback recipients
+
+The hand-rolled inner ix picked `buyback_fee_recipient` from a vendored static list. The
+program validates that account against the **on-chain** `global.buyback_fee_recipients`
+(present in the IDL `Global` struct), and the function already decodes `global`. A static
+list silently breaks every buyback if pump ever rotates/extends the set.
+
+**Fix:** `pickBuybackFeeRecipient(global)` prefers `global.buybackFeeRecipients` and falls
+back to the static list only when an older Global layout omits it
+([pump-swap-ix.js:104](../../api/_lib/pump-swap-ix.js#L104)). Two unit tests added: one
+asserting selection from the on-chain list, one asserting static fallback.
+
+### Polish — `quote_mint` in API responses showed the zero pubkey
+
+SOL curves store `quote_mint = PublicKey.default`, so buy/sell/quote responses surfaced
+`1111…1111`. Now normalized to wrapped SOL for legacy coins across `buy-prep`,
+`sell-prep`, and the `quote` curve branch (the AMM branch already used the real pool
+quote mint).
+
+## Decision: USDC-quoted ("stable paired") coins
+
+**Conclusion: the trade-building infrastructure is implemented and correct after this
+audit; the remaining work is product/UX surface, deferred behind a flag until pump
+enables USDC.**
+
+USDC support divides into two layers:
+
+**Plumbing (done — quote-asset-agnostic, allowed under the coin rule):**
+
+- Quote-mint detection from the on-chain curve, with explicit `quote_mint` override.
+- Curve buy/sell via `buyV2Instructions`/`sellV2Instructions` (USDC) — rows 2, 4.
+- AMM buy/sell via the quote-keyed pool PDA — rows 6, 7.
+- Read-side quotes for USDC curves and pools — row 8.
+- Launch create+buy for USDC pairs — row 9 (estimate fixed in GAP-B).
+- Confirm + trade recording for USDC buys — row 10 (fixed in GAP-A).
+- USDC mints are supplied at runtime (`SOLANA_USDC_MINT` / `SOLANA_USDC_MINT_DEVNET`,
+ or an explicit `quote_mint` param). No specific non-`$THREE` coin is surfaced; only
+ the USDC quote-asset mint, which is infrastructure plumbing.
+
+**Productization (planned — needs UI/product input, not shipped here):**
+
+1. **Balances UI / decimals.** The buy/sell widget ([src/game/coin-buy.js](../../src/game/coin-buy.js))
+ is SOL-only (sends `sol`, shows SOL balances). For USDC coins it must read the
+ curve's `quote_mint`, prompt in USDC (6 decimals), show the wallet's USDC balance,
+ and POST `usdc_amount`. Effort: ~1 focused PR on the widget + the balances fetch.
+2. **Trade-amount column.** `pump_agent_trades` has only `sol_amount` (lamports). Add a
+ nullable `quote_amount numeric(40,0)` + `quote_mint text` so USDC buys/sells record a
+ meaningful amount (today USDC buys store `sol_amount = null`). Small migration; do it
+ alongside the UI PR so analytics/portfolio reflect USDC volume.
+3. **Portfolio / P&L.** `handlePortfolio` aggregates in SOL; extend to per-quote-asset
+ sub-totals once (2) lands.
+4. **End-to-end verification.** Trading USDC-paired coins is **not yet live** on pump.fun
+ (the announcement: "no quote mint other than native SOL can be used to create or trade
+ coins… we will add USDC next week, exact date TBD"). Gate the USDC buy/sell UI behind a
+ flag and run a real devnet/mainnet buy+sell the day pump enables it; record the
+ signatures here.
+
+**Recommendation:** keep the now-correct plumbing in place, land items 1–2 as the next
+USDC PR behind a feature flag, and only flip the flag once pump enables USDC trading.
+
+## Recommendations (not changed — flagged for product)
+
+- **Future-proof the SOL buy/sell path to `buy_v2`/`sell_v2`.** The announcement urges all
+ integrations to migrate to the unified interface. Our SOL path uses legacy `buy`/`sell`
+ (supported, identical cost). Migrating means swapping `buyInstructions`→`buyV2Instructions`
+ (passing wSOL as quote) for SOL coins. Low user-visible impact; do it when touching that
+ handler next. Left as-is now to avoid risk to the live SOL flow.
+
+## Verification
+
+- **Unit tests:** `tests/pump-swap-ix.test.js` + `tests/pump-swap-quote.test.js` →
+ **24 passed** (incl. 2 new buyback-recipient tests). Broader pump suite
+ (`pump-mcp-tools`, `pumpfun-mcp-tools`, `pumpfun-ported-skills`, `pump-channel-feed`,
+ `pumpfun-mcp`) → **33 passed**.
+- **Build:** `npm run build` → green.
+- **Prettier:** the repo's committed sources (incl. recently-committed files) do **not**
+ conform to the current `.prettierrc` (`printWidth: 100` vs. the de-facto narrower
+ committed style), so `prettier --check` fails repo-wide independent of this change.
+ Running `prettier --write` on the touched 4000-line files would produce a large,
+ unjustified reformatting diff. Per the minimal-diff / "read like the surrounding code"
+ rules, edits match the surrounding tab-indented style instead; no whole-file reformat.
+- **On-chain test:** **not executed** — no `SOLANA_RPC_URL_DEVNET` and no funded signer
+ keypair in this environment, and USDC-paired trading is not yet enabled upstream.
+ Instruction-building is verified offline against the IDL + unit tests as above.
diff --git a/prompts/finish-features/README.md b/prompts/finish-features/README.md
deleted file mode 100644
index 94581c9e9..000000000
--- a/prompts/finish-features/README.md
+++ /dev/null
@@ -1,65 +0,0 @@
-# Finish-features queue
-
-Each file below is a **fully self-contained prompt**. You can hand any one of
-them to a fresh Claude Code session (or to yourself in a future turn) without
-loading anything else from this directory — they restate all the context they
-need.
-
-**Run any file at any time.** Files do not depend on each other. There is no
-ordering between them.
-
-## Rails every prompt repeats (CLAUDE.md, non-negotiable)
-
-- No mocks, no fake data, no placeholders, no TODOs, no stubs, no
- `throw new Error('not implemented')`, no commented-out code, no
- `setTimeout` fake-loading, no fallback sample arrays.
-- Real APIs only: Pump.fun, Solana RPC, OpenAI/Anthropic via worker proxies,
- Resend, Neon Postgres, R2.
-- Errors handled at boundaries only (network, user input).
-- Done = code wired, dev server confirms feature in a real browser with no
- console errors, `npm test` green, `git diff` reviewed.
-- Push to **both** `origin` (nirholas/3D-Agent) and `threews` (nirholas/three.ws)
- only when the user explicitly says push.
-
-## The queue
-
-### From `docs/internal/TODO.md` (curated, agent-doable)
-
-| File | Subagents? | Estimate |
-|---|---|---|
-| [finish-resend-integration.md](finish-resend-integration.md) | Yes — Explore to map callers | medium |
-| [add-healthz-resend-probe.md](add-healthz-resend-probe.md) | No | small |
-| [document-persona-hub.md](document-persona-hub.md) | Yes — Explore to read all persona code | medium |
-| [expand-lipsync-tests.md](expand-lipsync-tests.md) | No | small |
-| [verify-demo-routes.md](verify-demo-routes.md) | No | small |
-| [stale-todo-sweep.md](stale-todo-sweep.md) | Yes — Explore for the grep, recurring task | small |
-
-### Real code TODOs found in `src/` and `api/`
-
-| File | Subagents? | Estimate |
-|---|---|---|
-| [fix-referral-code-uniqueness.md](fix-referral-code-uniqueness.md) | No | small |
-| [implement-pump-swap-inner-ix.md](implement-pump-swap-inner-ix.md) | Yes — Explore for pump-swap SDK + Solana CPI | large |
-| [clarify-speech-provider-errors.md](clarify-speech-provider-errors.md) | No | small |
-| [wasm-vanity-grinder.md](wasm-vanity-grinder.md) | Yes — Explore for Rust crate + wasm-pack | large |
-| [resolve-viewer-light-todo.md](resolve-viewer-light-todo.md) | No | small |
-
-### Decisions deferred in `docs/internal/NEXT.md`
-
-| File | Subagents? | Estimate |
-|---|---|---|
-| [server-side-glb-render.md](server-side-glb-render.md) | Yes — Explore for OG card flow + puppeteer integration | large |
-| [add-mesh-compression-deps.md](add-mesh-compression-deps.md) | No | small |
-
-## What is NOT in this queue and why
-
-- **Abstract base classes** (`src/onchain/adapters/base.js`,
- `src/onchain/tokens/base.js`): the `throw new Error('not implemented')`
- calls there are the documented abstract contract that family-specific
- subclasses override. They are not stubs.
-- **JSON-RPC `-32601 method not found`** in `api/pump-fun-mcp.js` and
- `workers/pump-fun-mcp/worker.js`: standard JSON-RPC sentinel. Not a stub.
-- **Human-blocked items** (3D-Agent mirror PAT, Resend domain verify,
- `RESEND_AUDIENCE_ID`, confirm Resend test email delivery): need credentials
- or dashboard access only the user has. Tracked in
- `docs/internal/TODO.md` under "Human-blocked".
diff --git a/prompts/finish-features/add-healthz-resend-probe.md b/prompts/finish-features/add-healthz-resend-probe.md
deleted file mode 100644
index 84ed00c47..000000000
--- a/prompts/finish-features/add-healthz-resend-probe.md
+++ /dev/null
@@ -1,148 +0,0 @@
-# Task: Add Resend probe to `/api/healthz`
-
-## Repo context
-
-Working tree: `/workspaces/three.ws`. Backend: Vercel functions in `api/`.
-The existing health endpoint is `api/healthz.js`. It already reports the
-status of the things the app depends on (database, R2, etc.). Email is
-sent through Resend via `api/_lib/email.js`. There is no Resend probe
-yet, so a broken / missing key only surfaces when a user-facing flow
-tries to send.
-
-## Rails (CLAUDE.md — non-negotiable)
-
-- No mocks, no fake data, no placeholders, no TODOs, no stubs, no
- `throw new Error('not implemented')`, no commented-out code, no
- `setTimeout` fake-loading, no fallback sample arrays.
-- Real APIs only — the probe must hit Resend over the network.
-- Errors handled at boundaries only.
-- Done = `curl /api/healthz` against `npm run dev` returns the new field,
- `npm test` green, `git diff` reviewed.
-- Push to both remotes only when the user says push.
-
-## Problem
-
-`api/healthz.js` should expose a `resend` field with one of three values:
-
-- `"configured"` — `RESEND_API_KEY` is set and the key is accepted by
- Resend.
-- `"missing"` — `RESEND_API_KEY` is unset or empty.
-- `"key_invalid"` — `RESEND_API_KEY` is set but Resend rejected it as
- invalid (HTTP 401 with `restricted_api_key` is treated as **valid**,
- since send-only keys legitimately can't list domains).
-
-The probe must be cheap and rate-limited — Resend will complain if we
-hammer it. Cache the result for **5 minutes** in module scope.
-
-## What to implement
-
-### Step 1 — read the current endpoint
-
-Open `api/healthz.js`. Note how existing probes (db, r2) are structured.
-Match the same pattern.
-
-### Step 2 — add the Resend probe
-
-Inside the handler (or as a small module-scoped helper above the
-handler):
-
-```js
-// Module-scoped cache: { value, expiresAt }
-let _resendCache = { value: null, expiresAt: 0 };
-
-async function probeResend() {
- const now = Date.now();
- if (_resendCache.value && _resendCache.expiresAt > now) {
- return _resendCache.value;
- }
-
- const key = process.env.RESEND_API_KEY;
- if (!key) {
- _resendCache = { value: 'missing', expiresAt: now + 5 * 60 * 1000 };
- return 'missing';
- }
-
- let result;
- try {
- const r = await fetch('https://api.resend.com/domains', {
- method: 'GET',
- headers: { Authorization: `Bearer ${key}` },
- // 3s upper bound — healthz must stay fast
- signal: AbortSignal.timeout(3000),
- });
- if (r.ok) result = 'configured';
- else if (r.status === 401) {
- // Could be a restricted (send-only) key, which is still valid.
- const body = await r.text().catch(() => '');
- result = body.includes('restricted_api_key') ? 'configured' : 'key_invalid';
- } else if (r.status === 403) result = 'configured'; // send-only often returns 403
- else result = 'key_invalid';
- } catch {
- // Network error / timeout — don't fail healthz, report as missing-signal.
- // Caller treats this conservatively as "unknown" → 'key_invalid'.
- result = 'key_invalid';
- }
-
- _resendCache = { value: result, expiresAt: now + 5 * 60 * 1000 };
- return result;
-}
-```
-
-Call `probeResend()` inside the handler and include the result under
-the key `resend` in the JSON response. Place it alongside the other
-dependency-status fields.
-
-### Step 3 — add a test
-
-`tests/healthz.test.js` (create if it does not exist). Use `vitest`
-(the repo's test runner — confirm by reading `package.json`). The test
-should:
-
-1. Stub `globalThis.fetch` for the Resend call only (other healthz
- probes hit the real db; do not mock those — instead skip the test
- under no-db env, the same way other tests in the repo skip).
- Override `fetch` with a small function that returns `{ ok: true,
- status: 200 }` to assert `resend === 'configured'`.
-2. Reset the module-scoped cache between cases. Either re-import with
- `vi.resetModules()`, or export a `_resetResendCache` helper from
- `api/healthz.js` for test use. Pick whichever fits the existing
- pattern in `tests/`.
-3. Cases: `missing`, `configured` (200), `configured` (401 with
- `restricted_api_key` body), `key_invalid` (401 without it),
- `key_invalid` (500), `key_invalid` (timeout — reject fetch).
-
-Do **not** call the real Resend API in tests. The probe itself in
-production hits the real API; tests assert the dispatch logic.
-
-### Step 4 — verify in dev
-
-```bash
-npm run dev
-curl http://localhost:3000/api/healthz
-```
-
-Confirm the response includes `resend: "..."`. If `RESEND_API_KEY` is
-set in `.env`, expect `configured`. If unset, expect `missing`.
-
-### Step 5 — run the full suite
-
-```bash
-npm test
-```
-
-## Definition of done
-
-- `api/healthz.js` returns a `resend` field with one of the three
- documented values.
-- The result is cached for 5 minutes in module scope.
-- `tests/healthz.test.js` covers all five branches without calling the
- real Resend API.
-- `curl /api/healthz` against `npm run dev` shows the new field.
-- `npm test` is green.
-
-## Constraints
-
-- Do not increase healthz latency beyond ~3 seconds upper bound.
-- Do not log the API key value anywhere.
-- Do not delete or rewrite the existing probes — only add `resend`.
-- Cache TTL is exactly 5 minutes, not configurable via env. Hard-code it.
diff --git a/prompts/finish-features/add-mesh-compression-deps.md b/prompts/finish-features/add-mesh-compression-deps.md
deleted file mode 100644
index 575bd5541..000000000
--- a/prompts/finish-features/add-mesh-compression-deps.md
+++ /dev/null
@@ -1,186 +0,0 @@
-# Task: Add `meshoptimizer` + `draco3d` to the GLB bake pipeline
-
-## Repo context
-
-Working tree: `/workspaces/three.ws`. The bake pipeline at
-`api/_lib/bake.js` already runs a `weld + quantize + textureCompress`
-compression pass on every baked avatar GLB (see `docs/internal/
-PROGRESS.md` item 1). That ships an ~5-10× reduction over the
-uncompressed source. The pipeline could do another 2-3× by adding the
-`meshopt()` and `draco()` transforms from `@gltf-transform/functions`
-— but those transforms require the optional peer dependencies
-`meshoptimizer` and `draco3d`, which are not currently installed
-(~5 MB combined).
-
-`docs/internal/NEXT.md` documents the deferred decision.
-
-## Rails (CLAUDE.md — non-negotiable)
-
-- No mocks. No fake data. No placeholders.
-- Real APIs only — the compression must actually decode in the
- browser, which means we must verify the in-browser GLTFLoader has
- the matching decoders wired.
-- Done = baked GLBs are 2-3× smaller than the current baseline, every
- avatar still renders correctly in the viewer, `npm test` green.
-- Push to both remotes only when the user says push.
-
-## What to implement
-
-### Step 1 — install the deps
-
-```bash
-npm install meshoptimizer draco3d
-```
-
-These go into runtime `dependencies` because they are used by the
-serverless bake function at request time. (`@gltf-transform/
-functions` is already in `package.json`.)
-
-### Step 2 — wire `meshopt()` and `draco()` into `api/_lib/bake.js`
-
-Read the existing transform chain:
-
-```bash
-cat api/_lib/bake.js | head -200
-```
-
-The current pass (per `docs/internal/PROGRESS.md` item 1):
-
-```js
-await doc.transform(
- weld(),
- quantize({ ... }),
- textureCompress({ encoder: sharp, ... }),
-);
-```
-
-Add the meshopt + draco transforms. Order matters:
-
-```js
-import { MeshoptEncoder } from 'meshoptimizer';
-import draco3d from 'draco3d';
-
-await MeshoptEncoder.ready;
-
-await doc.transform(
- weld(),
- quantize({ /* same as before */ }),
- // EXT_meshopt_compression — fast browser decode, ~2× extra reduction
- meshopt({ encoder: MeshoptEncoder, level: 'medium' }),
- textureCompress({ encoder: sharp, ... }),
-);
-```
-
-`draco3d` is for `KHR_draco_mesh_compression`, which yields a bit
-more reduction than meshopt but decodes slower in the browser. **Pick
-one, not both.** Meshopt is the right call for avatars (small, many,
-decoded on page load) — draco is better for large static models.
-
-Use meshopt only. Keep the `draco3d` install for now because gltf-
-transform may transitively require it; but do not add a `draco()`
-transform to the chain. If after install `npm ls draco3d` shows it
-is unused, `npm uninstall draco3d` in the same diff.
-
-### Step 3 — preserve the fallback
-
-The existing pipeline has a try/catch fallback to a minimal
-`unpartition + prune + dedup` chain for pathological inputs. Keep it.
-If the new meshopt pass throws on some weird input, the fallback path
-saves the bake. Do not remove safety nets to chase max compression.
-
-### Step 4 — verify browser decoders are wired
-
-The in-app viewer (`src/viewer/internal.js` or wherever
-`getDecoders()` lives) must register the MeshoptDecoder:
-
-```js
-import { MeshoptDecoder } from 'three/examples/jsm/libs/meshopt_decoder.module.js';
-gltfLoader.setMeshoptDecoder(MeshoptDecoder);
-```
-
-`docs/internal/PROGRESS.md` notes the main viewer already has this.
-Confirm by reading the file. If the marketplace lobby viewer
-(`src/marketplace-lobby.js`) does **not** have it, add it — otherwise
-meshopt-compressed avatars will fail to load there.
-
-### Step 5 — run the existing tests
-
-```bash
-npm test -- tests/avatar-bake.test.js
-```
-
-These 9 tests assert correctness invariants (morph weights baked,
-accessory parented to bone, hash stability, etc.). They should all
-still pass — meshopt is transparent to those guarantees. If any fail,
-the compression broke a structural invariant; fix the transform
-parameters until they all pass.
-
-### Step 6 — measure size change
-
-`scripts/measure-bake-size.mjs` (create if it does not exist).
-Reads a known avatar from R2 (or `tests/fixtures/`), bakes it once
-**before** the new transforms (via `git stash` of just this change,
-or a copy of the old function), and **after**. Reports both sizes
-and the ratio.
-
-If the after/before ratio is worse than 0.6 (i.e. less than 40%
-reduction), something is wrong — meshopt should yield 30-50%
-reduction on top of the existing pipeline for typical avatars.
-
-If the script existed before this task, just extend it. Do not
-duplicate.
-
-### Step 7 — manual browser smoke
-
-```bash
-npm run dev
-```
-
-Open the avatar customizer, load an existing avatar, Save (triggers
-a re-bake), then reload the page from a clean browser cache and
-confirm:
-
-1. Network tab shows the baked GLB is meaningfully smaller than
- before.
-2. The avatar renders with no console errors.
-3. Morph targets still work (facial expressions visibly change when
- the agent-avatar empathy layer activates).
-4. Animations still play.
-
-Also check the marketplace lobby route — that viewer was flagged in
-`docs/internal/PROGRESS.md` as historically lacking decoders. Verify
-it loads meshopt-compressed avatars correctly.
-
-### Step 8 — clean up `docs/internal/NEXT.md`
-
-Remove the "meshoptimizer / draco3d peer deps" section. Add a line
-under `docs/internal/PROGRESS.md` describing the new compression
-ratio measured in Step 6.
-
-## Definition of done
-
-- `meshoptimizer` is in `dependencies`.
-- `draco3d` is in `dependencies` only if something transitively
- requires it; otherwise uninstalled.
-- `api/_lib/bake.js` applies `meshopt()` after `quantize()` and
- before `textureCompress()`.
-- The fallback path is preserved.
-- Browser-side decoder is registered in every viewer that loads
- baked avatars.
-- `tests/avatar-bake.test.js` (all 9 tests) still passes.
-- A measurement script shows 30-50% additional size reduction on a
- reference avatar.
-- Manual browser smoke confirms no rendering regression.
-- `docs/internal/NEXT.md` no longer lists this as deferred.
-
-## Constraints
-
-- Do not enable `KHR_draco_mesh_compression` (`draco()`) — it decodes
- slower in the browser and the meshopt path is already a clear win.
-- Do not raise meshopt `level` above `'medium'`. `'high'` increases
- bake time substantially with marginal extra reduction.
-- Do not change the bake API surface (function signatures, R2 key
- layout). This is internal pipeline only.
-- If meshopt breaks for a specific avatar, **fix the input** or
- **tune the transform** — do not silently skip meshopt for that
- case. A silently-uncompressed GLB is a regression.
diff --git a/prompts/finish-features/clarify-speech-provider-errors.md b/prompts/finish-features/clarify-speech-provider-errors.md
deleted file mode 100644
index e9a4b1623..000000000
--- a/prompts/finish-features/clarify-speech-provider-errors.md
+++ /dev/null
@@ -1,159 +0,0 @@
-# Task: Clarify speech-provider error wording in `src/runtime/speech.js`
-
-## Repo context
-
-Working tree: `/workspaces/three.ws`. The speech runtime is in
-`src/runtime/speech.js`. Around lines 500-513:
-
-```js
-export function createTTS(config = {}) {
- const provider = config.provider || 'browser';
- if (provider === 'none') return null;
- if (provider === 'browser') return new BrowserTTS(config);
- if (provider === 'elevenlabs') return new ElevenLabsTTS(config);
- throw new Error(`TTS provider "${provider}" not implemented yet`);
-}
-
-export function createSTT(config = {}) {
- const provider = config.provider || 'browser';
- if (provider === 'none') return null;
- if (provider === 'browser') return new BrowserSTT(config);
- throw new Error(`STT provider "${provider}" not implemented yet`);
-}
-```
-
-The message `"not implemented yet"` is misleading. It triggers on **any
-unknown provider name** — typos, copy-pasted configs from another
-project, future provider names. The user thinks the system is
-incomplete; in reality their config is wrong.
-
-## Rails (CLAUDE.md — non-negotiable)
-
-- No mocks, no fake data, no placeholders, no TODOs, no stubs.
-- Real APIs only.
-- Errors handled at boundaries only.
-- Done = error messages are honest, `npm test` green.
-- Push to both remotes only when the user says push.
-
-## What to implement
-
-### Step 1 — read the current file
-
-```
-src/runtime/speech.js
-```
-
-Confirm the supported providers for TTS and STT. As of today: TTS
-supports `browser`, `elevenlabs`, `none`; STT supports `browser`,
-`none`.
-
-### Step 2 — rewrite the rejection branches
-
-Replace the two trailing `throw new Error(...)` lines with:
-
-```js
-const supportedTTS = ['none', 'browser', 'elevenlabs'];
-const supportedSTT = ['none', 'browser'];
-
-// inside createTTS:
-throw new Error(
- `Unknown TTS provider "${provider}". Supported: ${supportedTTS.join(', ')}.`
-);
-
-// inside createSTT:
-throw new Error(
- `Unknown STT provider "${provider}". Supported: ${supportedSTT.join(', ')}.`
-);
-```
-
-Two upgrades over the current wording:
-
-1. "Unknown provider" is honest — these branches fire on typos.
-2. The list of supported providers is shown, so the user can fix
- their config without grepping the source.
-
-Keep the `supportedTTS` / `supportedSTT` arrays as module-scoped
-constants near the top of the factory functions so they are the single
-source of truth (currently they are encoded twice — once in the `if`
-chain, once implicitly in the error). Refactor the `if` chain to
-iterate the constant if it stays readable:
-
-```js
-const TTS_FACTORIES = {
- none: () => null,
- browser: (cfg) => new BrowserTTS(cfg),
- elevenlabs: (cfg) => new ElevenLabsTTS(cfg),
-};
-
-export function createTTS(config = {}) {
- const provider = config.provider || 'browser';
- const factory = TTS_FACTORIES[provider];
- if (!factory) {
- throw new Error(
- `Unknown TTS provider "${provider}". Supported: ${Object.keys(TTS_FACTORIES).join(', ')}.`
- );
- }
- return factory(config);
-}
-```
-
-Apply the same shape to `createSTT`.
-
-### Step 3 — add a test
-
-Either extend an existing `tests/speech*.test.js` or create a small
-one. Cases:
-
-1. `createTTS({ provider: 'browser' })` returns a `BrowserTTS`
- instance.
-2. `createTTS({ provider: 'elevenlabs' })` returns an
- `ElevenLabsTTS` instance.
-3. `createTTS({ provider: 'none' })` returns `null`.
-4. `createTTS({ provider: 'azure' })` throws an error whose message
- contains "Unknown TTS provider" and "browser, elevenlabs".
-5. Symmetric for `createSTT`.
-
-Do not stub `BrowserTTS` / `ElevenLabsTTS` — just assert
-`instanceof`. They have constructors that should run in jsdom; if not,
-read the file and adjust accordingly (the simpler way is to check
-constructor name).
-
-### Step 4 — run the suite
-
-```bash
-npm test
-```
-
-### Step 5 — verify in dev
-
-```bash
-npm run dev
-```
-
-If the user's app has a TTS / STT config UI, ensure it still works.
-Specifically: change the provider to `browser` and confirm voice
-synthesis still happens. Then deliberately set it to `azure` and
-confirm the new error is shown to the user (if there is user-facing
-error surfacing — otherwise check the console).
-
-## Definition of done
-
-- `src/runtime/speech.js` no longer says "not implemented yet" for
- unknown providers.
-- Error messages now say "Unknown ... provider" and list supported
- values.
-- The supported-provider list is encoded in a single place per
- factory.
-- A test covers both the success and the unknown-provider branches.
-- `npm test` is green.
-- Manual smoke in dev confirms no regression.
-
-## Constraints
-
-- Do not add new providers in this task. Adding OpenAI TTS, PlayHT,
- Deepgram STT, etc. is out of scope — file a follow-up if you want
- to add them later.
-- Do not change the public function signatures (`createTTS`,
- `createSTT`).
-- Do not silently swallow unknown providers (returning `null`) — keep
- the throw so a misconfigured runtime fails loudly.
diff --git a/prompts/finish-features/document-persona-hub.md b/prompts/finish-features/document-persona-hub.md
deleted file mode 100644
index 62e1c151a..000000000
--- a/prompts/finish-features/document-persona-hub.md
+++ /dev/null
@@ -1,130 +0,0 @@
-# Task: Complete `docs/persona-hub.md`
-
-## Repo context
-
-Working tree: `/workspaces/three.ws`. The "Persona Hub" is a feature that
-issues short-lived signed identity tokens to tenant applications so they
-can verify which user is making a request without re-implementing auth.
-Pieces involved:
-
-- `scripts/generate-persona-key.mjs` — generates a keypair for ES256
- signing.
-- `api/auth/persona/issue.js` (or under `api/auth/[action].js`) — issues
- the persona token after the user authenticates here.
-- `api/auth/persona/verify.js` (or under `api/auth/[action].js`) —
- verifies a token presented by a tenant.
-- `/.well-known/jwks.json` — publishes the active public keys so tenants
- can verify offline.
-- HS256 fallback for dev / when no ES256 key is configured.
-
-`docs/persona-hub.md` exists but is partial. This task is **docs only**
-— do not change any code.
-
-## Rails (CLAUDE.md — non-negotiable)
-
-- No mocks, no fake data, no placeholders, no TODOs, no stubs.
-- Examples in the doc must be **real code that runs** against the
- shipped endpoints. Test every snippet end-to-end before committing
- the doc.
-- Done = doc renders cleanly, every snippet has been executed once.
-- Push to both remotes only when the user says push.
-
-## What to implement
-
-### Step 1 — read the current code (delegate to subagent)
-
-Spawn an **Explore** subagent with this prompt:
-
-> In `/workspaces/three.ws`, find and summarize the Persona Hub
-> implementation. Return:
->
-> 1. Where `scripts/generate-persona-key.mjs` lives and what it does
-> (output format, env vars set).
-> 2. The exact path + HTTP method of the issue endpoint, request body
-> shape, response body shape, auth requirement.
-> 3. The exact path + HTTP method of the verify endpoint, request body
-> shape, response body shape.
-> 4. The path serving `/.well-known/jwks.json` and the JWK format it
-> publishes.
-> 5. The ES256 → HS256 fallback logic: under which condition does it
-> fall back? Where in the code is that decided?
-> 6. Any rate limits, scopes, or audience claims enforced.
->
-> Quote file paths with line numbers. Do not modify anything.
-
-### Step 2 — read the current doc
-
-```bash
-cat docs/persona-hub.md
-```
-
-Identify what is already covered vs missing.
-
-### Step 3 — rewrite `docs/persona-hub.md` to cover
-
-The final doc must include, in this order:
-
-1. **Overview** — one paragraph: what Persona Hub is, who issues
- tokens, who verifies them, what a tenant is, why ES256 (offline
- verification via JWKS).
-2. **Key generation** — how to run `scripts/generate-persona-key.mjs`,
- what files / env vars it produces, where the private key must live
- (Vercel env var name), where the public key is published.
-3. **Issuing a token** — full request/response with a curl example and
- a fetch example. Include the auth requirement (session cookie?
- bearer? CSRF?). Show the decoded JWT claims (iss, aud, sub, exp,
- custom claims).
-4. **Verifying a token (tenant side)** — two complete code examples:
- - Node.js using `jose` (verify against JWKS). Show the import,
- the JWKS fetch + cache, and the verify call.
- - Browser using `jose` from a CDN (or a bundler import). Same
- shape.
- Both examples must be runnable as-is once the reader fills in the
- issuer URL.
-5. **ES256 vs HS256 fallback** — explain exactly when the server falls
- back to HS256 (e.g. no ES256 private key set), and what tenants
- should do in that environment (they can't verify offline; they must
- call the verify endpoint).
-6. **Tokens in practice** — a one-paragraph note on rotation, TTL,
- revocation (or explicit "no revocation list — short TTL only").
-7. **Troubleshooting** — list of common errors (`jwks_uri unreachable`,
- `kid not found`, `alg mismatch`, `aud mismatch`, `expired`) with the
- one-line fix for each.
-
-### Step 4 — verify every snippet
-
-For each code snippet in the doc:
-
-1. Copy it into a scratch file (do not commit the scratch).
-2. Fill in the issuer URL with `http://localhost:3000` (or wherever the
- local dev server runs).
-3. Run it against `npm run dev`.
-4. Confirm it does what the doc says it does.
-
-If a snippet fails, fix the doc (or the snippet) until it works. Never
-ship a "should work" example you have not executed.
-
-### Step 5 — sanity check links
-
-Every relative link in the doc must resolve to a file that exists.
-Every external link must return 200.
-
-## Definition of done
-
-- `docs/persona-hub.md` covers all seven sections listed above.
-- Every code snippet in the doc has been executed at least once
- against the local dev server.
-- All links resolve.
-- No code changes (only the doc and possibly a `.gitignore` line if a
- generated key file path needs ignoring).
-- `git diff` shows only the doc changing.
-
-## Constraints
-
-- Do not add code under `src/` or `api/`. Docs only.
-- Do not include screenshots — keep it text + code.
-- Do not invent endpoint shapes — read the actual handlers via the
- Explore subagent and quote them.
-- If the Explore subagent reports that an endpoint is missing or
- broken, stop and report — do not paper over a broken endpoint with
- doc text.
diff --git a/prompts/finish-features/expand-lipsync-tests.md b/prompts/finish-features/expand-lipsync-tests.md
deleted file mode 100644
index 18067ace8..000000000
--- a/prompts/finish-features/expand-lipsync-tests.md
+++ /dev/null
@@ -1,127 +0,0 @@
-# Task: Expand lip-sync analyser test coverage
-
-## Repo context
-
-Working tree: `/workspaces/three.ws`. The lip-sync analyser drives the
-avatar's mouth shapes from an audio stream. Pieces involved:
-
-- `src/lip-sync-analyser.js` — reads `AnalyserNode` FFT bins, computes
- open/wide/round channel intensities.
-- `src/agent-avatar.js` — consumes the analyser output and applies it
- to the avatar's mouth morph targets.
-- `tests/agent-avatar-lipsync.test.js` — current test file. New; not
- exhaustive.
-
-## Rails (CLAUDE.md — non-negotiable)
-
-- No mocks of the production code under test. Stub only the host
- environment (Web Audio API), not the analyser itself.
-- No fake data — feed the analyser real PCM samples shaped to exercise
- each branch.
-- Done = `npm test` green and the new cases visibly exercise the
- branches they claim to cover.
-- Push to both remotes only when the user says push.
-
-## Problem
-
-The existing test file covers the happy path. The following behaviors
-are likely uncovered and matter in production:
-
-1. **Very short audio** (< 200 ms). The analyser may not have enough
- samples to settle; output should be defined and bounded, not NaN.
-2. **Silence** (audio playing but all samples ≈ 0). Mouth channels
- should report ~0, not random noise from the FFT floor.
-3. **Multiple back-to-back utterances**. State from utterance N must
- not bleed into utterance N+1. Tear-down and re-attach must work.
-4. **Browser without `AnalyserNode`**. Older / restricted browsers
- (Safari iOS pre-15 lock-screen contexts, some embedded WebViews).
- The driver should degrade to a no-op without throwing, and the
- avatar's mouth should sit at rest, not freeze in an odd shape.
-
-## What to implement
-
-### Step 1 — read the existing tests + source
-
-```
-src/lip-sync-analyser.js
-src/agent-avatar.js
-tests/agent-avatar-lipsync.test.js
-```
-
-Note which of the four behaviors above are already tested and which
-are missing. Skip cases that are already covered — do not duplicate.
-
-### Step 2 — add the missing tests
-
-For each uncovered behavior, add one or more tests in
-`tests/agent-avatar-lipsync.test.js`. Use the same setup pattern as
-the existing tests (vitest, jsdom). Where the test needs a fake audio
-source, construct one against the real Web Audio spec:
-
-- For the silence test: an `AnalyserNode` whose `getByteFrequencyData`
- fills the buffer with zeros. Assert all three mouth channels are
- ≤ 0.05 (small epsilon for FFT floor).
-- For the short-audio test: drive the analyser for ~5 frames
- (`requestAnimationFrame` equivalents) and assert outputs are finite
- numbers in `[0, 1]`.
-- For the back-to-back test: attach analyser A to source A, detach,
- attach analyser B to source B, assert output reflects only B.
- Inspect any module-scoped state (smoothing buffers, etc.) and
- confirm it resets cleanly on detach.
-- For the no-`AnalyserNode` test: temporarily delete `AnalyserNode`
- from the global (or replace `window.AnalyserNode` with undefined).
- Construct the driver, drive a frame, assert it returned zeros and
- did not throw. Restore the global in `afterEach`.
-
-Keep each test focused. One assertion per behavior, plus the
-"doesn't throw" guard.
-
-### Step 3 — run the suite
-
-```bash
-npm test -- tests/agent-avatar-lipsync.test.js
-npm test
-```
-
-Both must be green. The first call confirms your new tests pass in
-isolation; the second confirms nothing else regressed.
-
-### Step 4 — verify in a real browser
-
-```bash
-npm run dev
-```
-
-Open the Talk overlay (the route documented in
-`src/voice/talk-mode.js` — typically `/talk` or similar). Speak one
-utterance, then another. Open devtools, confirm:
-
-- No console errors.
-- The avatar's mouth animates during each utterance.
-- The mouth returns to rest between utterances (not stuck in the
- shape of the last frame of N when N+1 begins).
-
-If you can test in Safari iOS or a restricted WebView, do so. If you
-cannot (most likely case), say so explicitly in your final summary
-rather than claiming it works there.
-
-## Definition of done
-
-- `tests/agent-avatar-lipsync.test.js` covers all four behaviors that
- were not already covered.
-- `npm test` is green.
-- Manual verification in `npm run dev` showed no regression for the
- happy path.
-- The summary explicitly notes which environments were and were not
- manually tested.
-
-## Constraints
-
-- Do not change `src/lip-sync-analyser.js` or `src/agent-avatar.js`
- unless the new tests reveal a real bug. If they do, fix it — but
- call it out clearly in the summary.
-- Do not add a real audio fixture binary to the repo. Generate audio
- programmatically inside the test (zeros for silence; a sine for
- signal).
-- If the existing test setup already covers a behavior, **delete that
- case from this prompt's scope** rather than adding a duplicate.
diff --git a/prompts/finish-features/finish-resend-integration.md b/prompts/finish-features/finish-resend-integration.md
deleted file mode 100644
index d52695831..000000000
--- a/prompts/finish-features/finish-resend-integration.md
+++ /dev/null
@@ -1,123 +0,0 @@
-# Task: Audit Resend integration end-to-end
-
-## Repo context
-
-Working tree: `/workspaces/three.ws`. Vanilla JS + Vite frontend
-(`npm run dev` → port 3000). Backend: Vercel functions in `api/`, workers in
-`workers/`. Email is sent through Resend via `api/_lib/email.js`. The
-codebase ships email for: auth (signup, password reset), SIWE/SIWS auth flows,
-payments (EVM + Solana), cron jobs, newsletter subscribe.
-
-## Rails (CLAUDE.md — non-negotiable)
-
-- No mocks, no fake data, no placeholders, no TODOs, no stubs, no
- `throw new Error('not implemented')`, no commented-out code, no
- `setTimeout` fake-loading, no fallback sample arrays.
-- Real APIs only — for tests, use fixture-based assertions against real
- Resend response shapes, not mocked Resend clients.
-- Errors handled at boundaries only.
-- Done = `npm test` green, `git diff` reviewed.
-- Push to both remotes only when the user says push.
-
-## Problem
-
-`api/_lib/email.js` is the single send path, but call sites have drifted.
-Some risks:
-
-1. `RESEND_API_KEY` is unset in dev and on preview deploys. Every caller
- must handle that without throwing — return early, no-op, log once.
-2. Template names and argument shapes may have diverged between caller and
- the helper (a renamed prop silently breaks the rendered HTML).
-3. Some templates may render invalid HTML (unclosed tags, broken URLs,
- missing alt text) — never noticed because no one inspects the rendered
- output.
-4. There are no fixture-based unit tests under `tests/email.test.js`.
-
-## What to implement
-
-### Step 1 — map every caller (delegate to subagent)
-
-Spawn an **Explore** subagent with this prompt:
-
-> Find every file in `/workspaces/three.ws` that imports from
-> `api/_lib/email.js` or calls `sendEmail` / `sendTemplate` / similar
-> exports. For each hit, return: file path, line number, the exact call
-> shape (function name + arg keys), and the calling endpoint or job name.
-> Exclude `node_modules`, `dist`, `publish`, `agent-voice-chat/` (vendored),
-> `agent-payments-sdk/` (vendored). Return as a markdown table.
-
-Use the returned table as the audit checklist.
-
-### Step 2 — audit each call site sequentially
-
-For each caller in the table:
-
-1. Read the file. Confirm it handles the no-API-key case **without
- throwing**. The helper itself should already return early on missing
- key — the caller should likewise not block the user-facing flow.
-2. Confirm the template name passed to the helper exists in
- `api/_lib/email.js` (or wherever templates live).
-3. Confirm the argument shape matches what the template expects (no
- missing keys; no extra keys silently dropped).
-4. Render the template once locally (via a script under `scripts/` if
- one helps) and visually scan the HTML for: unclosed tags, broken
- image URLs (must be absolute https), broken action URLs, missing
- `<title>`, missing plain-text alternative.
-
-Fix any issue you find in place. Do not leave a TODO. Do not stub a
-template.
-
-### Step 3 — write fixture-based unit tests
-
-Create `tests/email.test.js` (or extend it if it exists). For each
-template, write a test that:
-
-1. Calls the template-render function with a realistic argument set.
-2. Asserts the rendered HTML contains the key user-facing strings
- (subject, action URL, recipient display name).
-3. Asserts the HTML parses as a valid DOM (use `linkedom` or `jsdom`
- — both are in the repo's deps; check `package.json` before adding).
-4. Asserts that when `RESEND_API_KEY` is unset, the public `sendEmail`
- export returns the documented "skipped" shape and does not throw.
-
-Do not mock the Resend client itself. Use the helper's documented
-no-key short-circuit behavior to exercise the skipped path. For the
-"would-send" path, assert the payload constructed before the network
-call (the helper should expose this either by returning it under a
-`debug` key in test mode, or via a separate `buildPayload` export — if
-neither exists, add the export rather than mocking fetch).
-
-### Step 4 — run the suite
-
-```bash
-npm test
-```
-
-All existing tests must still pass. New tests must pass.
-
-### Step 5 — summarize what changed
-
-Write to the response: which call sites were broken, how you fixed each
-one, what tests you added. Do not commit unless the user asks.
-
-## Definition of done
-
-- Every call site of `api/_lib/email.js` is documented and audited.
-- Every caller handles missing `RESEND_API_KEY` without throwing.
-- Every template renders valid HTML with the expected user-facing
- strings.
-- `tests/email.test.js` exists with at least one fixture-based test per
- template.
-- `npm test` is green.
-- `git diff` shows only intentional changes.
-
-## Constraints
-
-- Do not mock the Resend SDK. Use real payload assertions.
-- Do not add new templates unless an existing caller is broken because
- the template it references is missing.
-- Do not change the public signature of `sendEmail` unless every caller
- is updated in the same diff.
-- If you discover that the audit reveals more than ~6 broken call sites,
- stop and report — the user may want to triage rather than fix all in
- one pass.
diff --git a/prompts/finish-features/fix-referral-code-uniqueness.md b/prompts/finish-features/fix-referral-code-uniqueness.md
deleted file mode 100644
index e0e00c226..000000000
--- a/prompts/finish-features/fix-referral-code-uniqueness.md
+++ /dev/null
@@ -1,150 +0,0 @@
-# Task: Fix referral-code uniqueness race in signup
-
-## Repo context
-
-Working tree: `/workspaces/three.ws`. The signup handler is in
-`api/auth/[action].js`. Around line 109, after the user is inserted,
-a referral code is generated for the new account:
-
-```js
-// TODO: loop until referral code is unique
-const newReferralCode = generateReferralCode();
-const [user] = await sql`insert into users (... referral_code) values (... ${newReferralCode}) returning ...`;
-```
-
-`generateReferralCode()` returns a short string (likely 6-8 alphanumeric
-chars). The `users.referral_code` column has a unique index — so two
-simultaneous signups can collide and the second one will fail with a
-Postgres unique-violation, returning a confusing 500 to the user.
-
-## Rails (CLAUDE.md — non-negotiable)
-
-- No mocks, no fake data, no placeholders, no TODOs, no stubs.
-- Real APIs only — the fix must work against the real Postgres unique
- index, not a sentinel check.
-- Errors handled at boundaries only — the loop is at the boundary
- (insert), so a try/catch on the unique-violation error code is the
- right level.
-- Done = the TODO comment is gone, the race is closed, `npm test`
- green.
-- Push to both remotes only when the user says push.
-
-## What to implement
-
-### Step 1 — confirm the unique index exists
-
-```bash
-grep -rn "referral_code" /workspaces/three.ws/migrations/
-```
-
-If `users.referral_code` has a unique index, the retry loop is the
-fix. If it does not, **add a migration that creates the unique index**
-first, then add the retry loop. Both pieces ship in the same diff.
-
-A unique partial index is fine if `referral_code` is nullable:
-
-```sql
-CREATE UNIQUE INDEX IF NOT EXISTS users_referral_code_unique
- ON users (referral_code)
- WHERE referral_code IS NOT NULL;
-```
-
-### Step 2 — implement the retry loop
-
-Replace the current single-shot generation with a bounded retry. The
-postgres unique-violation `SQLSTATE` is `23505`.
-
-```js
-async function insertUserWithUniqueReferralCode(fields) {
- const MAX_TRIES = 8;
- for (let i = 0; i < MAX_TRIES; i += 1) {
- const code = generateReferralCode();
- try {
- const [row] = await sql`
- insert into users (email, password_hash, display_name, referred_by_id, referral_code)
- values (${fields.email}, ${fields.passwordHash}, ${fields.displayName}, ${fields.referredById}, ${code})
- returning id, display_name, plan, created_at, referral_code
- `;
- return row;
- } catch (err) {
- // Postgres unique-violation
- if (err && err.code === '23505' && /referral_code/.test(err.message || '')) {
- continue; // try a new code
- }
- throw err;
- }
- }
- throw new Error('referral_code_generation_exhausted');
-}
-```
-
-Use it in place of the existing `const newReferralCode = ...; const
-[user] = await sql\`insert ...\`;` block. Delete the TODO comment.
-
-The `referral_code_generation_exhausted` error should be caught
-upstream in the handler and converted into a 500 with a short message
-— but in practice the probability of 8 consecutive collisions on an
-8-char alphanumeric space (62^8 ≈ 2.18e14) is vanishingly small unless
-`generateReferralCode()` itself is broken.
-
-### Step 3 — confirm `generateReferralCode()` has enough entropy
-
-```bash
-grep -rn "generateReferralCode" /workspaces/three.ws/src /workspaces/three.ws/api
-```
-
-Read the implementation. It must use a CSPRNG (`crypto.randomUUID()`
-substring, or `crypto.getRandomValues()`, or Node's `crypto.
-randomBytes`). It must **not** use `Math.random()`. If it does, fix it
-in the same diff — that is a real bug.
-
-### Step 4 — add a unit test
-
-Create or extend `tests/auth-signup.test.js`. Use vitest. The test:
-
-1. Sets up an in-memory or test-db connection (read other tests in
- `tests/` to find the pattern used; do not invent a new DB harness).
-2. Inserts a user with a known referral_code.
-3. Stubs `generateReferralCode` to return the same code on the first
- call and a different code on the second call.
-4. Calls the signup handler.
-5. Asserts the inserted user has the **second** referral_code.
-6. Asserts no error was returned to the client.
-
-If the repo's other tests use Vercel handler harnesses (`node-mocks-
-http` or similar), match that pattern.
-
-### Step 5 — run the suite
-
-```bash
-npm test
-```
-
-### Step 6 — manual smoke
-
-```bash
-npm run dev
-# signup with curl, confirm 201 and a referral_code in the response
-```
-
-Run the curl twice with two different emails; confirm both succeed.
-
-## Definition of done
-
-- The `// TODO: loop until referral code is unique` comment in
- `api/auth/[action].js` is gone.
-- The collision-retry loop is in place and bounded.
-- `generateReferralCode()` uses a CSPRNG.
-- A test covers the collision path.
-- `npm test` is green.
-- Two consecutive signups via `curl` both return 201.
-
-## Constraints
-
-- Do not raise `MAX_TRIES` above 8. If you find yourself wanting to,
- the generator's entropy is too low — fix the generator instead.
-- Do not log the referral code at error level. It's user-facing data;
- keep it out of error logs.
-- Do not change the response shape of the signup endpoint.
-- Do not remove the unique index even if you add the retry loop. The
- index is the authoritative guard; the retry loop is the UX shield.
diff --git a/prompts/finish-features/implement-pump-swap-inner-ix.md b/prompts/finish-features/implement-pump-swap-inner-ix.md
deleted file mode 100644
index 454eee6a6..000000000
--- a/prompts/finish-features/implement-pump-swap-inner-ix.md
+++ /dev/null
@@ -1,227 +0,0 @@
-# Task: Implement the pump-swap inner instruction in the buyback cron
-
-## Repo context
-
-Working tree: `/workspaces/three.ws`. The buyback cron at
-`api/cron/[name].js` (around line 1178) currently runs only the
-**burn** path of the Pump.fun buyback program. The **full-swap** path
-is stubbed:
-
-```js
-const params = {
- globalBuybackAuthority: payerPk,
- currencyMint: currency,
- swapProgramToInvoke: PUMP_PROGRAM_ID || payerPk, // sentinel for skip-swap
- swapInstructionData: Buffer.alloc(0), // empty = skip swap, just burn
- remainingAccounts: [],
-};
-
-if (fullSwap) {
- // TODO(Phase 3.1): build pump-swap inner ix here. Skipping for safety;
- // keepers should supply this off-chain until tested on devnet.
-}
-
-let ix;
-try {
- ix = await offline.buybackTrigger(params);
- // ...
-}
-```
-
-`fullSwap` is a configured boolean per buyback mint. When true, the
-cron is supposed to build a real pump-swap inner instruction
-(buy-on-curve → burn), populate `swapInstructionData` + `remaining-
-Accounts`, then let `offline.buybackTrigger(params)` wrap them into the
-outer buyback CPI. Today it does nothing in the `fullSwap` branch,
-which means buybacks configured for full-swap silently fall back to
-burn-only.
-
-## Rails (CLAUDE.md — non-negotiable)
-
-- No mocks. The implementation must build a **real** pump-swap ix
- against the on-chain program, not a placeholder buffer.
-- No fake data. Account lists are derived from real on-chain state
- (PDA derivations against the actual program).
-- Done = the `TODO(Phase 3.1)` comment is gone, an end-to-end devnet
- run completes a full-swap buyback successfully, `npm test` green.
-- Push to both remotes only when the user says push.
-- **No on-chain operations against mainnet without explicit user
- approval.** Devnet only for testing.
-
-## Subagent delegation
-
-This task is big and research-heavy. Spawn subagents in parallel for
-the research phase, then implement sequentially.
-
-### Subagent A (Explore)
-
-> In `/workspaces/three.ws`, find every reference to pump-swap and
-> the buyback program. Return:
->
-> 1. The exact import path and exported surface of `@pump-fun/agent-
-> payments-sdk`. Quote the `buybackTrigger` signature and the
-> expected shapes of `swapInstructionData` and `remainingAccounts`.
-> 2. Every existing builder for a pump-swap or pump-fun program ix
-> in the repo (likely under `solana-agent-sdk/`, `sdk/`, or
-> `agent-payments-sdk/`). Quote the function names and signatures.
-> 3. Any existing devnet test or script that exercises a full-swap
-> buyback. Even partial / disabled tests count — quote the path.
-> 4. The `PUMP_PROGRAM_ID` value (mainnet vs devnet) and any other
-> program-ID constants used by the swap path.
-
-### Subagent B (Explore)
-
-> In `/workspaces/three.ws`, find the schema for the `pump_buyback_
-> mints` table (or whatever the buyback config table is named).
-> Return:
->
-> 1. The column list, especially anything indicating `fullSwap`,
-> pool/curve identity, slippage tolerance, max-buy-amount, and
-> devnet-vs-mainnet flag.
-> 2. Every place where `fullSwap` is read or written, including the
-> admin UI that toggles it.
-
-### Subagent C (Plan)
-
-> Given the pump-swap program's published ix surface (research it
-> via the SDK source under `agent-payments-sdk/` and any pump-fun
-> docs), produce a step-by-step plan for building a buy-on-curve
-> inner ix that fits into `offline.buybackTrigger`'s
-> `swapInstructionData` + `remainingAccounts` slots. Specifically:
->
-> 1. Which pump-swap ix (buy? exact-out buy?) we should use.
-> 2. The full account list for that ix (in order, with PDA seeds).
-> 3. The data layout (discriminator + args).
-> 4. How slippage / min-amount-out is encoded.
-> 5. What we need to fetch on-chain before building it (curve PDA
-> state for current price, etc.).
-
-Wait for all three subagents to return before starting Step 1.
-
-## What to implement
-
-### Step 1 — build the inner-ix helper
-
-In `api/cron/[name].js` (or a small new module imported from there,
-e.g. `api/_lib/pump-swap-ix.js`), implement:
-
-```js
-async function buildPumpSwapInnerIx({
- mint, // base58 string
- currency, // PublicKey of quote currency (USDC etc.)
- amountIn, // BigInt or BN — quote-currency in
- minAmountOut, // BigInt or BN — base-token out floor (slippage guard)
- cluster, // 'devnet' | 'mainnet-beta'
-}) {
- // Returns: { data: Buffer, accounts: AccountMeta[] }
-}
-```
-
-The function:
-
-1. Derives the curve PDA for `mint` against the pump-swap program.
-2. Fetches its current state (read-only RPC call) to confirm the curve
- exists and is in a state that accepts buys.
-3. Builds the buy-on-curve ix data buffer (discriminator + `amount_in`
- + `min_amount_out` in the wire layout produced by Subagent C).
-4. Builds the `AccountMeta[]` list in program order: payer, curve PDA,
- base mint, base vault, quote mint, quote vault, fee recipient,
- program id, token program, system program, rent — adapt to the
- actual list Subagent C returns.
-5. Returns the raw `data` + `accounts` — **not** a `TransactionInstruction`
- wrapper, because `buybackTrigger` consumes them via
- `swapInstructionData` + `remainingAccounts` independently.
-
-### Step 2 — call it from the buyback cron
-
-Replace the empty `if (fullSwap) { ... }` block with:
-
-```js
-if (fullSwap) {
- const inner = await buildPumpSwapInnerIx({
- mint: m.mint,
- currency,
- amountIn: m.buy_amount_lamports, // or whatever column holds it
- minAmountOut: m.min_out_lamports,
- cluster: m.network,
- });
- params.swapProgramToInvoke = PUMP_SWAP_PROGRAM_ID; // not PUMP_PROGRAM_ID
- params.swapInstructionData = inner.data;
- params.remainingAccounts = inner.accounts;
-}
-```
-
-`PUMP_SWAP_PROGRAM_ID` is exported by `@pump-fun/agent-payments-sdk`
-(confirm via Subagent A). Use the real export — do not hard-code the
-base58 string.
-
-Delete the `TODO(Phase 3.1)` comment.
-
-### Step 3 — slippage / amount columns
-
-If the buyback-config table is missing `buy_amount` / `min_out_lamports`
-columns (Subagent B will tell you), add a migration that introduces
-them. The cron should read them per mint, not hard-code values.
-
-### Step 4 — unit test the builder
-
-`tests/pump-swap-ix.test.js`. Without hitting the chain, assert:
-
-1. `buildPumpSwapInnerIx` produces a `data` buffer whose first bytes
- are the documented discriminator.
-2. `min_amount_out` is encoded in the documented offset and is exactly
- the value passed in (little-endian, 8-byte).
-3. `accounts` length matches the program's expected list length, and
- key accounts (curve PDA, mints) appear at the right index.
-
-For the curve-state fetch, stub the RPC client at the boundary (the
-`Connection` instance), not the builder. Provide a fake account-info
-return value shaped like a real curve account.
-
-### Step 5 — devnet end-to-end run
-
-```bash
-SOLANA_CLUSTER=devnet npm run dev
-# or whatever script invokes the buyback cron locally
-```
-
-Configure a devnet test mint with `full_swap = true`, a tiny
-`buy_amount`, and a high slippage tolerance. Trigger the cron path
-(there should be an admin endpoint or a script under `scripts/` —
-check existing `scripts/` for a buyback runner).
-
-Watch:
-
-- The transaction succeeds on devnet.
-- `pump_buyback_runs` row records `status = 'success'`.
-- A Solana explorer link to the tx shows the inner pump-swap ix
- executed before the outer burn.
-
-If it fails, debug — do not paper over with a try/catch and a TODO.
-
-### Step 6 — keep the burn-only path working
-
-Run the existing burn-only path (a mint with `full_swap = false`) on
-devnet too. Confirm it still works — your changes must not regress it.
-
-## Definition of done
-
-- The `TODO(Phase 3.1)` comment is gone.
-- `buildPumpSwapInnerIx` exists, is tested, and is called from the
- cron when `fullSwap` is true.
-- A real devnet full-swap buyback run is recorded as success.
-- A real devnet burn-only buyback run still works.
-- `npm test` is green.
-- The summary includes the devnet tx signatures for both runs so a
- reviewer can verify on the explorer.
-
-## Constraints
-
-- Devnet only for testing. Do not run against mainnet.
-- Do not hard-code program IDs as base58 strings — import them from
- `@pump-fun/agent-payments-sdk`.
-- Do not catch the inner-ix builder's errors and silently fall back
- to burn-only. If `fullSwap` is configured and the inner ix fails,
- record `status = 'failed'` and surface the error.
-- Do not raise the outer cron timeout to mask a slow RPC. Investigate
- the slow RPC.
diff --git a/prompts/finish-features/resolve-viewer-light-todo.md b/prompts/finish-features/resolve-viewer-light-todo.md
deleted file mode 100644
index 6ff484ac0..000000000
--- a/prompts/finish-features/resolve-viewer-light-todo.md
+++ /dev/null
@@ -1,133 +0,0 @@
-# Task: Resolve `TODO(#116)` in `src/viewer.js`
-
-## Repo context
-
-Working tree: `/workspaces/three.ws`. `src/viewer.js` is the in-app
-GLTF viewer / inspector. At two sites (lines 92 and 1187) there is a
-comment:
-
-```js
-directIntensity: 0.8 * Math.PI, // TODO(#116)
-```
-
-and
-
-```js
-lightFolder.add(this.state, 'directIntensity', 0, 4), // TODO(#116)
-```
-
-`#116` refers to an issue. This file appears to be derived from (or
-inspired by) the KhronosGroup `glTF-Sample-Viewer` — that repo's
-issue #116 is the original tracker for "direct light intensity factor
-of π is non-physical."
-
-## Rails (CLAUDE.md — non-negotiable)
-
-- No mocks, no fake data, no placeholders, no TODOs, no stubs.
-- Real APIs only.
-- Done = the TODO comment is either resolved (with a real fix) or
- explicitly retired (with a one-line doc note explaining the choice),
- `npm test` green.
-- Push to both remotes only when the user says push.
-
-## What to implement
-
-### Step 1 — confirm provenance
-
-```bash
-git log --diff-filter=A -- src/viewer.js | head -20
-git log -p src/viewer.js | head -200
-```
-
-Confirm whether this file was vendored from
-`KhronosGroup/glTF-Sample-Viewer` or written in-house. Read the top
-of the file for any attribution comment.
-
-### Step 2 — read the actual issue
-
-If the file is vendored: open
-`https://github.com/KhronosGroup/glTF-Sample-Viewer/issues/116` (or
-the issue tracker the file's upstream uses). Read what the issue is
-actually about. The `0.8 * Math.PI` factor is a known fudge to
-compensate for a missing pre-Lambertian factor — the proper fix is
-to multiply *inside* the lighting math, not at the input, but that
-requires touching shader code.
-
-If the file is in-house: the TODO might be unrelated to upstream. Read
-the surrounding shader / light code to understand what `#116` refers
-to in this codebase's issue tracker (GitHub issues on
-nirholas/three.ws or nirholas/3D-Agent).
-
-### Step 3 — decide one of three outcomes
-
-A. **Implement the fix.** If the upstream issue has a resolved fix
- (a commit / PR in glTF-Sample-Viewer), port it. The fix typically
- involves removing the `* Math.PI` from the intensity multiplier
- and adjusting the shader uniform that consumes it. Validate
- visually: load `public/avatars/default.glb` (or whatever scene the
- viewer renders), confirm the lighting is approximately the same
- brightness, not 3× brighter or darker.
-
-B. **Retire the TODO with a doc note.** If the fix is too invasive
- for this task and the current behavior matches user expectation,
- replace the inline `TODO(#116)` with a one-line comment explaining
- why the magic factor stays:
-
- ```js
- // 0.8 * π keeps direct lights visually matched to the Sample-Viewer
- // reference baseline. Removing the π factor requires a shader-side
- // adjustment — see KhronosGroup/glTF-Sample-Viewer#116.
- directIntensity: 0.8 * Math.PI,
- ```
-
- This is allowed under CLAUDE.md: the rule forbids `TODO`, not
- informational comments. A `WHY` comment is fine.
-
-C. **Delete the lights folder feature.** Only if the viewer UI no
- longer exposes direct-light controls to the user.
-
-Pick the outcome based on what you find in Step 2.
-
-### Step 4 — apply the change
-
-Edit `src/viewer.js` at both line 92 and line 1187. Be consistent —
-either both lines fix the math, or both lines get the doc note.
-
-### Step 5 — verify visually
-
-```bash
-npm run dev
-```
-
-Open the viewer route (typically `/viewer` or `/playground` — confirm
-in `pages/` or `vite.config.js`). Load a known scene. Compare to a
-screenshot of the same scene before your change. The two should look
-visually similar — if not, you went with outcome A and the lighting
-should now match a physical reference, which means it will look a bit
-different. Either way, no console errors, no obviously-wrong shading.
-
-### Step 6 — run the suite
-
-```bash
-npm test
-```
-
-## Definition of done
-
-- Neither `// TODO(#116)` comment remains in `src/viewer.js`.
-- The replacement (real fix, doc note, or removal) is explained in
- the commit message body.
-- Viewer renders without console errors.
-- `npm test` is green.
-
-## Constraints
-
-- Do not change the public API of `Viewer` (the exported class /
- function in `src/viewer.js`) unless option C is chosen and the
- callers are updated in the same diff.
-- Do not silently delete the inline comment without explanation. The
- comment is load-bearing context for the next reader — replace it
- with either a real fix or a documented rationale, not nothing.
-- Do not pursue option A if you cannot test the visual outcome in a
- real browser. Without a visual comparison, you cannot verify the
- fix is correct — fall back to option B in that case.
diff --git a/prompts/finish-features/server-side-glb-render.md b/prompts/finish-features/server-side-glb-render.md
deleted file mode 100644
index be8636a5a..000000000
--- a/prompts/finish-features/server-side-glb-render.md
+++ /dev/null
@@ -1,222 +0,0 @@
-# Task: Server-side GLB → PNG renderer for OG cards
-
-## Repo context
-
-Working tree: `/workspaces/three.ws`. The avatar thumbnail flow today
-(after the recent `avatar-snapshot` ship documented in
-`docs/internal/PROGRESS.md` item 4):
-
-- Client renders a JPEG snapshot of the current three.js frame
- (`src/voice/avatar-snapshot.js`) after the customizer Save lands.
-- The snapshot is presigned + uploaded to R2 via
- `/api/avatars/...` (presign-thumbnail).
-- `/api/avatars/...?action=auto-tag` runs Claude Haiku vision on the
- snapshot to generate tags + a description.
-- `thumbnail_key` on the avatar row points to the R2 object.
-
-What's missing: **crawl-time OG card generation.** When Twitter,
-Discord, Slack, etc. crawl an avatar's public page, they fetch
-`/api/avatar-og.js?id=...` (or similar). If the avatar has no
-client-uploaded thumbnail yet (the customizer was never saved, or the
-avatar was created via API), the OG endpoint cannot produce a real
-PNG. Today it likely falls back to a generic placeholder.
-
-`docs/internal/NEXT.md` documents the deferred decision and recommends
-`puppeteer-core` + `@sparticuz/chromium-min` as the lowest-friction
-path despite the ~60 MB function bundle hit.
-
-## Rails (CLAUDE.md — non-negotiable)
-
-- No mocks. No fake data. No placeholders. No fallback sample
- arrays.
-- Real APIs only — the renderer must actually render the avatar GLB
- in a real browser engine, not an SVG approximation.
-- Done = a server-side render endpoint returns a real PNG for any
- avatar; OG crawlers fetching the avatar page see a real preview
- image; `npm test` green.
-- Push to both remotes only when the user says push.
-
-## Subagent delegation
-
-### Subagent A (Explore)
-
-> In `/workspaces/three.ws`, map the existing OG card and thumbnail
-> flow. Return:
->
-> 1. The path + signature of the avatar OG endpoint (likely
-> `api/avatar-og.js` or `api/a-og.js`). Quote the file.
-> 2. The path + signature of `api/avatars/...?action=auto-tag` and
-> `api/avatars/...?action=presign-thumbnail`.
-> 3. `src/voice/avatar-snapshot.js` — its exported API and where
-> it's called.
-> 4. The avatar page handler that emits OG meta tags (likely
-> `api/avatar-page.js` or `pages/avatar-page.html` + a runtime
-> that injects meta).
-> 5. The R2 / storage path scheme: what key does the client-uploaded
-> thumbnail land at? What key would a server-rendered PNG land at?
-
-### Subagent B (Explore)
-
-> Read `docs/internal/NEXT.md` and quote the section on server-side
-> GLB → PNG render. Then assess feasibility:
->
-> 1. Current Vercel function size budget for this repo (check
-> `vercel.json`, `package.json` for any `maxDuration` /
-> `regions` / size hints, and any existing large dep).
-> 2. The current cold-start latency of a similarly-sized function
-> in this repo (look at any function that imports puppeteer-core
-> or @sparticuz/chromium today — there may already be one).
-> 3. Whether the function should live under `api/` (Vercel) or in a
-> separate worker. The size budget answer determines this.
-
-Wait for both before starting Step 1.
-
-## What to implement
-
-### Step 1 — install deps
-
-```bash
-npm install puppeteer-core @sparticuz/chromium-min
-```
-
-These go into runtime `dependencies`, not devDependencies — they
-ship with the function.
-
-### Step 2 — build the renderer
-
-Create `api/_lib/render-glb.js` (or co-located under the existing
-`api/_lib/` patterns Subagent A surfaces). Export:
-
-```js
-export async function renderGlbToPng({ glbUrl, width = 1200, height = 630, background = 'transparent' }) {
- // Launches headless chromium, loads a tiny static viewer HTML page,
- // posts the glb URL into it, waits for the model to load + first
- // paint, screenshots the canvas, returns a PNG Buffer.
-}
-```
-
-Implementation:
-
-1. Use `chromium.executablePath` from `@sparticuz/chromium-min`.
-2. Launch `puppeteer-core` with `chromium.args` and
- `headless: chromium.headless`.
-3. Navigate to a tiny static HTML page bundled into the function.
- The HTML loads three.js + GLTFLoader + the provided GLB, renders
- one frame at the target resolution with deterministic camera +
- lighting, and exposes `window.__renderDone = true` when ready.
-4. `page.waitForFunction('window.__renderDone === true', { timeout:
- 15_000 })`.
-5. `page.screenshot({ type: 'png', omitBackground: background ===
- 'transparent', clip: { x: 0, y: 0, width, height } })`.
-6. Close the browser. Return the buffer.
-
-The tiny static HTML page should be **inlined as a string constant**
-in `render-glb.js` so the function bundle does not need a separate
-file. The string can reference three.js from a known CDN
-(`https://unpkg.com/three@0.<ver>/...`) — version must match
-`package.json` so the renderer behaves the same as the in-app viewer.
-
-### Step 3 — wire it into the avatar OG endpoint
-
-In whichever file Subagent A identified as the OG endpoint:
-
-1. Try the client-uploaded thumbnail first. If `thumbnail_key` is
- set and the R2 object exists, redirect (or stream) the existing
- PNG/JPEG.
-2. If no thumbnail exists, fall through to the server renderer:
- - Look up the avatar's GLB URL (the same URL the viewer loads).
- - Call `renderGlbToPng({ glbUrl, width: 1200, height: 630 })`.
- - Upload the resulting PNG to R2 under the documented key.
- - Update `thumbnail_key` on the avatar row.
- - Stream the PNG back to the crawler with the correct
- `Content-Type` and cache headers.
-
-Subsequent crawls of the same avatar should hit the cached thumbnail
-in R2 — the server render is amortized.
-
-### Step 4 — concurrency + budget guards
-
-Cold-start latency for chromium is real. Guard against:
-
-1. Concurrent renders for the same avatar: use a simple in-memory
- lock (Map of `avatarId → Promise`) so two simultaneous crawls do
- not both spin up chromium. The second one awaits the first.
-2. Function timeout: set `maxDuration: 30` in `vercel.json` for this
- endpoint (or whatever the platform's max allows). Render budget
- is 15s + 5s overhead.
-3. Bytes returned: if the GLB itself is >10 MB, the renderer will
- be slow and may OOM. Add a size precheck — head request the GLB
- URL, abort with a fallback placeholder if Content-Length > 10 MB.
- The placeholder is the **generic site logo**, not a synthetic
- "no preview" SVG.
-
-### Step 5 — manual end-to-end test
-
-```bash
-npm run dev
-```
-
-(Note: `puppeteer-core` + `@sparticuz/chromium-min` are designed for
-Vercel runtime; on local dev the chromium binary download from
-`@sparticuz/chromium-min` is a one-time blob.)
-
-1. Pick an avatar that has no `thumbnail_key` yet (or set
- `thumbnail_key = null` on a test row in dev).
-2. `curl -o /tmp/og.png 'http://localhost:3000/api/avatar-og.js?id=
- <id>'`
-3. Open `/tmp/og.png` — confirm it shows the avatar, not a
- placeholder.
-4. Curl again, confirm the second call is faster (cached path).
-5. Check Twitter's card validator / a meta-tag inspector against the
- public avatar page URL once deployed.
-
-### Step 6 — tests
-
-`tests/render-glb.test.js`. The full render path needs a real
-chromium and a real GLB, which makes it slow and CI-unfriendly. Two
-test layers:
-
-1. Unit: assert that `renderGlbToPng({ glbUrl: '...' })` returns a
- Buffer whose first 8 bytes are the PNG magic
- (`\x89PNG\r\n\x1a\n`). Use a tiny test GLB committed under
- `tests/fixtures/` (or generate one programmatically). Skip the
- test under CI by checking an env var (e.g. `process.env.CI &&
- !process.env.RUN_HEADFUL_TESTS`); document the skip.
-2. Integration with the OG endpoint: stub `renderGlbToPng` at the
- module boundary (since the unit test exercises the real path).
- Assert the endpoint reads `thumbnail_key`, falls through correctly,
- uploads to R2, updates the row.
-
-### Step 7 — clean up `docs/internal/NEXT.md`
-
-Remove the "deferred — server-side GLB → PNG render" section. Add a
-line under PROGRESS.md (item N+1) describing what was implemented.
-
-## Definition of done
-
-- `api/_lib/render-glb.js` exists and renders real GLB files to real
- PNGs via headless chromium.
-- The avatar OG endpoint serves: (a) the client thumbnail if
- present, (b) a freshly-rendered PNG if not, (c) a real fallback
- image (site logo) only if the GLB is too large.
-- Subsequent OG crawls hit the cached R2 object.
-- `npm test` is green (with the headful test appropriately skipped
- in CI).
-- A real social-media-card debugger shows the rendered preview for
- the avatar's public page.
-- `docs/internal/NEXT.md` no longer lists this as a deferred decision.
-
-## Constraints
-
-- Do not bundle `puppeteer` (full). Only `puppeteer-core` +
- `@sparticuz/chromium-min`. The full puppeteer ships a chromium
- download — incompatible with Vercel.
-- Do not call this renderer on every request. Always check the R2
- cache first.
-- Do not use a sentinel PNG (single-color or "no preview" SVG) as
- the fallback. CLAUDE.md forbids placeholder data — either render
- the avatar, or serve the real site logo, full stop.
-- Do not lock the function for >20s waiting for a render. If it
- times out, return the fallback and surface the timeout in logs
- (not as an error to the crawler — a 200 with the logo is better
- than a 500).
diff --git a/prompts/finish-features/stale-todo-sweep.md b/prompts/finish-features/stale-todo-sweep.md
deleted file mode 100644
index 9ae19b49d..000000000
--- a/prompts/finish-features/stale-todo-sweep.md
+++ /dev/null
@@ -1,134 +0,0 @@
-# Task: Stale-TODO sweep (recurring)
-
-## Repo context
-
-Working tree: `/workspaces/three.ws`. CLAUDE.md forbids `TODO`,
-`// implement later`, stub functions, and `throw new Error("not
-implemented")` in shipped code. This sweep is a **recurring task** —
-run it whenever the prompt is loaded, even if a previous run cleaned
-the repo.
-
-## Rails (CLAUDE.md — non-negotiable)
-
-- No mocks, no fake data, no placeholders, no TODOs, no stubs, no
- `throw new Error('not implemented')`, no commented-out code, no
- `setTimeout` fake-loading, no fallback sample arrays.
-- Real APIs only.
-- Done = every grep hit is either resolved or explicitly classified
- as legitimate (abstract base, JSON-RPC sentinel, vendored code).
-- Push to both remotes only when the user says push.
-
-## What to implement
-
-### Step 1 — delegate the grep to a subagent
-
-Spawn an **Explore** subagent with this prompt:
-
-> In `/workspaces/three.ws`, grep these directories only:
->
-> - `src/`
-> - `api/`
-> - `workers/`
-> - `pages/`
-> - `services/`
-> - `tasks/` (excluding the markdown task files)
-> - `scripts/`
->
-> Skip: `node_modules/`, `dist/`, `publish/`, `agent-voice-chat/`,
-> `agent-payments-sdk/`, `agent-protocol-sdk/`, `agent-voice-chat/`,
-> `solana-agent-sdk/`, `sdk/`, `avatar-sdk/`, `chat-plugin/`,
-> `multiplayer/`, `experiments/`, `scratch/`, `examples/`, all
-> `*.test.js` / `*.spec.js` files, and `docs/`.
->
-> Find every match for these patterns in `.js`, `.ts`, `.mjs`,
-> `.cjs`, `.jsx`, `.tsx`, `.html`, `.css`:
->
-> - `\bTODO\b`
-> - `\bFIXME\b`
-> - `\bXXX\b`
-> - `\bHACK\b`
-> - `implement later`
-> - `not implemented`
-> - `throw new Error\((['"])(not implemented|unimplemented|todo|stub)`
->
-> Also find every match for these patterns in the same scope:
->
-> - `const fake[A-Z]` (fake-data arrays)
-> - `const sample[A-Z][a-z]+` (sample-data arrays)
-> - `setTimeout\([^)]+,\s*\d+\).*//.*(fake|simulate|placeholder)`
->
-> Return a markdown table: `file:line | pattern | one-line context`.
-
-### Step 2 — classify each hit
-
-For each row in the table, classify into exactly one of:
-
-- **real-unfinished** — a feature or fix that was started and stopped.
- Must be implemented now.
-- **abstract-base** — `throw new Error('not implemented')` inside an
- `@abstract` class whose method is the documented interface for
- subclasses. Legitimate. Skip.
-- **jsonrpc-sentinel** — `throw rpcError(-32601, ...)` for "method
- not found" in a JSON-RPC handler. Legitimate. Skip.
-- **vendor-tracked** — a TODO referencing an upstream issue number
- (e.g. `TODO(#116)` in vendored code like the glTF Sample Viewer).
- Leave the comment; do not implement. Skip with note.
-- **perf-tracked** — a `TODO(perf):` comment for an optimization that
- is not currently broken (e.g. WASM grinder upgrade). Leave the
- comment; surface to user. Do not silently delete.
-
-### Step 3 — implement every real-unfinished item
-
-For each `real-unfinished` hit:
-
-1. Read the file and surrounding context.
-2. Implement the missing behavior with real wires per CLAUDE.md.
-3. Delete the comment / replace the throw with the implementation.
-4. Add a test if the file under `tests/` has a sibling for this
- module — extend it. Do not create a brand-new test file just for
- the comment removal unless the behavior change is non-trivial.
-
-If a `real-unfinished` item is genuinely out of scope (depends on
-infra you cannot touch, or needs credentials only the user has),
-stop and surface it. Do not delete the comment to silence the lint.
-
-### Step 4 — run the suite
-
-```bash
-npm test
-npx vite build
-```
-
-Both must succeed.
-
-### Step 5 — write a summary
-
-Return a markdown summary with:
-
-- A table of every hit, its classification, and the action taken.
-- A list of items left as `perf-tracked` so the user sees them.
-- A list of items escalated as out-of-scope (if any).
-
-Do not commit unless the user asks.
-
-## Definition of done
-
-- Every `real-unfinished` hit is implemented or escalated.
-- No `real-unfinished` hit remains in the codebase.
-- `vendor-tracked`, `abstract-base`, `jsonrpc-sentinel`, and
- `perf-tracked` items remain documented in their inline form.
-- `npm test` and `npx vite build` both succeed.
-- Summary report includes every grep hit and what happened to it.
-
-## Constraints
-
-- Do not delete code to silence the grep. Either finish it or
- escalate it.
-- Do not add new `TODO` comments to replace the old ones. If
- something is deferred, escalate it — do not re-encode it.
-- Do not touch vendored code (`agent-voice-chat/`,
- `agent-payments-sdk/`, etc.) even when matches appear under those
- trees if a stray grep slipped through.
-- This sweep is recurring. If a previous run already implemented the
- obvious items, you may find zero `real-unfinished` hits — that is
- the success state. Report it and stop.
diff --git a/prompts/finish-features/verify-demo-routes.md b/prompts/finish-features/verify-demo-routes.md
deleted file mode 100644
index 6c7eccd5b..000000000
--- a/prompts/finish-features/verify-demo-routes.md
+++ /dev/null
@@ -1,160 +0,0 @@
-# Task: Verify the demo route reorg + write `docs/demo-routes.md`
-
-## Repo context
-
-Working tree: `/workspaces/three.ws`. A recent refactor (commit
-`2071392c refactor(routes): use canonical clean URLs across JS, pages, and api
-redirects`) moved demo routes around:
-
-- `/coin` → `/demo/coin` (legacy URL should redirect, not 404)
-- `/demo/avatar-os/*` added
-- `/demos/*` added (plural index of demos)
-
-Routes are wired in two places:
-
-- `vercel.json` — production redirects/rewrites.
-- `vite.config.js` — dev-server entry points and aliases.
-
-## Rails (CLAUDE.md — non-negotiable)
-
-- No mocks. The verification must hit the **real** dev server and the
- **real** redirects, not a simulated router.
-- No fake data — read actual responses from `curl` and inspect them.
-- Done = every route returns a 200 (or the documented redirect to a
- 200), the new doc exists, `git diff` reviewed.
-- Push to both remotes only when the user says push.
-
-## What to implement
-
-### Step 1 — list every route to test
-
-Read `vercel.json` and `vite.config.js`. Enumerate:
-
-- Every entry under `/demo/*`.
-- Every entry under `/demos/*`.
-- Every redirect whose source contains `coin` (to verify the legacy
- `/coin` → `/demo/coin` mapping).
-- Every page file under `pages/` whose name starts with `demo-` or
- contains `coin`.
-
-Build a single markdown table with columns: `route`, `expected status`,
-`expected final URL` (after redirects).
-
-### Step 2 — start the dev server
-
-```bash
-npm run dev
-```
-
-Wait for it to come up (the build banner prints the port — typically
-`http://localhost:3000`). Run subsequent curl commands in another shell
-or with `&`.
-
-### Step 3 — curl each route
-
-For each row in the table:
-
-```bash
-curl -sIL -o /dev/null -w "%{http_code} %{url_effective}\n" http://localhost:3000<route>
-```
-
-`-L` follows redirects. `%{http_code}` is the final status.
-`%{url_effective}` is the final URL after any 30x bounces.
-
-Fill in the actual values in the table.
-
-### Step 4 — for each 200, inspect the rendered HTML
-
-```bash
-curl -sL http://localhost:3000<route> | grep -i -E "<title>|error|404"
-```
-
-Confirm:
-
-- A `<title>` exists and is not the generic Vite placeholder.
-- No "error" or "404" text in the rendered HTML.
-- The page loads its JS bundle (look for a `<script type="module"
- src=`).
-
-If any of these fail, **fix the underlying route**:
-
-- If `vercel.json` is missing a rewrite, add it. Match the convention
- of the entries already there.
-- If `vite.config.js` is missing an entry under `build.rollupOptions.
- input`, add it. Match the convention.
-- Then re-curl until the row passes.
-
-### Step 5 — verify in a real browser
-
-```bash
-# server already running
-```
-
-For each route, open `http://localhost:3000<route>` in a browser.
-Confirm:
-
-- No console errors in devtools.
-- Network tab shows the expected HTML + JS + GLB / asset fetches all
- succeeding.
-
-The user can see things curl can't — do this step honestly.
-
-### Step 6 — write `docs/demo-routes.md`
-
-Structure:
-
-```markdown
-# Demo routes
-
-The canonical map of every `/demo/*` and `/demos/*` route as of
-<today's date>. Update whenever a route is added, removed, or moved.
-
-## Routes
-
-| Route | Page file | What it does |
-|---|---|---|
-| `/demo/coin` | `pages/pump-coin-page.html` | ... |
-| ... | | |
-
-## Legacy redirects
-
-| Old | New | Configured in |
-|---|---|---|
-| `/coin` | `/demo/coin` | `vercel.json` |
-| ... | | |
-
-## Adding a new demo
-
-1. Create the page under `pages/demo-foo.html`.
-2. Add to `vite.config.js` under `build.rollupOptions.input`.
-3. Add to `vercel.json` rewrites if the URL is not the file name.
-4. Add a row to the table above.
-5. Curl-verify the route returns 200.
-```
-
-Fill in every row from the verified table.
-
-### Step 7 — kill the dev server
-
-```bash
-# Ctrl-C / kill the background pid
-```
-
-## Definition of done
-
-- Every route in the table returns the expected status (200 or
- documented 30x).
-- Every legacy redirect lands on a 200.
-- `docs/demo-routes.md` exists and reflects the live state.
-- `git diff` shows only intentional changes (the new doc, and any
- route fixes in `vercel.json` / `vite.config.js`).
-
-## Constraints
-
-- Do not change page content. Only fix routing (`vercel.json`,
- `vite.config.js`) when a route is broken.
-- If a page file is missing entirely for a route the config tries to
- serve, do not invent the page. Report and stop — the user may have
- removed it intentionally.
-- Do not generate the route table by reading config alone. Verify
- every row with a real curl. Config can lie; HTTP cannot.
diff --git a/prompts/finish-features/wasm-vanity-grinder.md b/prompts/finish-features/wasm-vanity-grinder.md
deleted file mode 100644
index ddd666e1f..000000000
--- a/prompts/finish-features/wasm-vanity-grinder.md
+++ /dev/null
@@ -1,184 +0,0 @@
-# Task: WASM-backed vanity-address grinder
-
-## Repo context
-
-Working tree: `/workspaces/three.ws`. `src/solana/vanity/grinder.js` is
-a pure-JS Solana keypair vanity grinder — it generates ed25519 keypairs
-in a loop until the public key's base58 representation matches a
-user-supplied prefix. Today it runs ~50-200k keypairs/sec depending on
-device; a WASM build of the same loop typically runs ~10× faster.
-
-A `TODO(perf)` comment at line 138 says:
-
-> TODO(perf): drop in a WASM grinder backed by the toolkit's Rust crate
-
-## Rails (CLAUDE.md — non-negotiable)
-
-- No mocks, no fake data, no placeholders, no TODOs, no stubs.
-- Real builds — the WASM must be produced from real Rust source, not
- copied from a CDN of unverified origin.
-- Done = the TODO comment is gone, a real WASM grinder is wired in
- with a measurable speedup, `npm test` green.
-- Push to both remotes only when the user says push.
-
-## Subagent delegation
-
-This task crosses Rust + WASM + JS, which is a large surface. Spawn
-subagents for research; implement sequentially.
-
-### Subagent A (Explore)
-
-> In `/workspaces/three.ws`, find:
->
-> 1. The exact API surface of `src/solana/vanity/grinder.js`: every
-> exported function with its signature, return shape, callers.
-> 2. Every caller (likely `src/erc8004/vanity-modal.js` and possibly
-> a Web Worker).
-> 3. Whether the grinder runs in the main thread or a Web Worker
-> today (read the call site).
-> 4. Any existing Rust / WASM build steps in the repo (`Cargo.toml`,
-> `wasm-pack`, `vite.config.js` WASM plugins).
-
-### Subagent B (Explore)
-
-> Survey existing open-source Solana ed25519 vanity grinders that
-> compile to WASM. Specifically:
->
-> 1. Is there a published npm package (e.g. `@solana/vanity-wasm`,
-> `solana-vanity-wasm`) we can install instead of building our
-> own? If so, quote its API.
-> 2. If we must build our own, identify a small audited Rust crate
-> (e.g. `ed25519-dalek` + `bs58`) that compiles cleanly to WASM
-> with `wasm-pack`.
-> 3. Note any licensing constraints.
-
-Wait for both subagents before deciding the path.
-
-## What to implement
-
-### Path A — published package (preferred if Subagent B finds one)
-
-1. `npm install <package>` (devDependency or dependency depending on
- whether the grinder is shipped to the browser; it is — so prod
- dep).
-2. Replace the JS grinding loop in `src/solana/vanity/grinder.js`
- with a call into the WASM package. Keep the exported function
- signature identical so callers do not need to change.
-3. Add a `await initWasm()` step at module load if the package
- requires it.
-4. Skip to **Step 5 — benchmark**.
-
-### Path B — build from Rust source (if no good published package)
-
-1. Create `crates/vanity-grinder/` with:
- - `Cargo.toml` declaring `crate-type = ["cdylib"]`, dependencies
- `wasm-bindgen`, `ed25519-dalek`, `bs58`, `getrandom = { version =
- "*", features = ["js"] }`.
- - `src/lib.rs` exposing one function:
- ```rust
- #[wasm_bindgen]
- pub fn grind(prefix: &str, batch: u32) -> JsValue { ... }
- ```
- Grinds up to `batch` keypairs; returns `null` if no hit, else
- `{ secretKey: Uint8Array, publicKey: string }`.
-2. Add `wasm-pack` to devDependencies via npm script:
- ```json
- "build:wasm": "wasm-pack build crates/vanity-grinder --target web --out-dir ../../src/solana/vanity/wasm"
- ```
-3. Commit the generated `src/solana/vanity/wasm/` output (`.wasm`,
- `.js`, `.d.ts`). Add an `.npmrc`-style note in
- `src/solana/vanity/wasm/README.md` that it is generated from the
- Rust crate and must not be edited.
-4. Wire the wasm into `grinder.js`:
- ```js
- import init, { grind } from './wasm/vanity_grinder.js';
- let _ready = false;
- async function ensure() { if (!_ready) { await init(); _ready = true; } }
- export async function grindKeypair(prefix, opts = {}) {
- await ensure();
- const batchSize = opts.batchSize ?? 50_000;
- while (!opts.signal?.aborted) {
- const hit = grind(prefix, batchSize);
- if (hit) return hit;
- await new Promise((r) => setTimeout(r, 0)); // yield to event loop
- }
- throw new Error('aborted');
- }
- ```
- The exact shape depends on Subagent A's findings about the current
- exported signature — match it.
-
-### Step 5 — benchmark
-
-Run the existing pure-JS grinder once on a known prefix (3 chars,
-e.g. `"abc"`), record the wall-clock time. Then run the WASM grinder
-on the same prefix, record the time. Document both in the PR / commit
-message. Expected speedup is at least 5×; if it is below that, the
-WASM build is not configured right (likely a debug build instead of
-release).
-
-### Step 6 — preserve abort semantics
-
-The current grinder accepts an `AbortSignal` so the modal can cancel
-when the user closes it. Verify your WASM path honors abort within a
-reasonable latency (one batch at most). If the WASM `grind()` call
-blocks for several seconds per batch, lower `batchSize` to keep abort
-latency under 200 ms.
-
-### Step 7 — Web Worker
-
-If Subagent A reports the grinder runs in a Web Worker today (likely),
-keep it in the Worker. WASM works inside Workers — make sure the
-Worker imports the same wasm-bindgen output. Verify the modal's UI
-stays responsive while grinding.
-
-### Step 8 — tests
-
-Extend whatever `tests/` covers `grinder.js`. Cases:
-
-1. Grinding for a known prefix returns a keypair whose public key
- starts with that prefix.
-2. The secret key, when used to sign a known message and verified
- against the returned public key, validates.
-3. Aborting via the AbortSignal returns within 200 ms.
-
-Test against the real WASM; do not stub it.
-
-### Step 9 — run the full suite + dev smoke
-
-```bash
-npm test
-npm run dev
-# Open the vanity modal in the UI, grind a 2-char prefix, watch it
-# finish in well under a second. Confirm no console errors.
-```
-
-### Step 10 — clean up
-
-- Delete the `TODO(perf)` comment.
-- If Path B was taken, add a CI step (or a doc note) that
- `npm run build:wasm` must run after any Rust change. Vite must not
- silently serve a stale wasm.
-
-## Definition of done
-
-- The `TODO(perf)` comment in `src/solana/vanity/grinder.js` is gone.
-- The grinder uses a real WASM implementation (path A or path B).
-- A benchmark shows at least 5× speedup on a 3-char prefix.
-- Tests pass.
-- Manual UI smoke test confirms no regression in the vanity modal.
-- `git diff` reviewed.
-
-## Constraints
-
-- Do not copy a pre-built `.wasm` from an unverified source. Either
- install a published npm package or build from Rust source in this
- repo.
-- Do not freeze the main thread. The grinder must yield (Worker or
- batched microtasks) so the UI stays responsive.
-- Do not log secret keys at any level. Even in dev.
-- This task is **perf**, not a feature. If the WASM grinder is more
- trouble than the speedup is worth (Subagent B finds no clean path,
- Rust toolchain not available, etc.), report and stop — leave the
- JS grinder in place and convert the `TODO(perf)` comment into a
- doc note explaining the decision.
diff --git a/public/features.json b/public/features.json
index 03ae324a8..08cabb923 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-08T04:53:56.117Z",
+ "generated_at": "2026-06-08T05:24:40.143Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -1155,6 +1155,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/news/three-ws-first-month-3d-agent-layer",
+ "title": "One Month In: How three.ws Built the 3D Agent Layer of the Internet",
+ "description": "In one month, three.ws went from launch to global coverage: browser-native 3D AI agents listed across major exchanges and data platforms, deployed on four hyperscale clouds, live in Anthropic's MCP Registry, and covered from CoinMarketCap to Vogue. A look back at 30 days of shipping.",
+ "added": null,
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/news/cmc-mcp-registry-article",
"title": "three.ws Brings Autonomous Payments and 3D Generation to Anthropic's Official MCP Registry",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 9d155a002..d90f15379 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -716,6 +716,12 @@ URL: https://three.ws/news/
Product launches, integrations, and announcements from three.ws.
+### One Month In: How three.ws Built the 3D Agent Layer of the Internet
+
+URL: https://three.ws/news/three-ws-first-month-3d-agent-layer
+
+In one month, three.ws went from launch to global coverage: browser-native 3D AI agents listed across major exchanges and data platforms, deployed on four hyperscale clouds, live in Anthropic's MCP Registry, and covered from CoinMarketCap to Vogue. A look back at 30 days of shipping.
+
### three.ws Brings Autonomous Payments and 3D Generation to Anthropic's Official MCP Registry
URL: https://three.ws/news/cmc-mcp-registry-article
diff --git a/public/llms.txt b/public/llms.txt
index f5ce5f3b5..ed8a261c9 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -144,6 +144,7 @@ Long-form announcements, launches, and writing from three.ws.
Product launches, integrations, and announcements from three.ws.
- [News & Announcements](https://three.ws/news/): Product launches, integrations, and announcements from three.ws.
+- [One Month In: How three.ws Built the 3D Agent Layer of the Internet](https://three.ws/news/three-ws-first-month-3d-agent-layer): In one month, three.ws went from launch to global coverage: browser-native 3D AI agents listed across major exchanges and data platforms, deployed on four hyperscale clouds, live in Anthropic's MCP Registry, and covered from CoinMarketCap to Vogue. A look back at 30 days of shipping.
- [three.ws Brings Autonomous Payments and 3D Generation to Anthropic's Official MCP Registry](https://three.ws/news/cmc-mcp-registry-article): CoinMarketCap article: three.ws brings autonomous payments and 3D generation to Anthropic's official MCP Registry — two new MCP servers give Claude and any MCP client the ability to spawn 3D agents and make on-chain x402 payments via the Coinbase-powered x402 Bazaar.
- [three.ws Ships Two New MCP Servers: x402 Bazaar + 3D Agent Avatar](https://three.ws/news/mcp-servers-x402-bazaar-coinbase): two new MCP servers are now live in Anthropic's official MCP Registry: the x402 Bazaar MCP (powered by Coinbase) lets agents discover, pay for, and call any x402 service in USDC settled on-chain; the 3D Avatar MCP lets any Claude or MCP client spawn a full browser-native 3D agent.
- [$three Listed on Bybit Alpha](https://three.ws/news/bybit-alpha-listing): $three is now listed on Bybit Alpha — the dedicated launchpad for new and emerging assets on Bybit, one of the world's top three crypto exchanges.
diff --git a/public/paywall.html b/public/paywall.html
index d41954bc7..70806db9b 100644
--- a/public/paywall.html
+++ b/public/paywall.html
@@ -199,6 +199,53 @@
display: none;
}
.wallet-status.visible { display: block; }
+ .wallet-status.pw-status-error {
+ border-color: rgba(248,113,113,0.3);
+ background: rgba(248,113,113,0.07);
+ color: #f87171;
+ }
+ .wallet-status.pw-status-error strong { color: #fca5a5; }
+ .pw-status-row { display: flex; align-items: center; gap: 10px; }
+ .pw-spin { flex-shrink: 0; color: var(--text-2); animation: pw-spin 0.8s linear infinite; }
+ @keyframes pw-spin { to { transform: rotate(360deg); } }
+
+ /* Unlocked / confirmed state */
+ .service-icon.pw-ok-icon {
+ background: #0b2a18; border-color: #14532d; color: #4ade80;
+ }
+ .pw-receipt {
+ margin-top: 18px;
+ display: flex; flex-direction: column; gap: 6px;
+ }
+ .pw-receipt-row {
+ display: flex; align-items: center; justify-content: space-between; gap: 12px;
+ font-family: var(--font-mono); font-size: 12px;
+ }
+ .pw-receipt-row .pw-k { color: var(--text-3); }
+ .pw-receipt-row .pw-v { color: var(--text); text-align: right; word-break: break-all; }
+ .pw-receipt-row .pw-v a { color: #6aa8ff; }
+ .pw-receipt-row .pw-v a:hover { text-decoration: underline; }
+ .pw-unlocked-label {
+ font-family: var(--font-mono); font-size: 10.5px;
+ letter-spacing: 0.15em; text-transform: uppercase;
+ color: var(--text-4); margin-bottom: 10px;
+ }
+ .pw-content-pre {
+ margin: 0;
+ background: var(--surface-2);
+ border: 1px solid var(--hairline);
+ border-radius: 8px;
+ padding: 14px;
+ font-family: var(--font-mono); font-size: 11.5px; line-height: 1.5;
+ color: var(--text-2);
+ overflow: auto; max-height: 320px;
+ white-space: pre-wrap; word-break: break-word;
+ }
+ .pw-content-frame {
+ width: 100%; min-height: 280px; max-height: 60vh;
+ border: 1px solid var(--hairline);
+ border-radius: 8px; background: #fff;
+ }
/* Advanced: paste tx hash */
.accordion-trigger {
@@ -380,6 +427,7 @@
<footer class="page-footer">Secured by the x402 micropayment protocol</footer>
+<script type="module" src="/x402-pay-core.js"></script>
<script src="/paywall.js"></script>
<script src="/brand.js" defer></script>
</body>
diff --git a/public/paywall.js b/public/paywall.js
index 0f441e9cf..d2905c962 100644
--- a/public/paywall.js
+++ b/public/paywall.js
@@ -193,46 +193,151 @@
});
}
- // ── Wallet click ───────────────────────────────────────────────────────
+ // ── Wallet click — real x402 payment flow ───────────────────────────────
+
+ var paymentInFlight = false;
+
+ var PHASE_TEXT = {
+ connecting: 'Connecting wallet…',
+ building: 'Building payment…',
+ signing: 'Waiting for signature…',
+ confirming: 'Confirming on-chain…',
+ };
+
+ function spinnerSvg() {
+ return '<svg class="pw-spin" width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true">' +
+ '<circle cx="12" cy="12" r="9" stroke="currentColor" stroke-width="3" stroke-opacity="0.25" />' +
+ '<path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" stroke-width="3" stroke-linecap="round" />' +
+ '</svg>';
+ }
+
+ function setWalletStatus(statusEl, phase, text) {
+ statusEl.classList.add('visible');
+ statusEl.classList.remove('pw-status-error');
+ statusEl.setAttribute('role', 'status');
+ var msg = text || PHASE_TEXT[phase] || 'Working…';
+ statusEl.innerHTML =
+ '<span class="pw-status-row">' + spinnerSvg() + '<span>' + escHtml(msg) + '</span></span>';
+ }
+
+ function setWalletError(statusEl, message) {
+ statusEl.classList.add('visible');
+ statusEl.classList.add('pw-status-error');
+ statusEl.setAttribute('role', 'alert');
+ statusEl.innerHTML = '<strong>Payment failed.</strong> ' + escHtml(message);
+ }
+
+ function setButtonsDisabled(disabled) {
+ document.querySelectorAll('.wallet-btn').forEach(function (b) {
+ b.disabled = disabled;
+ });
+ }
/**
- * Show an "Opening wallet…" message with the raw payment requirements.
- * Full on-chain wallet integration is browser-wallet-specific; this UI
- * explains what would happen and surfaces the requirements for dev use.
+ * Connect the chosen wallet, build + sign the x402 payment per the surfaced
+ * requirement, settle on-chain, retry the gated resource with the proof, and
+ * reveal the unlocked content. Drives real connecting/signing/confirming
+ * states throughout — no fake progress.
*/
function handleWalletClick(walletName, net, requirements) {
- var statusId = 'wallet-status-' + net;
- var statusEl = document.getElementById(statusId);
+ if (paymentInFlight) return;
+ var statusEl = document.getElementById('wallet-status-' + net);
if (!statusEl) return;
- var req = (requirements || []).find(function (r) {
+ var api = window.PaywallWallet;
+ if (!api || typeof api.pay !== 'function') {
+ setWalletError(statusEl, 'Payment module failed to load. Reload the page and try again.');
+ return;
+ }
+
+ var accept = (requirements || []).find(function (r) {
return net === 'solana' ? isSolana(r.network) : isBase(r.network);
});
+ if (!accept) {
+ setWalletError(statusEl, 'No payment option is available for this network.');
+ return;
+ }
- statusEl.classList.add('visible');
+ var resourceUrl = api.resolveResourceUrl(accept, getReturnUrl());
+
+ paymentInFlight = true;
+ setButtonsDisabled(true);
+ setWalletStatus(statusEl, 'connecting');
+
+ api.pay({
+ accept: accept,
+ resourceUrl: resourceUrl,
+ walletName: walletName,
+ onStatus: function (phase, text) {
+ if (phase === 'error') setWalletError(statusEl, text);
+ else if (phase !== 'done') setWalletStatus(statusEl, phase, text);
+ },
+ }).then(function (outcome) {
+ paymentInFlight = false;
+ revealUnlocked(outcome, accept);
+ }).catch(function (err) {
+ paymentInFlight = false;
+ setButtonsDisabled(false);
+ setWalletError(statusEl, (err && err.message) || 'Payment failed. Please try again.');
+ });
+ }
+
+ // ── Unlocked state ───────────────────────────────────────────────────────
- if (walletName === 'metamask' || walletName === 'coinbase' || walletName === 'walletconnect') {
- statusEl.innerHTML =
- '<strong>Opening ' + escHtml(walletName.charAt(0).toUpperCase() + walletName.slice(1)) + ' Wallet…</strong><br />' +
- 'Full browser wallet integration is coming to three.ws. To pay manually as a developer, ' +
- 'use the x402 CLI or SDK with the requirements shown in the Advanced panel below.' +
- (req ? '<br /><br /><strong>Pay to:</strong> <code>' + escHtml(req.payTo || '') + '</code>' +
- '<br /><strong>Amount:</strong> ' + escHtml(formatAmount(req.amount, (req.extra && req.extra.decimals) || 6)) +
- '<br /><strong>Asset:</strong> <code>' + escHtml(req.asset || '') + '</code>' : '');
- } else if (walletName === 'phantom' || walletName === 'solflare') {
- statusEl.innerHTML =
- '<strong>Opening ' + escHtml(walletName.charAt(0).toUpperCase() + walletName.slice(1)) + '…</strong><br />' +
- 'Solana wallet signing is coming soon. Use the x402 Solana SDK to pay programmatically.' +
- (req ? '<br /><br /><strong>Pay to:</strong> <code>' + escHtml(req.payTo || '') + '</code>' +
- '<br /><strong>Amount:</strong> ' + escHtml(formatAmount(req.amount, 6)) : '');
+ function receiptRow(label, valueHtml, isRaw) {
+ return '<div class="pw-receipt-row"><span class="pw-k">' + escHtml(label) + '</span>' +
+ '<span class="pw-v">' + (isRaw ? valueHtml : escHtml(valueHtml)) + '</span></div>';
+ }
+
+ function shortId(value, head, tail) {
+ if (!value) return '—';
+ return value.slice(0, head) + '…' + value.slice(-tail);
+ }
+
+ function revealUnlocked(outcome, accept) {
+ var card = document.getElementById('pay-card');
+ if (!card) return;
+ var net = accept.network;
+ var explorer = window.PaywallWallet.explorerUrl(net, outcome.transaction);
+ var txCell = null;
+ if (outcome.transaction) {
+ var txShort = escHtml(shortId(outcome.transaction, 10, 8));
+ txCell = explorer
+ ? '<a href="' + escHtml(explorer) + '" target="_blank" rel="noopener">' + txShort + ' ↗</a>'
+ : txShort;
}
- // Open the accordion automatically so the developer sees the raw requirements
- var advBody = document.getElementById('adv-body');
- var advToggle = document.getElementById('adv-toggle');
- if (advBody && !advBody.classList.contains('open')) {
- advBody.classList.add('open');
- if (advToggle) advToggle.classList.add('open');
+ var isHtml = (outcome.contentType || '').indexOf('html') !== -1 && typeof outcome.result === 'string';
+ var contentHtml = isHtml
+ ? '<iframe id="pw-content-frame" class="pw-content-frame" sandbox="allow-same-origin" title="Unlocked content"></iframe>'
+ : '<pre class="pw-content-pre">' + escHtml(
+ typeof outcome.result === 'string' ? outcome.result : JSON.stringify(outcome.result, null, 2)
+ ) + '</pre>';
+
+ card.innerHTML =
+ '<div class="card-head">' +
+ '<div class="service-row">' +
+ '<div class="service-icon pw-ok-icon">✓</div>' +
+ '<div><div class="service-name">Payment confirmed</div>' +
+ '<div class="service-desc">Content unlocked — settled on-chain via x402.</div></div>' +
+ '</div>' +
+ '<div class="pw-receipt">' +
+ receiptRow('Network', networkLabel(net)) +
+ receiptRow('Payer', shortId(outcome.payer, 6, 4)) +
+ (txCell ? receiptRow('Transaction', txCell, true) : '') +
+ '</div>' +
+ '</div>' +
+ '<div class="card-body">' +
+ '<div class="pw-unlocked-label">Unlocked content</div>' +
+ contentHtml +
+ '</div>' +
+ '<div class="card-foot">' +
+ '<span class="foot-text">Settled on ' + escHtml(networkLabel(net)) + ' · powered by x402</span>' +
+ '</div>';
+
+ if (isHtml) {
+ var frame = document.getElementById('pw-content-frame');
+ if (frame) frame.srcdoc = outcome.result;
}
}
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index b699f3604..43053ea08 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -919,6 +919,13 @@
<span class="sm-desc">Product launches, integrations, and announcements from three.ws.</span>
</a>
</li>
+ <li>
+ <a href="/news/three-ws-first-month-3d-agent-layer">
+ <span class="sm-title">One Month In: How three.ws Built the 3D Agent Layer of the Internet</span>
+ <span class="sm-path">/news/three-ws-first-month-3d-agent-layer</span>
+ <span class="sm-desc">In one month, three.ws went from launch to global coverage: browser-native 3D AI agents listed across major exchanges and data platforms, deployed on four hyperscale clouds, live in Anthropic's MCP Registry, and covered from CoinMarketCap to Vogue. A look back at 30 days of shipping.</span>
+ </a>
+ </li>
<li>
<a href="/news/cmc-mcp-registry-article">
<span class="sm-title">three.ws Brings Autonomous Payments and 3D Generation to Anthropic's Official MCP Registry</span>
diff --git a/public/x402-pay-core.js b/public/x402-pay-core.js
new file mode 100644
index 000000000..0063564eb
--- /dev/null
+++ b/public/x402-pay-core.js
@@ -0,0 +1,490 @@
+// x402-pay-core.js — browser-native wallet payment core for the three.ws paywall.
+//
+// The full-page paywall (paywall.html / paywall.js) lists wallet buttons but
+// historically dead-ended on click. This module performs the real x402 payment
+// flow, driving each wallet button from connect → sign → settle → unlock with
+// no fake progress. It mirrors the proven flow already shipped in the drop-in
+// modal (public/x402.js): Solana wallets sign a server-prepared SPL transfer
+// (via /api/x402-checkout), EVM wallets sign EIP-3009 transferWithAuthorization
+// typed data locally. The signed payload is base64-encoded into the X-PAYMENT
+// header, the original gated resource is retried, and the unlocked content +
+// settlement receipt are returned to the caller.
+//
+// Loaded as a native ES module (`<script type="module">`); it attaches
+// `window.PaywallWallet` for the classic paywall.js controller, and exports its
+// pure helpers as named exports so the payment-building logic is unit-testable
+// without a browser or a wallet.
+
+// ──────────────────────────────────────────────────────── network helpers ────
+
+// USDC EIP-3009 typed-data domains, keyed by CAIP-2 network id. `version` must
+// match the deployed USDC implementation's EIP712 domain version — Base USDC is
+// at "2"; signing with the wrong version yields a domain hash the facilitator
+// rejects.
+export const EVM_NETWORKS = {
+ 'eip155:8453': { chainId: 8453, name: 'Base', explorer: 'https://basescan.org/tx/' },
+ 'eip155:84532': {
+ chainId: 84532,
+ name: 'Base Sepolia',
+ explorer: 'https://sepolia.basescan.org/tx/',
+ },
+ 'eip155:42161': { chainId: 42161, name: 'Arbitrum', explorer: 'https://arbiscan.io/tx/' },
+ 'eip155:10': { chainId: 10, name: 'Optimism', explorer: 'https://optimistic.etherscan.io/tx/' },
+};
+
+export function isSolanaNetwork(net) {
+ return typeof net === 'string' && (net === 'solana' || net.startsWith('solana:'));
+}
+
+export function isEvmNetwork(net) {
+ return typeof net === 'string' && net.startsWith('eip155:');
+}
+
+// The paywall only signs EIP-3009 transferWithAuthorization for EVM. When the
+// server publishes both an EIP-3009 entry and a Permit2 sibling (the
+// gas-sponsoring path used by SDK clients), pick the EIP-3009 one — signing
+// typed-data against the Permit2 entry builds a payload the facilitator rejects.
+export function isEip3009Accept(accept) {
+ if (!isEvmNetwork(accept?.network)) return false;
+ const m = accept?.extra?.assetTransferMethod;
+ return !m || m === 'eip3009';
+}
+
+export function explorerUrl(network, tx) {
+ if (!tx) return null;
+ if (isSolanaNetwork(network)) return `https://solscan.io/tx/${tx}`;
+ const meta = EVM_NETWORKS[network];
+ return meta ? `${meta.explorer}${tx}` : null;
+}
+
+// The x402 spec's canonical atomic-price field is `maxAmountRequired`; our
+// server (and many merchants) emit `amount`. We read `amount` everywhere
+// downstream, so coerce once at ingestion.
+export function normalizeAccept(accept) {
+ if (!accept || typeof accept !== 'object') return accept;
+ const amount = accept.amount ?? accept.maxAmountRequired;
+ return amount != null && accept.amount == null ? { ...accept, amount: String(amount) } : accept;
+}
+
+// Resolve the absolute URL of the gated resource to retry after payment. Each
+// 402 `accept` entry carries the resource URL server-side; fall back to the
+// paywall's `?return=` URL (made absolute) when it doesn't.
+export function resolveResourceUrl(accept, fallbackUrl, origin) {
+ const base = origin || (typeof location !== 'undefined' ? location.origin : 'https://three.ws');
+ const candidate = accept?.resource || fallbackUrl || '/';
+ try {
+ return new URL(candidate, base).href;
+ } catch {
+ return new URL('/', base).href;
+ }
+}
+
+// ─────────────────────────────────────────────────────────── encoding ────────
+
+export function b64encode(obj) {
+ const json = JSON.stringify(obj);
+ if (typeof Buffer !== 'undefined') return Buffer.from(json, 'utf8').toString('base64');
+ return btoa(unescape(encodeURIComponent(json)));
+}
+
+export function b64decode(str) {
+ if (!str) return null;
+ try {
+ const bin =
+ typeof Buffer !== 'undefined'
+ ? Buffer.from(str, 'base64').toString('utf8')
+ : decodeURIComponent(escape(atob(str)));
+ return JSON.parse(bin);
+ } catch {
+ return null;
+ }
+}
+
+export function base64ToUint8Array(b64) {
+ if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(b64, 'base64'));
+ const bin = atob(b64);
+ const arr = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);
+ return arr;
+}
+
+export function uint8ArrayToBase64(arr) {
+ if (typeof Buffer !== 'undefined') return Buffer.from(arr).toString('base64');
+ let bin = '';
+ for (let i = 0; i < arr.length; i++) bin += String.fromCharCode(arr[i]);
+ return btoa(bin);
+}
+
+export function randomHex(bytes) {
+ const arr = new Uint8Array(bytes);
+ (globalThis.crypto || crypto).getRandomValues(arr);
+ return Array.from(arr)
+ .map((b) => b.toString(16).padStart(2, '0'))
+ .join('');
+}
+
+export function friendlyError(err) {
+ const msg = err?.shortMessage || err?.message || String(err);
+ if (/user rejected|user denied|reject|cancell?ed/i.test(msg)) return 'Cancelled in wallet';
+ return msg.slice(0, 240);
+}
+
+// ──────────────────────────────────────────── payment payload builders ────────
+
+// Body for POST /api/x402-checkout?action=prepare. The server returns a
+// partially-signed v0 SPL transfer for the buyer's wallet to co-sign.
+export function buildPrepareBody(accept, buyer) {
+ return { accept: normalizeAccept(accept), buyer };
+}
+
+// EIP-3009 transferWithAuthorization typed data for an EVM USDC payment.
+// `nowSeconds` is injectable so the build is deterministic under test.
+export function buildEip3009TypedData({ accept, payerAddress, chainId, nowSeconds, nonce }) {
+ const now = nowSeconds != null ? nowSeconds : Math.floor(Date.now() / 1000);
+ const validAfter = 0;
+ const validBefore = now + (accept.maxTimeoutSeconds || 600);
+ const authNonce = nonce || '0x' + randomHex(32);
+ const domain = {
+ name: accept.extra?.name || 'USD Coin',
+ version: accept.extra?.version || '2',
+ chainId,
+ verifyingContract: accept.asset,
+ };
+ const types = {
+ EIP712Domain: [
+ { name: 'name', type: 'string' },
+ { name: 'version', type: 'string' },
+ { name: 'chainId', type: 'uint256' },
+ { name: 'verifyingContract', type: 'address' },
+ ],
+ TransferWithAuthorization: [
+ { name: 'from', type: 'address' },
+ { name: 'to', type: 'address' },
+ { name: 'value', type: 'uint256' },
+ { name: 'validAfter', type: 'uint256' },
+ { name: 'validBefore', type: 'uint256' },
+ { name: 'nonce', type: 'bytes32' },
+ ],
+ };
+ const message = {
+ from: payerAddress,
+ to: accept.payTo,
+ value: accept.amount,
+ validAfter,
+ validBefore,
+ nonce: authNonce,
+ };
+ return {
+ typedData: { primaryType: 'TransferWithAuthorization', types, domain, message },
+ authorization: {
+ from: payerAddress,
+ to: accept.payTo,
+ value: accept.amount,
+ validAfter,
+ validBefore,
+ nonce: authNonce,
+ },
+ };
+}
+
+// Assemble the x402 PaymentPayload for an EVM EIP-3009 signature.
+export function buildEvmPaymentPayload({ accept, signature, authorization, resourceUrl }) {
+ return {
+ x402Version: 2,
+ scheme: 'exact',
+ network: accept.network,
+ resource: { url: resourceUrl, mimeType: 'application/json' },
+ accepted: accept,
+ payload: { signature, authorization },
+ };
+}
+
+// ──────────────────────────────────────────────────── runtime dependencies ────
+
+let _solanaWeb3 = null;
+async function loadSolanaWeb3() {
+ if (_solanaWeb3) return _solanaWeb3;
+ // Dynamic import from esm.sh keeps the paywall tiny — web3.js is only fetched
+ // when a Solana payment is actually attempted. Mirrors public/x402.js.
+ _solanaWeb3 = await import('https://esm.sh/@solana/[email protected]?bundle');
+ return _solanaWeb3;
+}
+
+async function postJson(url, body) {
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ const text = await res.text();
+ let data;
+ try {
+ data = JSON.parse(text);
+ } catch {
+ data = { error: 'parse_error', error_description: text.slice(0, 200) };
+ }
+ if (!res.ok) {
+ const err = new Error(data.error_description || data.error || `HTTP ${res.status}`);
+ err.status = res.status;
+ err.data = data;
+ throw err;
+ }
+ return data;
+}
+
+// ───────────────────────────────────────────────────── provider detection ────
+
+export function getSolanaProvider(walletName) {
+ if (typeof window === 'undefined') return null;
+ if (walletName === 'solflare') {
+ // Solflare injects window.solflare; some builds also flag window.solana.
+ if (window.solflare?.isSolflare || window.solflare) return window.solflare;
+ if (window.solana?.isSolflare) return window.solana;
+ return null;
+ }
+ // Phantom (default Solana wallet).
+ if (window.phantom?.solana) return window.phantom.solana;
+ if (window.solana?.isPhantom) return window.solana;
+ return window.solana || null;
+}
+
+// Pick the injected EVM provider matching the requested wallet. EIP-6963 / legacy
+// multi-provider environments expose siblings under window.ethereum.providers.
+export function getEvmProvider(walletName) {
+ if (typeof window === 'undefined') return null;
+ const eth = window.ethereum;
+ if (!eth) return null;
+ const list = Array.isArray(eth.providers) && eth.providers.length ? eth.providers : [eth];
+ const pick = (pred) => list.find(pred);
+ if (walletName === 'coinbase') {
+ return (
+ pick((p) => p.isCoinbaseWallet) ||
+ window.coinbaseWalletExtension ||
+ (eth.isCoinbaseWallet ? eth : null)
+ );
+ }
+ if (walletName === 'metamask') {
+ return pick((p) => p.isMetaMask && !p.isCoinbaseWallet) || (eth.isMetaMask ? eth : null);
+ }
+ // Generic injected fallback.
+ return eth;
+}
+
+const WALLET_LABELS = {
+ phantom: 'Phantom',
+ solflare: 'Solflare',
+ metamask: 'MetaMask',
+ coinbase: 'Coinbase Wallet',
+ walletconnect: 'WalletConnect',
+};
+
+function walletNotFound(walletName) {
+ const label = WALLET_LABELS[walletName] || 'Wallet';
+ const err = new Error(
+ `${label} not detected. Install the ${label} extension, then reload this page.`,
+ );
+ err.code = 'wallet_not_found';
+ return err;
+}
+
+// ─────────────────────────────────────────────────────── settle + retry ──────
+
+// Retry the gated resource with the X-PAYMENT proof and return the unlocked
+// content plus the decoded settlement receipt.
+async function executePaid({ xPayment, resourceUrl, onStatus, accept, payerAddress }) {
+ onStatus?.('confirming', 'Unlocking content…');
+ const res = await fetch(resourceUrl, {
+ method: 'GET',
+ headers: { 'X-PAYMENT': xPayment, Accept: '*/*' },
+ });
+ const ct = res.headers.get('content-type') || '';
+ const text = await res.text();
+ let result;
+ if (ct.includes('json')) {
+ try {
+ result = JSON.parse(text);
+ } catch {
+ result = text;
+ }
+ } else {
+ result = text;
+ }
+ if (!res.ok) {
+ const msg =
+ (result && typeof result === 'object' && (result.error_description || result.error)) ||
+ `HTTP ${res.status}`;
+ throw new Error(msg);
+ }
+ const payment = b64decode(res.headers.get('x-payment-response')) || {};
+ onStatus?.('done', 'Unlocked');
+ return {
+ ok: true,
+ result,
+ payment,
+ contentType: ct,
+ status: res.status,
+ network: payment.network || accept?.network || null,
+ payer: payment.payer || payerAddress || null,
+ transaction: payment.transaction || null,
+ };
+}
+
+// ────────────────────────────────────────────────────────────── Solana pay ───
+
+export async function paySolana({ accept, resourceUrl, walletName, onStatus, origin }) {
+ accept = normalizeAccept(accept);
+ const apiOrigin = origin || (typeof location !== 'undefined' ? location.origin : '');
+ const label = walletName === 'solflare' ? 'Solflare' : 'Phantom';
+ const provider = getSolanaProvider(walletName);
+ if (!provider || typeof provider.connect !== 'function') throw walletNotFound(walletName);
+
+ onStatus?.('connecting', `Opening ${label}…`);
+ const conn = await provider.connect();
+ const payerAddress = (conn?.publicKey || provider.publicKey)?.toString();
+ if (!payerAddress) throw new Error(`${label} did not return a public key`);
+
+ onStatus?.('building', 'Building payment…');
+ const prep = await postJson(
+ `${apiOrigin}/api/x402-checkout?action=prepare`,
+ buildPrepareBody(accept, payerAddress),
+ );
+
+ onStatus?.('signing', `Approve the payment in ${label}…`);
+ const txBytes = base64ToUint8Array(prep.tx_base64);
+ const web3 = await loadSolanaWeb3();
+ const tx = web3.VersionedTransaction.deserialize(txBytes);
+ // The wallet adds the buyer's signature; the facilitator's fee-payer signature
+ // is added during /settle.
+ const signed = await provider.signTransaction(tx);
+ const signedB64 = uint8ArrayToBase64(signed.serialize());
+
+ onStatus?.('confirming', 'Settling on-chain…');
+ const enc = await postJson(`${apiOrigin}/api/x402-checkout?action=encode`, {
+ accept,
+ signed_tx_base64: signedB64,
+ resource_url: resourceUrl,
+ });
+
+ return executePaid({ xPayment: enc.x_payment, resourceUrl, onStatus, accept, payerAddress });
+}
+
+// ───────────────────────────────────────────────────────────────── EVM pay ───
+
+async function resolveEvmProvider(walletName, onStatus) {
+ if (walletName === 'walletconnect') {
+ const projectId = getWcProjectId();
+ if (!projectId) {
+ const err = new Error(
+ 'WalletConnect is not configured here. Use MetaMask or Coinbase Wallet, or pay with a Solana wallet.',
+ );
+ err.code = 'wc_unconfigured';
+ throw err;
+ }
+ onStatus?.('connecting', 'Opening WalletConnect…');
+ // WalletConnect glue is a public/ runtime asset, not a bundled module.
+ // Keep the specifier non-static (+ @vite-ignore) so Vite's import-analysis
+ // doesn't try to resolve a /public path at build/test time; the browser
+ // loads it from the served URL at runtime only.
+ const wcProviderUrl = '/wallet/wc-provider.js';
+ const { initWCProvider } = await import(/* @vite-ignore */ wcProviderUrl);
+ const wc = await initWCProvider({
+ projectId,
+ optionalChains: Object.values(EVM_NETWORKS).map((n) => n.chainId),
+ });
+ await wc.enable();
+ return wc;
+ }
+ const provider = getEvmProvider(walletName);
+ if (!provider || typeof provider.request !== 'function') throw walletNotFound(walletName);
+ return provider;
+}
+
+function getWcProjectId() {
+ if (typeof document !== 'undefined') {
+ const meta = document.querySelector('meta[name="x402-wc-project-id"]');
+ if (meta?.content) return meta.content;
+ }
+ if (typeof window !== 'undefined' && window.WALLETCONNECT_PROJECT_ID) {
+ return window.WALLETCONNECT_PROJECT_ID;
+ }
+ return null;
+}
+
+export async function payEvm({ accept, resourceUrl, walletName, onStatus }) {
+ accept = normalizeAccept(accept);
+ const meta = EVM_NETWORKS[accept.network];
+ if (!meta) throw new Error(`Unsupported EVM network ${accept.network}`);
+ const label = WALLET_LABELS[walletName] || 'wallet';
+
+ const eth = await resolveEvmProvider(walletName, onStatus);
+ onStatus?.('connecting', `Opening ${label}…`);
+ const accounts = await eth.request({ method: 'eth_requestAccounts' });
+ const payerAddress = accounts?.[0];
+ if (!payerAddress) throw new Error(`${label} did not return an account`);
+
+ // Switch to the required chain if the wallet is elsewhere.
+ const currentChainHex = await eth.request({ method: 'eth_chainId' });
+ const desiredChainHex = '0x' + meta.chainId.toString(16);
+ if (currentChainHex !== desiredChainHex) {
+ onStatus?.('connecting', `Switch ${label} to ${meta.name}…`);
+ try {
+ await eth.request({
+ method: 'wallet_switchEthereumChain',
+ params: [{ chainId: desiredChainHex }],
+ });
+ } catch {
+ throw new Error(`Switch ${label} to ${meta.name} (${desiredChainHex}) and try again`);
+ }
+ }
+
+ onStatus?.('signing', `Authorize payment in ${label}…`);
+ const { typedData, authorization } = buildEip3009TypedData({
+ accept,
+ payerAddress,
+ chainId: meta.chainId,
+ });
+ const signature = await eth.request({
+ method: 'eth_signTypedData_v4',
+ params: [payerAddress, JSON.stringify(typedData)],
+ });
+
+ onStatus?.('confirming', 'Settling on-chain…');
+ const paymentPayload = buildEvmPaymentPayload({
+ accept,
+ signature,
+ authorization,
+ resourceUrl,
+ });
+ const xPayment = b64encode(paymentPayload);
+ return executePaid({ xPayment, resourceUrl, onStatus, accept, payerAddress });
+}
+
+// ─────────────────────────────────────────────────────────── dispatcher ──────
+
+// Single entry point for the paywall controller. Routes a wallet button to the
+// correct chain-specific payer based on the network of the matching `accept`.
+export async function pay({ accept, resourceUrl, walletName, onStatus, origin }) {
+ if (isSolanaNetwork(accept?.network)) {
+ return paySolana({ accept, resourceUrl, walletName, onStatus, origin });
+ }
+ if (isEvmNetwork(accept?.network)) {
+ return payEvm({ accept, resourceUrl, walletName, onStatus });
+ }
+ throw new Error(`Unsupported network ${accept?.network}`);
+}
+
+// Attach to window for the classic paywall.js controller.
+if (typeof window !== 'undefined') {
+ window.PaywallWallet = Object.freeze({
+ pay,
+ paySolana,
+ payEvm,
+ isSolanaNetwork,
+ isEvmNetwork,
+ isEip3009Accept,
+ resolveResourceUrl,
+ explorerUrl,
+ getSolanaProvider,
+ getEvmProvider,
+ });
+}
diff --git a/scripts/compress-glbs.mjs b/scripts/compress-glbs.mjs
index 5543e9786..fa8f9d5b3 100644
--- a/scripts/compress-glbs.mjs
+++ b/scripts/compress-glbs.mjs
@@ -3,8 +3,9 @@
* GLB compression pipeline.
*
* Reads GLB files with @gltf-transform, applies a lossless-perceptual transform
- * chain (dedup → prune → resample → quantize → EXT_meshopt_compression) and
- * writes the result back in place — but only if the output is actually smaller.
+ * chain (dedup → prune → resample → quantize → EXT_meshopt_compression →
+ * WebP texture recompression via EXT_texture_webp) and writes the result back
+ * in place — but only if the output is actually smaller.
*
* node scripts/compress-glbs.mjs # scan public/ + rider/assets/
* node scripts/compress-glbs.mjs public/avatars/x.glb # explicit file list
@@ -24,8 +25,9 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { NodeIO } from '@gltf-transform/core';
import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
-import { dedup, prune, resample, quantize, meshopt } from '@gltf-transform/functions';
+import { dedup, prune, resample, quantize, meshopt, textureCompress } from '@gltf-transform/functions';
import { MeshoptEncoder, MeshoptDecoder } from 'meshoptimizer';
+import sharp from 'sharp';
const ROOT = path.resolve(fileURLToPath(import.meta.url), '../..');
const DEFAULT_SCAN_DIRS = ['public', 'rider/assets'];
@@ -108,8 +110,7 @@ async function main() {
resample(),
quantize(),
meshopt({ encoder: MeshoptEncoder, level: 'medium' }),
- // TODO: add textureCompress({ encoder: sharp, targetFormat: 'webp', quality: 85 })
- // once sharp is wired into the asset pipeline (it needs a native binary).
+ textureCompress({ encoder: sharp, targetFormat: 'webp', quality: 85 }),
);
const bytes = await io.writeBinary(document);
diff --git a/src/nich-agent.js b/src/nich-agent.js
index 898b35ee6..c5839c16d 100644
--- a/src/nich-agent.js
+++ b/src/nich-agent.js
@@ -370,6 +370,16 @@ export class NichAgent {
}
if (res.status === 503) {
streamEl.remove();
+ // A 503 carrying retry_after is transient capacity exhaustion (every
+ // upstream provider was rate-limited / briefly down), not a missing
+ // config. Back off and retry like a 429 — do NOT disable the API path,
+ // or one throttle window would permanently fall the agent back to the
+ // offline pattern-matcher. A 503 without retry_after is a genuine
+ // "no provider configured" and still disables.
+ const data = await res.json().catch(() => ({}));
+ if (data.retry_after != null) {
+ return { ok: false, rateLimited: true, retryAfter: data.retry_after };
+ }
return { ok: false, disable: true, reason: 'unconfigured' };
}
if (res.status === 429) {
diff --git a/src/pump/pump-modals.js b/src/pump/pump-modals.js
index c86d4668a..5935ebf31 100644
--- a/src/pump/pump-modals.js
+++ b/src/pump/pump-modals.js
@@ -482,9 +482,21 @@ function openLaunch({ identity, agentId, avatarId, formData }) {
`;
} else if (step === 2) {
const initialBuyVal = formData?.initialBuy || inner._formCache?.buyin || 0;
+ // Quote pair. USDC-paired is the default for agent coins: the agent
+ // earns USDC, and its buyback swaps that USDC → token & burns in the
+ // same currency. SOL-paired is the classic pump.fun curve.
+ const quoteCur = inner._formCache?.quoteCurrency || 'usdc';
+ const buyMax = quoteCur === 'usdc' ? 100000 : 50;
+ const buyStep = quoteCur === 'usdc' ? 1 : 0.1;
body.innerHTML = `
- <label>Buyback share</label>
- <input type="range" min="0" max="5000" step="50" value="500" id="pmodal-launch-bps" />
+ <label>Quote pair</label>
+ <div class="pmodal-quote-toggle" role="radiogroup" aria-label="Quote currency">
+ <button type="button" class="pmodal-quote-opt${quoteCur === 'usdc' ? ' active' : ''}" data-quote="usdc" role="radio" aria-checked="${quoteCur === 'usdc'}">USDC</button>
+ <button type="button" class="pmodal-quote-opt${quoteCur === 'sol' ? ' active' : ''}" data-quote="sol" role="radio" aria-checked="${quoteCur === 'sol'}">SOL</button>
+ </div>
+ <div class="pmodal-sub" id="pmodal-quote-note" style="margin-top:0.4rem"></div>
+ <label style="margin-top:0.8rem">Buyback share</label>
+ <input type="range" min="0" max="5000" step="50" value="${inner._formCache?.bps ?? 500}" id="pmodal-launch-bps" />
<div class="pmodal-slider-label">
<span>0%</span>
<b id="pmodal-launch-bps-val">5.0%</b>
@@ -494,10 +506,10 @@ function openLaunch({ identity, agentId, avatarId, formData }) {
<span>If this agent earns $10/mo:</span>
<b id="pmodal-launch-projection">$0.50/mo burned</b>
</div>
- <label>Creator initial buy (SOL, optional)</label>
- <input type="number" id="pmodal-launch-buyin" value="${Number(initialBuyVal) || 0}" min="0" max="50" step="0.1" />
+ <label>Creator initial buy (<span id="pmodal-buyin-unit">${quoteCur.toUpperCase()}</span>, optional)</label>
+ <input type="number" id="pmodal-launch-buyin" value="${Number(initialBuyVal) || 0}" min="0" max="${buyMax}" step="${buyStep}" />
<div class="pmodal-sub" style="margin-top:0.7rem">
- Buyback share is locked at launch — choose carefully.
+ Buyback share and quote pair are locked at launch — choose carefully.
</div>
`;
const bps = body.querySelector('#pmodal-launch-bps');
@@ -509,16 +521,49 @@ function openLaunch({ identity, agentId, avatarId, formData }) {
proj.textContent = `$${((10 * pct) / 100).toFixed(2)}/mo burned`;
};
bps.addEventListener('input', update);
+ update();
+
+ const note = body.querySelector('#pmodal-quote-note');
+ const buyUnit = body.querySelector('#pmodal-buyin-unit');
+ const buyInput = body.querySelector('#pmodal-launch-buyin');
+ const symForNote = inner._formCache?.symbol || symbolDefault;
+ const renderQuote = (cur) => {
+ if (note)
+ note.innerHTML =
+ cur === 'usdc'
+ ? `USDC-paired — the agent's USDC earnings buy back &amp; burn $${esc(symForNote)} in the same currency it earns.`
+ : `SOL-paired — the classic pump.fun curve. Buyback burns are funded by swapping the agent's USDC earnings into SOL first.`;
+ if (buyUnit) buyUnit.textContent = cur.toUpperCase();
+ if (buyInput) {
+ buyInput.max = cur === 'usdc' ? 100000 : 50;
+ buyInput.step = cur === 'usdc' ? 1 : 0.1;
+ }
+ };
+ renderQuote(quoteCur);
+ body.querySelectorAll('.pmodal-quote-opt').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const cur = btn.dataset.quote;
+ inner._formCache = { ...(inner._formCache || {}), quoteCurrency: cur };
+ body.querySelectorAll('.pmodal-quote-opt').forEach((b) => {
+ const on = b === btn;
+ b.classList.toggle('active', on);
+ b.setAttribute('aria-checked', String(on));
+ });
+ renderQuote(cur);
+ });
+ });
} else if (step === 3) {
const f = inner._formCache || {};
const name = f.name || nameDefault;
const symbol = f.symbol || symbolDefault;
+ const cur = (f.quoteCurrency || 'usdc').toUpperCase();
body.innerHTML = `
<div class="pmodal-row"><span>Name</span><b>${esc(name)}</b></div>
<div class="pmodal-row"><span>Symbol</span><b>$${esc(symbol)}</b></div>
+ <div class="pmodal-row"><span>Quote pair</span><b>${esc(cur)}</b></div>
<div class="pmodal-row"><span>Mint mark</span><b><code>3ws</code>…</b></div>
<div class="pmodal-row"><span>Buyback</span><b>${((f.bps || 500) / 100).toFixed(1)}%</b></div>
- <div class="pmodal-row"><span>Initial buy</span><b>${f.buyin || 0} SOL</b></div>
+ <div class="pmodal-row"><span>Initial buy</span><b>${f.buyin || 0} ${esc(cur)}</b></div>
<div class="pmodal-row"><span>Tx</span><b>createInstruction + PumpAgent.create</b></div>
<div class="pmodal-sub" style="margin-top:0.7rem">
Every three.ws coin is stamped <code>3ws…</code> on-chain. We grind the mark in your browser, then you sign once — the mint keypair and your wallet co-sign.
@@ -575,7 +620,8 @@ function openLaunch({ identity, agentId, avatarId, formData }) {
} else if (step === 2) {
const bps = parseInt(inner.querySelector('#pmodal-launch-bps').value, 10);
const buyin = parseFloat(inner.querySelector('#pmodal-launch-buyin').value || '0');
- inner._formCache = { ...(inner._formCache || {}), bps, buyin };
+ const quoteCurrency = inner._formCache?.quoteCurrency || 'usdc';
+ inner._formCache = { ...(inner._formCache || {}), bps, buyin, quoteCurrency };
step = 3;
render();
} else {
@@ -639,7 +685,12 @@ function openLaunch({ identity, agentId, avatarId, formData }) {
symbol: f.symbol,
uri: f.uri,
buyback_bps: f.bps || 0,
- sol_buy_in: f.buyin || 0,
+ // USDC-paired by default so the buyback swaps in the same
+ // currency the agent earns; the server resolves the mint.
+ quote_currency: f.quoteCurrency || 'usdc',
+ ...((f.quoteCurrency || 'usdc') === 'usdc'
+ ? { usdc_buy_in: f.buyin || 0 }
+ : { sol_buy_in: f.buyin || 0 }),
mint_address: mintKp.publicKey.toBase58(),
network: 'mainnet',
}),
diff --git a/tests/api/llm.test.js b/tests/api/llm.test.js
index 9be737dbe..9d35be151 100644
--- a/tests/api/llm.test.js
+++ b/tests/api/llm.test.js
@@ -125,6 +125,46 @@ describe('llmComplete — Anthropic is BYOK-only', () => {
});
});
+describe('llmComplete — opt-in server Anthropic (serverAnthropic)', () => {
+ it('uses the server ANTHROPIC_API_KEY first when serverAnthropic is set', async () => {
+ process.env.ANTHROPIC_API_KEY = 'sk-server';
+ process.env.GROQ_API_KEY = 'g';
+ const calls = installFetch({ [ANTHROPIC_HOST]: anthropicShape('server claude') });
+ const out = await llm.llmComplete({ system: 's', user: 'u', serverAnthropic: true });
+ expect(out.provider).toBe('anthropic');
+ expect(out.text).toBe('server claude');
+ expect(calls[0].headers['x-api-key']).toBe('sk-server');
+ });
+
+ it('still ignores the server key when serverAnthropic is NOT set (default policy)', async () => {
+ process.env.ANTHROPIC_API_KEY = 'sk-server';
+ process.env.GROQ_API_KEY = 'g';
+ const calls = installFetch({ [GROQ_HOST]: openaiShape('groq wins') });
+ const out = await llm.llmComplete({ system: 's', user: 'u' });
+ expect(out.provider).toBe('groq');
+ expect(calls.every((c) => !c.url.includes(ANTHROPIC_HOST))).toBe(true);
+ });
+
+ it('falls over from server Anthropic to a free provider when Anthropic errors', async () => {
+ process.env.ANTHROPIC_API_KEY = 'sk-server';
+ process.env.GROQ_API_KEY = 'g';
+ const calls = installFetch({
+ [ANTHROPIC_HOST]: errResp(429),
+ [GROQ_HOST]: openaiShape('groq fallback'),
+ });
+ const out = await llm.llmComplete({ system: 's', user: 'u', serverAnthropic: true });
+ expect(out.provider).toBe('groq');
+ expect(out.text).toBe('groq fallback');
+ expect(calls.map((c) => (c.url.includes(ANTHROPIC_HOST) ? 'anthropic' : 'groq'))).toEqual(['anthropic', 'groq']);
+ });
+
+ it('llmConfigured reflects serverAnthropic when only the server key is present', () => {
+ process.env.ANTHROPIC_API_KEY = 'sk-server';
+ expect(llm.llmConfigured()).toBe(false); // default policy ignores server key
+ expect(llm.llmConfigured({ serverAnthropic: true })).toBe(true);
+ });
+});
+
describe('llmComplete — failure modes', () => {
it('throws LlmUnavailableError (503) when no provider is configured', async () => {
installFetch({});
diff --git a/tests/api/provider-health.test.js b/tests/api/provider-health.test.js
new file mode 100644
index 000000000..1c44d8ab7
--- /dev/null
+++ b/tests/api/provider-health.test.js
@@ -0,0 +1,43 @@
+// Tests for api/_lib/provider-health.js — the LLM provider circuit breaker.
+// Runs against the in-memory cache fallback (no UPSTASH_* env), so no network.
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+
+// Ensure the cache layer uses its in-memory fallback (not Redis).
+delete process.env.UPSTASH_REDIS_REST_URL;
+delete process.env.UPSTASH_REDIS_REST_TOKEN;
+
+const { markProviderCooldown, providersInCooldown } = await import('../../api/_lib/provider-health.js');
+
+const ALL = ['anthropic', 'groq', 'openrouter', 'openai'];
+
+describe('provider-health circuit breaker', () => {
+ it('reports no cooldowns before anything is marked', async () => {
+ const cooling = await providersInCooldown(ALL);
+ expect(cooling.size).toBe(0);
+ });
+
+ it('marks a provider in cooldown and reports it', async () => {
+ await markProviderCooldown('groq', 30);
+ const cooling = await providersInCooldown(ALL);
+ expect(cooling.has('groq')).toBe(true);
+ // Only the marked provider is cooling.
+ expect(cooling.has('anthropic')).toBe(false);
+ expect(cooling.has('openrouter')).toBe(false);
+ });
+
+ it('only surfaces a provider once it has actually been marked', async () => {
+ // A name never marked is never reported as cooling.
+ const fresh = await providersInCooldown(['never-marked-xyz']);
+ expect(fresh.has('never-marked-xyz')).toBe(false);
+ // After marking, it surfaces.
+ await markProviderCooldown('openai', 30);
+ const after = await providersInCooldown(['openai']);
+ expect(after.has('openai')).toBe(true);
+ });
+
+ it('is best-effort: a falsy provider is a no-op, never throws', async () => {
+ await expect(markProviderCooldown('')).resolves.toBeUndefined();
+ await expect(markProviderCooldown(undefined)).resolves.toBeUndefined();
+ });
+});
diff --git a/tests/chat-models.test.js b/tests/chat-models.test.js
index a77127e19..b2b5937c7 100644
--- a/tests/chat-models.test.js
+++ b/tests/chat-models.test.js
@@ -72,9 +72,15 @@ describe('usableModels (route selector)', () => {
});
describe('reliability-first ordering', () => {
- it('ranks groq first and openai last (over-quota tier)', () => {
- expect(DEFAULT_PROVIDER_ORDER[0]).toBe('groq');
+ it('ranks anthropic first (keyed paid tier) and openai last (over-quota tier)', () => {
+ // Anthropic leads so the happy path resolves on attempt 0 when keyed,
+ // instead of burning the rate-limited free tiers first. When Anthropic is
+ // unkeyed it's skipped, so the effective lead becomes groq (the free tier).
+ expect(DEFAULT_PROVIDER_ORDER[0]).toBe('anthropic');
expect(DEFAULT_PROVIDER_ORDER[DEFAULT_PROVIDER_ORDER.length - 1]).toBe('openai');
+ // Free tiers still rank ahead of the over-quota OpenAI account.
+ expect(DEFAULT_PROVIDER_ORDER.indexOf('groq')).toBeLessThan(DEFAULT_PROVIDER_ORDER.indexOf('openai'));
+ expect(DEFAULT_PROVIDER_ORDER.indexOf('openrouter')).toBeLessThan(DEFAULT_PROVIDER_ORDER.indexOf('openai'));
});
it('does not lead the free tier with the moderation-gated model', () => {
diff --git a/tests/public/x402-pay-core.test.js b/tests/public/x402-pay-core.test.js
new file mode 100644
index 000000000..ad312f2d0
--- /dev/null
+++ b/tests/public/x402-pay-core.test.js
@@ -0,0 +1,210 @@
+// Unit tests for the paywall's wallet-payment core (public/x402-pay-core.js).
+// Exercises the pure payment-building logic — the parts that can be verified
+// without a real browser wallet: requirement normalization, resource-URL
+// resolution, EIP-3009 typed-data construction, payload assembly, and encoding.
+//
+// Test fixtures use $THREE (the only coin) for Solana asset/payTo and a clearly
+// synthetic 0x… address for EVM, per CLAUDE.md.
+
+import { describe, it, expect } from 'vitest';
+import {
+ normalizeAccept,
+ isSolanaNetwork,
+ isEvmNetwork,
+ isEip3009Accept,
+ resolveResourceUrl,
+ buildPrepareBody,
+ buildEip3009TypedData,
+ buildEvmPaymentPayload,
+ b64encode,
+ b64decode,
+ base64ToUint8Array,
+ uint8ArrayToBase64,
+ explorerUrl,
+ friendlyError,
+} from '../../public/x402-pay-core.js';
+
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const SYNTH_EVM = '0x0000000000000000000000000000000000000003';
+
+const solanaAccept = {
+ scheme: 'exact',
+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ amount: '1000',
+ asset: THREE_MINT,
+ payTo: THREE_MINT,
+ maxTimeoutSeconds: 60,
+ resource: 'https://three.ws/api/x402/demo?x=1',
+ extra: { name: 'USDC', decimals: 6, feePayer: THREE_MINT },
+};
+
+const baseAccept = {
+ scheme: 'exact',
+ network: 'eip155:8453',
+ amount: '1000',
+ asset: SYNTH_EVM,
+ payTo: SYNTH_EVM,
+ maxTimeoutSeconds: 600,
+ extra: { name: 'USD Coin', version: '2', decimals: 6 },
+};
+
+describe('network detection', () => {
+ it('classifies solana and evm networks', () => {
+ expect(isSolanaNetwork(solanaAccept.network)).toBe(true);
+ expect(isSolanaNetwork('solana')).toBe(true);
+ expect(isSolanaNetwork(baseAccept.network)).toBe(false);
+ expect(isEvmNetwork(baseAccept.network)).toBe(true);
+ expect(isEvmNetwork(solanaAccept.network)).toBe(false);
+ });
+
+ it('only treats eip3009 (non-permit2) EVM entries as signable', () => {
+ expect(isEip3009Accept(baseAccept)).toBe(true);
+ expect(
+ isEip3009Accept({
+ ...baseAccept,
+ extra: { ...baseAccept.extra, assetTransferMethod: 'permit2' },
+ }),
+ ).toBe(false);
+ expect(isEip3009Accept(solanaAccept)).toBe(false);
+ });
+});
+
+describe('normalizeAccept', () => {
+ it('coerces maxAmountRequired into amount', () => {
+ const out = normalizeAccept({ network: 'solana', maxAmountRequired: 2500 });
+ expect(out.amount).toBe('2500');
+ });
+
+ it('leaves an existing amount untouched', () => {
+ expect(normalizeAccept(solanaAccept)).toBe(solanaAccept);
+ });
+});
+
+describe('resolveResourceUrl', () => {
+ it('prefers the accept.resource URL', () => {
+ expect(resolveResourceUrl(solanaAccept, '/ignored', 'https://three.ws')).toBe(
+ 'https://three.ws/api/x402/demo?x=1',
+ );
+ });
+
+ it('falls back to the return URL made absolute against the origin', () => {
+ expect(
+ resolveResourceUrl({ network: 'solana' }, '/api/x402/paid?id=7', 'https://three.ws'),
+ ).toBe('https://three.ws/api/x402/paid?id=7');
+ });
+
+ it('degrades to the origin root when nothing is usable', () => {
+ expect(resolveResourceUrl(null, null, 'https://three.ws')).toBe('https://three.ws/');
+ });
+});
+
+describe('buildPrepareBody', () => {
+ it('returns the normalized accept + buyer for /api/x402-checkout?action=prepare', () => {
+ const body = buildPrepareBody(
+ { ...solanaAccept, amount: undefined, maxAmountRequired: '1000' },
+ THREE_MINT,
+ );
+ expect(body.buyer).toBe(THREE_MINT);
+ expect(body.accept.amount).toBe('1000');
+ expect(body.accept.extra.feePayer).toBe(THREE_MINT);
+ });
+});
+
+describe('buildEip3009TypedData', () => {
+ it('builds deterministic transferWithAuthorization typed data', () => {
+ const { typedData, authorization } = buildEip3009TypedData({
+ accept: baseAccept,
+ payerAddress: SYNTH_EVM,
+ chainId: 8453,
+ nowSeconds: 1_000,
+ nonce: '0x' + 'ab'.repeat(32),
+ });
+ expect(typedData.primaryType).toBe('TransferWithAuthorization');
+ expect(typedData.domain).toEqual({
+ name: 'USD Coin',
+ version: '2',
+ chainId: 8453,
+ verifyingContract: SYNTH_EVM,
+ });
+ expect(typedData.message.from).toBe(SYNTH_EVM);
+ expect(typedData.message.to).toBe(baseAccept.payTo);
+ expect(typedData.message.value).toBe('1000');
+ expect(typedData.message.validAfter).toBe(0);
+ // validBefore = now + maxTimeoutSeconds
+ expect(typedData.message.validBefore).toBe(1_000 + 600);
+ expect(authorization.nonce).toBe('0x' + 'ab'.repeat(32));
+ });
+
+ it('generates a random 32-byte nonce when none is supplied', () => {
+ const a = buildEip3009TypedData({
+ accept: baseAccept,
+ payerAddress: SYNTH_EVM,
+ chainId: 8453,
+ });
+ const b = buildEip3009TypedData({
+ accept: baseAccept,
+ payerAddress: SYNTH_EVM,
+ chainId: 8453,
+ });
+ expect(a.authorization.nonce).toMatch(/^0x[0-9a-f]{64}$/);
+ expect(a.authorization.nonce).not.toBe(b.authorization.nonce);
+ });
+});
+
+describe('buildEvmPaymentPayload', () => {
+ it('wraps the signature + authorization into an x402 v2 payload', () => {
+ const payload = buildEvmPaymentPayload({
+ accept: baseAccept,
+ signature: '0xdead',
+ authorization: { from: SYNTH_EVM, to: baseAccept.payTo, value: '1000' },
+ resourceUrl: 'https://three.ws/api/paid',
+ });
+ expect(payload.x402Version).toBe(2);
+ expect(payload.scheme).toBe('exact');
+ expect(payload.network).toBe('eip155:8453');
+ expect(payload.resource.url).toBe('https://three.ws/api/paid');
+ expect(payload.accepted).toBe(baseAccept);
+ expect(payload.payload.signature).toBe('0xdead');
+ });
+});
+
+describe('encoding helpers', () => {
+ it('round-trips JSON through base64', () => {
+ const obj = { a: 1, b: 'x402', nested: { c: true } };
+ expect(b64decode(b64encode(obj))).toEqual(obj);
+ });
+
+ it('round-trips bytes through base64', () => {
+ const bytes = new Uint8Array([0, 1, 2, 250, 255]);
+ expect(Array.from(base64ToUint8Array(uint8ArrayToBase64(bytes)))).toEqual([
+ 0, 1, 2, 250, 255,
+ ]);
+ });
+
+ it('returns null for undecodable base64', () => {
+ expect(b64decode('')).toBe(null);
+ expect(b64decode('@@not-base64@@')).toBe(null);
+ });
+});
+
+describe('explorerUrl', () => {
+ it('maps networks to their explorers', () => {
+ expect(explorerUrl(solanaAccept.network, 'SIG')).toBe('https://solscan.io/tx/SIG');
+ expect(explorerUrl('eip155:8453', '0xabc')).toBe('https://basescan.org/tx/0xabc');
+ expect(explorerUrl('eip155:8453', null)).toBe(null);
+ });
+});
+
+describe('friendlyError', () => {
+ it('collapses wallet rejection messages', () => {
+ expect(friendlyError(new Error('User rejected the request'))).toBe('Cancelled in wallet');
+ expect(friendlyError({ message: 'User denied transaction signature' })).toBe(
+ 'Cancelled in wallet',
+ );
+ });
+
+ it('passes through and truncates other messages', () => {
+ expect(friendlyError(new Error('boom'))).toBe('boom');
+ expect(friendlyError(new Error('x'.repeat(500))).length).toBe(240);
+ });
+});
diff --git a/tests/pump-quote.test.js b/tests/pump-quote.test.js
new file mode 100644
index 000000000..5b5d577a0
--- /dev/null
+++ b/tests/pump-quote.test.js
@@ -0,0 +1,76 @@
+import { describe, it, expect } from 'vitest';
+import { classifyLaunchQuote, usdcMintFor, WSOL_MINT } from '../api/_lib/pump-quote.js';
+import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET } from '../api/payments/_config.js';
+
+const SYSTEM_DEFAULT = '11111111111111111111111111111111';
+// A non-USDC, non-SOL stable/other quote mint — clearly-synthetic placeholder.
+const OTHER_MINT = 'THREEsynthetic1111111111111111111111111111';
+
+describe('usdcMintFor', () => {
+ it('returns the mainnet USDC mint by default', () => {
+ expect(usdcMintFor('mainnet')).toBe(SOLANA_USDC_MINT);
+ expect(usdcMintFor()).toBe(SOLANA_USDC_MINT);
+ });
+ it('returns the devnet USDC mint on devnet', () => {
+ expect(usdcMintFor('devnet')).toBe(SOLANA_USDC_MINT_DEVNET);
+ });
+});
+
+describe('classifyLaunchQuote', () => {
+ it('treats null/undefined/empty as SOL-paired', () => {
+ for (const q of [null, undefined, '', ' ']) {
+ expect(classifyLaunchQuote({ quoteMint: q })).toEqual({
+ isUsdc: false,
+ quoteMint: null,
+ label: 'SOL',
+ });
+ }
+ });
+
+ it('treats wSOL and the system default pubkey as SOL-paired (canonicalized to null)', () => {
+ expect(classifyLaunchQuote({ quoteMint: WSOL_MINT })).toEqual({
+ isUsdc: false,
+ quoteMint: null,
+ label: 'SOL',
+ });
+ expect(classifyLaunchQuote({ quoteMint: SYSTEM_DEFAULT })).toEqual({
+ isUsdc: false,
+ quoteMint: null,
+ label: 'SOL',
+ });
+ });
+
+ it('classifies the network USDC mint as USDC-paired', () => {
+ expect(classifyLaunchQuote({ quoteMint: SOLANA_USDC_MINT, network: 'mainnet' })).toEqual({
+ isUsdc: true,
+ quoteMint: SOLANA_USDC_MINT,
+ label: 'USDC',
+ });
+ expect(classifyLaunchQuote({ quoteMint: SOLANA_USDC_MINT_DEVNET, network: 'devnet' })).toEqual({
+ isUsdc: true,
+ quoteMint: SOLANA_USDC_MINT_DEVNET,
+ label: 'USDC',
+ });
+ });
+
+ it('labels a non-SOL, non-USDC quote as a generic TOKEN pair but still isUsdc/stable', () => {
+ const r = classifyLaunchQuote({ quoteMint: OTHER_MINT, network: 'mainnet' });
+ expect(r.isUsdc).toBe(true);
+ expect(r.quoteMint).toBe(OTHER_MINT);
+ expect(r.label).toBe('TOKEN');
+ });
+
+ it('trims surrounding whitespace before classifying', () => {
+ expect(classifyLaunchQuote({ quoteMint: ` ${SOLANA_USDC_MINT} ` }).quoteMint).toBe(
+ SOLANA_USDC_MINT,
+ );
+ });
+
+ it('does not treat the mainnet USDC mint as USDC when network is devnet (mint mismatch → TOKEN)', () => {
+ // Guards against cross-network mislabeling: the mainnet USDC mint on a
+ // devnet launch is a non-canonical stable, so it labels as TOKEN.
+ const r = classifyLaunchQuote({ quoteMint: SOLANA_USDC_MINT, network: 'devnet' });
+ expect(r.isUsdc).toBe(true);
+ expect(r.label).toBe('TOKEN');
+ });
+});