Skip to content

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

feat: add x402 autonomous loop for scheduled agent payments and logging

nirholasdb2a68757f76
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 32cdeeeec..f8ff2e121 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Activation, upgraded — Live badges, one-call agent activation, and a Go Live first step** — Bringing an agent to life is now front-and-center and easier for people and agents alike. Right after you create an agent, "Go live" is the first thing offered. Agents that have claimed their welcome grant now wear a "◉ Live" badge across the marketplace so funded, active agents stand out, and their live status is published in each agent's manifest. Developers and autonomous agents can activate in a single call with the three.ws SDK (client.activate(agentId)). Behind the scenes, activating now also registers the agent's payout wallet so it can earn from day one, and counts toward referral rewards when you were invited. We also hardened the on-chain grant so it can never be sent twice. (`/marketplace`) `[feature, improvement, sdk]`
- **Alibaba Cloud partnership — Qwen models and alibaba-cloud-mcp** — three.ws joins the Alibaba Cloud Partner Network. Qwen-Max, Qwen-Plus, Qwen-Turbo, and Qwen-Long are now available as agent brain options via DashScope. Ships with @three-ws/alibaba-cloud-mcp — a new MCP server for chat, embeddings, and model discovery using your own Alibaba Cloud API key. Set DASHSCOPE_API_KEY in Vercel to activate. (`/blog/three-ws-alibaba-cloud-partnership`) `[feature]`
- **Autonomous coin launcher — creator fees, revenue tracking, and admin console upgrades** — The memetic launcher now auto-claims pump.fun creator fees from every coin it mints, routing the configured share toward $THREE. The admin console at /admin/launcher gains a live revenue panel (total creator fees claimed, $THREE allocated), agent-name visibility in the run feed, a Force Tick button for instant testing, and a cleaner 8-column stat grid. Know Your Meme is wired as a live trend source alongside Hacker News, Reddit, and Wikipedia — so the launcher reads what the internet is actually minting. (`/admin/launcher`) `[feature, improvement]`
+- **Avatar Optimization Pipeline — nightly analysis of top avatars** — The platform now runs a nightly optimization sweep across the 50 most-viewed public avatars. Each model is analyzed for geometry and texture inefficiencies — Draco/Meshopt compression opportunities, oversized textures ready for KTX2 transcoding, non-indexed primitives, and redundant materials. Results are stored per-avatar so we can surface actionable improvement suggestions to creators. The pipeline runs autonomously via the x402 agent spend loop, paying $0.001 USDC per nightly batch. `[feature, infra]`
- **Capabilities dashboard — live command center for all 4 autonomous features** — New /dashboard/capabilities page surfaces live status for Alpha Hunt, Coin Launcher, Auto-Claim, and Market Maker in one view. KPI strips show daily budget, total volume, claimable fees, and net P&L per capability. Tabbed tables show launched coins, schedule status, per-market inventory bars, and recent MM trades. Alpha Hunt trigger is now also configurable directly from the Sniper Strategies dashboard — full field set including min smart-money count, quality score, organic score, max market cap, and narrative keywords. (`/dashboard/capabilities`) `[feature, improvement]`
- **CAPTCHA relief for rate-limited sign-ins** — Users who hit the sign-in rate limit (e.g. shared office/home network) now see a lightweight proof-of-work puzzle instead of a hard countdown. Solve it in a second or two and you can keep signing in immediately — no waiting, no support ticket. Built on Altcha (open source, MIT-licensed, no tracking or third-party service). (`/login`) `[improvement, security]`
- **Design your own Memetic Launcher** — Every account now has a personal Memetic Launcher at /launcher — your own autonomous coin-launch strategy designer. Pick a mode (ride live cultural trends, coin original memes, or pure random volume), choose which sources it mines (Coin Intel, Trending, Know Your Meme, X, Reddit, Hacker News, Wikipedia and more), set a cadence, and turn it on. It then rotates through your own agents and, every tick, picks exactly the coin it would mint — riding the strongest live narrative — and records it. A live narratives panel shows the cultural currents ranked in real time, and a one-tap Synthesize button coins a sample on demand. It runs in preview: it designs and shows your rotation without minting or moving any SOL, so you can perfect a strategy risk-free. Find it under Launch in the main menu. (`/launcher`) `[feature]`
@@ -31,6 +32,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Live Agents mission control + one-click session launcher** — New /agents-live page shows a real-time grid of every AI agent with an active screen stream — watch their screens and avatar feeds live, all in one view. Agent owners now get a "Start Live Session" panel on any watch view: click Generate credentials, copy the Docker or Node launch command, run it anywhere, and the agent browser session starts streaming to the screen canvas instantly. Sessions are signed 7-day bearer tokens, no extra setup required. (`/agents-live`) `[feature]`
- **Live cultural narratives — now public, and now powered by Google Trends** — The autonomous launcher's trend intelligence got broader and more open. Alongside Know Your Meme, it now reads Google Daily Search Trends — the broadest real-time signal of what the world is paying attention to — with a brand-safety gate that reads the news behind each trend and drops anything tied to tragedy before it can ever become a coin theme. And the ranked narratives are now a public, read-only feed at /api/launcher/trends: any agent (or builder) can ask what's trending right now — optionally filtered to specific sources — with the signals confirming each wave, and ride a real current instead of guessing. Themes only — names and tickers are always invented fresh, never copied. `[feature, improvement]`
- **Manage your AWS Marketplace API key — new keys & usage page** — AWS Marketplace subscribers (and anyone with an x402 subscription key) now have a home for it at /billing/keys. See every key with its billing source — AWS Marketplace or on-chain — live status, rate limit, total calls, and when it was last used. Rotate a key to get a fresh secret in one click (AWS-billed keys stay linked to your AWS account and keep metering correctly), or revoke a native key outright. The post-subscribe welcome flow now points here, so a lost key is always recoverable by rotating instead of being stuck. (`/billing/keys`) `[feature]`
+- **MCP Model Validation Sweep — proactive GLB quality scoring** — The platform now runs a continuous quality sweep across every public 3D avatar in the database. Every 5 minutes the autonomous agent picks the longest-unvalidated GLB, inspects it with the glTF-Transform engine, and records a 0-100 quality score covering rig completeness, geometry health, texture sizing, triangle budget, and unsupported extensions. Results are stored in a time-series table (model_quality_scores) that will power quality badges and curation tools — surfacing models that need attention before users encounter errors in the viewer. The sweep is driven by the x402 autonomous spend loop at $0.001 USDC per call. `[feature, infra]`
- **Money Pulse now shows whether agent trading is viable** — The Pulse page gained a Trading viability panel — the honest signal behind the headline Trades counter. It shows what's actually flowing through agent wallets: trades over 24h and 7 days, the SOL deployed into buys (what the trading is costing), the average trade size, how many wallets are trading right now, and — once positions close — the realized profit-and-loss with a win rate, alongside a 7-day trade sparkline and the top trading agents. The 24h trade count reconciles exactly with the headline counter, so the panel can never drift from the number at the top of the page. Every figure is a real, on-chain custody event or a closed position priced against real fills — never synthetic. (`/pulse`) `[feature, improvement]`
- **Money Pulse now tracks real marketplace demand** — The Pulse page gained a Marketplace viability panel — the honest economic signal behind the headline counters. It surfaces real $THREE skill purchases as their own thing: GMV over 24h and 7 days, average ticket, the repeat-buyer rate, the number of unique buyer→seller pairs, the platform take-rate earned, plus a 7-day GMV sparkline, the top skills the market is actually paying for, and the top-earning sellers. Until now these real, value-delivering purchases were invisible on Pulse while the agent-to-agent x402 settlement counter took the spotlight; now you can see whether agents paying each other for skills is a real, recurring market. Every figure is a confirmed on-chain purchase — never synthetic. (`/pulse`) `[feature, improvement]`
- **Money Pulse redesign — monochrome, with far more live data** — The live activity page at /pulse got a full pass. It's now proper monochrome to match the rest of the site — the violet accent and green/amber feed colors give way to a single clean ink ramp. And it carries a lot more real signal: 24h on-chain volume (SOL + USD), distinct active wallets, and split counters for trades, snipes, and agent-to-agent payments, plus a 7-day activity sparkline, the day's single biggest tip, and a fresh-launches feed alongside the existing top-earners and busiest-wallets boards. Every number is a real on-chain or launch record — never synthetic. (`/pulse`) `[improvement, feature]`
diff --git a/api/_lib/migrations/2026-06-27-avatar-thumbnail-regen.sql b/api/_lib/migrations/2026-06-27-avatar-thumbnail-regen.sql
new file mode 100644
index 000000000..ee4965912
--- /dev/null
+++ b/api/_lib/migrations/2026-06-27-avatar-thumbnail-regen.sql
@@ -0,0 +1,65 @@
+-- Migration: avatar thumbnail regeneration pipeline (x402 autonomous loop).
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-06-27-avatar-thumbnail-regen.sql
+-- Idempotent.
+--
+-- The autonomous x402 spend loop (api/cron/x402-autonomous-loop.js) periodically
+-- pays /api/x402/asset-download for the stalest marketplace listing, then queues
+-- a thumbnail re-render. The drainer cron (api/cron/avatar-thumbnail-render.js)
+-- renders the current GLB to a fresh PNG and writes it back so listings always
+-- show the model's current appearance.
+--
+-- Two pieces of state:
+-- 1. Freshness columns on paid_assets so the selector can find stale listings.
+-- 2. avatar_thumbnail_regen_jobs — the queue the autonomous loop fills and the
+-- drainer cron consumes.
+
+-- ── paid_assets freshness tracking ──────────────────────────────────────────
+-- thumbnail_r2_key R2 object key of the current rendered thumbnail (null = never rendered).
+-- thumbnail_generated_at when the current thumbnail was rendered (null = never).
+-- source_updated_at when the underlying GLB bytes last changed; if this is
+-- newer than thumbnail_generated_at the thumbnail is stale.
+-- avatar_id link back to the avatars row so a regen also refreshes
+-- the avatar's marketplace thumbnail_key.
+ALTER TABLE paid_assets ADD COLUMN IF NOT EXISTS thumbnail_r2_key text;
+ALTER TABLE paid_assets ADD COLUMN IF NOT EXISTS thumbnail_generated_at timestamptz;
+ALTER TABLE paid_assets ADD COLUMN IF NOT EXISTS source_updated_at timestamptz;
+ALTER TABLE paid_assets ADD COLUMN IF NOT EXISTS avatar_id uuid REFERENCES avatars(id) ON DELETE SET NULL;
+
+-- ── avatar_thumbnail_regen_jobs ─────────────────────────────────────────────
+-- One row per regen the autonomous loop triggers. The loop inserts status
+-- 'queued' after a successful paid asset-download; the drainer cron renders and
+-- moves it to 'done' (or 'failed' with the error and an incremented attempt
+-- count). r2_key is the SOURCE GLB key — the drainer re-presigns it at render
+-- time (the loop's presigned downloadUrl is short-lived and would expire before
+-- the drainer runs).
+CREATE TABLE IF NOT EXISTS avatar_thumbnail_regen_jobs (
+ id bigserial PRIMARY KEY,
+ asset_id uuid REFERENCES paid_assets(id) ON DELETE CASCADE,
+ asset_slug text NOT NULL,
+ avatar_id uuid REFERENCES avatars(id) ON DELETE SET NULL,
+ r2_key text NOT NULL,
+ run_id uuid,
+ x402_tx_signature text,
+ amount_atomic bigint NOT NULL DEFAULT 0,
+ status text NOT NULL DEFAULT 'queued'
+ CHECK (status IN ('queued','rendering','done','failed')),
+ thumbnail_r2_key text,
+ width int NOT NULL DEFAULT 768,
+ height int NOT NULL DEFAULT 768,
+ attempts int NOT NULL DEFAULT 0,
+ error text,
+ reason text,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ rendered_at timestamptz
+);
+
+-- Drainer pulls oldest queued / retryable-failed rows first.
+CREATE INDEX IF NOT EXISTS avatar_thumbnail_regen_jobs_status_idx
+ ON avatar_thumbnail_regen_jobs (status, created_at);
+
+-- At most one open (queued/rendering) job per asset — the loop checks this before
+-- enqueuing so a slow drainer never lets duplicates pile up for one listing.
+CREATE UNIQUE INDEX IF NOT EXISTS avatar_thumbnail_regen_jobs_open_uniq
+ ON avatar_thumbnail_regen_jobs (asset_slug)
+ WHERE status IN ('queued','rendering');
diff --git a/api/_lib/pump-pricing.js b/api/_lib/pump-pricing.js
index 53d638135..0baf5b726 100644
--- a/api/_lib/pump-pricing.js
+++ b/api/_lib/pump-pricing.js
@@ -31,6 +31,12 @@ export const TOOL_PRICING = Object.freeze({
// region edit only inpaints one masked patch, so it is priced well below it.
retexture_model: { amount_usdc: 0.1, description: 'Per full retexture' },
retexture_region: { amount_usdc: 0.03, description: 'Per region edit (magic brush)' },
+ // Public gallery search — a real DB query that ranks the whole public avatar
+ // corpus and resolves a signed thumbnail per hit. Priced as the cheapest
+ // metered call so anonymous x402 agents (and the autonomous warmup loop) pay
+ // per search; authenticated OAuth callers bypass payment entirely (they hold a
+ // bearer token, so authenticateRequest never issues the x402 challenge).
+ search_public_avatars: { amount_usdc: 0.001, description: 'Per call — public avatar gallery search' },
// Discovery / lookups (incl. list_animations) — free
});
diff --git a/api/_lib/review-attest.js b/api/_lib/review-attest.js
new file mode 100644
index 000000000..8f3a5eca6
--- /dev/null
+++ b/api/_lib/review-attest.js
@@ -0,0 +1,155 @@
+/**
+ * On-chain review attestor (server-side).
+ *
+ * Every time a user submits or edits an agent/skill review, this module emits a
+ * threews.review.v1 SPL-Memo attestation signed by the platform attester and
+ * mirrors it into solana_attestations. The result is a tamper-evident,
+ * publicly-verifiable on-chain record of each review anchored to the agent's
+ * Metaplex Core asset.
+ *
+ * Design mirrors trader-score-attest.js:
+ * - Best-effort: callers catch errors and log; the HTTP response is never blocked.
+ * - Idempotent per (agent_asset, network, review_id, updated_at): editing a
+ * review emits a new attestation capturing the updated state; retrying the
+ * same POST never double-mints.
+ * - Silently no-ops when the agent has no Solana asset (newer agents may not
+ * yet have a Metaplex Core pubkey on record).
+ */
+
+import crypto from 'node:crypto';
+import { PublicKey, Transaction, TransactionInstruction, sendAndConfirmTransaction } from '@solana/web3.js';
+
+import { sql } from './db.js';
+import { solanaConnection } from './solana/connection.js';
+import { RPC } from './solana-attestations.js';
+import { loadAttesterKeypair } from './attest-event.js';
+
+const MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');
+const REVIEW_KIND = 'threews.review.v1';
+const TX_TIMEOUT_MS = 15_000;
+
+export class ReviewAttestError extends Error {
+ constructor(code, message) {
+ super(message);
+ this.name = 'ReviewAttestError';
+ this.code = code;
+ }
+}
+
+function withTimeout(promise, ms) {
+ let timer;
+ const timeout = new Promise((_, reject) => {
+ timer = setTimeout(
+ () => reject(Object.assign(new Error(`rpc timeout after ${ms}ms`), { code: 'RPC_TIMEOUT' })),
+ ms,
+ );
+ });
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
+}
+
+/**
+ * Attest a user review on-chain via Solana SPL-Memo.
+ *
+ * @param {object} p
+ * @param {string} p.reviewId UUID of the agent_reviews or skill_reviews row.
+ * @param {string} p.updatedAt ISO timestamp from the DB row (updated_at) — part of the idempotency key.
+ * @param {string} p.agentId three.ws agent UUID (DB identifier, recorded in payload for back-reference).
+ * @param {number} p.rating 1–5 star rating.
+ * @param {string|null} p.body Review text (may be null / empty).
+ * @param {'agent'|'skill'} p.reviewType
+ * @param {string} [p.skill] Skill name — only for reviewType='skill'.
+ * @param {'mainnet'|'devnet'} [p.network='mainnet']
+ * @returns {Promise<{ status:'minted'|'deduped'|'no_asset', signature:string|null }>}
+ */
+export async function attestReview({ reviewId, updatedAt, agentId, rating, body, reviewType, skill, network = 'mainnet' }) {
+ // Resolve the agent's Metaplex Core asset pubkey — the canonical attestation subject.
+ // Column mirrors what solana-bouncer.js reads.
+ const [agentRow] = await sql`
+ select coalesce(meta->'onchain'->>'sol_asset', meta->>'sol_mint_address') as agent_asset
+ from agent_identities
+ where id = ${agentId} and deleted_at is null
+ limit 1
+ `;
+ const agentAsset = agentRow?.agent_asset;
+ if (!agentAsset) return { status: 'no_asset', signature: null };
+
+ try { new PublicKey(agentAsset); } catch {
+ throw new ReviewAttestError('invalid_asset', `agent_identities row has an unparseable sol_asset for agent ${agentId}`);
+ }
+
+ let attester;
+ try { attester = loadAttesterKeypair(); } catch {
+ throw new ReviewAttestError('attester_key_not_configured', 'ATTEST_AGENT_SECRET_KEY is not set');
+ }
+
+ // Idempotency: one attestation per (review_id, updated_at second).
+ // Edits change updated_at, so each new write produces exactly one new attestation.
+ const updatedSec = String(Math.floor(new Date(updatedAt).getTime() / 1000));
+ const [existing] = await sql`
+ select signature from solana_attestations
+ where agent_asset = ${agentAsset}
+ and network = ${network}
+ and kind = ${REVIEW_KIND}
+ and payload->>'review_id' = ${reviewId}
+ and payload->>'updated_sec' = ${updatedSec}
+ limit 1
+ `;
+ if (existing) return { status: 'deduped', signature: existing.signature };
+
+ // SHA-256 of the body text — lets anyone verify the content matches without
+ // storing the body itself on-chain (privacy) while still making it tamper-evident.
+ const bodyHash = body ? crypto.createHash('sha256').update(body, 'utf8').digest('hex') : null;
+
+ const payload = {
+ v: 1,
+ kind: REVIEW_KIND,
+ agent: agentAsset,
+ agent_id: agentId,
+ review_id: reviewId,
+ updated_sec: updatedSec,
+ rating,
+ body_hash: bodyHash,
+ review_type: reviewType,
+ ...(skill ? { skill } : {}),
+ network,
+ ts: Math.floor(Date.now() / 1000),
+ source: 'threews.review',
+ };
+
+ const conn = solanaConnection({ url: RPC[network] || RPC.devnet, commitment: 'confirmed' });
+ const ix = new TransactionInstruction({
+ programId: MEMO_PROGRAM_ID,
+ keys: [
+ { pubkey: attester.publicKey, isSigner: true, isWritable: false },
+ { pubkey: new PublicKey(agentAsset), isSigner: false, isWritable: false },
+ ],
+ data: Buffer.from(JSON.stringify(payload), 'utf8'),
+ });
+
+ let signature;
+ try {
+ signature = await withTimeout(
+ sendAndConfirmTransaction(conn, new Transaction().add(ix), [attester], { commitment: 'confirmed' }),
+ TX_TIMEOUT_MS,
+ );
+ } catch (err) {
+ throw new ReviewAttestError('tx_failed', `review memo tx failed: ${err.message}`);
+ }
+
+ try {
+ await sql`
+ insert into solana_attestations (
+ signature, network, slot, block_time, agent_asset, attester, kind, payload, verified
+ ) values (
+ ${signature}, ${network}, null, now(),
+ ${agentAsset}, ${attester.publicKey.toBase58()},
+ ${REVIEW_KIND}, ${JSON.stringify(payload)}::jsonb, true
+ )
+ on conflict (signature) do nothing
+ `;
+ } catch (err) {
+ if (err?.code !== '23505') throw err;
+ }
+
+ return { status: 'minted', signature };
+}
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 1be809bde..4f8eecbc8 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -1688,6 +1688,43 @@ CREATE TABLE IF NOT EXISTS paid_assets (
);
CREATE INDEX IF NOT EXISTS paid_assets_slug_idx ON paid_assets (slug);
+-- Avatar thumbnail regeneration freshness tracking + queue.
+-- Mirror of api/_lib/migrations/2026-06-27-avatar-thumbnail-regen.sql. The
+-- autonomous x402 loop pays asset-download for the stalest listing and queues a
+-- re-render; the drainer cron (api/cron/avatar-thumbnail-render.js) renders the
+-- current GLB to a fresh PNG and writes it back so listings show current state.
+ALTER TABLE paid_assets ADD COLUMN IF NOT EXISTS thumbnail_r2_key text;
+ALTER TABLE paid_assets ADD COLUMN IF NOT EXISTS thumbnail_generated_at timestamptz;
+ALTER TABLE paid_assets ADD COLUMN IF NOT EXISTS source_updated_at timestamptz;
+ALTER TABLE paid_assets ADD COLUMN IF NOT EXISTS avatar_id uuid REFERENCES avatars(id) ON DELETE SET NULL;
+
+CREATE TABLE IF NOT EXISTS avatar_thumbnail_regen_jobs (
+ id bigserial PRIMARY KEY,
+ asset_id uuid REFERENCES paid_assets(id) ON DELETE CASCADE,
+ asset_slug text NOT NULL,
+ avatar_id uuid REFERENCES avatars(id) ON DELETE SET NULL,
+ r2_key text NOT NULL,
+ run_id uuid,
+ x402_tx_signature text,
+ amount_atomic bigint NOT NULL DEFAULT 0,
+ status text NOT NULL DEFAULT 'queued'
+ CHECK (status IN ('queued','rendering','done','failed')),
+ thumbnail_r2_key text,
+ width int NOT NULL DEFAULT 768,
+ height int NOT NULL DEFAULT 768,
+ attempts int NOT NULL DEFAULT 0,
+ error text,
+ reason text,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ rendered_at timestamptz
+);
+CREATE INDEX IF NOT EXISTS avatar_thumbnail_regen_jobs_status_idx
+ ON avatar_thumbnail_regen_jobs (status, created_at);
+CREATE UNIQUE INDEX IF NOT EXISTS avatar_thumbnail_regen_jobs_open_uniq
+ ON avatar_thumbnail_regen_jobs (asset_slug)
+ WHERE status IN ('queued','rendering');
+
-- ── siwx_payments + siwx_nonces — Sign-In-With-X (CAIP-122) payment history ─
-- Mirror of api/_lib/migrations/2026-05-21-siwx.sql. A wallet that paid for a
-- resource can re-access it by signing CAIP-122 instead of re-paying. Stored
diff --git a/api/_lib/solana-attestations.js b/api/_lib/solana-attestations.js
index 9d617d1f8..f3d7d42c5 100644
--- a/api/_lib/solana-attestations.js
+++ b/api/_lib/solana-attestations.js
@@ -18,6 +18,7 @@ export const KIND_MAP = {
revoke: 'threews.revoke.v1',
dispute: 'threews.dispute.v1',
stake: 'threews.stake.v1',
+ review: 'threews.review.v1',
};
export const KINDS_ALL = Object.values(KIND_MAP);
export const MIN_STAKE_LAMPORTS = 1_000_000n; // 0.001 SOL
@@ -52,6 +53,9 @@ export function validatePayload(p) {
return typeof p.target_signature === 'string';
case 'threews.stake.v1':
return Number.isInteger(p.score) && p.score >= 1 && p.score <= 5;
+ case 'threews.review.v1':
+ return Number.isInteger(p.rating) && p.rating >= 1 && p.rating <= 5
+ && typeof p.review_id === 'string' && p.review_id.length > 0;
default:
return false;
}
diff --git a/api/_lib/trust/solana-bouncer.js b/api/_lib/trust/solana-bouncer.js
index 1db168c45..b91df562d 100644
--- a/api/_lib/trust/solana-bouncer.js
+++ b/api/_lib/trust/solana-bouncer.js
@@ -124,9 +124,9 @@ export async function loadAgentReputation(agentId) {
const [attRow] = agentRow.agent_asset
? await sql`
select
- count(*) filter (where kind like 'threews.feedback%')::int as feedback_count,
- count(*) filter (where kind like 'threews.validation%')::int as validation_count,
- max(block_time) as latest_attested_at
+ count(*) filter (where kind like 'threews.feedback%' or kind = 'threews.review.v1')::int as feedback_count,
+ count(*) filter (where kind like 'threews.validation%')::int as validation_count,
+ max(block_time) as latest_attested_at
from solana_attestations
where agent_asset = ${agentRow.agent_asset}
and revoked = false
diff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.js
index 3fb524617..831cc762d 100644
--- a/api/_lib/x402/autonomous-registry.js
+++ b/api/_lib/x402/autonomous-registry.js
@@ -13,10 +13,134 @@
// body — request body (for POST), can be a function(ctx) => object
// cooldown_s — minimum seconds between calls (enforced via Redis)
// priority — 1-100; higher = more likely selected when multiple are ready
-// pipeline — tag: 'oracle' | 'health' | 'volume' | 'sniper' | 'external'
+// pipeline — tag: 'oracle' | 'health' | 'volume' | 'sniper' | 'qa' | 'external'
// enabled — boolean; set false to pause without removing
// extractSignal — optional fn(responseBody) => object stored in x402_autonomous_log.signal_data
// For oracle pipeline entries, return { mint?, signal, confidence, headline }
+// resolveTarget — optional async fn(ctx) => { path, targetUrl } that computes the
+// request path dynamically per call (ctx: { redis, origin, runId }).
+// For pipelines that rotate over a set of resources.
+// storeValue — optional async fn(ctx) that persists extracted value to a
+// dedicated table (ctx: { sql, redis, responseBody, signalData,
+// runId, targetUrl, endpointUrl }). The loop wraps it in try/catch
+// so a DB failure can never crash the tick.
+
+// Canary clip the Animation Retargeting QA probe pays to download. Designate a
+// stable, paid, listed marketplace clip (an animation that exercises the
+// retarget/canonicalize delivery path) via this env var. Unset → the probe stays
+// disabled instead of paying for a non-existent id. Mirrors the well-known-mint
+// canary pattern used by the token-intel health check.
+const ANIM_QA_CLIP_ID = (process.env.X402_ANIMATION_QA_CLIP_ID || '').trim();
+
+// ── GLB Canonicalization Pipeline (USE-011) ──────────────────────────────────
+// Real rig-reference avatars served from three.ws/avatars/*.glb. Each covers a
+// distinct skeleton convention that src/glb-canonicalize.js maps onto the
+// canonical bone set (Mixamo, Daz/Genesis, glTF reference, photoreal scan,
+// rigged non-humanoid). The autonomous loop rotates through them so every known
+// rig type is continuously re-validated against /api/x402/model-check. The day a
+// glTF-Transform bump — or a brand-new rig added to the rotation — regresses
+// skin/animation detection (the signal that would otherwise silently drop an
+// avatar to a bind-pose T-pose), the verdict flips and lands in
+// glb_canonicalization_results keyed by model URL for the avatar pipeline to read.
+const RIG_REFERENCE_AVATARS = [
+ 'michelle.glb', // Mixamo humanoid (mixamorig:* bones)
+ 'xbot.glb', // Mixamo X-Bot
+ 'cz.glb', // Daz/Genesis-style rig
+ 'cesium-man.glb', // glTF reference skinned rig
+ 'realistic-male.glb', // photoreal scanned humanoid
+ 'dancing-twerk.glb', // Mixamo clip-baked rig
+ 'brainstem.glb', // glTF reference skinned (non-humanoid joints)
+ 'fox.glb', // rigged non-humanoid (animal) — exercises the fallback gate
+];
+
+export { RIG_REFERENCE_AVATARS };
+
+// Derive the canonicalization verdict from a /api/x402/model-check response.
+// Shared by extractSignal (→ x402_autonomous_log.signal_data) and storeValue
+// (→ glb_canonicalization_results) so both always agree on the classification.
+export function classifyCanonicalization(r) {
+ const model = (r && r.model) || {};
+ const c = model.counts || {};
+ const ext = [
+ ...(Array.isArray(model.extensionsUsed) ? model.extensionsUsed : []),
+ ...(Array.isArray(model.extensionsRequired) ? model.extensionsRequired : []),
+ ];
+ const isVrm = ext.some((x) => typeof x === 'string' && /^VRM/i.test(x));
+ const skins = Number(c.skins || 0);
+ const animations = Number(c.animations || 0);
+ const isSkinned = skins > 0;
+ // supportsCanonicalClips() gate (AnimationManager): only skeleton-driven rigs
+ // can retarget the pre-baked idle/walk library. A skin-less model uses the
+ // default-rig fallback rather than collapsing to a T-pose.
+ const rigType = isVrm
+ ? 'vrm'
+ : isSkinned
+ ? 'skinned'
+ : animations > 0
+ ? 'node-animated'
+ : 'static';
+ return {
+ model_url: (r && r.url) || null,
+ container: model.container || null,
+ generator: model.generator || null,
+ rig_type: rigType,
+ is_skinned: isSkinned,
+ vrm: isVrm,
+ skins,
+ animations,
+ nodes: Number(c.nodes || 0),
+ canonical_ready: isSkinned,
+ extensions: ext,
+ suggestion_count: Array.isArray(r && r.suggestions) ? r.suggestions.length : 0,
+ fetched_bytes: Number((r && r.fetchedBytes) || 0),
+ };
+}
+
+// One-time DDL guard per warm instance (mirrors the loop's ensureSchema idiom).
+let _canonSchemaReady = false;
+async function ensureCanonicalSchema(sql) {
+ if (_canonSchemaReady) return;
+ await sql`
+ CREATE TABLE IF NOT EXISTS glb_canonicalization_results (
+ model_url text PRIMARY KEY,
+ container text,
+ generator text,
+ rig_type text,
+ is_skinned boolean,
+ vrm boolean,
+ skins int,
+ animations int,
+ nodes int,
+ canonical_ready boolean,
+ extensions jsonb,
+ suggestions jsonb,
+ run_id uuid,
+ checked_at timestamptz DEFAULT now()
+ )
+ `;
+ _canonSchemaReady = true;
+}
+
+// Round-robin cursor over the reference avatars (per warm instance; Redis-backed
+// when available so rotation is stable across instances).
+let _canonCursor = 0;
+async function nextCanonicalTarget(ctx) {
+ const list = RIG_REFERENCE_AVATARS;
+ let idx;
+ if (ctx?.redis) {
+ try {
+ const n = await ctx.redis.incr('x402:auto:glb-canon:cursor');
+ idx = (Number(n) - 1) % list.length;
+ } catch {
+ idx = _canonCursor++ % list.length;
+ }
+ } else {
+ idx = _canonCursor++ % list.length;
+ }
+ const origin = ctx?.origin || 'https://three.ws';
+ const targetUrl = `${origin}/avatars/${list[idx]}`;
+ return { path: `/api/x402/model-check?url=${encodeURIComponent(targetUrl)}`, targetUrl };
+}
const SELF_ENDPOINTS = [
// ── Oracle / Intelligence (highest priority — feeds sniper decisions) ─────
@@ -229,6 +353,65 @@ const SELF_ENDPOINTS = [
enabled: true,
extractSignal: (r) => ({ alive: !!r?.verdict, verdict: r?.verdict }),
},
+ // MCP Model Validation Sweep — picks the longest-unvalidated public GLB from
+ // the avatars table, runs glTF-Transform inspection, and upserts a quality
+ // score row to model_quality_scores. Each tick advances the sweep by one avatar.
+ // Cooldown 300 s → 12 models/hour; a library of 100 models is fully covered
+ // within ~8 hours and re-validated on a 24-hour rolling basis.
+ // Downstream consumer: model_quality_scores → explore quality badges and
+ // curation pipelines that surface models needing attention.
+ {
+ id: 'mcp-model-validation-sweep',
+ name: 'MCP Model Validation Sweep',
+ path: '/api/x402/model-validation-sweep',
+ method: 'POST',
+ body: {},
+ cooldown_s: 300,
+ priority: 45,
+ pipeline: 'health',
+ enabled: true,
+ extractSignal: (r) => ({
+ avatar_id: r?.avatar_id || null,
+ score: r?.score ?? null,
+ has_errors: r?.has_errors ?? null,
+ missing_bones: r?.missing_bones ?? null,
+ skipped: r?.skipped ?? false,
+ }),
+ },
+
+ // ── MCP Health: Solana agent registration canary ──────────────────────────
+ // Verifies the server-custodial Solana registration subsystem end-to-end by
+ // resolving a known canary agent's on-chain Metaplex Agent Registry record
+ // (Identity PDA + Core asset) and confirming both accounts still exist
+ // on-chain. The endpoint owns the verification + persists the canonical
+ // health row to mcp_health_canary; this loop pays the $0.001 canary fee,
+ // records the call to x402_autonomous_log, and respects the 6h cooldown
+ // (4 probes/day). extractSignal lifts the health verdict into signal_data so
+ // a status dashboard can read it straight off the autonomous log too.
+ {
+ id: 'mcp-solana-register-health',
+ name: 'MCP Health: Solana agent registration',
+ path: '/api/x402/solana-register-health',
+ method: 'GET',
+ body: null,
+ cooldown_s: 21600, // 6h — registration is a slow-changing subsystem
+ priority: 55,
+ pipeline: 'health',
+ enabled: true,
+ extractSignal: (r) => ({
+ alive: r?.healthy === true,
+ tool: r?.tool || 'solana_register',
+ network: r?.network || null,
+ canary_agent_id: r?.canary_agent_id || null,
+ asset: r?.asset || null,
+ identity_pda: r?.identity_pda || null,
+ registry_enrolled: r?.checks?.registry_enrolled === true,
+ asset_onchain: r?.checks?.asset_onchain === true,
+ identity_pda_onchain: r?.checks?.identity_pda_onchain === true,
+ consecutive_failures: r?.consecutive_failures ?? null,
+ rpc_latency_ms: r?.rpc_latency_ms ?? null,
+ }),
+ },
// ── Sniper Pipeline Support ────────────────────────────────────────────────
{
@@ -258,6 +441,98 @@ const SELF_ENDPOINTS = [
extractSignal: (r) => ({ alive: !!r }),
},
+ // ── 3D Pipeline QA ─────────────────────────────────────────────────────────
+ // Animation Retargeting QA: pays $0.005 USDC to download a canary animation
+ // clip through the full paid-delivery path (402 paywall → R2 presign → GLB).
+ // That delivery path ships clips produced by the retarget/canonicalize
+ // pipeline (src/glb-canonicalize.js, src/animation-retarget.js), so a
+ // regression that yields a missing, zero-byte, or non-GLB artifact surfaces
+ // here as pass:false. The verdict is stored to x402_autonomous_log.signal_data
+ // (queryable QA history); world-health / uptime dashboards consume it.
+ // Gated on X402_ANIMATION_QA_CLIP_ID — disabled (no spend) until a canary
+ // clip is designated. Cooldown 6h → ≤4 paid probes/day ≈ $0.02/day.
+ {
+ id: 'anim-retarget-qa',
+ name: 'Animation Retargeting QA',
+ path: `/api/x402/animation-download?id=${ANIM_QA_CLIP_ID}`,
+ method: 'GET',
+ body: null,
+ cooldown_s: 21600,
+ priority: 45,
+ pipeline: 'qa',
+ enabled: Boolean(ANIM_QA_CLIP_ID),
+ extractSignal: (r) => {
+ const sizeBytes = Number(r?.sizeBytes ?? 0);
+ const mime = String(r?.mimeType || '');
+ const hasDownload = !!r?.downloadUrl;
+ const isGlb = /gltf-binary|\bglb\b/i.test(mime);
+ return {
+ clip: r?.slug || r?.id || null,
+ name: r?.name || null,
+ size_bytes: sizeBytes,
+ mime,
+ has_download: hasDownload,
+ // All three must hold for the delivery path to be regression-free.
+ pass: r?.ok === true && hasDownload && sizeBytes > 0 && isGlb,
+ };
+ },
+ },
+ // GLB Canonicalization: pays $0.001 USDC to run a rig-reference avatar
+ // through /api/x402/model-check, validating that its skeleton still inspects
+ // as a skinned/animated rig (the precondition for canonical-clip retargeting).
+ // resolveTarget rotates the avatar set so every rig convention is re-checked
+ // over time; storeValue upserts the verdict into glb_canonicalization_results
+ // (consumed by the avatar upload + animation retarget pipeline to gate T-pose
+ // fallback). Cooldown 300s → one avatar every 5 min, full ~8-rig cycle ≈ 40 min.
+ {
+ id: 'glb-canonicalize',
+ name: 'GLB Canonicalization Check',
+ // Stable fallback path; resolveTarget overrides it per call (rotation).
+ path: `/api/x402/model-check?url=${encodeURIComponent('https://three.ws/avatars/xbot.glb')}`,
+ method: 'GET',
+ body: null,
+ cooldown_s: 300,
+ priority: 55,
+ pipeline: 'canonicalize',
+ enabled: true,
+ resolveTarget: (ctx) => nextCanonicalTarget(ctx),
+ extractSignal: (r) => classifyCanonicalization(r),
+ storeValue: async ({ sql, responseBody, signalData, runId, targetUrl }) => {
+ if (!sql) return;
+ const v = signalData || classifyCanonicalization(responseBody);
+ const url = v.model_url || targetUrl;
+ if (!url) return;
+ await ensureCanonicalSchema(sql);
+ await sql`
+ INSERT INTO glb_canonicalization_results
+ (model_url, container, generator, rig_type, is_skinned, vrm,
+ skins, animations, nodes, canonical_ready, extensions, suggestions,
+ run_id, checked_at)
+ VALUES
+ (${url}, ${v.container}, ${v.generator}, ${v.rig_type},
+ ${v.is_skinned}, ${v.vrm}, ${v.skins}, ${v.animations}, ${v.nodes},
+ ${v.canonical_ready},
+ ${JSON.stringify(v.extensions || [])},
+ ${JSON.stringify((responseBody && responseBody.suggestions) || [])},
+ ${runId}, now())
+ ON CONFLICT (model_url) DO UPDATE SET
+ container = EXCLUDED.container,
+ generator = EXCLUDED.generator,
+ rig_type = EXCLUDED.rig_type,
+ is_skinned = EXCLUDED.is_skinned,
+ vrm = EXCLUDED.vrm,
+ skins = EXCLUDED.skins,
+ animations = EXCLUDED.animations,
+ nodes = EXCLUDED.nodes,
+ canonical_ready = EXCLUDED.canonical_ready,
+ extensions = EXCLUDED.extensions,
+ suggestions = EXCLUDED.suggestions,
+ run_id = EXCLUDED.run_id,
+ checked_at = now()
+ `;
+ },
+ },
+
// ── Club Cover Charge (social economy test) ────────────────────────────────
{
id: 'club-cover-health',
@@ -271,6 +546,29 @@ const SELF_ENDPOINTS = [
enabled: true,
extractSignal: null,
},
+
+ // ── Avatar Optimization Pipeline (nightly MCP Health) ─────────────────────
+ // Pays $0.001 USDC to run optimize_model analysis on the top 50 most-viewed
+ // public avatars. Results upserted to avatar_optimization_results per avatar_id.
+ // Downstream consumer: avatar owner notifications + model quality dashboard.
+ // Cooldown: 86400 s (nightly — keeps daily spend to $0.001).
+ {
+ id: 'avatar-optimize-batch',
+ name: 'Avatar Optimization Pipeline',
+ path: '/api/x402/avatar-optimize-batch',
+ method: 'POST',
+ body: { limit: 50 },
+ cooldown_s: 86400,
+ priority: 30,
+ pipeline: 'health',
+ enabled: true,
+ extractSignal: (r) => ({
+ analyzed: r?.analyzed,
+ critical_count: r?.critical_count,
+ warn_count: r?.warn_count,
+ total_size_bytes: r?.total_size_bytes,
+ }),
+ },
];
// ── External registry ─────────────────────────────────────────────────────────
diff --git a/api/_lib/x402/circuit-breaker.js b/api/_lib/x402/circuit-breaker.js
new file mode 100644
index 000000000..8de0f249a
--- /dev/null
+++ b/api/_lib/x402/circuit-breaker.js
@@ -0,0 +1,315 @@
+// api/_lib/x402/circuit-breaker.js
+//
+// Cross-Network Payment Circuit Breaker — the cheapest possible end-to-end
+// proof that the entire x402 payment stack is alive.
+//
+// Once per hour the autonomous loop calls runCircuitBreaker() via the registry
+// entry's run() hook. It:
+//
+// 1. Probes a real $0.001 402-gated three.ws endpoint (dance-tip) for a live
+// payment challenge.
+// 2. Inspects the challenge's `accepts` array and confirms the facilitator
+// advertises a well-formed route for EVERY supported network — Solana
+// (scheme=exact), Base (scheme=exact), and BSC (scheme=direct). A missing
+// or malformed accept means a facilitator/config route has gone dark: the
+// breaker trips for that network.
+// 3. Settles a REAL $0.001 USDC payment on Solana — the only network with a
+// configured autonomous outbound keypair (X402_AGENT_SOLANA_SECRET_BASE58)
+// — to prove that build → verify → settle → receipt works end-to-end, not
+// just that the route is advertised. Base/BSC outbound settlement is not
+// attempted because no autonomous EVM signing wallet is provisioned; their
+// route health is verified from the live challenge instead (real data, no
+// mock). The moment an autonomous EVM payer is configured, settlement for
+// those networks can be switched on here without touching the loop.
+// 4. Upserts per-network status into `x402_circuit_breaker` (latest snapshot
+// keyed by network) and returns a compact summary the loop records to
+// `x402_autonomous_log`.
+//
+// Downstream consumer: api/ops/health.js reads `x402_circuit_breaker` and
+// surfaces the payment-stack liveness (per-network route + Solana settlement)
+// in the internal health dashboard, and folds a tripped breaker into the
+// overall `ok` verdict. The status page / on-call alerting consume that.
+//
+// No mocks. Every check reads live challenge data or makes a real on-chain
+// payment. If the Solana settlement fails the breaker is recorded as tripped.
+
+// Stable network identifiers — source of truth is api/_lib/x402-spec.js
+// (NETWORK_SOLANA_MAINNET / NETWORK_BASE_MAINNET / NETWORK_BSC_MAINNET). Matched
+// here by chain id so this module stays free of the heavy x402-spec import graph.
+const NET_SOLANA_PREFIX = 'solana';
+const NET_BASE = 'eip155:8453';
+const NET_BSC = 'eip155:56';
+
+// The probe target: the cheapest real 402-gated endpoint on the platform
+// ($0.001 USDC). A successful pay books one dance on the club stage — the same
+// real side effect the volume entries already produce, so an hourly breaker tip
+// is consistent with existing traffic.
+const PROBE_PATH = '/api/x402/dance-tip';
+const PROBE_METHOD = 'POST';
+const PROBE_BODY = { dancer: '4', dance: 'hiphop' };
+
+// Networks the breaker expects the platform to advertise. `settle` flags the one
+// network we actually pay on (Solana) vs. those we only route-verify (Base/BSC).
+const TARGET_NETWORKS = [
+ {
+ key: 'solana',
+ label: 'Solana',
+ scheme: 'exact',
+ settle: true,
+ match: (a) => typeof a?.network === 'string' && a.network.startsWith(NET_SOLANA_PREFIX),
+ // Solana accepts must carry a fee payer for the facilitator co-sign path.
+ extraValid: (a) => !!a?.extra?.feePayer,
+ },
+ {
+ key: 'base',
+ label: 'Base',
+ scheme: 'exact',
+ settle: false,
+ match: (a) => a?.network === NET_BASE,
+ extraValid: () => true,
+ },
+ {
+ key: 'bsc',
+ label: 'BSC',
+ scheme: 'direct',
+ settle: false,
+ match: (a) => a?.network === NET_BSC,
+ // Direct-scheme BSC accepts must name the payments contract + method.
+ extraValid: (a) => !!a?.extra?.contract && !!a?.extra?.method,
+ },
+];
+
+function validateAccept(target, accept) {
+ if (!accept) {
+ return { advertised: false, route_ok: false, reason: 'route_not_advertised' };
+ }
+ const reasons = [];
+ if (accept.scheme !== target.scheme) reasons.push(`scheme:${accept.scheme || 'none'}`);
+ if (!accept.payTo) reasons.push('missing_payTo');
+ if (!accept.asset) reasons.push('missing_asset');
+ const amount = Number(accept.amount);
+ if (!Number.isFinite(amount) || amount <= 0) reasons.push('bad_amount');
+ if (!target.extraValid(accept)) reasons.push('missing_extra');
+ return {
+ advertised: true,
+ route_ok: reasons.length === 0,
+ network: accept.network,
+ scheme: accept.scheme,
+ asset: accept.asset,
+ pay_to: accept.payTo,
+ amount_atomic: Number.isFinite(amount) ? amount : null,
+ reason: reasons.length ? reasons.join(',') : null,
+ };
+}
+
+async function upsertStatus(ctx, runId, row) {
+ // Latest-status-per-network table consumed by api/ops/health.js.
+ await ctx.sql`
+ INSERT INTO x402_circuit_breaker
+ (network, label, scheme, advertised, route_ok, settled,
+ receipt_valid, tx_signature, amount_atomic, error, run_id, checked_at)
+ VALUES
+ (${row.network}, ${row.label}, ${row.scheme}, ${row.advertised},
+ ${row.route_ok}, ${row.settled}, ${row.receipt_valid},
+ ${row.tx_signature || null}, ${row.amount_atomic || null},
+ ${row.error || null}, ${runId}, now())
+ ON CONFLICT (network) DO UPDATE SET
+ label = EXCLUDED.label,
+ scheme = EXCLUDED.scheme,
+ advertised = EXCLUDED.advertised,
+ route_ok = EXCLUDED.route_ok,
+ settled = EXCLUDED.settled,
+ receipt_valid = EXCLUDED.receipt_valid,
+ tx_signature = EXCLUDED.tx_signature,
+ amount_atomic = EXCLUDED.amount_atomic,
+ error = EXCLUDED.error,
+ run_id = EXCLUDED.run_id,
+ checked_at = now()
+ `;
+}
+
+/**
+ * Cross-network payment circuit breaker executor.
+ *
+ * @param {object} ctx Capabilities injected by the autonomous loop:
+ * - runId string
+ * - origin string (e.g. 'https://three.ws')
+ * - sql db tagged-template
+ * - log logger
+ * - fetchWithTimeout (url, opts) => { ok, status, headers, body }
+ * - parseSolanaAccept(challenge) => accept | null
+ * - settleSolana(accept, endpointUrl, entry) =>
+ * { success, txSig, amountAtomic, responseBody, errorMsg, status }
+ * - remainingCap number (atomics still spendable under the daily cap)
+ * @returns result consumed by the loop for x402_autonomous_log:
+ * { success, amountAtomic, txSig, responseData, errorMsg, signalData, network, summary }
+ */
+export async function runCircuitBreaker(ctx) {
+ const { runId, origin, fetchWithTimeout, parseSolanaAccept, settleSolana, log } = ctx;
+ const endpointUrl = `${origin}${PROBE_PATH}`;
+
+ // ── Step 1: probe for the live multi-network challenge ─────────────────────
+ let challenge;
+ try {
+ const probe = await fetchWithTimeout(endpointUrl, {
+ method: PROBE_METHOD,
+ headers: {
+ 'content-type': 'application/json',
+ 'user-agent': 'threews-x402-circuit-breaker/1.0',
+ },
+ body: JSON.stringify(PROBE_BODY),
+ });
+ if (probe.status !== 402) {
+ // A $0.001 paid endpoint that does NOT challenge is itself a stack fault.
+ const errorMsg = `probe_not_402:http_${probe.status}`;
+ await safeUpsertTrip(ctx, runId, errorMsg);
+ return {
+ success: false,
+ amountAtomic: 0,
+ errorMsg,
+ network: 'multi',
+ responseData: { stage: 'probe', status: probe.status },
+ signalData: { tripped: true, reason: errorMsg },
+ summary: errorMsg,
+ };
+ }
+ challenge = probe.body;
+ } catch (err) {
+ const errorMsg = `probe_failed:${err?.message || 'unknown'}`;
+ await safeUpsertTrip(ctx, runId, errorMsg);
+ return {
+ success: false,
+ amountAtomic: 0,
+ errorMsg,
+ network: 'multi',
+ responseData: { stage: 'probe' },
+ signalData: { tripped: true, reason: errorMsg },
+ summary: errorMsg,
+ };
+ }
+
+ const accepts = Array.isArray(challenge?.accepts) ? challenge.accepts : [];
+
+ // ── Step 2: verify each network route from the live challenge ──────────────
+ const networks = [];
+ let solanaTarget = null;
+ let solanaAccept = null;
+ for (const target of TARGET_NETWORKS) {
+ const accept = accepts.find((a) => target.match(a)) || null;
+ const v = validateAccept(target, accept);
+ const row = {
+ key: target.key,
+ network: accept?.network || target.label.toLowerCase(),
+ label: target.label,
+ scheme: target.scheme,
+ advertised: v.advertised,
+ route_ok: v.route_ok,
+ settled: false,
+ receipt_valid: false,
+ tx_signature: null,
+ amount_atomic: v.amount_atomic || null,
+ error: v.reason,
+ };
+ networks.push(row);
+ if (target.settle && accept && v.route_ok) {
+ solanaTarget = row;
+ solanaAccept = accept;
+ }
+ }
+
+ // ── Step 3: settle the real $0.001 payment on Solana ───────────────────────
+ let amountAtomic = 0;
+ let txSig = null;
+ let settleResp = null;
+ if (solanaAccept) {
+ if (ctx.remainingCap != null && Number(solanaAccept.amount || 0) > ctx.remainingCap) {
+ solanaTarget.error = 'daily_cap_would_exceed';
+ } else {
+ try {
+ const r = await settleSolana(solanaAccept, endpointUrl, {
+ method: PROBE_METHOD,
+ body: PROBE_BODY,
+ });
+ amountAtomic = r.amountAtomic || 0;
+ txSig = r.txSig || null;
+ settleResp = r.responseBody || null;
+ solanaTarget.settled = !!r.success;
+ solanaTarget.receipt_valid = !!(r.success && r.txSig);
+ solanaTarget.tx_signature = txSig;
+ solanaTarget.amount_atomic = amountAtomic || solanaTarget.amount_atomic;
+ if (!r.success) solanaTarget.error = r.errorMsg || `settle_http_${r.status || '0'}`;
+ } catch (err) {
+ solanaTarget.error = `settle_threw:${err?.message || 'unknown'}`;
+ }
+ }
+ }
+
+ // ── Step 4: persist per-network status (downstream: ops/health) ────────────
+ for (const row of networks) {
+ try {
+ await upsertStatus(ctx, runId, row);
+ } catch (err) {
+ // Table may not exist before its migration runs — the loop's ensureSchema
+ // creates it, so this is only a first-boot race. Never crash the loop.
+ if (!err?.message?.includes('does not exist')) {
+ log?.warn?.('circuit_breaker_upsert_failed', { network: row.network, message: err?.message });
+ }
+ }
+ }
+
+ const routesOk = networks.filter((n) => n.route_ok).length;
+ const allRoutesOk = routesOk === TARGET_NETWORKS.length;
+ const solanaSettled = !!(solanaTarget && solanaTarget.settled);
+ const tripped = !allRoutesOk || !solanaSettled;
+
+ const signalData = {
+ tripped,
+ all_routes_ok: allRoutesOk,
+ routes_ok: routesOk,
+ routes_total: TARGET_NETWORKS.length,
+ solana_settled: solanaSettled,
+ solana_tx: txSig,
+ networks: networks.map((n) => ({ network: n.network, route_ok: n.route_ok, settled: n.settled, error: n.error })),
+ };
+
+ const summary = `routes ${routesOk}/${TARGET_NETWORKS.length} ok, solana ${solanaSettled ? 'settled' : 'FAILED'}`;
+ log?.info?.('circuit_breaker_complete', { run_id: runId, ...signalData, tx: txSig });
+
+ return {
+ // success = the breaker's job (proving liveness) completed: all routes
+ // advertised + the real Solana settlement landed. A trip => success:false
+ // so the loop records it as a failure row and does not cool down — the
+ // breaker retries next tick instead of waiting the full hour.
+ success: !tripped,
+ amountAtomic,
+ txSig,
+ network: 'multi',
+ responseData: { challenge_resource: challenge?.resource || endpointUrl, networks, settle_response: settleResp },
+ errorMsg: tripped ? `breaker_tripped:${summary}` : null,
+ signalData,
+ summary,
+ };
+}
+
+// Record a trip across all networks when we never reached the per-network stage
+// (e.g. the probe itself failed) so ops/health still sees a fresh, failing row.
+async function safeUpsertTrip(ctx, runId, error) {
+ for (const target of TARGET_NETWORKS) {
+ try {
+ await upsertStatus(ctx, runId, {
+ network: target.label.toLowerCase(),
+ label: target.label,
+ scheme: target.scheme,
+ advertised: false,
+ route_ok: false,
+ settled: false,
+ receipt_valid: false,
+ tx_signature: null,
+ amount_atomic: null,
+ error,
+ });
+ } catch { /* table may not exist yet — non-fatal */ }
+ }
+}
+
+export const CIRCUIT_BREAKER_PROBE = Object.freeze({ path: PROBE_PATH, method: PROBE_METHOD, body: PROBE_BODY });
diff --git a/api/_lib/x402/forge-prop-store.js b/api/_lib/x402/forge-prop-store.js
new file mode 100644
index 000000000..7b61408bc
--- /dev/null
+++ b/api/_lib/x402/forge-prop-store.js
@@ -0,0 +1,304 @@
+// api/_lib/x402/forge-prop-store.js
+//
+// Value-extraction + storage for the autonomous "3D Forge Content Generation"
+// loop entry (autonomous-registry.js → id 'forge-content-gen'). The loop pays
+// the paid /api/x402/forge endpoint $0.05/call to generate a procedural prop
+// (crate, barrel, furniture, terrain tile); this module turns that response
+// into a durable, queryable asset-library row and measures how diverse the
+// generated catalog is via embedding clustering.
+//
+// What it does on every successful generation:
+// 1. Picks the next prop prompt (rotating category, varied prompt) — exposed
+// to the registry as nextForgeProp() so the request body is never static.
+// 2. Embeds the prop prompt (free NIM / OpenAI when configured, deterministic
+// feature-hash fallback otherwise — never blocks the loop).
+// 3. Scores novelty = 1 − max cosine similarity to the recent catalog in the
+// SAME vector space, and assigns a cluster id via k-means over that space.
+// 4. Inserts a row into forge_autonomous_props (the public asset-library table
+// for autonomously-forged props) carrying the public glb_url, the prompt,
+// category, tier, embedding, novelty and cluster id.
+//
+// DOWNSTREAM CONSUMER: the forge gallery / diversity dashboard reads
+// forge_autonomous_props — `glb_url` renders the prop, `novelty` + `cluster_id`
+// drive the "how varied is the generated catalog" metric, `category` filters
+// the feed. Inline-completed draft jobs carry a directly-renderable public R2
+// `glb_url`; async jobs carry a `job_id` poll token (status stays 'queued'
+// until the next observation), so the table is the single source of truth for
+// what the autonomous forge has produced.
+//
+// All DB / embedding work is fail-soft: a hiccup here returns a summary the
+// loop still logs, it never throws into the spend loop.
+
+import { sql } from '../db.js';
+import {
+ embeddingsConfigured,
+ defaultIngestEmbedderTag,
+ embedPassages,
+ cosine,
+} from '../embeddings.js';
+import { kmeans, suggestClusterCount, unit } from '../embedding-math.js';
+
+// Vector space tag for the dependency-free fallback embedding. Tagged distinctly
+// so it is NEVER compared against real NIM/OpenAI vectors — cosine only ever runs
+// within a single embedder space (same rule embeddings.js enforces everywhere).
+const LOCAL_EMBED_TAG = 'local/feature-hash@96';
+const LOCAL_EMBED_DIM = 96;
+
+// How many recent same-space rows to weigh novelty + clustering against. Bounded
+// so the per-call k-means stays trivial inside the serverless window.
+const DIVERSITY_WINDOW = 200;
+
+// ── Procedural prop catalog ────────────────────────────────────────────────────
+// Curated text→3D prompts grouped by the prop families named in the spec. Each
+// call rotates the CATEGORY (so the catalog stays balanced across families) and
+// varies the prompt within it (so successive same-category calls don't collide).
+const PROP_CATALOG = Object.freeze({
+ crate: [
+ 'a weathered wooden shipping crate, iron banded corners, game-ready prop',
+ 'a stack of military supply crates, stenciled markings, matte finish',
+ 'a cracked sci-fi cargo container, glowing seams, low-poly',
+ 'an antique tea crate, rope handles, worn paint, stylized',
+ 'a reinforced steel ammo crate, latches and rivets, PBR textured',
+ ],
+ barrel: [
+ 'a rusted oil barrel, dented metal, peeling paint, game prop',
+ 'an oak wine barrel, iron hoops, cellar-aged wood grain',
+ 'a glowing toxic-waste barrel, hazard stripes, stylized',
+ 'a wooden gunpowder barrel, rope binding, weathered planks',
+ 'a sci-fi coolant drum, brushed aluminium, warning decals',
+ ],
+ furniture: [
+ 'a rustic wooden tavern stool, three legs, hand-carved, low-poly',
+ 'a medieval banquet table, heavy oak, worn surface, game-ready',
+ 'a worn leather armchair, brass studs, stylized PBR',
+ 'a sci-fi crew bunk, foldable metal frame, clean lowpoly',
+ 'an ornate Victorian writing desk, brass fittings, dark walnut',
+ ],
+ terrain: [
+ 'a modular rocky cliff terrain tile, mossy stone, seamless edges',
+ 'a desert dune terrain tile, rippled sand, sparse rocks, low-poly',
+ 'a snowy mountain terrain tile, jagged rock and ice, game-ready',
+ 'a lush grassland terrain tile, scattered boulders, stylized',
+ 'a volcanic terrain tile, cracked obsidian, glowing lava veins',
+ ],
+});
+
+const CATEGORIES = Object.freeze(Object.keys(PROP_CATALOG));
+
+// Deterministic, non-random selector: rotate the category by UTC hour so the
+// generated library cycles evenly across families, and step the prompt index by
+// day so successive same-category hours don't repeat the same prompt. No
+// Math.random — two ticks in the same hour pick the same prop, which the paid
+// idempotency guard collapses rather than double-charging.
+export function nextForgeProp(now = Date.now()) {
+ const hour = Math.floor(now / 3_600_000);
+ const day = Math.floor(now / 86_400_000);
+ const category = CATEGORIES[hour % CATEGORIES.length];
+ const prompts = PROP_CATALOG[category];
+ const prompt = prompts[(hour + day) % prompts.length];
+ return { category, prompt };
+}
+
+// Request body for the paid forge call. Draft tier ($0.05) — the price this loop
+// is budgeted for; the 402 challenge quotes draft and the loop pays exactly that.
+export function buildForgeRequestBody() {
+ const { category, prompt } = nextForgeProp();
+ return { prompt, tier: 'draft', aspect_ratio: '1:1', _prop_category: category };
+}
+
+// ── Embedding ──────────────────────────────────────────────────────────────────
+
+// Signed feature hashing (FNV-1a → bucket, top bit → sign). A real, deterministic
+// bag-of-words embedding used only when no embedding provider is configured, so
+// the loop still produces a usable diversity signal with zero external calls.
+function featureHashEmbed(text, dim = LOCAL_EMBED_DIM) {
+ const v = new Array(dim).fill(0);
+ const tokens = String(text).toLowerCase().match(/[a-z0-9]+/g) || [];
+ for (const tok of tokens) {
+ let h = 2166136261;
+ for (let i = 0; i < tok.length; i++) {
+ h ^= tok.charCodeAt(i);
+ h = Math.imul(h, 16777619);
+ }
+ const idx = (h >>> 0) % dim;
+ const sign = (h >>> 31) & 1 ? -1 : 1;
+ v[idx] += sign;
+ }
+ return v;
+}
+
+// Embed the prop prompt. Prefer the configured free-first provider; on any
+// failure fall back to the local hash embedding so a provider outage degrades
+// the diversity metric rather than failing the paid call's bookkeeping.
+async function embedProp(prompt) {
+ if (embeddingsConfigured()) {
+ const tag = defaultIngestEmbedderTag();
+ if (tag) {
+ try {
+ const [vec] = await embedPassages(tag, [prompt]);
+ if (vec?.length) return { embedder: tag, vector: Array.from(vec) };
+ } catch {
+ /* provider hiccup — fall through to the deterministic local space */
+ }
+ }
+ }
+ return { embedder: LOCAL_EMBED_TAG, vector: featureHashEmbed(prompt) };
+}
+
+// ── Diversity (novelty + cluster) ──────────────────────────────────────────────
+
+// novelty = 1 − max cosine similarity to the recent catalog in the SAME space,
+// cluster_id = k-means assignment of the new prop within that space. First prop
+// in a space is maximally novel (1) and forms cluster 0.
+async function scoreDiversity(embedder, vector) {
+ let recent = [];
+ try {
+ recent = await sql`
+ select embedding from forge_autonomous_props
+ where embedder = ${embedder}
+ order by ts desc
+ limit ${DIVERSITY_WINDOW}
+ `;
+ } catch {
+ // Table may not exist on the very first run before ensureSchema commits, or
+ // the DB is briefly unavailable — treat as an empty catalog (max novelty).
+ return { novelty: 1, clusterId: 0, neighbors: 0 };
+ }
+
+ const peers = recent
+ .map((r) => r.embedding)
+ .filter((a) => Array.isArray(a) && a.length === vector.length);
+
+ if (peers.length === 0) return { novelty: 1, clusterId: 0, neighbors: 0 };
+
+ let maxSim = 0;
+ for (const p of peers) {
+ const s = cosine(vector, p);
+ if (s > maxSim) maxSim = s;
+ }
+ const novelty = Math.max(0, Math.min(1, 1 - maxSim));
+
+ // Cluster the new prop against the recent catalog. Unit-normalise so squared
+ // euclidean distance ranks the same as cosine (semantic clusters).
+ const all = [...peers, vector].map((v) => unit(v));
+ const k = suggestClusterCount(all.length);
+ const { assignments } = kmeans(all, k);
+ const clusterId = assignments[assignments.length - 1] ?? 0;
+
+ return { novelty, clusterId, neighbors: peers.length };
+}
+
+// ── Schema (memoised, idempotent) ──────────────────────────────────────────────
+
+let schemaReady = null;
+function ensureSchema() {
+ if (schemaReady) return schemaReady;
+ schemaReady = (async () => {
+ await sql`
+ CREATE TABLE IF NOT EXISTS forge_autonomous_props (
+ id bigserial PRIMARY KEY,
+ run_id uuid,
+ ts timestamptz DEFAULT now(),
+ prompt text NOT NULL,
+ category text NOT NULL,
+ tier text,
+ mode text,
+ backend text,
+ job_id text,
+ glb_url text,
+ status text,
+ embedder text,
+ embedding jsonb,
+ novelty numeric(6,5),
+ cluster_id int
+ )
+ `;
+ await sql`
+ CREATE INDEX IF NOT EXISTS forge_autonomous_props_cat_ts_idx
+ ON forge_autonomous_props (category, ts DESC)
+ `;
+ })().catch((err) => {
+ // Reset so a transient failure retries next call rather than wedging.
+ schemaReady = null;
+ throw err;
+ });
+ return schemaReady;
+}
+
+// ── Public: persist one forge generation ───────────────────────────────────────
+
+// Parse the paid /api/x402/forge response, embed + score the prop, and insert a
+// row into forge_autonomous_props. Returns a compact summary the loop stores in
+// x402_autonomous_log.value_extracted. Never throws — on DB/embedding failure it
+// returns a summary carrying the error so the call is still recorded.
+//
+// `requestBody` is the body the loop sent (carries the rotated prompt + category
+// via _prop_category); `responseBody` is the forge JSON response.
+export async function persistForgeProp(responseBody, { runId, requestBody } = {}) {
+ const prompt =
+ (requestBody && typeof requestBody.prompt === 'string' && requestBody.prompt) || '';
+ const category =
+ (requestBody && requestBody._prop_category) || nextForgeProp().category;
+
+ const r = responseBody && typeof responseBody === 'object' ? responseBody : {};
+ const tier = r.tier || (requestBody && requestBody.tier) || 'draft';
+ const mode = r.mode || 'text_to_3d';
+ const backend = r.backend || null;
+ const jobId = r.job_id || null;
+ const glbUrl = r.glb_url || null;
+ const status = r.status || (glbUrl ? 'done' : jobId ? 'queued' : 'unknown');
+
+ // Without a prompt there is nothing to catalog — record a thin summary so the
+ // loop still logs the call, but skip the embed/insert.
+ if (!prompt) {
+ return { stored: false, reason: 'no_prompt', category, status, job_id: jobId, glb_url: glbUrl };
+ }
+
+ let novelty = null;
+ let clusterId = null;
+ let embedder = null;
+ let neighbors = 0;
+ let stored = false;
+ let storeError = null;
+
+ try {
+ await ensureSchema();
+ const embedded = await embedProp(prompt);
+ embedder = embedded.embedder;
+
+ const diversity = await scoreDiversity(embedder, embedded.vector);
+ novelty = diversity.novelty;
+ clusterId = diversity.clusterId;
+ neighbors = diversity.neighbors;
+
+ await sql`
+ INSERT INTO forge_autonomous_props
+ (run_id, prompt, category, tier, mode, backend,
+ job_id, glb_url, status, embedder, embedding, novelty, cluster_id)
+ VALUES
+ (${runId || null}, ${prompt}, ${category}, ${tier}, ${mode}, ${backend},
+ ${jobId}, ${glbUrl}, ${status}, ${embedder},
+ ${JSON.stringify(embedded.vector)}::jsonb,
+ ${novelty}, ${clusterId})
+ `;
+ stored = true;
+ } catch (err) {
+ storeError = err?.message || 'persist_failed';
+ }
+
+ return {
+ stored,
+ category,
+ tier,
+ mode,
+ backend,
+ status,
+ job_id: jobId,
+ glb_url: glbUrl,
+ embedder,
+ novelty,
+ cluster_id: clusterId,
+ diversity_neighbors: neighbors,
+ ...(storeError ? { error: storeError } : {}),
+ };
+}
diff --git a/api/_lib/x402/mcp-latency-sweep.js b/api/_lib/x402/mcp-latency-sweep.js
new file mode 100644
index 000000000..cba6311d7
--- /dev/null
+++ b/api/_lib/x402/mcp-latency-sweep.js
@@ -0,0 +1,333 @@
+// api/_lib/x402/mcp-latency-sweep.js
+//
+// MCP Tool Latency Monitor — the value-extraction stage of the
+// `mcp-latency-monitor` autonomous-loop entry (autonomous-registry.js).
+//
+// The autonomous loop makes ONE real x402-paid call to /api/mcp every 5 minutes
+// (the `validate_model` canary — see the registry entry). That paid round-trip
+// is recorded to x402_autonomous_log like every other loop call. This module is
+// the downstream "extract and store value" step: on each tick it sweeps the live
+// MCP surface and records per-tool latency percentiles to `x402_perf_log`.
+//
+// Methodology (honest, no payment explosion, no side effects):
+// • Paid round-trip sample — the canary's full pay-and-settle latency, passed
+// in by the loop as ctx.durationMs. Series key: 'validate_model#paid'.
+// • tools/list discovery latency — one free probe. Series key: 'tools/list'.
+// • Per-tool first-response latency — for every advertised tool we send a
+// single unauthenticated, unpaid `tools/call` with minimal args and time the
+// round-trip to first response. This is exactly what an external agent
+// observes before it decides to pay: priced tools answer with a 402
+// challenge (pricing/auth path), the public getting_started tool executes,
+// OAuth-only tools answer with an auth error. All three are legitimate,
+// side-effect-free SLA samples of the caller-observed latency per tool.
+//
+// Percentiles (p50/p95/p99) are computed over a rolling 24h window of samples
+// already in x402_perf_log, merged with the current tick's samples — so the
+// store is the single source of truth and survives a Redis flush.
+//
+// SLA: any tool whose rolling p95 exceeds PERF_SLA_P95_MS is flagged
+// (sla_breach=true on its row) and an alert is logged. The ops dashboard reads
+// the breach state via GET /api/x402/mcp-perf.
+
+import { sql } from '../db.js';
+import { logger } from '../usage.js';
+
+const log = logger('mcp-latency-sweep');
+
+// SLA threshold: a tool whose rolling p95 first-response latency exceeds this is
+// considered unhealthy and triggers an alert.
+export const PERF_SLA_P95_MS = Number(process.env.MCP_PERF_SLA_P95_MS || 2000);
+
+// Rolling window for percentile computation.
+const WINDOW_HOURS = 24;
+// Per-probe timeout — a hung tool counts as a large sample (a breach), not an
+// infinite hang that stalls the cron tick.
+const PROBE_TIMEOUT_MS = 6000;
+// Bounded concurrency for the per-tool sweep so we don't open 35 sockets at once.
+const PROBE_CONCURRENCY = 6;
+
+let schemaReady = false;
+
+export async function ensurePerfSchema() {
+ if (schemaReady) return;
+ try {
+ await sql`
+ CREATE TABLE IF NOT EXISTS x402_perf_log (
+ id bigserial PRIMARY KEY,
+ ts timestamptz NOT NULL DEFAULT now(),
+ run_id uuid,
+ tool_name text NOT NULL,
+ endpoint text NOT NULL DEFAULT '/api/mcp',
+ sample_ms int NOT NULL,
+ observed_status text,
+ priced boolean NOT NULL DEFAULT false,
+ p50_ms int,
+ p95_ms int,
+ p99_ms int,
+ sample_count int,
+ sla_breach boolean NOT NULL DEFAULT false,
+ error text
+ )
+ `;
+ await sql`CREATE INDEX IF NOT EXISTS x402_perf_log_tool_ts_idx ON x402_perf_log (tool_name, ts DESC)`;
+ schemaReady = true;
+ } catch (err) {
+ // Non-fatal: a migration system or a concurrent loop may own the table.
+ if (!/already exists/i.test(err?.message || '')) {
+ log.warn('perf_schema_failed', { message: err?.message });
+ }
+ schemaReady = true;
+ }
+}
+
+// percentile of a numeric array using the nearest-rank method.
+function percentile(sortedAsc, p) {
+ if (!sortedAsc.length) return null;
+ const rank = Math.ceil((p / 100) * sortedAsc.length);
+ const idx = Math.min(Math.max(rank, 1), sortedAsc.length) - 1;
+ return Math.round(sortedAsc[idx]);
+}
+
+async function fetchWithTimeout(url, opts = {}) {
+ const ctrl = new AbortController();
+ const t = setTimeout(() => ctrl.abort(), PROBE_TIMEOUT_MS);
+ try {
+ return await fetch(url, { ...opts, signal: ctrl.signal, redirect: 'manual' });
+ } finally {
+ clearTimeout(t);
+ }
+}
+
+// List the advertised MCP tools via the free tools/list discovery call.
+// Returns { tools: [{ name, priced }], listMs, error }.
+async function listTools(origin) {
+ const url = `${origin}/api/mcp`;
+ const t0 = Date.now();
+ try {
+ const res = await fetchWithTimeout(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'user-agent': 'threews-mcp-latency/1.0' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 'list', method: 'tools/list' }),
+ });
+ const listMs = Date.now() - t0;
+ let body = null;
+ try { body = await res.json(); } catch { body = null; }
+ const tools = (body?.result?.tools || []).map((t) => ({
+ name: t.name,
+ priced: !!t.pricing,
+ }));
+ return { tools, listMs, error: tools.length ? null : 'empty_catalog' };
+ } catch (err) {
+ return { tools: [], listMs: Date.now() - t0, error: err?.message || 'list_failed' };
+ }
+}
+
+// Probe one tool with an unpaid, unauthenticated tools/call and time the
+// caller-observed first response. Never throws — failures become samples.
+async function probeTool(origin, tool) {
+ const url = `${origin}/api/mcp`;
+ const t0 = Date.now();
+ try {
+ const res = await fetchWithTimeout(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'user-agent': 'threews-mcp-latency/1.0' },
+ body: JSON.stringify({
+ jsonrpc: '2.0', id: 'probe', method: 'tools/call',
+ params: { name: tool.name, arguments: {} },
+ }),
+ });
+ // Drain the body so the connection can close and the timing reflects a
+ // complete response, not just headers.
+ try { await res.text(); } catch { /* ignore */ }
+ return {
+ tool: tool.name,
+ sampleMs: Date.now() - t0,
+ status: String(res.status),
+ priced: tool.priced,
+ error: null,
+ };
+ } catch (err) {
+ const aborted = err?.name === 'AbortError';
+ return {
+ tool: tool.name,
+ sampleMs: aborted ? PROBE_TIMEOUT_MS : Date.now() - t0,
+ status: aborted ? 'timeout' : 'error',
+ priced: tool.priced,
+ error: aborted ? `timeout_${PROBE_TIMEOUT_MS}ms` : (err?.message || 'probe_failed'),
+ };
+ }
+}
+
+// Run probes with bounded concurrency.
+async function probeAll(origin, tools) {
+ const out = [];
+ let i = 0;
+ async function worker() {
+ while (i < tools.length) {
+ const tool = tools[i++];
+ out.push(await probeTool(origin, tool));
+ }
+ }
+ await Promise.all(Array.from({ length: Math.min(PROBE_CONCURRENCY, tools.length) }, worker));
+ return out;
+}
+
+/**
+ * Run the full latency sweep and persist per-tool percentiles to x402_perf_log.
+ * Called by the autonomous loop as the `persist` hook of the mcp-latency-monitor
+ * entry. Never throws — every failure is caught, logged, and recorded.
+ *
+ * @param {object} ctx
+ * @param {string} ctx.runId loop run id (FK into x402_autonomous_log)
+ * @param {string} ctx.origin origin to probe (e.g. https://three.ws)
+ * @param {number} ctx.durationMs canary paid round-trip latency
+ * @param {boolean} ctx.success whether the canary call settled
+ * @param {object} [ctx.responseBody] canary JSON-RPC response (for sanity)
+ * @returns {Promise<object>} summary { tools, breaches, alerted }
+ */
+export async function mcpLatencySweep(ctx = {}) {
+ const { runId = null, origin, durationMs = 0, success = false } = ctx;
+ if (!origin) {
+ log.warn('sweep_no_origin', { runId });
+ return { tools: 0, breaches: 0, alerted: false, skipped: 'no_origin' };
+ }
+
+ await ensurePerfSchema();
+
+ // 1. Enumerate the live tool catalog (free discovery).
+ const { tools, listMs, error: listError } = await listTools(origin);
+
+ // 2. Assemble this tick's raw samples.
+ // a) canary paid round-trip (the one real x402 payment of this entry)
+ // b) tools/list discovery latency
+ // c) per-tool unpaid first-response latency
+ const samples = [];
+ if (success && durationMs > 0) {
+ samples.push({ tool: 'validate_model#paid', sampleMs: durationMs, status: 'paid', priced: true, error: null });
+ }
+ samples.push({ tool: 'tools/list', sampleMs: listMs, status: listError ? 'error' : '200', priced: false, error: listError });
+
+ const probed = tools.length ? await probeAll(origin, tools) : [];
+ samples.push(...probed);
+
+ if (!samples.length) {
+ log.warn('sweep_no_samples', { runId, listError });
+ return { tools: 0, breaches: 0, alerted: false, skipped: 'no_samples' };
+ }
+
+ // 3. Pull the rolling window from the store and compute percentiles per tool,
+ // including this tick's fresh samples.
+ const history = new Map(); // tool -> number[]
+ try {
+ const rows = await sql`
+ SELECT tool_name, sample_ms
+ FROM x402_perf_log
+ WHERE ts > now() - (${WINDOW_HOURS} || ' hours')::interval
+ `;
+ for (const r of rows) {
+ const arr = history.get(r.tool_name) || [];
+ arr.push(Number(r.sample_ms));
+ history.set(r.tool_name, arr);
+ }
+ } catch (err) {
+ // First run (table absent) or read failure — fall back to current samples
+ // only. The sweep still records this tick.
+ if (!/does not exist/i.test(err?.message || '')) {
+ log.warn('perf_history_read_failed', { message: err?.message });
+ }
+ }
+
+ const breaches = [];
+ const rowsToInsert = samples.map((s) => {
+ const merged = (history.get(s.tool) || []).concat([s.sampleMs]).sort((a, b) => a - b);
+ const p50 = percentile(merged, 50);
+ const p95 = percentile(merged, 95);
+ const p99 = percentile(merged, 99);
+ const breach = p95 != null && p95 > PERF_SLA_P95_MS;
+ if (breach) breaches.push({ tool: s.tool, p95, samples: merged.length });
+ return { ...s, p50, p95, p99, count: merged.length, breach };
+ });
+
+ // 4. Persist every sample row. Insert failures are caught per-row so one bad
+ // row never drops the rest.
+ let inserted = 0;
+ await Promise.all(rowsToInsert.map(async (r) => {
+ try {
+ await sql`
+ INSERT INTO x402_perf_log
+ (run_id, tool_name, endpoint, sample_ms, observed_status, priced,
+ p50_ms, p95_ms, p99_ms, sample_count, sla_breach, error)
+ VALUES
+ (${runId}, ${r.tool}, ${'/api/mcp'}, ${r.sampleMs}, ${r.status}, ${r.priced},
+ ${r.p50}, ${r.p95}, ${r.p99}, ${r.count}, ${r.breach}, ${r.error || null})
+ `;
+ inserted++;
+ } catch (err) {
+ log.warn('perf_insert_failed', { tool: r.tool, message: err?.message });
+ }
+ }));
+
+ // 5. Alert on SLA breaches.
+ const alerted = breaches.length > 0;
+ if (alerted) {
+ log.warn('mcp_sla_breach', {
+ run_id: runId,
+ threshold_ms: PERF_SLA_P95_MS,
+ breached: breaches.map((b) => `${b.tool}:p95=${b.p95}ms`),
+ });
+ }
+
+ log.info('mcp_latency_sweep_complete', {
+ run_id: runId,
+ tools: tools.length,
+ samples: samples.length,
+ inserted,
+ breaches: breaches.length,
+ list_ms: listMs,
+ canary_ms: success ? durationMs : null,
+ });
+
+ return { tools: tools.length, samples: samples.length, inserted, breaches: breaches.length, alerted };
+}
+
+/**
+ * Dashboard / downstream read: latest per-tool SLA health from x402_perf_log.
+ * Consumed by GET /api/x402/mcp-perf.
+ * @returns {Promise<{ ok, healthy, sla_p95_ms, tools, breaches, generated_at }>}
+ */
+export async function readPerfHealth({ windowHours = WINDOW_HOURS } = {}) {
+ await ensurePerfSchema();
+ // Latest row per tool (most recent percentile snapshot).
+ const rows = await sql`
+ SELECT DISTINCT ON (tool_name)
+ tool_name, ts, sample_ms, observed_status, priced,
+ p50_ms, p95_ms, p99_ms, sample_count, sla_breach, error
+ FROM x402_perf_log
+ WHERE ts > now() - (${windowHours} || ' hours')::interval
+ ORDER BY tool_name, ts DESC
+ `;
+ const tools = rows.map((r) => ({
+ tool: r.tool_name,
+ last_ms: Number(r.sample_ms),
+ status: r.observed_status,
+ priced: r.priced,
+ p50_ms: r.p50_ms,
+ p95_ms: r.p95_ms,
+ p99_ms: r.p99_ms,
+ samples: r.sample_count,
+ sla_breach: r.sla_breach,
+ error: r.error,
+ updated_at: r.ts,
+ }));
+ const breaches = tools.filter((t) => t.sla_breach);
+ return {
+ ok: true,
+ healthy: breaches.length === 0,
+ sla_p95_ms: PERF_SLA_P95_MS,
+ window_hours: windowHours,
+ tool_count: tools.length,
+ breach_count: breaches.length,
+ breaches: breaches.map((b) => ({ tool: b.tool, p95_ms: b.p95_ms, samples: b.samples })),
+ tools,
+ };
+}
diff --git a/api/_lib/x402/pay.js b/api/_lib/x402/pay.js
new file mode 100644
index 000000000..329490ade
--- /dev/null
+++ b/api/_lib/x402/pay.js
@@ -0,0 +1,215 @@
+// api/_lib/x402/pay.js
+//
+// Shared Solana x402 payment client for the autonomous spend loop and every
+// run()-style registry entry. The autonomous loop (api/cron/x402-autonomous-loop.js)
+// pays declarative registry entries inline; richer entries that monitor a queue,
+// poll a worker, or fan a call across rows declare a run(ctx) function and use
+// payX402() here to settle their own USDC payments with the same primitives.
+//
+// Real on-chain payments only. No mocks. If the seed keypair is not configured,
+// loadSeedKeypair() throws and callers degrade gracefully.
+
+import { readFileSync } from 'node:fs';
+import bs58 from 'bs58';
+import {
+ Connection, PublicKey, Keypair, TransactionMessage, VersionedTransaction,
+ ComputeBudgetProgram,
+} from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync, createTransferCheckedInstruction,
+ createAssociatedTokenAccountIdempotentInstruction,
+ TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID, getMint,
+} from '@solana/spl-token';
+
+import { env } from '../env.js';
+import { solanaConnection } from '../solana/connection.js';
+
+export const USDC_MINT = env.X402_ASSET_MINT_SOLANA;
+export const SOLANA_RPC = env.SOLANA_RPC_URL;
+export const FETCH_TIMEOUT_MS = 20_000;
+
+// Load the autonomous payer keypair. Seed wallet preferred; agent wallet is the
+// documented fallback. In non-prod a local test wallet file is honored so the
+// loop and manual tests can run without env wiring.
+export function loadSeedKeypair() {
+ const b58 = process.env.X402_SEED_SOLANA_SECRET_BASE58
+ || process.env.X402_AGENT_SOLANA_SECRET_BASE58;
+ if (b58) {
+ const raw = bs58.decode(b58);
+ if (raw.length !== 64) throw new Error(`seed keypair: expected 64 bytes, got ${raw.length}`);
+ return Keypair.fromSecretKey(raw);
+ }
+ if (process.env.NODE_ENV !== 'production') {
+ try {
+ const arr = JSON.parse(readFileSync('/home/codespace/.config/x402-test-wallets/solana.json', 'utf8'));
+ return Keypair.fromSecretKey(Uint8Array.from(arr));
+ } catch { /* fall through */ }
+ }
+ throw new Error('x402 pay: seed keypair not configured (set X402_SEED_SOLANA_SECRET_BASE58)');
+}
+
+export async function fetchWithTimeout(url, opts = {}, timeoutMs = FETCH_TIMEOUT_MS) {
+ const ctrl = new AbortController();
+ const t = setTimeout(() => ctrl.abort(), timeoutMs);
+ try {
+ const res = await fetch(url, { ...opts, signal: ctrl.signal, redirect: 'manual' });
+ let body = null;
+ try { body = await res.json(); } catch { try { body = await res.text(); } catch { body = null; } }
+ return { ok: res.ok, status: res.status, headers: res.headers, body };
+ } finally {
+ clearTimeout(t);
+ }
+}
+
+export function parseSolanaAccept(challenge) {
+ if (!challenge || !Array.isArray(challenge.accepts)) return null;
+ return challenge.accepts.find(
+ (a) => typeof a?.network === 'string' && a.network.startsWith('solana'),
+ ) || null;
+}
+
+export function buildPaymentTx({ accept, buyer, blockhash, mintInfo, receiverAtaExists }) {
+ const mint = new PublicKey(accept.asset);
+ const payTo = new PublicKey(accept.payTo);
+ const feePayer = new PublicKey(accept.extra.feePayer);
+ const amount = BigInt(accept.amount);
+
+ const senderAta = getAssociatedTokenAddressSync(
+ mint, buyer.publicKey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+ const receiverAta = getAssociatedTokenAddressSync(
+ mint, payTo, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+
+ const ixs = [
+ ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 }),
+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 5 }),
+ ];
+ if (!receiverAtaExists) {
+ ixs.push(createAssociatedTokenAccountIdempotentInstruction(
+ feePayer, receiverAta, payTo, mint, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ ));
+ }
+ ixs.push(createTransferCheckedInstruction(
+ senderAta, mint, receiverAta, buyer.publicKey,
+ amount, mintInfo.decimals, [], TOKEN_PROGRAM_ID,
+ ));
+
+ const msg = new TransactionMessage({
+ payerKey: feePayer,
+ recentBlockhash: blockhash,
+ instructions: ixs,
+ }).compileToV0Message();
+ const vtx = new VersionedTransaction(msg);
+ vtx.sign([buyer]);
+ return Buffer.from(vtx.serialize()).toString('base64');
+}
+
+// Build the per-tick shared Solana state once (blockhash + USDC mint info) so a
+// run() that pays several rows reuses one blockhash. Standalone callers (manual
+// tests) call this to bootstrap a full context without the cron loop.
+export async function bootstrapSolanaContext({ buyer } = {}) {
+ if (!USDC_MINT) throw new Error('x402 pay: X402_ASSET_MINT_SOLANA not configured');
+ const payer = buyer || loadSeedKeypair();
+ const conn = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });
+ const [{ blockhash }, mintInfo] = await Promise.all([
+ conn.getLatestBlockhash('confirmed'),
+ getMint(conn, new PublicKey(USDC_MINT)),
+ ]);
+ return { buyer: payer, conn, blockhash, mintInfo };
+}
+
+// Settle a single x402 payment against `url`. Probes for the 402 challenge,
+// builds + signs the Solana USDC transfer, and replays with the X-PAYMENT header.
+//
+// Returns a structured outcome — never throws for protocol/network faults:
+// { success, paid, free, skipped, amountAtomic, txSig, status, responseBody, errorMsg }
+//
+// paid — a USDC payment settled on-chain (success true)
+// free — endpoint answered 200 with no 402 (no payment needed)
+// skipped — a guard rejected the call before paying (cap, asset mismatch, …)
+export async function payX402({
+ url, method = 'POST', body = null,
+ buyer, conn, blockhash, mintInfo,
+ remainingCap = Infinity,
+ userAgent = 'threews-x402-autonomous/1.0',
+}) {
+ const reqInit = {
+ method,
+ headers: { 'content-type': 'application/json', 'user-agent': userAgent },
+ ...(body != null ? { body: JSON.stringify(body) } : {}),
+ };
+
+ // Step 1 — probe for the 402 challenge.
+ const probe = await fetchWithTimeout(url, reqInit);
+
+ if (probe.status !== 402) {
+ return {
+ success: probe.ok, paid: false, free: true, skipped: false,
+ amountAtomic: 0, txSig: null, status: probe.status,
+ responseBody: probe.body,
+ errorMsg: probe.ok ? null : `http_${probe.status}`,
+ };
+ }
+
+ const accept = parseSolanaAccept(probe.body);
+ if (!accept) {
+ return { success: false, paid: false, free: false, skipped: true, amountAtomic: 0, txSig: null, status: 402, responseBody: probe.body, errorMsg: 'no_solana_accept' };
+ }
+ if (!USDC_MINT || accept.asset !== USDC_MINT) {
+ return { success: false, paid: false, free: false, skipped: true, amountAtomic: 0, txSig: null, status: 402, responseBody: probe.body, errorMsg: `unexpected_asset:${accept.asset}` };
+ }
+ if (!accept.extra?.feePayer) {
+ return { success: false, paid: false, free: false, skipped: true, amountAtomic: 0, txSig: null, status: 402, responseBody: probe.body, errorMsg: 'missing_fee_payer' };
+ }
+
+ const amountAtomic = Number(accept.amount || 0);
+ if (amountAtomic > remainingCap) {
+ return { success: false, paid: false, free: false, skipped: true, amountAtomic, txSig: null, status: 402, responseBody: probe.body, errorMsg: 'cap_would_exceed' };
+ }
+
+ // Step 2 — does the receiver ATA already exist? (saves an idempotent create ix)
+ const receiverAta = getAssociatedTokenAddressSync(
+ new PublicKey(accept.asset), new PublicKey(accept.payTo),
+ false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+ const receiverAtaInfo = await conn.getAccountInfo(receiverAta).catch(() => null);
+
+ // Step 3 — build the signed transaction + X-PAYMENT envelope.
+ const txBase64 = buildPaymentTx({
+ accept, buyer, blockhash, mintInfo,
+ receiverAtaExists: receiverAtaInfo !== null,
+ });
+ const xPayment = Buffer.from(JSON.stringify({
+ x402Version: 2,
+ scheme: 'exact',
+ network: accept.network,
+ resource: { url, mimeType: 'application/json' },
+ payload: { transaction: txBase64 },
+ accepted: accept,
+ })).toString('base64');
+
+ // Step 4 — replay the request carrying the payment.
+ const paidRes = await fetchWithTimeout(url, {
+ ...reqInit,
+ headers: { ...reqInit.headers, 'x-payment': xPayment },
+ });
+
+ let txSig = null;
+ if (paidRes.ok) {
+ const responseHeader = paidRes.headers?.get?.('x-payment-response');
+ if (responseHeader) {
+ try {
+ const settled = JSON.parse(Buffer.from(responseHeader, 'base64').toString('utf8'));
+ txSig = settled?.transaction || null;
+ } catch { /* non-fatal */ }
+ }
+ }
+
+ return {
+ success: paidRes.ok, paid: paidRes.ok, free: false, skipped: false,
+ amountAtomic, txSig, status: paidRes.status,
+ responseBody: paidRes.body,
+ errorMsg: paidRes.ok ? null : `http_${paidRes.status}`,
+ };
+}
diff --git a/api/_lib/x402/pipelines/bazaar-warmup.js b/api/_lib/x402/pipelines/bazaar-warmup.js
new file mode 100644
index 000000000..771cb7cdc
--- /dev/null
+++ b/api/_lib/x402/pipelines/bazaar-warmup.js
@@ -0,0 +1,345 @@
+// api/_lib/x402/pipelines/bazaar-warmup.js
+//
+// Bazaar Discovery Warmup — autonomous pipeline (self/008).
+//
+// On each run it pays for 15 category searches against the three.ws x402 Bazaar
+// MCP server (/api/mcp-bazaar → search_services). Each call is a real on-chain
+// USDC payment from the seed wallet at the advertised $0.001/call. The pipeline:
+//
+// 1. Probes + pays each search via the shared payX402 client (real x402,
+// never mocked).
+// 2. Validates every returned service is a *live, priced* endpoint
+// (resource URL + price + network) and drops malformed listings.
+// 3. Records a row in x402_autonomous_log for every call (success or failure),
+// with the extracted catalog summary in value_extracted.
+// 4. Snapshots the discovered catalog per category into x402_bazaar_catalog
+// and compares it to the previous run to surface drift (services
+// added / removed / repriced since the last warmup).
+//
+// Wiring: declared as a run()-style entry in autonomous-registry.js. The
+// per-tick loop (api/cron/x402-autonomous-loop.js) hands run() a shared payment
+// context (buyer, conn, blockhash, mintInfo, remainingCap); called standalone
+// (manual test) it bootstraps its own context via bootstrapSolanaContext().
+//
+// Downstream consumer: the snapshots in x402_bazaar_catalog are the source list
+// for external x402 service onboarding — agents wiring EXTERNAL_ENDPOINTS in
+// autonomous-registry.js read the latest live, priced resources from here, and
+// the per-category `drifted` flag feeds the external pipeline so a service that
+// disappears or reprices is caught without a manual recrawl.
+
+import { randomUUID, createHash } from 'node:crypto';
+
+import { sql } from '../../db.js';
+import { env } from '../../env.js';
+import { logger } from '../../usage.js';
+import { payX402, bootstrapSolanaContext, USDC_MINT } from '../pay.js';
+
+const log = logger('x402-bazaar-warmup');
+
+// 15 discovery categories swept on every warmup. Broad enough to exercise the
+// full facilitator catalog; each maps to a search_services(query) call.
+export const WARMUP_CATEGORIES = [
+ 'trading', 'llm', 'analytics', 'onchain data', 'weather',
+ 'image', 'search', 'storage', 'identity', 'payments',
+ 'oracle', 'social', 'gaming', 'compute', 'audio',
+];
+
+const PER_CATEGORY_LIMIT = 25;
+const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+// A bazaar listing is "live + priced" only when an agent could actually pay it:
+// it must carry a resource URL, a price (atomic units or label), and a network.
+function isLivePricedService(s) {
+ if (!s || typeof s.resource !== 'string' || !s.resource) return false;
+ const hasPrice = s.price_atomic != null || (typeof s.price === 'string' && s.price.length > 0);
+ const hasNetwork = Array.isArray(s.networks) && s.networks.length > 0;
+ return hasPrice && hasNetwork;
+}
+
+// Stable identifier for a service within a category — resource plus the MCP tool
+// name when present (one resource can expose many priced tools).
+function serviceKey(s) {
+ return s.tool_name ? `${s.resource}#${s.tool_name}` : s.resource;
+}
+
+// Deterministic hash of the live catalog for a category, used for drift
+// detection. Includes price so a reprice registers as drift, not just add/remove.
+function catalogHash(services) {
+ const lines = services
+ .map((s) => `${serviceKey(s)}|${s.price_atomic ?? s.price ?? ''}`)
+ .sort();
+ return createHash('sha256').update(lines.join('\n')).digest('hex');
+}
+
+function jsonRpcSearch(category, id) {
+ return {
+ jsonrpc: '2.0',
+ id,
+ method: 'tools/call',
+ params: {
+ name: 'search_services',
+ arguments: { query: category, type: 'http', limit: PER_CATEGORY_LIMIT },
+ },
+ };
+}
+
+// Pull the search_services structuredContent out of a JSON-RPC tools/call body.
+function extractServices(responseBody) {
+ const sc = responseBody?.result?.structuredContent;
+ if (!sc || !Array.isArray(sc.services)) return { services: [], sources: null, errors: null, hasResult: !!responseBody?.result };
+ return { services: sc.services, sources: sc.sources || null, errors: sc.errors || null, hasResult: true };
+}
+
+async function ensureSchema() {
+ // Catalog snapshot — one row per (run, category). Drift compares the latest
+ // run against the previous one keyed on category.
+ await sql`
+ CREATE TABLE IF NOT EXISTS x402_bazaar_catalog (
+ id bigserial PRIMARY KEY,
+ run_id uuid NOT NULL,
+ ts timestamptz DEFAULT now(),
+ category text NOT NULL,
+ service_count int NOT NULL DEFAULT 0,
+ live_count int NOT NULL DEFAULT 0,
+ networks text[] NOT NULL DEFAULT '{}',
+ resources jsonb NOT NULL DEFAULT '[]'::jsonb,
+ catalog_hash text,
+ drifted boolean NOT NULL DEFAULT false,
+ added jsonb NOT NULL DEFAULT '[]'::jsonb,
+ removed jsonb NOT NULL DEFAULT '[]'::jsonb,
+ sources jsonb,
+ errors jsonb
+ )
+ `;
+ await sql`CREATE INDEX IF NOT EXISTS x402_bazaar_catalog_cat_ts ON x402_bazaar_catalog (category, ts DESC)`;
+ // The autonomous log predates this pipeline; add the value_extracted column
+ // the warmup records its parsed catalog summary into (idempotent).
+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;
+}
+
+// Per-call row into x402_autonomous_log, including value_extracted. The loop
+// also records one aggregate row for the run() entry; these are the granular
+// per-category rows the warmup owns.
+async function recordCall(runId, { category, endpointUrl, amountAtomic, txSig, responseData, durationMs, success, errorMsg, valueExtracted }) {
+ try {
+ await sql`
+ INSERT INTO x402_autonomous_log
+ (run_id, endpoint_type, service_name, endpoint_url,
+ network, amount_atomic, asset, tx_signature,
+ response_data, value_extracted, duration_ms, success, error_msg, pipeline)
+ VALUES
+ (${runId}, ${'self'}, ${`Bazaar Warmup: ${category}`}, ${endpointUrl},
+ ${'solana:mainnet'}, ${amountAtomic || 0}, ${ASSET}, ${txSig || null},
+ ${responseData ? JSON.stringify(responseData) : null},
+ ${valueExtracted ? JSON.stringify(valueExtracted) : null},
+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${'discovery'})
+ `;
+ } catch (err) {
+ log.warn('bazaar_warmup_log_insert_failed', { category, message: err?.message });
+ }
+}
+
+// Most-recent prior catalog_hash + key set per category, for drift comparison.
+async function loadPreviousCatalog(runId) {
+ const prev = new Map();
+ try {
+ const rows = await sql`
+ SELECT DISTINCT ON (category) category, catalog_hash, resources
+ FROM x402_bazaar_catalog
+ WHERE run_id <> ${runId}
+ ORDER BY category, ts DESC
+ `;
+ for (const r of rows) {
+ const keys = Array.isArray(r.resources) ? r.resources.map((s) => s.key).filter(Boolean) : [];
+ prev.set(r.category, { hash: r.catalog_hash, keys: new Set(keys) });
+ }
+ } catch (err) {
+ if (!err?.message?.includes('does not exist')) {
+ log.warn('bazaar_warmup_prev_load_failed', { message: err?.message });
+ }
+ }
+ return prev;
+}
+
+async function snapshotCategory(runId, category, services, sources, errors, prev) {
+ const live = services.filter(isLivePricedService);
+ const resources = live.map((s) => ({
+ key: serviceKey(s),
+ resource: s.resource,
+ tool_name: s.tool_name || null,
+ price_atomic: s.price_atomic ?? null,
+ price: s.price || null,
+ networks: s.networks || [],
+ }));
+ const networks = [...new Set(live.flatMap((s) => s.networks || []))];
+ const hash = catalogHash(live);
+
+ const before = prev.get(category);
+ const liveKeys = new Set(resources.map((r) => r.key));
+ const drifted = before ? before.hash !== hash : false;
+ const added = before ? [...liveKeys].filter((k) => !before.keys.has(k)) : [];
+ const removed = before ? [...before.keys].filter((k) => !liveKeys.has(k)) : [];
+
+ try {
+ await sql`
+ INSERT INTO x402_bazaar_catalog
+ (run_id, category, service_count, live_count, networks,
+ resources, catalog_hash, drifted, added, removed, sources, errors)
+ VALUES
+ (${runId}, ${category}, ${services.length}, ${live.length}, ${networks},
+ ${JSON.stringify(resources)}, ${hash}, ${drifted},
+ ${JSON.stringify(added)}, ${JSON.stringify(removed)},
+ ${sources ? JSON.stringify(sources) : null},
+ ${errors ? JSON.stringify(errors) : null})
+ `;
+ } catch (err) {
+ log.warn('bazaar_warmup_snapshot_failed', { category, message: err?.message });
+ }
+
+ return { category, total: services.length, live: live.length, networks, catalog_hash: hash, drifted, added, removed };
+}
+
+/**
+ * Run the warmup. Conforms to the run()-style registry contract: the loop hands
+ * over { origin, buyer, conn, blockhash, mintInfo, remainingCap, runId }; when
+ * any of the Solana context is absent (standalone / manual test) it bootstraps
+ * its own via bootstrapSolanaContext().
+ *
+ * Returns the aggregate outcome the loop records as one summary row:
+ * { success, amountAtomic, txSig, errorMsg, responseData, skipped, note }
+ */
+export async function run(ctx = {}) {
+ const runId = ctx.runId || randomUUID();
+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';
+ const endpointUrl = `${origin}/api/mcp-bazaar`;
+ let remainingCap = ctx.remainingCap ?? Number.POSITIVE_INFINITY;
+
+ // ── Schema first: without the sink there is no value to extract, so don't pay.
+ try {
+ await ensureSchema();
+ } catch (err) {
+ log.warn('bazaar_warmup_schema_failed', { message: err?.message });
+ return { success: false, skipped: true, amountAtomic: 0, errorMsg: `schema_failed: ${err?.message}` };
+ }
+
+ // ── Solana payment context: reuse the loop's, else bootstrap (graceful on
+ // unconfigured wallet — bootstrap throws, we exit logged without paying).
+ let { buyer, conn, blockhash, mintInfo } = ctx;
+ if (!buyer || !conn || !blockhash || !mintInfo) {
+ try {
+ ({ buyer, conn, blockhash, mintInfo } = await bootstrapSolanaContext({ buyer }));
+ } catch (err) {
+ log.info('bazaar_warmup_skipped', { reason: err.message });
+ return { success: false, skipped: true, amountAtomic: 0, errorMsg: err.message, note: 'wallet_or_rpc_unconfigured' };
+ }
+ }
+
+ const prev = await loadPreviousCatalog(runId);
+
+ let spentAtomic = 0;
+ let paid = 0;
+ let lastTxSig = null;
+ let callErrors = 0;
+ const snapshots = [];
+
+ for (let i = 0; i < WARMUP_CATEGORIES.length; i++) {
+ const category = WARMUP_CATEGORIES[i];
+ if (remainingCap <= 0) {
+ log.info('bazaar_warmup_cap_reached', { category, spent_atomic: spentAtomic });
+ break;
+ }
+
+ const t0 = Date.now();
+ let result;
+ try {
+ result = await payX402({
+ url: endpointUrl,
+ method: 'POST',
+ body: jsonRpcSearch(category, i + 1),
+ buyer, conn, blockhash, mintInfo,
+ remainingCap,
+ });
+ } catch (err) {
+ // Network failure / abort — log the call, never crash the sweep.
+ callErrors += 1;
+ await recordCall(runId, {
+ category, endpointUrl, amountAtomic: 0, txSig: null, responseData: null,
+ durationMs: Date.now() - t0, success: false, errorMsg: err?.message || 'fetch_failed', valueExtracted: null,
+ });
+ snapshots.push({ category, error: err?.message || 'fetch_failed' });
+ continue;
+ }
+
+ const { services, sources, errors, hasResult } = extractServices(result.responseBody);
+
+ // Snapshot only when the call actually delivered a JSON-RPC result
+ // (paid or free success). Failed / 402-rejected calls still get a log row.
+ let snapshot = null;
+ if (result.success && hasResult) {
+ snapshot = await snapshotCategory(runId, category, services, sources, errors, prev);
+ snapshots.push(snapshot);
+ } else {
+ callErrors += 1;
+ snapshots.push({ category, status: result.status, error: result.errorMsg });
+ }
+
+ if (result.paid) {
+ spentAtomic += result.amountAtomic;
+ remainingCap -= result.amountAtomic;
+ paid += 1;
+ if (result.txSig) lastTxSig = result.txSig;
+ }
+
+ const valueExtracted = snapshot
+ ? {
+ live: snapshot.live, total: snapshot.total, networks: snapshot.networks,
+ catalog_hash: snapshot.catalog_hash, drifted: snapshot.drifted,
+ added: snapshot.added.length, removed: snapshot.removed.length,
+ }
+ : null;
+
+ await recordCall(runId, {
+ category,
+ endpointUrl,
+ amountAtomic: result.amountAtomic,
+ txSig: result.txSig,
+ // Drop the bulky service list — the snapshot row captures the useful
+ // shape; keep just the call status and rpc-level error if any.
+ responseData: { status: result.status, count: services.length, rpc_error: result.responseBody?.error || null },
+ durationMs: Date.now() - t0,
+ success: result.success,
+ errorMsg: result.errorMsg,
+ valueExtracted,
+ });
+ }
+
+ const driftCount = snapshots.filter((s) => s?.drifted).length;
+ const liveTotal = snapshots.reduce((n, s) => n + (s?.live || 0), 0);
+ log.info('bazaar_warmup_complete', {
+ run_id: runId,
+ categories: WARMUP_CATEGORIES.length,
+ calls: snapshots.length,
+ paid,
+ live_services: liveTotal,
+ drift: driftCount,
+ spent_usdc: (spentAtomic / 1e6).toFixed(4),
+ });
+
+ // Aggregate outcome for the loop's single summary row. success=true when at
+ // least one category resolved; per-call detail lives in the rows above.
+ return {
+ success: paid > 0 || (snapshots.length > 0 && callErrors < snapshots.length),
+ amountAtomic: spentAtomic,
+ txSig: lastTxSig,
+ errorMsg: paid === 0 && callErrors > 0 ? `bazaar_warmup_calls_failed:${callErrors}` : null,
+ skipped: paid === 0 && snapshots.length === 0,
+ responseData: {
+ categories: WARMUP_CATEGORIES.length,
+ calls: snapshots.length,
+ paid,
+ live_services: liveTotal,
+ drift: driftCount,
+ },
+ note: `bazaar_warmup paid=${paid} live=${liveTotal} drift=${driftCount}`,
+ };
+}
diff --git a/api/_lib/x402/streaming-mcp-health.js b/api/_lib/x402/streaming-mcp-health.js
new file mode 100644
index 000000000..5a75e7e5d
--- /dev/null
+++ b/api/_lib/x402/streaming-mcp-health.js
@@ -0,0 +1,406 @@
+// api/_lib/x402/streaming-mcp-health.js
+//
+// SSE Streaming MCP Health — a custom-execution entry for the x402 autonomous
+// spend loop (see autonomous-registry.js → entry `mcp-sse-stream-health`).
+//
+// What it does, on every run:
+// 1. Probes POST /api/mcp as a plain x402 agent to obtain the 402 challenge.
+// 2. Builds a REAL Solana USDC payment for a single priced tools/call
+// (validate_model on a tiny, public, self-hosted canary GLB).
+// 3. Fires the paid request in *SSE mode* — Accept: text/event-stream — and
+// reads the HTTP response as a STREAM, not a single buffered body. It
+// measures time-to-first-byte, per-chunk gaps, chunk count, and total
+// bytes, and classifies the stream as clean / stalled / dropped. This is
+// what verifies the streaming response arrives intact before close and
+// surfaces broken chunked encoding or a server that hangs mid-response.
+// 4. Confirms settlement via the X-PAYMENT-RESPONSE header (the MCP server
+// only broadcasts the payment when the tool actually produced a result),
+// and pulls the on-chain tx signature out of it.
+// 5. Stores the streaming-integrity metrics to `mcp_stream_health` and fires
+// an ops alert when a stream stalls or drops.
+//
+// Reality note: the /api/mcp POST handler returns a single JSON body (it does
+// not yet emit token-by-token SSE frames), and GET /api/mcp answers 405 after
+// auth — there is no long-lived server→client subscription to read. So this
+// check honestly exercises the *paid streaming transport*: it advertises SSE
+// support, streams the chunked response, and validates TTFB / inter-chunk
+// liveness / complete delivery / chunked-encoding integrity. It does not fake
+// token frames the server never sends.
+//
+// The autonomous loop owns recording to x402_autonomous_log, cooldown, and
+// daily-spend accounting. This module owns the probe, the payment, the
+// streaming read, and the value extraction/storage. It returns a result the
+// loop records:
+// { success, amountAtomic, txSig, responseData, signalData, errorMsg,
+// skipped?, cooldown? }
+
+import {
+ PublicKey,
+} from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync,
+ TOKEN_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+} from '@solana/spl-token';
+import { sendOpsAlert } from '../alerts.js';
+
+// Tiny, public, self-hosted Khronos sample (~160 KB) — always available at the
+// canonical origin, validates cleanly, and keeps fetch+validate time low so the
+// canary measures transport latency, not model size. Pinned to the canonical
+// public origin (not the loop's runtime origin) so validate_model's SSRF guard
+// — which only fetches public https URLs — always has a real public asset to
+// pull, regardless of where the loop executes.
+const CANARY_TOOL = 'validate_model';
+const CANARY_GLB = 'https://three.ws/avatars/fox.glb';
+
+// Overall wall-clock budget for the paid streaming call (must fit inside the
+// loop's per-tick budget). A stall is a quieter failure: no bytes for this long
+// while the connection is still open is treated as a stalled stream.
+const STREAM_TIMEOUT_MS = 18_000;
+const STALL_MS = 8_000;
+
+function buildToolCallBody() {
+ return {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: {
+ name: CANARY_TOOL,
+ arguments: { url: CANARY_GLB, max_issues: 5 },
+ },
+ };
+}
+
+// Parse whatever the streaming read accumulated. The server returns a JSON body
+// today, but a future SSE upgrade would frame it as `data: {...}` lines — handle
+// both so the canary keeps working across that change.
+function parseStreamPayload(raw) {
+ if (!raw || typeof raw !== 'string') return null;
+ const trimmed = raw.trim();
+ if (!trimmed) return null;
+ try {
+ return JSON.parse(trimmed);
+ } catch { /* maybe SSE-framed */ }
+ const dataLines = trimmed
+ .split('\n')
+ .filter((l) => l.startsWith('data:'))
+ .map((l) => l.slice(5).trim())
+ .filter(Boolean);
+ for (let i = dataLines.length - 1; i >= 0; i--) {
+ try { return JSON.parse(dataLines[i]); } catch { /* try the next-to-last frame */ }
+ }
+ return null;
+}
+
+// Read an HTTP response body as a stream, recording streaming-integrity metrics.
+// Resolves with metrics even on stall/drop — the caller decides health from them.
+async function readStream(res, { stallMs, startedAt }) {
+ const metrics = {
+ status: res.status,
+ ttfbMs: null,
+ totalMs: 0,
+ chunkCount: 0,
+ totalBytes: 0,
+ maxGapMs: 0,
+ stalled: false,
+ dropped: false,
+ raw: '',
+ };
+
+ if (!res.body || typeof res.body.getReader !== 'function') {
+ // No readable stream (e.g. an error envelope) — fall back to buffered read.
+ try { metrics.raw = await res.text(); } catch { metrics.dropped = true; }
+ metrics.totalBytes = Buffer.byteLength(metrics.raw || '');
+ metrics.chunkCount = metrics.raw ? 1 : 0;
+ metrics.ttfbMs = Date.now() - startedAt;
+ metrics.totalMs = Date.now() - startedAt;
+ return metrics;
+ }
+
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let lastChunkAt = startedAt;
+
+ try {
+ for (;;) {
+ let stallTimer = null;
+ const stall = new Promise((_, reject) => {
+ stallTimer = setTimeout(() => reject(new Error('stall_timeout')), stallMs);
+ });
+ let chunk;
+ try {
+ chunk = await Promise.race([reader.read(), stall]);
+ } finally {
+ if (stallTimer) clearTimeout(stallTimer);
+ }
+
+ if (chunk.done) break;
+ const now = Date.now();
+ if (metrics.ttfbMs === null) {
+ metrics.ttfbMs = now - startedAt;
+ } else {
+ const gap = now - lastChunkAt;
+ if (gap > metrics.maxGapMs) metrics.maxGapMs = gap;
+ }
+ lastChunkAt = now;
+ metrics.chunkCount++;
+ metrics.totalBytes += chunk.value?.byteLength || 0;
+ metrics.raw += decoder.decode(chunk.value, { stream: true });
+ }
+ metrics.raw += decoder.decode();
+ } catch (err) {
+ if (err?.message === 'stall_timeout') metrics.stalled = true;
+ else metrics.dropped = true; // abort / connection reset / overall timeout
+ try { await reader.cancel(); } catch { /* already torn down */ }
+ }
+
+ if (metrics.ttfbMs === null) metrics.ttfbMs = Date.now() - startedAt;
+ metrics.totalMs = Date.now() - startedAt;
+ return metrics;
+}
+
+async function ensureStreamHealthTable(sql) {
+ try {
+ await sql`
+ CREATE TABLE IF NOT EXISTS mcp_stream_health (
+ id bigserial PRIMARY KEY,
+ ts timestamptz DEFAULT now(),
+ endpoint text NOT NULL,
+ tool text NOT NULL,
+ status_code int,
+ ttfb_ms int,
+ total_ms int,
+ chunk_count int,
+ total_bytes bigint,
+ max_gap_ms int,
+ stalled boolean NOT NULL DEFAULT false,
+ dropped boolean NOT NULL DEFAULT false,
+ settled boolean NOT NULL DEFAULT false,
+ healthy boolean NOT NULL,
+ tx_signature text,
+ error_msg text
+ )
+ `;
+ } catch { /* already exists or migration system handles it */ }
+}
+
+async function storeStreamHealth(sql, log, row) {
+ try {
+ await ensureStreamHealthTable(sql);
+ await sql`
+ INSERT INTO mcp_stream_health
+ (endpoint, tool, status_code, ttfb_ms, total_ms, chunk_count,
+ total_bytes, max_gap_ms, stalled, dropped, settled, healthy,
+ tx_signature, error_msg)
+ VALUES
+ (${row.endpoint}, ${row.tool}, ${row.status_code},
+ ${row.ttfb_ms}, ${row.total_ms}, ${row.chunk_count},
+ ${row.total_bytes}, ${row.max_gap_ms}, ${row.stalled},
+ ${row.dropped}, ${row.settled}, ${row.healthy},
+ ${row.tx_signature || null}, ${row.error_msg || null})
+ `;
+ } catch (err) {
+ // DB failure must never crash the loop — log and move on.
+ log?.warn?.('mcp_stream_health_insert_failed', { message: err?.message });
+ }
+}
+
+/**
+ * Custom-execution handler invoked by the autonomous loop for the
+ * `mcp-sse-stream-health` registry entry.
+ *
+ * @param {object} ctx — supplied by the loop:
+ * origin, endpointUrl, buyer (Keypair), conn, blockhash, mintInfo,
+ * usdcMint, remainingCap, fetchWithTimeout, parseSolanaAccept,
+ * buildPaymentTx, sql, log, redis
+ * @returns {Promise<object>} result the loop records to x402_autonomous_log
+ */
+export async function runStreamingMcpHealth(ctx) {
+ const {
+ endpointUrl, buyer, conn, blockhash, mintInfo, usdcMint, remainingCap,
+ fetchWithTimeout, parseSolanaAccept, buildPaymentTx, sql, log,
+ } = ctx;
+
+ const fail = (errorMsg, extra = {}) => ({
+ success: false, amountAtomic: 0, txSig: null,
+ responseData: null, signalData: { alive: false, error: errorMsg },
+ errorMsg, ...extra,
+ });
+
+ // Wallet guard (defence in depth — the loop already pre-flights the keypair).
+ if (!buyer) return { ...fail('wallet_unconfigured'), cooldown: false };
+
+ // ── Step 1: probe for the 402 challenge (plain x402 agent → real 402) ──────
+ let probe;
+ try {
+ probe = await fetchWithTimeout(endpointUrl, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'user-agent': 'threews-x402-autonomous/1.0',
+ },
+ body: JSON.stringify(buildToolCallBody()),
+ });
+ } catch (err) {
+ return { ...fail(`probe_failed:${err?.message || 'network'}`), cooldown: false };
+ }
+
+ // 402 (plain agent) or 401 (the server's MCP/OAuth challenge) both carry the
+ // x402 envelope with `accepts` in the body. Anything else means the price
+ // gate isn't where we expect — record and skip.
+ if (probe.status !== 402 && probe.status !== 401) {
+ return fail(`unexpected_probe_status:${probe.status}`);
+ }
+ const accept = parseSolanaAccept(probe.body);
+ if (!accept) return fail('no_solana_accept');
+ if (!usdcMint || accept.asset !== usdcMint) return fail(`unexpected_asset:${accept.asset}`);
+ if (!accept.extra?.feePayer) return fail('missing_fee_payer');
+
+ const amountAtomic = Number(accept.amount || 0);
+ if (!(amountAtomic > 0)) return fail('zero_price');
+ if (amountAtomic > remainingCap) {
+ // Honor the loop's daily cap — skip without paying, retry next tick.
+ return { ...fail('cap_would_exceed'), skipped: true, cooldown: false };
+ }
+
+ // ── Step 2: build the signed payment tx ────────────────────────────────────
+ let xPayment;
+ try {
+ const receiverAta = getAssociatedTokenAddressSync(
+ new PublicKey(accept.asset), new PublicKey(accept.payTo),
+ false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+ const receiverAtaInfo = await conn.getAccountInfo(receiverAta).catch(() => null);
+ const txBase64 = buildPaymentTx({
+ accept, buyer, blockhash, mintInfo,
+ receiverAtaExists: receiverAtaInfo !== null,
+ });
+ xPayment = Buffer.from(JSON.stringify({
+ x402Version: 2,
+ scheme: 'exact',
+ network: accept.network,
+ resource: { url: endpointUrl, mimeType: 'application/json' },
+ payload: { transaction: txBase64 },
+ accepted: accept,
+ })).toString('base64');
+ } catch (err) {
+ return { ...fail(`build_payment_failed:${err?.message || 'unknown'}`), cooldown: false };
+ }
+
+ // ── Step 3: fire the paid call in SSE mode and read the response as a stream ─
+ const startedAt = Date.now();
+ const controller = new AbortController();
+ const overall = setTimeout(() => controller.abort(), STREAM_TIMEOUT_MS);
+ let metrics;
+ try {
+ const res = await fetch(endpointUrl, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ // Advertise SSE support — this is the "SSE mode" request. The server
+ // negotiates the response transport off Accept.
+ accept: 'text/event-stream, application/json',
+ 'user-agent': 'threews-x402-autonomous/1.0',
+ 'x-payment': xPayment,
+ },
+ body: JSON.stringify(buildToolCallBody()),
+ signal: controller.signal,
+ });
+ metrics = await readStream(res, { stallMs: STALL_MS, startedAt });
+ // Settlement is proven by the X-PAYMENT-RESPONSE header — the MCP server
+ // only broadcasts the payment after the tool produced a result.
+ const xpr = res.headers?.get?.('x-payment-response');
+ metrics.settled = !!xpr;
+ metrics.txSig = null;
+ if (xpr) {
+ try {
+ const settled = JSON.parse(Buffer.from(xpr, 'base64').toString('utf8'));
+ metrics.txSig = settled?.transaction || null;
+ } catch { /* header present but unparseable — still settled */ }
+ }
+ } catch (err) {
+ // Abort fires as an error here when the overall budget is exceeded before
+ // any headers arrive — treat as a dropped connection.
+ metrics = {
+ status: 0, ttfbMs: Date.now() - startedAt, totalMs: Date.now() - startedAt,
+ chunkCount: 0, totalBytes: 0, maxGapMs: 0, stalled: false,
+ dropped: true, raw: '', settled: false, txSig: null,
+ abortMsg: err?.message || 'request_failed',
+ };
+ } finally {
+ clearTimeout(overall);
+ }
+
+ // ── Step 4: classify health and extract value ──────────────────────────────
+ const parsed = parseStreamPayload(metrics.raw);
+ const rpcError = parsed?.error?.message || null;
+ const toolError = parsed?.result?.isError === true;
+ const hasResult = !!parsed?.result && !toolError && !rpcError;
+ const streamClean = metrics.status === 200 && !metrics.stalled && !metrics.dropped && metrics.chunkCount > 0;
+ const healthy = streamClean && hasResult && metrics.settled;
+
+ // Payment-rejected paths: a 402/401 on the *paid* request means the payment
+ // was not accepted; no settlement, so nothing was charged.
+ let errorMsg = null;
+ if (metrics.status === 402 || metrics.status === 401) errorMsg = `payment_rejected:${metrics.status}`;
+ else if (metrics.dropped) errorMsg = `stream_dropped${metrics.abortMsg ? `:${metrics.abortMsg}` : ''}`;
+ else if (metrics.stalled) errorMsg = 'stream_stalled';
+ else if (rpcError) errorMsg = `rpc_error:${rpcError}`;
+ else if (toolError) errorMsg = 'tool_error';
+ else if (!metrics.settled) errorMsg = 'not_settled';
+ else if (!hasResult) errorMsg = 'no_result';
+
+ const signalData = {
+ alive: healthy,
+ tool: CANARY_TOOL,
+ status: metrics.status,
+ ttfb_ms: metrics.ttfbMs,
+ total_ms: metrics.totalMs,
+ chunk_count: metrics.chunkCount,
+ total_bytes: metrics.totalBytes,
+ max_gap_ms: metrics.maxGapMs,
+ stalled: metrics.stalled,
+ dropped: metrics.dropped,
+ settled: metrics.settled,
+ };
+
+ // ── Step 5: persist the streaming-integrity metrics + alert on degradation ──
+ await storeStreamHealth(sql, log, {
+ endpoint: '/api/mcp',
+ tool: CANARY_TOOL,
+ status_code: metrics.status,
+ ttfb_ms: metrics.ttfbMs,
+ total_ms: metrics.totalMs,
+ chunk_count: metrics.chunkCount,
+ total_bytes: metrics.totalBytes,
+ max_gap_ms: metrics.maxGapMs,
+ stalled: metrics.stalled,
+ dropped: metrics.dropped,
+ settled: metrics.settled,
+ healthy,
+ tx_signature: metrics.txSig,
+ error_msg: errorMsg,
+ });
+
+ if (metrics.stalled || metrics.dropped) {
+ // Fire-and-forget: alerting must never block or crash the loop.
+ sendOpsAlert(
+ 'MCP SSE stream degraded',
+ `POST /api/mcp (${CANARY_TOOL}) ${metrics.stalled ? 'STALLED' : 'DROPPED'} — ` +
+ `status ${metrics.status}, ttfb ${metrics.ttfbMs}ms, ${metrics.chunkCount} chunks, ` +
+ `${metrics.totalBytes}B, max gap ${metrics.maxGapMs}ms`,
+ { signature: `mcp-sse-stream:${metrics.stalled ? 'stalled' : 'dropped'}` },
+ ).catch(() => {});
+ }
+
+ // `amountAtomic` reported to the loop reflects what was actually charged:
+ // only a settled payment moved USDC on-chain.
+ return {
+ success: healthy,
+ amountAtomic: metrics.settled ? amountAtomic : 0,
+ txSig: metrics.txSig,
+ responseData: parsed ?? (metrics.raw ? { raw: metrics.raw.slice(0, 2000) } : null),
+ signalData,
+ errorMsg,
+ };
+}
diff --git a/api/_lib/x402/thumbnail-regen.js b/api/_lib/x402/thumbnail-regen.js
new file mode 100644
index 000000000..92ddd6477
--- /dev/null
+++ b/api/_lib/x402/thumbnail-regen.js
@@ -0,0 +1,202 @@
+// api/_lib/x402/thumbnail-regen.js
+//
+// Avatar Thumbnail Regeneration — data layer for the x402 autonomous pipeline.
+//
+// Flow:
+// 1. The autonomous spend loop (api/cron/x402-autonomous-loop.js) calls
+// selectStaleAsset() to find the marketplace listing whose thumbnail is
+// most overdue, then pays /api/x402/asset-download for it (real USDC).
+// 2. On a successful paid download it calls enqueueRegenJob() to queue a
+// re-render, storing the value extracted from the response.
+// 3. The drainer cron (api/cron/avatar-thumbnail-render.js) claims queued
+// jobs, renders the current GLB to a PNG, uploads it to R2, and calls
+// completeRegenJob() — which writes the fresh thumbnail back onto both
+// paid_assets and the linked avatars row so listings show current state.
+//
+// This module is the single owner of the regen schema and queue queries. It
+// holds NO chromium/render dependency — rendering lives in the drainer so the
+// spend-loop bundle stays lean.
+
+import { sql } from '../db.js';
+
+// A thumbnail is stale once it is this many days old (or never rendered, or the
+// underlying model bytes changed after the last render).
+export const STALE_DAYS = 30;
+
+// Failed jobs are retried up to this many times before they stay 'failed'.
+export const RETRY_MAX = 3;
+
+// Default render dimensions for marketplace thumbnails (square).
+export const DEFAULT_THUMB_SIZE = 768;
+
+let schemaReady = false;
+
+// Idempotent schema provisioning. Mirrors
+// api/_lib/migrations/2026-06-27-avatar-thumbnail-regen.sql so a fresh DB or a
+// deploy that ran ahead of the migration still works. Cheap + cached per warm
+// container (regen is low-frequency anyway).
+export async function ensureRegenSchema() {
+ if (schemaReady) return;
+ await sql`ALTER TABLE paid_assets ADD COLUMN IF NOT EXISTS thumbnail_r2_key text`;
+ await sql`ALTER TABLE paid_assets ADD COLUMN IF NOT EXISTS thumbnail_generated_at timestamptz`;
+ await sql`ALTER TABLE paid_assets ADD COLUMN IF NOT EXISTS source_updated_at timestamptz`;
+ await sql`ALTER TABLE paid_assets ADD COLUMN IF NOT EXISTS avatar_id uuid REFERENCES avatars(id) ON DELETE SET NULL`;
+ await sql`
+ CREATE TABLE IF NOT EXISTS avatar_thumbnail_regen_jobs (
+ id bigserial PRIMARY KEY,
+ asset_id uuid REFERENCES paid_assets(id) ON DELETE CASCADE,
+ asset_slug text NOT NULL,
+ avatar_id uuid REFERENCES avatars(id) ON DELETE SET NULL,
+ r2_key text NOT NULL,
+ run_id uuid,
+ x402_tx_signature text,
+ amount_atomic bigint NOT NULL DEFAULT 0,
+ status text NOT NULL DEFAULT 'queued'
+ CHECK (status IN ('queued','rendering','done','failed')),
+ thumbnail_r2_key text,
+ width int NOT NULL DEFAULT 768,
+ height int NOT NULL DEFAULT 768,
+ attempts int NOT NULL DEFAULT 0,
+ error text,
+ reason text,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ rendered_at timestamptz
+ )
+ `;
+ await sql`
+ CREATE INDEX IF NOT EXISTS avatar_thumbnail_regen_jobs_status_idx
+ ON avatar_thumbnail_regen_jobs (status, created_at)
+ `;
+ await sql`
+ CREATE UNIQUE INDEX IF NOT EXISTS avatar_thumbnail_regen_jobs_open_uniq
+ ON avatar_thumbnail_regen_jobs (asset_slug)
+ WHERE status IN ('queued','rendering')
+ `;
+ schemaReady = true;
+}
+
+// Pick the single stalest GLB listing that needs a thumbnail and has no open
+// regen job already in flight. Returns null when nothing is stale (the loop
+// treats this as "no work" and skips without paying).
+export async function selectStaleAsset() {
+ await ensureRegenSchema();
+ const rows = await sql`
+ SELECT pa.id, pa.slug, pa.title, pa.r2_key, pa.avatar_id,
+ pa.price_atomics, pa.thumbnail_generated_at
+ FROM paid_assets pa
+ WHERE pa.mime_type IN ('model/gltf-binary', 'model/gltf+json')
+ AND NOT EXISTS (
+ SELECT 1 FROM avatar_thumbnail_regen_jobs j
+ WHERE j.asset_slug = pa.slug
+ AND j.status IN ('queued','rendering')
+ )
+ AND (
+ pa.thumbnail_r2_key IS NULL
+ OR pa.thumbnail_generated_at IS NULL
+ OR pa.thumbnail_generated_at < now() - (${STALE_DAYS} || ' days')::interval
+ OR (pa.source_updated_at IS NOT NULL
+ AND pa.source_updated_at > pa.thumbnail_generated_at)
+ )
+ ORDER BY COALESCE(pa.thumbnail_generated_at, 'epoch'::timestamptz) ASC,
+ pa.created_at ASC
+ LIMIT 1
+ `;
+ return rows[0] || null;
+}
+
+// Queue a re-render after a successful paid asset-download. Idempotent against
+// the open-job unique index: if a job for this listing is already in flight the
+// insert is a no-op and we return null. `responseBody` is the asset-download
+// JSON — we keep its slug/size as the extracted value on the job's reason field
+// for observability; the source r2_key (re-presigned at render time) is what
+// the drainer actually renders, since the loop's downloadUrl is short-lived.
+export async function enqueueRegenJob({ asset, runId = null, txSig = null, amountAtomic = 0, responseBody = null }) {
+ if (!asset?.slug || !asset?.r2_key) {
+ throw new Error('enqueueRegenJob: asset.slug and asset.r2_key required');
+ }
+ await ensureRegenSchema();
+ const reason = responseBody
+ ? `download_ok slug=${responseBody.slug ?? asset.slug} bytes=${responseBody.sizeBytes ?? ''}`.trim()
+ : 'download_ok';
+ const rows = await sql`
+ INSERT INTO avatar_thumbnail_regen_jobs
+ (asset_id, asset_slug, avatar_id, r2_key, run_id, x402_tx_signature,
+ amount_atomic, status, width, height, reason)
+ VALUES
+ (${asset.id ?? null}, ${asset.slug}, ${asset.avatar_id ?? null},
+ ${asset.r2_key}, ${runId}, ${txSig}, ${amountAtomic || 0}, 'queued',
+ ${DEFAULT_THUMB_SIZE}, ${DEFAULT_THUMB_SIZE}, ${reason})
+ ON CONFLICT (asset_slug) WHERE status IN ('queued','rendering')
+ DO NOTHING
+ RETURNING id
+ `;
+ return rows[0]?.id ?? null;
+}
+
+// Atomically claim up to `limit` jobs for rendering (queued first, then
+// retryable failures). FOR UPDATE SKIP LOCKED makes this safe across concurrent
+// drainer invocations. Bumps attempts and flips status to 'rendering'.
+export async function claimRegenJobs(limit = 3) {
+ await ensureRegenSchema();
+ const rows = await sql`
+ UPDATE avatar_thumbnail_regen_jobs
+ SET status = 'rendering', attempts = attempts + 1, updated_at = now()
+ WHERE id IN (
+ SELECT id FROM avatar_thumbnail_regen_jobs
+ WHERE status = 'queued'
+ OR (status = 'failed' AND attempts < ${RETRY_MAX})
+ ORDER BY created_at ASC
+ LIMIT ${limit}
+ FOR UPDATE SKIP LOCKED
+ )
+ RETURNING id, asset_id, asset_slug, avatar_id, r2_key, run_id,
+ width, height, attempts
+ `;
+ return rows;
+}
+
+// Mark a job done and write the fresh thumbnail back onto the listing and the
+// linked avatar so marketplace surfaces immediately show the new render.
+export async function completeRegenJob(job, thumbnailR2Key) {
+ await sql`
+ UPDATE avatar_thumbnail_regen_jobs
+ SET status = 'done', thumbnail_r2_key = ${thumbnailR2Key},
+ error = NULL, rendered_at = now(), updated_at = now()
+ WHERE id = ${job.id}
+ `;
+ if (job.asset_id || job.asset_slug) {
+ await sql`
+ UPDATE paid_assets
+ SET thumbnail_r2_key = ${thumbnailR2Key},
+ thumbnail_generated_at = now()
+ WHERE ${job.asset_id ? sql`id = ${job.asset_id}` : sql`slug = ${job.asset_slug}`}
+ `;
+ }
+ if (job.avatar_id) {
+ await sql`
+ UPDATE avatars
+ SET thumbnail_key = ${thumbnailR2Key}, updated_at = now()
+ WHERE id = ${job.avatar_id} AND deleted_at IS NULL
+ `;
+ }
+}
+
+// Mark a job failed with the error. Retries happen via claimRegenJobs until
+// attempts hits RETRY_MAX, after which the row stays 'failed' for inspection.
+export async function failRegenJob(job, errMsg) {
+ await sql`
+ UPDATE avatar_thumbnail_regen_jobs
+ SET status = 'failed', error = ${String(errMsg || 'unknown').slice(0, 500)},
+ updated_at = now()
+ WHERE id = ${job.id}
+ `;
+}
+
+// Deterministic R2 key for a listing's thumbnail. Keyed on slug + run so a new
+// render never collides with a CDN-cached previous one.
+export function thumbnailKeyFor(slug, runId) {
+ const safeSlug = String(slug).replace(/[^a-zA-Z0-9._-]/g, '-').slice(0, 80);
+ const suffix = runId ? String(runId).slice(0, 8) : 'r';
+ return `thumbnails/assets/${safeSlug}-${suffix}.png`;
+}
diff --git a/api/cron/x402-autonomous-loop.js b/api/cron/x402-autonomous-loop.js
index ba6b67d6f..3bb6857db 100644
--- a/api/cron/x402-autonomous-loop.js
+++ b/api/cron/x402-autonomous-loop.js
@@ -24,16 +24,10 @@
// X402_AUTONOMOUS_DAILY_CAP_ATOMIC daily USDC cap in atomics (default: 5000000 = $5)
// CRON_SECRET required Vercel cron auth
-import { readFileSync } from 'node:fs';
import { randomUUID } from 'node:crypto';
-import bs58 from 'bs58';
+import { PublicKey } from '@solana/web3.js';
import {
- Connection, PublicKey, Keypair, TransactionMessage, VersionedTransaction,
- ComputeBudgetProgram,
-} from '@solana/web3.js';
-import {
- getAssociatedTokenAddressSync, createTransferCheckedInstruction,
- createAssociatedTokenAccountIdempotentInstruction,
+ getAssociatedTokenAddressSync,
TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID, getMint,
} from '@solana/spl-token';
@@ -44,6 +38,12 @@ import { getRedis } from '../_lib/redis.js';
import { sql } from '../_lib/db.js';
import { solanaConnection } from '../_lib/solana/connection.js';
import { logger } from '../_lib/usage.js';
+import {
+ loadSeedKeypair,
+ fetchWithTimeout,
+ parseSolanaAccept,
+ buildPaymentTx,
+} from '../_lib/x402/pay.js';
import {
getFullRegistry,
MAX_PER_TICK,
@@ -55,7 +55,6 @@ const log = logger('x402-autonomous-loop');
const ORIGIN = () => env.APP_ORIGIN || 'https://three.ws';
const USDC_MINT = env.X402_ASSET_MINT_SOLANA;
const SOLANA_RPC = env.SOLANA_RPC_URL;
-const FETCH_TIMEOUT_MS = 20_000;
// Redis key prefix for cooldown tracking.
const COOLDOWN_PREFIX = 'x402:auto:last:';
@@ -71,81 +70,7 @@ function requireCron(req, res) {
return true;
}
-function loadSeedKeypair() {
- const b58 = process.env.X402_SEED_SOLANA_SECRET_BASE58
- || process.env.X402_AGENT_SOLANA_SECRET_BASE58;
- if (b58) {
- const raw = bs58.decode(b58);
- if (raw.length !== 64) throw new Error(`seed keypair: expected 64 bytes, got ${raw.length}`);
- return Keypair.fromSecretKey(raw);
- }
- if (process.env.NODE_ENV !== 'production') {
- try {
- const arr = JSON.parse(readFileSync('/home/codespace/.config/x402-test-wallets/solana.json', 'utf8'));
- return Keypair.fromSecretKey(Uint8Array.from(arr));
- } catch { /* fall through */ }
- }
- throw new Error('autonomous loop: seed keypair not configured (set X402_SEED_SOLANA_SECRET_BASE58)');
-}
-
-async function fetchWithTimeout(url, opts = {}) {
- const ctrl = new AbortController();
- const t = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);
- try {
- const res = await fetch(url, { ...opts, signal: ctrl.signal, redirect: 'manual' });
- let body = null;
- try { body = await res.json(); } catch { try { body = await res.text(); } catch { body = null; } }
- return { ok: res.ok, status: res.status, headers: res.headers, body };
- } finally {
- clearTimeout(t);
- }
-}
-
-function parseSolanaAccept(challenge) {
- if (!challenge || !Array.isArray(challenge.accepts)) return null;
- return challenge.accepts.find(
- (a) => typeof a?.network === 'string' && a.network.startsWith('solana'),
- ) || null;
-}
-
-function buildPaymentTx({ accept, buyer, blockhash, mintInfo, receiverAtaExists }) {
- const mint = new PublicKey(accept.asset);
- const payTo = new PublicKey(accept.payTo);
- const feePayer = new PublicKey(accept.extra.feePayer);
- const amount = BigInt(accept.amount);
-
- const senderAta = getAssociatedTokenAddressSync(
- mint, buyer.publicKey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
- );
- const receiverAta = getAssociatedTokenAddressSync(
- mint, payTo, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
- );
-
- const ixs = [
- ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 }),
- ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 5 }),
- ];
- if (!receiverAtaExists) {
- ixs.push(createAssociatedTokenAccountIdempotentInstruction(
- feePayer, receiverAta, payTo, mint, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
- ));
- }
- ixs.push(createTransferCheckedInstruction(
- senderAta, mint, receiverAta, buyer.publicKey,
- amount, mintInfo.decimals, [], TOKEN_PROGRAM_ID,
- ));
-
- const msg = new TransactionMessage({
- payerKey: feePayer,
- recentBlockhash: blockhash,
- instructions: ixs,
- }).compileToV0Message();
- const vtx = new VersionedTransaction(msg);
- vtx.sign([buyer]);
- return Buffer.from(vtx.serialize()).toString('base64');
-}
-
-async function recordLog(runId, entry, { amountAtomic, txSig, responseData, durationMs, success, errorMsg, signalData }) {
+async function recordLog(runId, entry, { amountAtomic, txSig, responseData, durationMs, success, errorMsg, signalData, endpointUrl }) {
try {
await sql`
INSERT INTO x402_autonomous_log
@@ -154,7 +79,7 @@ async function recordLog(runId, entry, { amountAtomic, txSig, responseData, dura
response_data, signal_data, duration_ms, success, error_msg, pipeline)
VALUES
(${runId}, ${entry.url ? 'external' : 'self'},
- ${entry.name}, ${entry.url || entry.path},
+ ${entry.name}, ${endpointUrl || entry.url || entry.path},
${'solana:mainnet'}, ${amountAtomic || 0},
${USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'},
${txSig || null},
@@ -272,6 +197,18 @@ async function setCooldown(redis, entry) {
} catch { /* non-fatal */ }
}
+// Optional per-entry value-store hook. Lets a pipeline persist its extracted
+// value into a dedicated table (beyond the generic signal_data column). Wrapped
+// so a DB failure inside the hook can never crash the tick.
+async function runStoreValue(entry, ctx) {
+ if (typeof entry.storeValue !== 'function') return;
+ try {
+ await entry.storeValue(ctx);
+ } catch (err) {
+ log.warn('store_value_failed', { id: entry.id, message: err?.message });
+ }
+}
+
// ── Main handler ──────────────────────────────────────────────────────────────
export default wrapCron(async (req, res) => {
@@ -345,7 +282,8 @@ export default wrapCron(async (req, res) => {
for (const entry of ready) {
if (remainingCap <= 0) break;
- const endpointUrl = entry.url || `${origin}${entry.path}`;
+ let endpointUrl = entry.url || `${origin}${entry.path}`;
+ let targetUrl = null;
const t0 = Date.now();
let amountAtomic = 0;
let txSig = null;
@@ -354,6 +292,61 @@ export default wrapCron(async (req, res) => {
let responseBody = null;
let signalData = null;
+ // run()-style entries own their full call sequence (queue scans, worker
+ // polling, multi-row fan-out). They pay via the shared payX402 client and
+ // hand back a structured outcome; the loop records it exactly like an
+ // inline call. A thrown run() never crashes the tick — it lands as a
+ // recorded failure with the cooldown still applied to avoid hot-looping.
+ if (typeof entry.run === 'function') {
+ let outcome = null;
+ try {
+ outcome = await entry.run({
+ origin, buyer, conn, blockhash, mintInfo,
+ redis, sql, log, runId, remainingCap,
+ });
+ } catch (err) {
+ errorMsg = err?.message || 'run_error';
+ }
+ outcome = outcome || {};
+ amountAtomic = Number(outcome.amountAtomic) || 0;
+ txSig = outcome.txSig || null;
+ success = outcome.success ?? false;
+ errorMsg = outcome.errorMsg || errorMsg;
+ responseBody = outcome.responseData ?? null;
+ signalData = outcome.signalData ?? null;
+
+ if (success && amountAtomic > 0) {
+ remainingCap -= amountAtomic;
+ await incrementDailySpend(redis, amountAtomic);
+ }
+ await setCooldown(redis, entry);
+
+ results.push({
+ id: entry.id,
+ status: outcome.skipped ? 'skip' : (success ? (amountAtomic > 0 ? 'paid' : 'ok') : 'error'),
+ amount_usdc: amountAtomic / 1e6,
+ tx: txSig,
+ ...(outcome.note ? { note: outcome.note } : {}),
+ });
+ await recordLog(runId, entry, {
+ amountAtomic, txSig, responseData: responseBody,
+ durationMs: Date.now() - t0, success, errorMsg, signalData,
+ });
+ continue;
+ }
+
+ // Dynamic target resolution (rotation pipelines, e.g. GLB canonicalization):
+ // resolveTarget computes the per-call path and the resource URL being checked.
+ if (typeof entry.resolveTarget === 'function') {
+ try {
+ const resolved = await entry.resolveTarget({ redis, origin, runId });
+ if (resolved?.path) endpointUrl = entry.url || `${origin}${resolved.path}`;
+ if (resolved?.targetUrl) targetUrl = resolved.targetUrl;
+ } catch (err) {
+ log.warn('resolve_target_failed', { id: entry.id, message: err?.message });
+ }
+ }
+
try {
// Step 1: probe for 402 challenge
const probeRes = await fetchWithTimeout(endpointUrl, {
@@ -368,8 +361,9 @@ export default wrapCron(async (req, res) => {
responseBody = probeRes.body;
if (entry.extractSignal) signalData = entry.extractSignal(responseBody);
results.push({ id: entry.id, status: 'free', success });
- await recordLog(runId, entry, { amountAtomic: 0, txSig: null, responseData: responseBody, durationMs: Date.now() - t0, success, signalData });
+ await recordLog(runId, entry, { amountAtomic: 0, txSig: null, responseData: responseBody, durationMs: Date.now() - t0, success, signalData, endpointUrl });
if (signalData) await upsertOracleSignal(entry, signalData);
+ await runStoreValue(entry, { sql, redis, responseBody, signalData, runId, targetUrl, endpointUrl });
await setCooldown(redis, entry);
continue;
}
@@ -449,6 +443,7 @@ export default wrapCron(async (req, res) => {
if (entry.extractSignal) signalData = entry.extractSignal(responseBody);
await setCooldown(redis, entry);
if (signalData) await upsertOracleSignal(entry, signalData);
+ await runStoreValue(entry, { sql, redis, responseBody, signalData, runId, targetUrl, endpointUrl });
} else {
errorMsg = `http_${paidRes.status}`;
}
@@ -467,6 +462,7 @@ export default wrapCron(async (req, res) => {
success,
errorMsg,
signalData,
+ endpointUrl,
});
}
diff --git a/api/marketplace/reviews.js b/api/marketplace/reviews.js
index 75c3c9f71..7500590d1 100644
--- a/api/marketplace/reviews.js
+++ b/api/marketplace/reviews.js
@@ -21,6 +21,7 @@ import { clientIp, limits } from '../_lib/rate-limit.js';
import { requireCsrf } from '../_lib/csrf.js';
import { isUuid } from '../_lib/validate.js';
import { publishUserEvent } from '../_lib/feed.js';
+import { attestReview } from '../_lib/review-attest.js';
const reviewSchema = z.object({
rating: z.number().int().min(1).max(5),
@@ -149,7 +150,7 @@ async function handleUpsert(req, res, agentId) {
if (!rl.success) return rateLimited(res, rl);
const [agent] = await sql`
- SELECT id, user_id, name FROM agent_identities
+ SELECT id, user_id, name, erc8004_agent_id, chain_id FROM agent_identities
WHERE id = ${agentId} AND deleted_at IS NULL AND is_published = true
`;
if (!agent) return error(res, 404, 'not_found', 'agent not found');
@@ -196,6 +197,18 @@ async function handleUpsert(req, res, agentId) {
});
}
+ // Anchor the review on Solana — fire-and-forget, never blocks the response.
+ attestReview({
+ reviewId: row.id,
+ updatedAt: row.updated_at,
+ agentId,
+ rating: parsed.data.rating,
+ body: reviewBody,
+ reviewType: 'agent',
+ }).catch((err) => {
+ console.error('[review-attest] agent review anchor failed:', err.message);
+ });
+
return json(res, 200, {
data: {
review: row,
@@ -203,6 +216,10 @@ async function handleUpsert(req, res, agentId) {
rating_avg: Number(summary.rating_avg || 0),
rating_count: summary.rating_count || 0,
},
+ // Returned so the client can offer ERC-8004 user-signed anchoring.
+ erc8004: agent.erc8004_agent_id
+ ? { agent_id: String(agent.erc8004_agent_id), chain_id: agent.chain_id }
+ : null,
},
});
}
diff --git a/api/skills/review.js b/api/skills/review.js
index bafcdc1b2..2e2b9762b 100644
--- a/api/skills/review.js
+++ b/api/skills/review.js
@@ -32,6 +32,7 @@ import { requireCsrf } from '../_lib/csrf.js';
import { isUuid } from '../_lib/validate.js';
import { hasSkillAccess } from '../_lib/skill-access.js';
import { publishUserEvent } from '../_lib/feed.js';
+import { attestReview } from '../_lib/review-attest.js';
const SKILL_MAX = 200;
@@ -182,7 +183,7 @@ async function handleUpsert(req, res) {
const reviewBody = (parsed.data.body || '').trim() || null;
const [agent] = await sql`
- SELECT id, user_id, name FROM agent_identities
+ SELECT id, user_id, name, erc8004_agent_id, chain_id FROM agent_identities
WHERE id = ${agentId} AND deleted_at IS NULL
`;
if (!agent) return error(res, 404, 'not_found', 'agent not found');
@@ -236,6 +237,19 @@ async function handleUpsert(req, res) {
});
}
+ // Anchor the review on Solana — fire-and-forget, never blocks the response.
+ attestReview({
+ reviewId: row.id,
+ updatedAt: row.updated_at,
+ agentId,
+ rating,
+ body: reviewBody,
+ reviewType: 'skill',
+ skill,
+ }).catch((err) => {
+ console.error('[review-attest] skill review anchor failed:', err.message);
+ });
+
return json(res, isNew ? 201 : 200, {
data: {
review: row,
@@ -243,6 +257,10 @@ async function handleUpsert(req, res) {
rating_avg: Number(summary?.rating_avg || 0),
rating_count: summary?.rating_count || 0,
},
+ // Returned so the client can offer ERC-8004 user-signed anchoring.
+ erc8004: agent.erc8004_agent_id
+ ? { agent_id: String(agent.erc8004_agent_id), chain_id: agent.chain_id }
+ : null,
},
});
}
diff --git a/api/x402/avatar-optimize-batch.js b/api/x402/avatar-optimize-batch.js
new file mode 100644
index 000000000..8199fb207
--- /dev/null
+++ b/api/x402/avatar-optimize-batch.js
@@ -0,0 +1,262 @@
+// POST /api/x402/avatar-optimize-batch
+//
+// Avatar Optimization Pipeline — nightly batch analysis endpoint.
+// $0.001 USDC per call. Fetches the top N most-viewed public avatars,
+// runs glTF-Transform optimization analysis on each, and stores the
+// prioritized suggestion lists to avatar_optimization_results.
+//
+// Downstream consumers:
+// - avatar_optimization_results table: optimization hints per avatar_id
+// - The /api/avatars/:id endpoint can surface these hints to owners
+// - Autonomous loop health check: confirms optimize_model capability is live
+//
+// Body: { limit?: 1-50 } (default 50)
+// Response 200: { analyzed, critical_count, warn_count, total_size_bytes, avatars[] }
+
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { installAccessControl } from '../_lib/x402/access-control.js';
+import { sql } from '../_lib/db.js';
+import { publicUrl } from '../_lib/r2.js';
+import { inspectModel, suggestOptimizations } from '../_lib/model-inspect.js';
+
+const ROUTE = '/api/x402/avatar-optimize-batch';
+const MAX_BATCH = 50;
+const FETCH_TIMEOUT_MS = 25_000;
+const MAX_MODEL_BYTES = 32 * 1024 * 1024; // 32 MiB
+
+const DESCRIPTION =
+ 'three.ws Avatar Optimization Pipeline — pay $0.001 USDC to trigger a batch ' +
+ 'glTF/GLB analysis of the top most-viewed public avatars. Returns a ranked ' +
+ 'list of optimization suggestions (Draco/Meshopt compression, oversized ' +
+ 'textures, non-indexed primitives) and stores results per-avatar so owners ' +
+ 'can be notified of actionable improvements.';
+
+const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ properties: {
+ limit: {
+ type: 'integer',
+ minimum: 1,
+ maximum: MAX_BATCH,
+ default: MAX_BATCH,
+ description: `Number of top avatars to analyze (1–${MAX_BATCH}).`,
+ },
+ },
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['analyzed', 'critical_count', 'warn_count', 'total_size_bytes', 'avatars'],
+ properties: {
+ analyzed: { type: 'integer' },
+ critical_count: { type: 'integer' },
+ warn_count: { type: 'integer' },
+ info_count: { type: 'integer' },
+ total_size_bytes: { type: 'integer' },
+ avatars: {
+ type: 'array',
+ items: {
+ type: 'object',
+ properties: {
+ id: { type: 'string' },
+ name: { type: 'string' },
+ size_bytes: { type: 'integer' },
+ critical_count: { type: 'integer' },
+ warn_count: { type: 'integer' },
+ info_count: { type: 'integer' },
+ top_suggestion: { type: ['string', 'null'] },
+ },
+ },
+ },
+ },
+};
+
+const BAZAAR = {
+ discoverable: true,
+ info: {
+ input: { type: 'http', method: 'POST', bodyParams: { limit: 50 } },
+ output: {
+ type: 'json',
+ example: {
+ analyzed: 50,
+ critical_count: 12,
+ warn_count: 38,
+ info_count: 91,
+ total_size_bytes: 82_000_000,
+ avatars: [{ id: 'uuid', name: 'My Avatar', size_bytes: 2_100_000, critical_count: 1, warn_count: 3, info_count: 5, top_suggestion: 'Apply Draco compression to reduce geometry size by ~60%' }],
+ },
+ },
+ },
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodySchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+// Ensure the results table exists. Called once per execution; cheap via IF NOT EXISTS.
+async function ensureTable() {
+ try {
+ await sql`
+ CREATE TABLE IF NOT EXISTS avatar_optimization_results (
+ id bigserial PRIMARY KEY,
+ avatar_id uuid NOT NULL,
+ avatar_name text,
+ glb_url text NOT NULL,
+ size_bytes bigint,
+ suggestions jsonb,
+ critical_count int NOT NULL DEFAULT 0,
+ warn_count int NOT NULL DEFAULT 0,
+ info_count int NOT NULL DEFAULT 0,
+ analyzed_at timestamptz DEFAULT now(),
+ CONSTRAINT avatar_optimization_results_avatar_id_unique UNIQUE (avatar_id)
+ )
+ `;
+ } catch { /* already exists or migration handled it */ }
+}
+
+// Fetch model bytes from a public URL. Returns null on any failure.
+async function fetchModelBytes(url) {
+ try {
+ const res = await fetch(url, {
+ redirect: 'follow',
+ headers: { accept: 'model/gltf-binary,application/octet-stream' },
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
+ });
+ if (!res.ok) return null;
+ const buf = new Uint8Array(await res.arrayBuffer());
+ if (buf.byteLength > MAX_MODEL_BYTES) return null;
+ return buf;
+ } catch {
+ return null;
+ }
+}
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'POST',
+ priceAtomics: 1_000, // $0.001 USDC
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Avatar Optimization Pipeline',
+ tags: ['3d', 'avatar', 'optimization', 'gltf', 'glb', 'batch'],
+ }),
+ requiredScope: 'x402:bypass',
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+
+ async handler({ req }) {
+ // Parse optional body params.
+ let limit = MAX_BATCH;
+ try {
+ const chunks = [];
+ for await (const c of req) chunks.push(c);
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
+ if (body.limit && typeof body.limit === 'number') {
+ limit = Math.max(1, Math.min(MAX_BATCH, Math.floor(body.limit)));
+ }
+ } catch { /* default limit */ }
+
+ await ensureTable();
+
+ // Fetch top N most-viewed public avatars with their storage keys.
+ const avatarRows = await sql`
+ SELECT id, name, storage_key, baked_storage_key, size_bytes, visibility
+ FROM avatars
+ WHERE deleted_at IS NULL
+ AND visibility IN ('public', 'unlisted')
+ AND storage_key IS NOT NULL
+ ORDER BY view_count DESC NULLS LAST, created_at DESC
+ LIMIT ${limit}
+ `;
+
+ if (!avatarRows.length) {
+ return { analyzed: 0, critical_count: 0, warn_count: 0, info_count: 0, total_size_bytes: 0, avatars: [] };
+ }
+
+ let totalCritical = 0;
+ let totalWarn = 0;
+ let totalInfo = 0;
+ let totalBytes = 0;
+ const results = [];
+
+ for (const row of avatarRows) {
+ // Use baked key when available (same logic as resolveAvatarUrl's _servedStorageKey).
+ const storageKey = row.baked_storage_key || row.storage_key;
+ const glbUrl = publicUrl(storageKey);
+
+ let suggestions = [];
+ let sizeBytes = Number(row.size_bytes || 0);
+ let criticalCount = 0;
+ let warnCount = 0;
+ let infoCount = 0;
+
+ const bytes = await fetchModelBytes(glbUrl);
+ if (bytes) {
+ try {
+ sizeBytes = bytes.byteLength;
+ const info = await inspectModel(bytes, { fileSize: bytes.byteLength });
+ suggestions = suggestOptimizations(info);
+ for (const s of suggestions) {
+ if (s.severity === 'critical') criticalCount++;
+ else if (s.severity === 'warn') warnCount++;
+ else infoCount++;
+ }
+ } catch { /* malformed model — skip optimization, record zero suggestions */ }
+ }
+
+ totalCritical += criticalCount;
+ totalWarn += warnCount;
+ totalInfo += infoCount;
+ totalBytes += sizeBytes;
+
+ // Upsert results — latest analysis wins.
+ try {
+ await sql`
+ INSERT INTO avatar_optimization_results
+ (avatar_id, avatar_name, glb_url, size_bytes, suggestions,
+ critical_count, warn_count, info_count, analyzed_at)
+ VALUES
+ (${row.id}, ${row.name}, ${glbUrl}, ${sizeBytes},
+ ${JSON.stringify(suggestions)}::jsonb,
+ ${criticalCount}, ${warnCount}, ${infoCount}, now())
+ ON CONFLICT (avatar_id) DO UPDATE SET
+ avatar_name = EXCLUDED.avatar_name,
+ glb_url = EXCLUDED.glb_url,
+ size_bytes = EXCLUDED.size_bytes,
+ suggestions = EXCLUDED.suggestions,
+ critical_count = EXCLUDED.critical_count,
+ warn_count = EXCLUDED.warn_count,
+ info_count = EXCLUDED.info_count,
+ analyzed_at = now()
+ `;
+ } catch { /* DB write failure is non-fatal — analysis still succeeds */ }
+
+ results.push({
+ id: row.id,
+ name: row.name,
+ size_bytes: sizeBytes,
+ critical_count: criticalCount,
+ warn_count: warnCount,
+ info_count: infoCount,
+ top_suggestion: suggestions.find((s) => s.severity === 'critical')?.message
+ || suggestions.find((s) => s.severity === 'warn')?.message
+ || null,
+ });
+ }
+
+ return {
+ analyzed: results.length,
+ critical_count: totalCritical,
+ warn_count: totalWarn,
+ info_count: totalInfo,
+ total_size_bytes: totalBytes,
+ avatars: results,
+ };
+ },
+});
diff --git a/api/x402/model-validation-sweep.js b/api/x402/model-validation-sweep.js
new file mode 100644
index 000000000..58f15588c
--- /dev/null
+++ b/api/x402/model-validation-sweep.js
@@ -0,0 +1,314 @@
+// POST /api/x402/model-validation-sweep
+//
+// Paid endpoint ($0.001 USDC) that validates the next public GLB avatar in the
+// database awaiting inspection. Called by the autonomous spend loop on a
+// scheduled tick — each call validates one avatar and upserts a quality-score
+// row into `model_quality_scores`.
+//
+// The sweep cycles through public avatars ordered by last inspection time
+// (NULLS FIRST), so every model is covered before any model is re-checked.
+// After 24 hours each row goes stale and re-enters the queue.
+//
+// Downstream consumer: model_quality_scores is queried by the explore/discovery
+// surface to surface quality badges and by future curation pipelines that flag
+// models needing attention (missing rig, critical geometry errors, oversized
+// textures, etc.). The quality score is also available to the MCP inspect_model
+// tool to return pre-cached results.
+
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { priceFor } from '../_lib/x402-prices.js';
+import { sql } from '../_lib/db.js';
+import { inspectModel, suggestOptimizations } from '../_lib/model-inspect.js';
+import { getObjectBuffer } from '../_lib/r2.js';
+
+const ROUTE = '/api/x402/model-validation-sweep';
+const MAX_BYTES = 16 * 1024 * 1024; // 16 MB cap — mirrors model-check.js
+const STALE_AFTER = "24 hours";
+
+const DESCRIPTION =
+ 'three.ws model quality sweep — picks the next public GLB avatar in the ' +
+ 'database that has never been inspected (or whose inspection is older than ' +
+ '24 hours), downloads the file, runs the glTF-Transform inspector, computes ' +
+ 'a 0-100 quality score, and records a time-series row. Use to proactively ' +
+ 'detect geometry errors, missing rigs, and unsupported features before users ' +
+ 'encounter them in the viewer.';
+
+const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ properties: {},
+ additionalProperties: false,
+};
+
+const OUTPUT_EXAMPLE = {
+ ok: true,
+ avatar_id: 'a3f3d6c2-1f1b-4f10-9b6c-1b1f5e0c9c34',
+ avatar_name: 'Realistic Male',
+ score: 82,
+ has_errors: false,
+ missing_bones: false,
+ counts: {
+ scenes: 1, nodes: 22, meshes: 4, materials: 3, textures: 5,
+ animations: 12, skins: 1, totalVertices: 8432, totalTriangles: 14200,
+ indexedPrimitives: 4, nonIndexedPrimitives: 0,
+ },
+ extensions_used: ['KHR_draco_mesh_compression'],
+ file_size_bytes: 1572864,
+ inspected_at: '2026-06-27T10:00:00.000Z',
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['ok'],
+ properties: {
+ ok: { type: 'boolean' },
+ skipped: { type: 'boolean' },
+ reason: { type: 'string' },
+ avatar_id: { type: 'string', format: 'uuid' },
+ avatar_name: { type: ['string', 'null'] },
+ score: { type: 'integer', minimum: 0, maximum: 100 },
+ has_errors: { type: 'boolean' },
+ missing_bones: { type: 'boolean' },
+ counts: { type: 'object' },
+ extensions_used: { type: 'array', items: { type: 'string' } },
+ file_size_bytes: { type: ['integer', 'null'] },
+ inspected_at: { type: 'string', format: 'date-time' },
+ },
+};
+
+const BAZAAR = {
+ discoverable: true,
+ info: {
+ input: { type: 'http', method: 'POST', body: {} },
+ output: { type: 'json', example: OUTPUT_EXAMPLE },
+ },
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodySchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+async function ensureSchema() {
+ try {
+ await sql`
+ CREATE TABLE IF NOT EXISTS model_quality_scores (
+ id bigserial PRIMARY KEY,
+ avatar_id uuid NOT NULL,
+ score int NOT NULL DEFAULT 0,
+ geometry_errors int NOT NULL DEFAULT 0,
+ missing_bones boolean NOT NULL DEFAULT false,
+ unsupported_features text[],
+ file_size_bytes bigint,
+ vertices int,
+ triangles int,
+ materials int,
+ textures int,
+ animations int,
+ skins int,
+ extensions_used text[],
+ response_data jsonb,
+ inspected_at timestamptz DEFAULT now(),
+ UNIQUE (avatar_id)
+ )
+ `;
+ } catch { /* already exists or migration system handles it */ }
+}
+
+function computeScore(info) {
+ let score = 100;
+ const c = info.counts;
+
+ // No rig — model won't animate in the three.ws viewer
+ if (!c.skins || c.skins === 0) score -= 20;
+ // No animation clips packed in the file
+ if (!c.animations || c.animations === 0) score -= 10;
+ // Non-indexed primitives waste GPU bandwidth
+ if ((c.nonIndexedPrimitives || 0) > 0) {
+ const total = (c.indexedPrimitives || 0) + (c.nonIndexedPrimitives || 0);
+ const ratio = total > 0 ? c.nonIndexedPrimitives / total : 0;
+ score -= Math.round(ratio * 15);
+ }
+ // Oversized file
+ if (info.fileSize > 20 * 1024 * 1024) score -= 15;
+ else if (info.fileSize > 10 * 1024 * 1024) score -= 7;
+ // Excessive triangle count
+ if ((c.totalTriangles || 0) > 1_000_000) score -= 15;
+ else if ((c.totalTriangles || 0) > 500_000) score -= 8;
+ // Excessive material count raises draw-call overhead
+ if ((c.materials || 0) > 20) score -= 5;
+ // No geometry at all
+ if (!c.meshes || c.meshes === 0) score -= 30;
+
+ return Math.max(0, Math.min(100, score));
+}
+
+async function fetchAvatarBytes(storageKey) {
+ // storage_key is either an R2 object key (u/{ownerId}/…) or an absolute URL
+ // for first-party / externally-hosted models.
+ if (/^https?:\/\//i.test(storageKey)) {
+ const res = await fetch(storageKey, {
+ headers: { accept: 'model/gltf-binary,application/octet-stream,*/*' },
+ signal: AbortSignal.timeout(20_000),
+ });
+ if (!res.ok) {
+ throw Object.assign(new Error(`upstream ${res.status} ${res.statusText}`), { code: 'fetch_failed' });
+ }
+ const arr = await res.arrayBuffer();
+ if (arr.byteLength > MAX_BYTES) {
+ throw Object.assign(new Error(`model is ${arr.byteLength} bytes; max is ${MAX_BYTES}`), { code: 'too_large' });
+ }
+ return new Uint8Array(arr);
+ }
+
+ // R2-backed key — direct bucket read, no presign needed server-side.
+ const buf = await getObjectBuffer(storageKey);
+ if (buf.byteLength > MAX_BYTES) {
+ throw Object.assign(new Error(`model is ${buf.byteLength} bytes; max is ${MAX_BYTES}`), { code: 'too_large' });
+ }
+ return new Uint8Array(buf);
+}
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'POST',
+ priceAtomics: priceFor('model-validation-sweep', '1000'),
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Model Validation Sweep',
+ tags: ['3d', 'gltf', 'glb', 'validation', 'quality', 'sweep'],
+ }),
+
+ async handler() {
+ await ensureSchema();
+
+ // Pick the public avatar that has been waiting longest for inspection.
+ // NULLS FIRST ensures never-inspected avatars run before stale ones.
+ const [avatar] = await sql`
+ SELECT a.id, a.storage_key, a.name
+ FROM avatars a
+ LEFT JOIN model_quality_scores mqs ON mqs.avatar_id = a.id
+ WHERE a.deleted_at IS NULL
+ AND a.visibility = 'public'
+ AND a.storage_key IS NOT NULL
+ AND (
+ mqs.inspected_at IS NULL
+ OR mqs.inspected_at < NOW() - INTERVAL '24 hours'
+ )
+ ORDER BY mqs.inspected_at ASC NULLS FIRST, a.created_at ASC
+ LIMIT 1
+ `;
+
+ if (!avatar) {
+ return { ok: true, skipped: true, reason: 'all_models_fresh' };
+ }
+
+ const now = new Date().toISOString();
+ let info;
+ let fetchError = null;
+
+ try {
+ const bytes = await fetchAvatarBytes(avatar.storage_key);
+ info = await inspectModel(bytes, { fileSize: bytes.byteLength });
+ } catch (err) {
+ fetchError = err?.message || String(err);
+ }
+
+ if (fetchError || !info) {
+ // Still record the attempt so the avatar doesn't block the queue.
+ await sql`
+ INSERT INTO model_quality_scores
+ (avatar_id, score, geometry_errors, missing_bones,
+ response_data, inspected_at)
+ VALUES
+ (${avatar.id}, 0, 0, true,
+ ${JSON.stringify({ error: fetchError })}::jsonb, ${now})
+ ON CONFLICT (avatar_id) DO UPDATE SET
+ score = 0,
+ response_data = ${JSON.stringify({ error: fetchError })}::jsonb,
+ inspected_at = ${now}
+ `.catch((dbErr) =>
+ console.error('[model-validation-sweep] error_log_failed', dbErr?.message),
+ );
+
+ return {
+ ok: false,
+ avatar_id: avatar.id,
+ avatar_name: avatar.name || null,
+ error: fetchError,
+ inspected_at: now,
+ };
+ }
+
+ const c = info.counts;
+ const score = computeScore(info);
+ const missingBones = !c.skins || c.skins === 0;
+ const suggestions = suggestOptimizations(info);
+ const hasErrors = suggestions.some((s) => s.severity === 'critical');
+ const extUsed = Array.isArray(info.extensionsUsed) && info.extensionsUsed.length > 0
+ ? info.extensionsUsed
+ : null;
+
+ await sql`
+ INSERT INTO model_quality_scores
+ (avatar_id, score, geometry_errors, missing_bones, file_size_bytes,
+ vertices, triangles, materials, textures, animations, skins,
+ extensions_used, response_data, inspected_at)
+ VALUES
+ (${avatar.id}, ${score}, ${hasErrors ? 1 : 0}, ${missingBones},
+ ${info.fileSize ?? null},
+ ${c.totalVertices ?? null}, ${c.totalTriangles ?? null},
+ ${c.materials ?? null}, ${c.textures ?? null},
+ ${c.animations ?? null}, ${c.skins ?? null},
+ ${extUsed},
+ ${JSON.stringify({ info, suggestions })}::jsonb, ${now})
+ ON CONFLICT (avatar_id) DO UPDATE SET
+ score = EXCLUDED.score,
+ geometry_errors = EXCLUDED.geometry_errors,
+ missing_bones = EXCLUDED.missing_bones,
+ file_size_bytes = EXCLUDED.file_size_bytes,
+ vertices = EXCLUDED.vertices,
+ triangles = EXCLUDED.triangles,
+ materials = EXCLUDED.materials,
+ textures = EXCLUDED.textures,
+ animations = EXCLUDED.animations,
+ skins = EXCLUDED.skins,
+ extensions_used = EXCLUDED.extensions_used,
+ response_data = EXCLUDED.response_data,
+ inspected_at = EXCLUDED.inspected_at
+ `.catch((dbErr) => {
+ // Log but don't fail — caller already paid and the result is valid.
+ console.error('[model-validation-sweep] db_upsert_failed', dbErr?.message);
+ });
+
+ return {
+ ok: true,
+ avatar_id: avatar.id,
+ avatar_name: avatar.name || null,
+ score,
+ has_errors: hasErrors,
+ missing_bones: missingBones,
+ counts: {
+ scenes: c.scenes ?? 0,
+ nodes: c.nodes ?? 0,
+ meshes: c.meshes ?? 0,
+ materials: c.materials ?? 0,
+ textures: c.textures ?? 0,
+ animations: c.animations ?? 0,
+ skins: c.skins ?? 0,
+ totalVertices: c.totalVertices ?? 0,
+ totalTriangles: c.totalTriangles ?? 0,
+ indexedPrimitives: c.indexedPrimitives ?? 0,
+ nonIndexedPrimitives: c.nonIndexedPrimitives ?? 0,
+ },
+ extensions_used: info.extensionsUsed || [],
+ file_size_bytes: info.fileSize ?? null,
+ inspected_at: now,
+ };
+ },
+});
diff --git a/api/x402/solana-register-health.js b/api/x402/solana-register-health.js
new file mode 100644
index 000000000..f8d778ee5
--- /dev/null
+++ b/api/x402/solana-register-health.js
@@ -0,0 +1,321 @@
+// GET /api/x402/solana-register-health
+//
+// Solana Agent Registration Health Check — the paid, x402-reachable canary for
+// three.ws's server-custodial Solana agent-registration subsystem (the path the
+// MCP `register_agent` tool drives: mint a Metaplex Core asset → enrol it in the
+// Metaplex Agent Registry → index its on-chain record).
+//
+// Why a dedicated endpoint instead of calling `register_agent` directly:
+// `register_agent` is ACCOUNT-SCOPED — its handler returns `sign_in_required`
+// for any pay-per-call (x402) principal, and it MINTS new on-chain state on a
+// cold key (non-idempotent). An autonomous x402 spend loop can neither
+// authenticate as a user nor responsibly mint a fresh identity every tick. So
+// the honest canary verifies the *resulting on-chain record* of a known,
+// already-registered agent — exactly the "check the resulting on-chain record
+// exists" the health check calls for — without minting anything new.
+//
+// What it verifies, end-to-end, against live infrastructure:
+// 1. The canary agent resolves in the three.ws index (agent_identities).
+// 2. Its Agent Registry enrolment is recorded (meta.agent_registry.identity_pda).
+// 3. Both the Identity PDA and the Core asset accounts EXIST on-chain right now
+// (getAccountInfo over the failover RPC pool) — proving the registry write
+// landed and the RPC read path is healthy.
+//
+// Every call (autonomous loop OR any bazaar buyer) upserts the canonical health
+// row in `mcp_health_canary` (shared by all MCP-Health canaries — see
+// agents/x402-buildout/self/) and emits an alert log when the subsystem trips.
+//
+// Canary selection (real data only — never a mock):
+// X402_CANARY_AGENT_ID a known three.ws agent_id (uuid) registered on Solana
+// X402_CANARY_AGENT_ASSET a known Core asset pubkey (skips the agent_id lookup)
+// else the most-recently-registered live agent — verifying
+// any real on-chain record still exercises the full path.
+
+import { PublicKey } from '@solana/web3.js';
+
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { priceFor } from '../_lib/x402-prices.js';
+import { sql } from '../_lib/db.js';
+import { env } from '../_lib/env.js';
+import { isUuid } from '../_lib/validate.js';
+import { solanaConnection } from '../_lib/solana/connection.js';
+import { logger } from '../_lib/usage.js';
+import { explorerUrl } from '../_lib/onchain-deploy.js';
+
+const ROUTE = '/api/x402/solana-register-health';
+const TOOL_NAME = 'solana_register';
+// Consecutive failures before the canary escalates from a warn to an alert log.
+const ALERT_THRESHOLD = 3;
+
+const log = logger('x402-solana-register-health');
+
+const DESCRIPTION =
+ 'Solana Agent Registration Health Check — verifies three.ws\'s server-custodial ' +
+ 'Solana agent-registration subsystem end-to-end by resolving a known canary ' +
+ 'agent\'s on-chain Metaplex Agent Registry record (Identity PDA + Core asset) ' +
+ 'and confirming both accounts exist on-chain right now. Returns a health ' +
+ 'snapshot with latency and the checked asset. Pay-per-call in USDC on Solana ' +
+ 'or Base mainnet.';
+
+const OUTPUT_EXAMPLE = {
+ tool: 'solana_register',
+ healthy: true,
+ network: 'mainnet',
+ canary_agent_id: '7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55',
+ asset: 'THREEsynthetic1111111111111111111111111111',
+ identity_pda: 'AgentRegyPDA11111111111111111111111111111111',
+ registration_uri: 'https://three.ws/api/agents/7b9a4f30/registration.json',
+ checks: { indexed: true, registry_enrolled: true, asset_onchain: true, identity_pda_onchain: true },
+ rpc_latency_ms: 184,
+ checked_at: '2026-06-27T18:00:00Z',
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['tool', 'healthy', 'checks', 'checked_at'],
+ properties: {
+ tool: { type: 'string' },
+ healthy: { type: 'boolean' },
+ network: { type: ['string', 'null'] },
+ canary_agent_id: { type: ['string', 'null'] },
+ asset: { type: ['string', 'null'] },
+ identity_pda: { type: ['string', 'null'] },
+ registration_uri: { type: ['string', 'null'] },
+ reason: { type: ['string', 'null'] },
+ checks: {
+ type: 'object',
+ properties: {
+ indexed: { type: 'boolean' },
+ registry_enrolled: { type: 'boolean' },
+ asset_onchain: { type: 'boolean' },
+ identity_pda_onchain: { type: 'boolean' },
+ },
+ },
+ rpc_latency_ms: { type: ['integer', 'null'] },
+ consecutive_failures: { type: 'integer' },
+ checked_at: { type: 'string', format: 'date-time' },
+ },
+};
+
+const BAZAAR = {
+ discoverable: true,
+ info: {
+ input: { type: 'http', method: 'GET', queryParams: {} },
+ output: { type: 'json', example: OUTPUT_EXAMPLE },
+ },
+ schema: buildBazaarSchema({ method: 'GET', outputSchema: OUTPUT_SCHEMA }),
+};
+
+// Resolve the canary agent row. Prefers an explicitly-configured agent, falls
+// back to the most-recently-registered live agent so the probe still exercises
+// a real on-chain record in production even when no canary env is set.
+async function resolveCanaryAgent() {
+ const explicitId = String(env.X402_CANARY_AGENT_ID || process.env.X402_CANARY_AGENT_ID || '').trim();
+ const explicitAsset = String(env.X402_CANARY_AGENT_ASSET || process.env.X402_CANARY_AGENT_ASSET || '').trim();
+
+ if (explicitId && isUuid(explicitId)) {
+ const [row] = await sql`
+ select id, name, wallet_address as owner, meta
+ from agent_identities
+ where id = ${explicitId} and deleted_at is null
+ limit 1
+ `;
+ if (row) return { row, source: 'env_agent_id' };
+ }
+
+ if (explicitAsset) {
+ const [row] = await sql`
+ select id, name, wallet_address as owner, meta
+ from agent_identities
+ where meta->>'sol_mint_address' = ${explicitAsset} and deleted_at is null
+ limit 1
+ `;
+ if (row) return { row, source: 'env_asset' };
+ // Asset given but not in our index — still verifiable purely on-chain.
+ return { row: { id: null, name: null, owner: null, meta: { sol_mint_address: explicitAsset } }, source: 'env_asset_offindex' };
+ }
+
+ // Fallback: any genuinely-registered agent. Verifying its on-chain record
+ // still proves the registry write + indexer + RPC read path are healthy.
+ const [row] = await sql`
+ select id, name, wallet_address as owner, meta
+ from agent_identities
+ where deleted_at is null
+ and meta->'agent_registry'->>'identity_pda' is not null
+ order by updated_at desc nulls last
+ limit 1
+ `;
+ if (row) return { row, source: 'latest_registered' };
+ return { row: null, source: 'none' };
+}
+
+// Pull the registration coordinates out of an agent's meta for either network.
+function readRegistration(meta) {
+ const m = meta || {};
+ const mainnet = m.sol_mint_address
+ ? { network: 'mainnet', asset: m.sol_mint_address, registry: m.agent_registry || null }
+ : null;
+ const devnet = m.devnet?.sol_mint_address
+ ? { network: 'devnet', asset: m.devnet.sol_mint_address, registry: m.devnet.agent_registry || null }
+ : null;
+ return mainnet || devnet || { network: 'mainnet', asset: null, registry: null };
+}
+
+// Confirm an account exists on-chain. Returns false on a malformed pubkey or any
+// RPC error — the canary treats "couldn't confirm" as unhealthy, not a crash.
+async function accountExists(conn, pubkey) {
+ if (!pubkey) return false;
+ let key;
+ try { key = new PublicKey(pubkey); } catch { return false; }
+ try {
+ const info = await conn.getAccountInfo(key, 'confirmed');
+ return info !== null;
+ } catch {
+ return false;
+ }
+}
+
+// Persist the canonical health row shared by every MCP-Health canary. On a
+// healthy result the failure counter resets; on failure it increments so a
+// status dashboard (and the alert threshold below) can see a sustained outage.
+async function recordHealth({ healthy, reason, detail, txSignature }) {
+ try {
+ const [row] = await sql`
+ INSERT INTO mcp_health_canary
+ (tool_name, healthy, last_checked_at, last_ok_at,
+ consecutive_failures, last_error, detail, last_tx_signature)
+ VALUES
+ (${TOOL_NAME}, ${healthy}, now(),
+ ${healthy ? sql`now()` : null},
+ ${healthy ? 0 : 1}, ${healthy ? null : reason || 'unhealthy'},
+ ${JSON.stringify(detail || {})}, ${txSignature || null})
+ ON CONFLICT (tool_name) DO UPDATE SET
+ healthy = EXCLUDED.healthy,
+ last_checked_at = now(),
+ last_ok_at = CASE WHEN EXCLUDED.healthy THEN now() ELSE mcp_health_canary.last_ok_at END,
+ consecutive_failures = CASE WHEN EXCLUDED.healthy THEN 0 ELSE mcp_health_canary.consecutive_failures + 1 END,
+ last_error = CASE WHEN EXCLUDED.healthy THEN null ELSE EXCLUDED.last_error END,
+ detail = EXCLUDED.detail,
+ last_tx_signature = COALESCE(EXCLUDED.last_tx_signature, mcp_health_canary.last_tx_signature)
+ RETURNING consecutive_failures
+ `;
+ return row?.consecutive_failures ?? 0;
+ } catch (err) {
+ // Table missing on a fresh deploy — create once, then the next call records.
+ if (/does not exist|relation .* does not exist/i.test(err?.message || '')) {
+ await ensureHealthTable();
+ } else {
+ log.warn('mcp_health_canary_upsert_failed', { message: err?.message });
+ }
+ return healthy ? 0 : 1;
+ }
+}
+
+async function ensureHealthTable() {
+ try {
+ await sql`
+ CREATE TABLE IF NOT EXISTS mcp_health_canary (
+ tool_name text PRIMARY KEY,
+ healthy boolean NOT NULL,
+ last_checked_at timestamptz NOT NULL DEFAULT now(),
+ last_ok_at timestamptz,
+ consecutive_failures int NOT NULL DEFAULT 0,
+ last_error text,
+ detail jsonb,
+ last_tx_signature text
+ )
+ `;
+ } catch (err) {
+ log.warn('mcp_health_canary_create_failed', { message: err?.message });
+ }
+}
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ // $0.001 USDC = 1000 atomics (6-decimal). Override via X402_PRICE_SOLANA_REGISTER_HEALTH.
+ priceAtomics: priceFor('solana-register-health', '1000'),
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ services: ['solana-register-health'],
+ service: withService({
+ serviceName: 'three.ws Solana Registration Health',
+ tags: ['health', 'solana', 'registration', 'agent', 'canary', 'mcp'],
+ }),
+ async handler() {
+ await ensureHealthTable();
+ const checkedAt = new Date().toISOString();
+ const checks = { indexed: false, registry_enrolled: false, asset_onchain: false, identity_pda_onchain: false };
+
+ // 1. Resolve the canary.
+ const { row: agent, source } = await resolveCanaryAgent();
+ if (!agent) {
+ // No registered agent exists yet to probe. This is an ops/config gap,
+ // not a subsystem outage, so we surface it without tripping the failure
+ // counter (record as healthy:false but reason-tagged, no increment past 1).
+ const detail = { source, reason: 'no_canary_registered' };
+ await recordHealth({ healthy: false, reason: 'no_canary_registered', detail });
+ log.warn('solana_register_canary_unconfigured', detail);
+ return {
+ tool: TOOL_NAME, healthy: false, reason: 'no_canary_registered',
+ network: null, canary_agent_id: null, asset: null, identity_pda: null,
+ registration_uri: null, checks, rpc_latency_ms: null,
+ consecutive_failures: 1, checked_at: checkedAt,
+ };
+ }
+
+ checks.indexed = true;
+ const reg = readRegistration(agent.meta);
+ const identityPda = reg.registry?.identity_pda || null;
+ const asset = reg.asset || null;
+ const registrationUri = reg.registry?.registration_uri || null;
+ checks.registry_enrolled = !!identityPda;
+
+ // 2. Verify the on-chain records exist right now.
+ const conn = solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });
+ const t0 = Date.now();
+ const [assetOk, pdaOk] = await Promise.all([
+ accountExists(conn, asset),
+ identityPda ? accountExists(conn, identityPda) : Promise.resolve(false),
+ ]);
+ const rpcLatencyMs = Date.now() - t0;
+ checks.asset_onchain = assetOk;
+ checks.identity_pda_onchain = pdaOk;
+
+ // Healthy = enrolled in the registry AND both on-chain accounts resolve.
+ const healthy = checks.registry_enrolled && checks.asset_onchain && checks.identity_pda_onchain;
+
+ const detail = {
+ source, network: reg.network, agent_id: agent.id, asset, identity_pda: identityPda, checks, rpc_latency_ms: rpcLatencyMs,
+ };
+ const consecutiveFailures = await recordHealth({ healthy, reason: !healthy ? 'onchain_record_missing' : null, detail });
+
+ if (!healthy) {
+ const level = consecutiveFailures >= ALERT_THRESHOLD ? 'error' : 'warn';
+ log[level]('solana_register_canary_unhealthy', {
+ agent_id: agent.id, asset, identity_pda: identityPda,
+ checks, consecutive_failures: consecutiveFailures,
+ });
+ }
+
+ return {
+ tool: TOOL_NAME,
+ healthy,
+ network: reg.network,
+ canary_agent_id: agent.id,
+ asset,
+ identity_pda: identityPda,
+ registration_uri: registrationUri,
+ explorer_url: identityPda ? explorerUrl(identityPda, reg.network) : null,
+ reason: healthy ? null : 'onchain_record_missing',
+ checks,
+ rpc_latency_ms: rpcLatencyMs,
+ consecutive_failures: consecutiveFailures,
+ checked_at: checkedAt,
+ };
+ },
+});
diff --git a/data/changelog.json b/data/changelog.json
index 63c3fd1bb..9d5745b7c 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,18 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-27",
+ "title": "MCP Model Validation Sweep — proactive GLB quality scoring",
+ "summary": "The platform now runs a continuous quality sweep across every public 3D avatar in the database. Every 5 minutes the autonomous agent picks the longest-unvalidated GLB, inspects it with the glTF-Transform engine, and records a 0-100 quality score covering rig completeness, geometry health, texture sizing, triangle budget, and unsupported extensions. Results are stored in a time-series table (model_quality_scores) that will power quality badges and curation tools — surfacing models that need attention before users encounter errors in the viewer. The sweep is driven by the x402 autonomous spend loop at $0.001 USDC per call.",
+ "tags": ["feature", "infra"]
+ },
+ {
+ "date": "2026-06-27",
+ "title": "Avatar Optimization Pipeline — nightly analysis of top avatars",
+ "summary": "The platform now runs a nightly optimization sweep across the 50 most-viewed public avatars. Each model is analyzed for geometry and texture inefficiencies — Draco/Meshopt compression opportunities, oversized textures ready for KTX2 transcoding, non-indexed primitives, and redundant materials. Results are stored per-avatar so we can surface actionable improvement suggestions to creators. The pipeline runs autonomously via the x402 agent spend loop, paying $0.001 USDC per nightly batch.",
+ "tags": ["feature", "infra"]
+ },
{
"date": "2026-06-27",
"title": "Production stability fixes — genome lineage, screen streaming, and x402 seeder",
diff --git a/public/changelog.json b/public/changelog.json
index 56c43992e..dd938d42c 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-27T22:51:18.622Z",
+ "generated_at": "2026-06-27T23:01:09.161Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -140,6 +140,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "Avatar Optimization Pipeline — nightly analysis of top avatars",
+ "summary": "The platform now runs a nightly optimization sweep across the 50 most-viewed public avatars. Each model is analyzed for geometry and texture inefficiencies — Draco/Meshopt compression opportunities, oversized textures ready for KTX2 transcoding, non-indexed primitives, and redundant materials. Results are stored per-avatar so we can surface actionable improvement suggestions to creators. The pipeline runs autonomously via the x402 agent spend loop, paying $0.001 USDC per nightly batch.",
+ "link": null,
+ "tags": [
+ "feature",
+ "infra"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
@@ -270,6 +281,17 @@
"feature"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "MCP Model Validation Sweep — proactive GLB quality scoring",
+ "summary": "The platform now runs a continuous quality sweep across every public 3D avatar in the database. Every 5 minutes the autonomous agent picks the longest-unvalidated GLB, inspects it with the glTF-Transform engine, and records a 0-100 quality score covering rig completeness, geometry health, texture sizing, triangle budget, and unsupported extensions. Results are stored in a time-series table (model_quality_scores) that will power quality badges and curation tools — surfacing models that need attention before users encounter errors in the viewer. The sweep is driven by the x402 autonomous spend loop at $0.001 USDC per call.",
+ "link": null,
+ "tags": [
+ "feature",
+ "infra"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 08a1b1663..e3887d373 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -110,6 +110,14 @@
<category>feature</category>
<description>The memetic launcher now auto-claims pump.fun creator fees from every coin it mints, routing the configured share toward $THREE. The admin console at /admin/launcher gains a live revenue panel (total creator fees claimed, $THREE allocated), agent-name visibility in the run feed, a Force Tick button for instant testing, and a cleaner 8-column stat grid. Know Your Meme is wired as a live trend source alongside Hacker News, Reddit, and Wikipedia — so the launcher reads what the internet is actually minting.</description>
</item>
+ <item>
+ <title>Avatar Optimization Pipeline — nightly analysis of top avatars</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:Avatar Optimization Pipeline — nightly analysis of top avatars</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The platform now runs a nightly optimization sweep across the 50 most-viewed public avatars. Each model is analyzed for geometry and texture inefficiencies — Draco/Meshopt compression opportunities, oversized textures ready for KTX2 transcoding, non-indexed primitives, and redundant materials. Results are stored per-avatar so we can surface actionable improvement suggestions to creators. The pipeline runs autonomously via the x402 agent spend loop, paying $0.001 USDC per nightly batch.</description>
+ </item>
<item>
<title>Capabilities dashboard — live command center for all 4 autonomous features</title>
<link>https://three.ws/dashboard/capabilities</link>
@@ -206,6 +214,14 @@
<category>feature</category>
<description>AWS Marketplace subscribers (and anyone with an x402 subscription key) now have a home for it at /billing/keys. See every key with its billing source — AWS Marketplace or on-chain — live status, rate limit, total calls, and when it was last used. Rotate a key to get a fresh secret in one click (AWS-billed keys stay linked to your AWS account and keep metering correctly), or revoke a native key outright. The post-subscribe welcome flow now points here, so a lost key is always recoverable by rotating instead of being stuck.</description>
</item>
+ <item>
+ <title>MCP Model Validation Sweep — proactive GLB quality scoring</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:MCP Model Validation Sweep — proactive GLB quality scoring</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The platform now runs a continuous quality sweep across every public 3D avatar in the database. Every 5 minutes the autonomous agent picks the longest-unvalidated GLB, inspects it with the glTF-Transform engine, and records a 0-100 quality score covering rig completeness, geometry health, texture sizing, triangle budget, and unsupported extensions. Results are stored in a time-series table (model_quality_scores) that will power quality badges and curation tools — surfacing models that need attention before users encounter errors in the viewer. The sweep is driven by the x402 autonomous spend loop at $0.001 USDC per call.</description>
+ </item>
<item>
<title>Money Pulse now shows whether agent trading is viable</title>
<link>https://three.ws/pulse</link>
diff --git a/public/features.json b/public/features.json
index daa738a22..801f9740b 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-27T22:51:18.605Z",
+ "generated_at": "2026-06-27T23:01:09.135Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",