Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Add agent-economy, wallet API, deployments, and press-kit docs; MCP safety fixture suite; settle-recovery and sweepback tests
nirholaseae7b2e6c43e
diff --git a/README.md b/README.mdindex 048b6933e..5e329ff24 100644--- a/README.md+++ b/README.md@@ -1,10 +1,12 @@# three.ws-[**Website**](https://three.ws) · [**X / Twitter**](https://x.com/trythreews) · [**GitHub**](https://github.com/nirholas/three.ws) · [**$THREE on pump.fun**](https://pump.fun/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump)+[**Website**](https://three.ws) · [**Docs**](https://three.ws/docs) · [**Changelog**](https://three.ws/changelog) · [**X / Twitter**](https://x.com/trythreews) · [**GitHub**](https://github.com/nirholas/three.ws) · [**$THREE on pump.fun**](https://pump.fun/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump)++[](https://three.ws) [](https://www.npmjs.com/package/@three-ws/sdk) [](https://www.npmjs.com/package/@three-ws/mcp-server) [](https://registry.modelcontextprotocol.io/?q=io.github.nirholas) [](https://www.x402scan.com/server/17cbd874-52ac-4920-a020-b22ff2489a07)https://github.com/user-attachments/assets/d52515d1-cb04-4dd6-98bd-fef233312dc4-**Give your AI a body.** three.ws is an open-source, browser-native 3D AI agent platform. Type a prompt and [**Forge**](https://three.ws/forge) generates a textured 3D model — or drop a GLB you already have. Add an LLM brain, register on-chain, and embed anywhere — no plugins, no server uploads, no installs required.+**Give your AI a body.** three.ws is a source-available, browser-native 3D AI agent platform. Type a prompt and [**Forge**](https://three.ws/forge) generates a textured 3D model, or drop a GLB you already have. Add an LLM brain, register on-chain, and embed anywhere: no plugins, no server uploads, no installs required.> **Try it in 60 seconds:** open [three.ws/forge](https://three.ws/forge), type *"a brass steampunk owl, full body"*, and download the GLB. Text→3D, image→3D, and sketch→3D — free draft tier, no account. [Jump to the Forge section ↓](#forge--text--image-to-3d)@@ -8429,6 +8431,8 @@ endsolid threews_avatar| **Contract Address (CA)** | `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump` || **Network** | Solana || **Trade** | [pump.fun](https://pump.fun/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump) |+| **Explorer** | [Solscan](https://solscan.io/token/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump) |+| **In the product** | [/pulse](https://three.ws/pulse) (live platform economy) · [/launches](https://three.ws/launches) (launch directory) |> Always verify the contract address above before trading. `$THREE` is the only token associated with three.ws.@@ -8525,7 +8529,7 @@ At its core, it does five things:The backend is a set of serverless-style handlers (in `api/`) served in production by a single Google Cloud Run container ([server/index.mjs](server/index.mjs)), backed by Neon Postgres for metadata, Cloudflare R2 for model storage, and Upstash Redis for rate limiting. It exposes a full OAuth 2.1 authorization server and an MCP (Model Context Protocol) endpoint so external AI systems can drive avatars programmatically.-three.ws is production-ready and serves [three.ws](https://three.ws) live on Google Cloud Run. The entire stack — viewer, agent runtime, contracts, backend, and web component — is open source under Apache 2.0.+three.ws is production-ready and serves [three.ws](https://three.ws) live on Google Cloud Run: `GET https://three.ws/api/version` returns the exact commit the site is running right now. The entire stack (viewer, agent runtime, contracts, backend, and web component) is source-available in this repository; see [LICENSE](LICENSE) for terms.---@@ -8711,7 +8715,7 @@ A map of every user-facing route. [`STRUCTURE.md`](STRUCTURE.md) maps each produ| **Walk** | `/walk` | Authoritative multiplayer walk scene (Colyseus on Fly.io) || **Coin Communities** | `/communities`, `/communities/[mint]`, `/worlds`, `/play` | Live 3D world per Solana token — lobby, coin profile, and the shared coin-keyed world || **City** | `/city` | Free-roam walkable 3D city scene |-| **Bazaar (x402)** | `/x402`, `/x402-discover`, `/x402-pay` | Paid-API marketplace, discovery, Stripe-style checkout |+| **Bazaar (x402)** | `/x402`, `/x402/studio`, `/x402-revenue` | Paid-API marketplace, listing studio, revenue dashboard || **Artifacts** | `/artifact`, `/artifact/snippet`, `/artifact-example` | Claude Artifact viewer || **Solana / DeFi** | `/pumpfun`, `/pump-visualizer`, `/vanity-wallet` | pump.fun launcher, live token visualizer, WASM vanity grinder || **Mobile (Seeker)** | Solana Mobile dApp Store | MWA wallet wired into the web app + Seeker release pipeline |@@ -8719,7 +8723,7 @@ A map of every user-facing route. [`STRUCTURE.md`](STRUCTURE.md) maps each produ| **Admin / Rep** | `/admin`, `/reputation` | Staff admin, reputation registry || **Experiments** | `/rider` | A-Frame WebVR music visualization || **Integrations** | `/cz`, `/lobehub/iframe` | CZ demo, LobeHub plugin |-| **IBM Showcase** | `/ibm`, `/ibm/galaxy`, `/ibm/oracle`, `/ibm/twin`, `/ibm/trust-layer`, `/ibm/proof`, `/ibm/vision` | Granite on watsonx.ai — semantic galaxy, TimeSeries oracle, digital twin, Guardian trust layer, on-chain proof, vision |+| **IBM / Granite** | `/galaxy`, `/ibm/x402-demo`, `/ibm/hello` | Granite on watsonx.ai: semantic agent galaxy, pay-per-call Granite demo, hello-world embed || **Docs** | `/docs`, `/docs/widgets` | Developer documentation || **Legal** | `/legal/privacy`, `/legal/tos` | Privacy policy and terms |@@ -10204,7 +10208,7 @@ three.ws is indexed in chain-ecosystem dApp directories so the community can dis## IBM watsonx & Granite-three.ws is an **IBM Business Partner**, and the agent runtime runs on **IBM Granite** foundation models served through **IBM watsonx.ai**. One IBM Cloud API key + project unlocks the whole suite; every call is real inference (no mock path — endpoints return `503` when unconfigured). Full docs: **[docs/ibm.md](docs/ibm.md)**. Live showcase: **[three.ws/ibm/galaxy](https://three.ws/ibm/galaxy)**.+three.ws is an **IBM Business Partner**, and the agent runtime runs on **IBM Granite** foundation models served through **IBM watsonx.ai**. One IBM Cloud API key + project unlocks the whole suite; every call is real inference (no mock path: endpoints return `503` when unconfigured). Full docs: **[docs/ibm.md](docs/ibm.md)**. Live showcase: **[three.ws/galaxy](https://three.ws/galaxy)**.> **The public showcase is not the partnership.** The demos under `/ibm/*` are independent tools three.ws built for developers to explore Granite on watsonx.ai and build their own integrations — they are not official IBM partnership deliverables, not IBM products, and not endorsed by IBM. Our formal partnership work with IBM is being built on the IBM platform and is not yet public.@@ -10216,7 +10220,7 @@ three.ws is an **IBM Business Partner**, and the agent runtime runs on **IBM Gra| `granite-embedding-278m-multilingual` | **Semantic** agent map + `/api/watsonx/embed` || `granite-vision-3-2-2b` | **Vision** — reads an avatar into a full agent identity |-Six showcase surfaces put it on screen, cross-linked by an in-page suite switcher: the [Agent Galaxy](https://three.ws/ibm/galaxy) (semantic 3D star-map), the [Granite Oracle](https://three.ws/ibm/oracle) (narrated forecast), the [Digital Twin](https://three.ws/ibm/twin) (back-test + what-if), the [Trust Layer](https://three.ws/ibm/trust-layer) (Guardian + hash-chained audit ledger), [Granite Proof](https://three.ws/ibm/proof) (a Guardian-governed forecast notarized on Solana), and [Granite Vision](https://three.ws/ibm/vision). The standalone connector [`@three-ws/ibm-watsonx-mcp`](packages/ibm-watsonx-mcp/) exposes watsonx.ai to any MCP host — it is community-built and not an IBM product; the hosted platform integration is what runs on IBM watsonx.ai.+Three live surfaces put it on screen: the [Agent Galaxy](https://three.ws/galaxy) (every public agent embedded by Granite into a navigable semantic 3D star-map), the [x402 Granite demo](https://three.ws/ibm/x402-demo) (pay-per-call Granite inference settled in USDC), and the [hello-world embed](https://three.ws/ibm/hello). The backend endpoints behind them live in [api/ibm/](api/ibm/) (`galaxy`, `oracle`, `twin`, `vision`, `attest`). The standalone connector [`@three-ws/ibm-watsonx-mcp`](packages/ibm-watsonx-mcp/) ([npm](https://www.npmjs.com/package/@three-ws/ibm-watsonx-mcp)) exposes watsonx.ai to any MCP host; it is community-built and not an IBM product. The hosted platform integration is what runs on IBM watsonx.ai.### Pay-per-call Granite over MCP (x402)@@ -10271,8 +10275,9 @@ Every CDP-settled endpoint ships a Permit2 sibling that accepts an EIP-2612 perm| Surface | Path | Purpose || ------------- | --------------------------------- | ------------------------------------------- || Bazaar | `/x402` | Browsable marketplace of paid endpoints |-| Discovery | `/x402-discover` | Search by tag, price, chain |-| Checkout | `/x402-pay`, `/api/x402-checkout` | Stripe-style one-shot purchase |+| Listing studio | `/x402/studio` | Author and publish your own paid listing |+| Revenue | `/x402-revenue` | Seller revenue dashboard |+| Checkout | `/api/x402-checkout` | Stripe-style one-shot purchase || SKU catalog | `/api/x402-skus` | Server-defined SKUs with per-row pricing || Dashboard | `/dashboard/x402` | Seller + buyer dashboard, receipts, payouts || Subscriptions | `/api/x402/subscriptions` | Recurring x402 charges on cron |diff --git a/api/_lib/x402/self-facilitator.js b/api/_lib/x402/self-facilitator.jsindex e819a5a8b..6340407f9 100644--- a/api/_lib/x402/self-facilitator.js+++ b/api/_lib/x402/self-facilitator.js@@ -550,6 +550,10 @@ export async function settleRingPayment({ paymentPayload, requirement, conn, fee}let signature;+ // Set only when the preflight-off resend below is attempted and also fails, so+ // the reported reason distinguishes "our read node was stale" from "the payment+ // was genuinely unsendable".+ let preflightRetryNote = '';try {signature = await connection.sendRawTransaction(tx.serialize(), {skipPreflight: false,@@ -616,41 +620,67 @@ export async function settleRingPayment({ paymentPayload, requirement, conn, feereplayed: true,};}- // The dominant broadcast failure reaches production logs with NO cause at all:- // web3.js renders the preflight rejection as "Transaction simulation failed.- // Logs: []" and drops the structured cause (res.error.data.err), while its own- // getLogs() only reads back a LANDED transaction — useless for a tx that never- // landed. Re-simulate on the failure path to recover that cause. Deliberately- // replaceRecentBlockhash:false, unlike the assertSettleable pre-check: the point- // is to see whether the blockhash this send actually carried was unknown to the- // endpoint that answered, which is how a rotating multi-RPC pool fails when the- // hash is fetched from one node and the send lands on another.- let cause = '';- if (!/Logs: \[[^\]]/.test(m)) {+ // A preflight "blockhash not found" is usually a FALSE rejection, not a dead+ // transaction. The buyer builds and signs the payment against THEIR RPC, so the+ // blockhash it carries is real; we then preflight it on whichever node our+ // rotating pool happens to answer with, and a node lagging even a few slots+ // behind the buyer's has simply never seen that hash. web3.js surfaces that as a+ // hard send failure, so a perfectly valid payment was reported broadcast_failed+ // and the buyer 502'd having already been charged for the handler.+ // Re-sending with preflight OFF hands the decision to the validator instead of+ // our read node: if the hash is live the settle lands, and if it genuinely+ // expired the transaction is dropped without landing and without a fee, so the+ // only cost is the confirm wait below. Resending the identical signed bytes is+ // idempotent (Solana dedupes by signature), so this cannot double-settle.+ if (provablyNeverLanded) {try {- const sim = await connection.simulateTransaction(tx, {- sigVerify: false,- replaceRecentBlockhash: false,- commitment: 'confirmed',+ signature = await connection.sendRawTransaction(tx.serialize(), {+ skipPreflight: true,+ maxRetries: 5,});- const simErr = sim?.value?.err ?? null;- const simLogs = Array.isArray(sim?.value?.logs) ? sim.value.logs : [];- if (simErr) {- cause = ` cause:${typeof simErr === 'object' ? JSON.stringify(simErr) : String(simErr)}`;+ } catch (retryErr) {+ preflightRetryNote = ` preflight_retry_failed:${String(retryErr?.message || retryErr).slice(0, 120)}`;+ }+ }+ // Only report a broadcast failure if the preflight-off resend above did not+ // produce a signature; otherwise fall through to the confirm step below.+ if (signature == null) {+ // The dominant broadcast failure reaches production logs with NO cause at all:+ // web3.js renders the preflight rejection as "Transaction simulation failed.+ // Logs: []" and drops the structured cause (res.error.data.err), while its own+ // getLogs() only reads back a LANDED transaction, useless for a tx that never+ // landed. Re-simulate on the failure path to recover that cause. Deliberately+ // replaceRecentBlockhash:false, unlike the assertSettleable pre-check: the point+ // is to see whether the blockhash this send actually carried was unknown to the+ // endpoint that answered, which is how a rotating multi-RPC pool fails when the+ // hash is fetched from one node and the send lands on another.+ let cause = '';+ if (!/Logs: \[[^\]]/.test(m)) {+ try {+ const sim = await connection.simulateTransaction(tx, {+ sigVerify: false,+ replaceRecentBlockhash: false,+ commitment: 'confirmed',+ });+ const simErr = sim?.value?.err ?? null;+ const simLogs = Array.isArray(sim?.value?.logs) ? sim.value.logs : [];+ if (simErr) {+ cause = ` cause:${typeof simErr === 'object' ? JSON.stringify(simErr) : String(simErr)}`;+ }+ if (simLogs.length) cause += ` logs:${simLogs.slice(-3).join(' | ')}`;+ } catch (reSimErr) {+ cause = ` cause_probe_failed:${String(reSimErr?.message || reSimErr).slice(0, 120)}`;}- if (simLogs.length) cause += ` logs:${simLogs.slice(-3).join(' | ')}`;- } catch (reSimErr) {- cause = ` cause_probe_failed:${String(reSimErr?.message || reSimErr).slice(0, 120)}`;}+ // web3.js appends the LAST simulation-log lines to the message, so the+ // failure cause sits at the END. A head-only truncation kept only the+ // ComputeBudget preamble and hid the failing instruction from every+ // production log. Keep the head (error class) and the tail (cause).+ const detail = `${m}${cause}${preflightRetryNote}`.replace(/\s+/g, ' ').trim();+ const full = `broadcast_failed:${detail}`;+ const reason = full.length <= 480 ? full : `${full.slice(0, 200)} … ${full.slice(-276)}`;+ return { success: false, reason };}- // web3.js appends the LAST simulation-log lines to the message, so the- // failure cause sits at the END. A head-only truncation kept only the- // ComputeBudget preamble and hid the failing instruction from every- // production log. Keep the head (error class) and the tail (cause).- const detail = `${m}${cause}`.replace(/\s+/g, ' ').trim();- const full = `broadcast_failed:${detail}`;- const reason = full.length <= 480 ? full : `${full.slice(0, 200)} … ${full.slice(-276)}`;- return { success: false, reason };}const conf = await confirmSignature(connection, signature);diff --git a/api/avatar/optimize.js b/api/avatar/optimize.jsindex e5d30dce2..8fe027972 100644--- a/api/avatar/optimize.js+++ b/api/avatar/optimize.js@@ -38,7 +38,6 @@ import { env } from '../_lib/env.js';import { sql } from '../_lib/db.js';import { publicUrl } from '../_lib/r2.js';import { NodeIO } from '@gltf-transform/core';-import { KHRDracoMeshCompression } from '@gltf-transform/extensions';import { dedup, prune, textureCompress, weld } from '@gltf-transform/functions';import { ARKIT_52, ARKIT_VISEMES, MORPH_ALIASES } from '../../src/runtime/arkit52.js';@@ -196,12 +195,9 @@ function transcodeIo() {}async function applyDraco(doc) {- const draco = doc.createExtension(KHRDracoMeshCompression).setRequired(true);- for (const mesh of doc.getRoot().listMeshes()) {- for (const prim of mesh.listPrimitives()) {- prim.setExtension('KHR_draco_mesh_compression', draco.createCompressedPrimitive(prim));- }- }+ const { draco } = await import('@gltf-transform/functions');+ // Draco encodes indexed primitives only, so weld before handing it the mesh.+ await doc.transform(weld(), draco());}export default wrap(async (req, res) => {diff --git a/blog/image-to-3d-on-nvidia-l4-and-blackwell.html b/blog/image-to-3d-on-nvidia-l4-and-blackwell.htmlindex 68c37e2b2..e454e2599 100644--- a/blog/image-to-3d-on-nvidia-l4-and-blackwell.html+++ b/blog/image-to-3d-on-nvidia-l4-and-blackwell.html@@ -78,6 +78,8 @@<meta property="og:image:width" content="1200"><meta property="og:image:height" content="630"><meta name="twitter:image" content="https://three.ws/og-image.png">+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"BlogPosting","headline":"Image-to-3D on NVIDIA L4 and Blackwell: Shipping Hunyuan3D 2.1 on Cloud Run GPUs","description":"A field report from the three.ws GPU fleet: why Hunyuan3D 2.1 could not load on an NVIDIA L4, why CUDA 12.4 wheels have no sm_120 kernels for RTX PRO 6000 Blackwell, and the regional quota that made the bigger card the available card.","image":"https://three.ws/og-image.png","datePublished":"2026-07-30T12:00:00.000Z","dateModified":"2026-07-30T12:00:00.000Z","author":{"@type":"Organization","name":"three.ws","url":"https://three.ws"},"publisher":{"@type":"Organization","name":"three.ws","url":"https://three.ws","logo":{"@type":"ImageObject","url":"https://three.ws/og-image.png"}},"mainEntityOfPage":{"@type":"WebPage","@id":"https://three.ws/blog/image-to-3d-on-nvidia-l4-and-blackwell"},"keywords":"Hunyuan3D 2.1, NVIDIA L4, RTX PRO 6000, Blackwell, sm_120, CUDA 12.8, Cloud Run GPU, image to 3D, text to 3D, PBR textures, GPU inference, PyTorch, TORCH_CUDA_ARCH_LIST, NVIDIA Inception, three.ws"}</script>+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://three.ws/"},{"@type":"ListItem","position":2,"name":"Blog","item":"https://three.ws/blog"},{"@type":"ListItem","position":3,"name":"Image-to-3D on NVIDIA L4 and Blackwell: Shipping Hunyuan3D 2.1 on Cloud Run GPUs","item":"https://three.ws/blog/image-to-3d-on-nvidia-l4-and-blackwell"}]}</script></head><body><div id="nav-container"></div>diff --git a/blog/index.html b/blog/index.htmlindex d28b1e534..845d9e233 100644--- a/blog/index.html+++ b/blog/index.html@@ -66,6 +66,33 @@<ul class="bl-list">+ <li class="bl-item">+ <a href="/blog/monetize-mcp-server-x402-paid-tools">+ <div class="bl-meta">+ <span class="bl-date">2026-07-30</span>+ <span class="bl-tag">x402</span>+ <span class="bl-tag">MCP</span>+ <span class="bl-tag">Guide</span>+ </div>+ <h2 class="bl-title">How to Monetize an MCP Server: Paid Tools with x402</h2>+ <p class="bl-summary">MCP solved distribution for tools and left payment unsolved, because every payment system on the web assumes a human completes a signup form. The full seller-side guide: choose work worth charging for, price it in atomic USDC units, wrap the route with <code>paid()</code> so unpaid calls get a real <code>402</code>, verify then work then settle in that order, charge inside a <code>tools/call</code> with the <code>_meta</code> payment convention, get indexed by the bazaar, and prove an assistant can buy it unattended. With a live endpoint you can curl right now.</p>+ </a>+ </li>++ <li class="bl-item">+ <a href="/blog/image-to-3d-on-nvidia-l4-and-blackwell">+ <div class="bl-meta">+ <span class="bl-date">2026-07-30</span>+ <span class="bl-tag">Engineering</span>+ <span class="bl-tag">NVIDIA</span>+ <span class="bl-tag">GPU</span>+ <span class="bl-tag">3D</span>+ </div>+ <h2 class="bl-title">Image-to-3D on NVIDIA L4 and Blackwell: Shipping Hunyuan3D 2.1 on Cloud Run GPUs</h2>+ <p class="bl-summary">A field report from the three.ws GPU fleet. Two walls, both invisible from the model card: a memory-backed <code>/tmp</code> that makes staged weights and loaded weights share one 32 GiB budget and SIGKILLs the instance mid-load, and CUDA 12.4 wheels that ship no sm_120 kernels for Blackwell. Plus the regional quota that made the bigger card the available card, the readiness signal that hid the failure for two days, and a nine-point checklist for your own port.</p>+ </a>+ </li>+<li class="bl-item"><a href="/blog/three-ws-openai-select-partner"><div class="bl-meta">diff --git a/blog/monetize-mcp-server-x402-paid-tools.html b/blog/monetize-mcp-server-x402-paid-tools.htmlnew file mode 100644index 000000000..6b59d999c--- /dev/null+++ b/blog/monetize-mcp-server-x402-paid-tools.html@@ -0,0 +1,371 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>How to Monetize an MCP Server: Paid Tools with x402</title>+ <meta name="description" content="A complete guide to charging for MCP tools with x402: price a tool in USDC, issue the 402 challenge, verify and settle on Solana, get discovered in the bazaar, and test the buyer side.">+ <meta name="keywords" content="monetize MCP server, MCP server payments, x402 MCP, paid MCP tools, agent payments, pay per call API, USDC, Solana, Model Context Protocol, x402 tutorial, HTTP 402">+ <link rel="canonical" href="https://three.ws/blog/monetize-mcp-server-x402-paid-tools">++ <meta property="og:title" content="How to Monetize an MCP Server: Paid Tools with x402">+ <meta property="og:description" content="Wrap a tool in a 402, get paid per call in USDC on Solana, and let any agent discover and buy it. Real code, real endpoints, no accounts or API keys.">+ <meta property="og:url" content="https://three.ws/blog/monetize-mcp-server-x402-paid-tools">+ <meta property="og:type" content="article">++ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:title" content="How to Monetize an MCP Server: Paid Tools with x402">+ <meta name="twitter:description" content="Charge per call for MCP tools: the 402 handshake, verify-then-work-then-settle, spend caps, bazaar discovery, and a live endpoint you can curl right now.">++ <link rel="shortcut icon" href="/favicon.ico">+ <link rel="stylesheet" href="/nav.css">+ <link rel="stylesheet" href="/footer.css">+ <style>+ :root { color-scheme: dark; }+ body { margin: 0; background: #060611; color: #e7e7f5; font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; -webkit-font-smoothing: antialiased; }+ .post-wrap { max-width: 760px; margin: 0 auto; padding: 96px 24px 80px; }+ .post-meta { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; color: #7a85a8; font-size: 13px; margin-bottom: 28px; }+ .post-date { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }+ .post-tag { padding: 2px 8px; border-radius: 999px; background: rgba(154,212,255,.08); color: #9ad4ff; font-size: 11px; font-weight: 500; letter-spacing: 0.02em; text-transform: uppercase; }+ h1 { font-size: clamp(26px, 4vw, 40px); font-weight: 700; letter-spacing: -0.02em; line-height: 1.2; margin: 0 0 20px; }+ h2 { font-size: 21px; font-weight: 600; margin: 48px 0 12px; letter-spacing: -0.01em; scroll-margin-top: 90px; }+ h3 { font-size: 16px; font-weight: 600; margin: 28px 0 10px; color: #e7e7f5; }+ p { color: #c8c8e0; line-height: 1.75; margin: 0 0 18px; font-size: 16px; }+ ul, ol { color: #c8c8e0; line-height: 1.75; margin: 0 0 18px; padding-left: 24px; font-size: 16px; }+ li { margin-bottom: 8px; }+ a { color: #9ad4ff; text-decoration: none; }+ a:hover { text-decoration: underline; }+ code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; background: rgba(154,212,255,.07); color: #9ad4ff; padding: 2px 6px; border-radius: 4px; }+ strong { color: #e7e7f5; }+ .lede { font-size: 18px; color: #d6d6ea; }+ pre { background: #0b0b1a; border: 1px solid rgba(255,255,255,.08); border-radius: 12px; padding: 16px 18px; overflow-x: auto; margin: 0 0 22px; }+ pre code { background: none; color: #dbe7ff; padding: 0; font-size: 13px; line-height: 1.65; display: block; }+ .table-scroll { overflow-x: auto; margin: 0 0 22px; border: 1px solid rgba(255,255,255,.08); border-radius: 12px; }+ table { border-collapse: collapse; width: 100%; font-size: 14px; min-width: 480px; }+ th, td { text-align: left; padding: 11px 14px; border-bottom: 1px solid rgba(255,255,255,.06); color: #c8c8e0; vertical-align: top; }+ th { color: #9ad4ff; font-weight: 600; font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; background: rgba(154,212,255,.04); }+ tbody tr:last-child td { border-bottom: none; }+ .callout { border: 1px solid rgba(154,212,255,.18); background: rgba(154,212,255,.05); border-radius: 12px; padding: 16px 18px; margin: 0 0 22px; }+ .callout p:last-child { margin-bottom: 0; }+ .toc { border: 1px solid rgba(255,255,255,.08); border-radius: 12px; padding: 18px 22px; margin: 0 0 34px; background: rgba(255,255,255,.02); }+ .toc h2 { font-size: 12px; text-transform: uppercase; letter-spacing: 0.06em; color: #7a85a8; margin: 0 0 10px; }+ .toc ol { margin: 0; padding-left: 20px; font-size: 15px; }+ .toc li { margin-bottom: 4px; }+ .faq-q { font-weight: 600; color: #e7e7f5; margin: 24px 0 6px; font-size: 16px; }+ .post-back { display: inline-flex; align-items: center; gap: 6px; color: #7a85a8; font-size: 14px; margin-bottom: 40px; text-decoration: none; }+ .post-back:hover { color: #9ad4ff; }+ hr { border: none; border-top: 1px solid rgba(255,255,255,.08); margin: 44px 0; }+ @media (max-width: 600px) { .post-wrap { padding: 72px 18px 64px; } }+ </style>+ <meta property="og:image" content="https://three.ws/og-image.png">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta name="twitter:image" content="https://three.ws/og-image.png">+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"BlogPosting","headline":"How to Monetize an MCP Server: Paid Tools with x402","description":"A complete guide to charging for MCP tools with x402: price a tool in USDC, issue the 402 challenge, verify and settle on Solana, get discovered in the bazaar, and test the buyer side.","image":"https://three.ws/og-image.png","datePublished":"2026-07-30T12:00:00.000Z","dateModified":"2026-07-30T12:00:00.000Z","author":{"@type":"Organization","name":"three.ws","url":"https://three.ws"},"publisher":{"@type":"Organization","name":"three.ws","url":"https://three.ws","logo":{"@type":"ImageObject","url":"https://three.ws/og-image.png"}},"mainEntityOfPage":{"@type":"WebPage","@id":"https://three.ws/blog/monetize-mcp-server-x402-paid-tools"},"keywords":"monetize MCP server, MCP server payments, x402 MCP, paid MCP tools, agent payments, pay per call API, USDC, Solana, Model Context Protocol, x402 tutorial, HTTP 402"}</script>+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://three.ws/"},{"@type":"ListItem","position":2,"name":"Blog","item":"https://three.ws/blog"},{"@type":"ListItem","position":3,"name":"How to Monetize an MCP Server: Paid Tools with x402","item":"https://three.ws/blog/monetize-mcp-server-x402-paid-tools"}]}</script>+</head>+<body>+ <div id="nav-container"></div>+ <main class="post-wrap">+ <a class="post-back" href="/blog">← Blog</a>+ <div class="post-meta">+ <span class="post-date">2026-07-30</span>+ <span class="post-tag">x402</span>+ <span class="post-tag">MCP</span>+ <span class="post-tag">Guide</span>+ </div>+ <h1>How to Monetize an MCP Server: Paid Tools with x402</h1>++ <p class="lede">The Model Context Protocol solved distribution for tools. Any assistant can now call your code. What it never solved is getting paid for it, because every payment system on the web assumes a human with a credit card completes a signup form. This guide fixes that: you will price a tool, make it answer unpaid requests with a real <code>402 Payment Required</code> challenge, verify and settle in USDC on Solana, publish it where agents look for paid capabilities, and test the buyer side from Claude.</p>++ <p>Everything below runs on the same rails three.ws uses in production, and every endpoint quoted here is live while you read this. No sandbox, no test tokens, no mocks.</p>++ <div class="toc">+ <h2>What you will build</h2>+ <ol>+ <li><a href="#why">Why per-call payment fits agent tools</a></li>+ <li><a href="#handshake">The x402 handshake, seven steps</a></li>+ <li><a href="#shapes">Two shapes for a paid MCP server</a></li>+ <li><a href="#work">Step 1: choose work worth charging for</a></li>+ <li><a href="#price">Step 2: price it in atomic units</a></li>+ <li><a href="#paid">Step 3: make the endpoint paid</a></li>+ <li><a href="#inside">Step 4: charge inside a tool call</a></li>+ <li><a href="#verify">Step 5: verify it against a real 402</a></li>+ <li><a href="#discovery">Step 6: get discovered</a></li>+ <li><a href="#buyer">Step 7: test the buyer side</a></li>+ <li><a href="#rules">Production rules that keep you honest</a></li>+ <li><a href="#faq">FAQ</a></li>+ </ol>+ </div>++ <h2 id="why">Why per-call payment fits agent tools</h2>+ <p>A subscription is a bet that a customer will use a service repeatedly and predictably. An autonomous agent is the opposite: it discovers a tool the moment it needs one, calls it two or three times, and may never return. Three properties make per-call payment the natural fit.</p>+ <ul>+ <li><strong>Real marginal cost.</strong> If a tool burns GPU time, model tokens, RPC calls, or paid upstream data, every call costs you money. Charging per call is the only pricing that tracks the cost honestly.</li>+ <li><strong>No signup a machine can complete.</strong> API keys assume an account, an email confirmation, and a dashboard visit. An agent has a wallet, not an inbox. A payment protocol it can satisfy in one round trip is the difference between being callable and being skipped.</li>+ <li><strong>Price is discoverable before purchase.</strong> The 402 challenge states the price, the asset, the chain, and the recipient. A caller can read the price and decide, which is exactly what a spending limit needs to work.</li>+ </ul>++ <h2 id="handshake">The x402 handshake, seven steps</h2>+ <p><a href="https://x402.org" rel="noopener">x402</a> takes the HTTP status code that has been reserved and unused since 1997 and turns it into a working payment rail. The whole protocol:</p>+ <ol>+ <li>The client requests your resource with no payment attached.</li>+ <li>You answer <code>402</code> with a JSON body whose <code>accepts[]</code> lists every payment you will take: scheme, network, asset, amount, pay-to address, timeout.</li>+ <li>The client picks one accept and signs a payment for it (an SPL transfer on Solana, a gasless <a href="https://eips.ethereum.org/EIPS/eip-3009" rel="noopener">EIP-3009</a> authorization on Base).</li>+ <li>The client retries the same request with the signed payload in an <code>X-PAYMENT</code> header.</li>+ <li>You verify the payment with a facilitator's <code>/verify</code>. Nothing has moved yet.</li>+ <li><strong>You do the work.</strong> Only now.</li>+ <li>You settle with the facilitator's <code>/settle</code>, then return <code>200</code> with the receipt in <code>X-PAYMENT-RESPONSE</code>.</li>+ </ol>+ <div class="callout">+ <p><strong>The ordering in steps 5 to 7 is the whole design.</strong> Verify before you work, so you never do unpaid work. Settle after the work succeeds, so a failure moves no money and the buyer can retry the same payment. Get this backwards and you will either be farmed for free compute or charge for errors.</p>+ </div>++ <h2 id="shapes">Two shapes for a paid MCP server</h2>+ <p>There are two places the payment can live, and picking the wrong one is the most common early mistake.</p>+ <div class="table-scroll">+ <table>+ <thead>+ <tr><th>Shape</th><th>Where payment happens</th><th>Choose it when</th></tr>+ </thead>+ <tbody>+ <tr>+ <td><strong>A. Paid HTTP endpoint</strong></td>+ <td>An ordinary HTTPS route answers <code>402</code> and settles the <code>X-PAYMENT</code> header.</td>+ <td>Your capability is useful to any caller: agents, scripts, backends, MCP clients through a buyer-side payer. This is the default. You may never need to ship an MCP server at all.</td>+ </tr>+ <tr>+ <td><strong>B. Paid MCP tool</strong></td>+ <td>Inside <code>tools/call</code>. The payment travels in <code>_meta["x402/payment"]</code> and the receipt comes back in <code>_meta["x402/payment-response"]</code>.</td>+ <td>The value is the tool ergonomics themselves: schemas, prompts, and a conversation-native surface, and you want per-tool prices inside one connector.</td>+ </tr>+ </tbody>+ </table>+ </div>+ <p>Most teams should build A first and add B when a client base asks for it. Shape A is a smaller surface, is testable with <code>curl</code>, and is what discovery indexes. Shape B is worth it when you run several priced tools behind one connector, which is how <a href="/docs/ibm-x402-mcp" rel="noopener">Granite over MCP</a> exposes five metered models with a free explainer tool in front of them.</p>++ <h3>Prerequisites</h3>+ <ul>+ <li><strong>Node 18 or newer.</strong> The server package uses global <code>fetch</code> and Web Crypto.</li>+ <li><strong>A public HTTPS URL.</strong> Buyer libraries refuse to send signed payloads to plaintext origins, so localhost works for unit tests only.</li>+ <li><strong>A Solana address to receive USDC.</strong> You do not need SOL in it. Settlement is facilitator-broadcast, and the fee payer is not you.</li>+ <li><strong>A piece of work worth money.</strong> The next step is about being honest with yourself here.</li>+ </ul>++ <h2 id="work">Step 1: choose work worth charging for</h2>+ <p>A paid endpoint that wraps a free public API is not a business, it is a toll booth on an open road, and agents route around it as soon as one of them reads the docs. Put a candidate through three tests before writing code.</p>+ <ol>+ <li><strong>Can it be done client-side?</strong> If the calling model can do it in-context, it will, and it should. Charge for what requires your data, your credentials, your hardware, or your index.</li>+ <li><strong>Does each call cost you something?</strong> Marginal cost is what makes per-call pricing defensible instead of extractive.</li>+ <li><strong>Is the output structured?</strong> The buyer is a language model. JSON it can reason over is worth more than prose it has to parse.</li>+ </ol>+ <p>Three that pass, all running on three.ws today: <a href="/docs/x402-endpoints" rel="noopener">model inspection</a> (fetch a glTF or GLB, return vertex and material counts plus optimization advice), agent reputation lookup (aggregate on-chain review history), and ticker availability (check a symbol against the live registry). Each needs something the caller does not have locally.</p>++ <h2 id="price">Step 2: price it in atomic units</h2>+ <p>Prices are strings of atomic units, never floats. USDC has six decimals, so:</p>+ <div class="table-scroll">+ <table>+ <thead><tr><th>Price</th><th>Atomic units</th><th>Fits</th></tr></thead>+ <tbody>+ <tr><td>$0.001</td><td><code>'1000'</code></td><td>Cheap lookups, validation, metadata reads</td></tr>+ <tr><td>$0.01</td><td><code>'10000'</code></td><td>A small model call, a parse, a summary</td></tr>+ <tr><td>$0.05</td><td><code>'50000'</code></td><td>Multi-step inference, a forecast, a render</td></tr>+ <tr><td>$0.25</td><td><code>'250000'</code></td><td>Heavy GPU work, long generation</td></tr>+ </tbody>+ </table>+ </div>+ <p>For calibration, here is what the live Granite tool tier charges per call: chat $0.02, code $0.025, embeddings $0.005, document analysis $0.04, time-series forecast $0.05. Agents are price sensitive in aggregate, so the practical ceiling for an impulse call with no prior relationship sits somewhere near a nickel. Above that, expect the caller to check a spend cap first, and make sure your 402 metadata explains what the money buys.</p>++ <h2 id="paid">Step 3: make the endpoint paid</h2>+ <p>The seller side is one wrapper. Install the merchant package:</p>+ <pre><code>npm install @three-ws/x402-server</code></pre>+ <p>Then wrap the handler. Unpaid requests get the challenge, paid ones run your code:</p>+ <pre><code>import { paid } from '@three-ws/x402-server';++export default paid(+ {+ price: '10000', // $0.01 in 6-decimal USDC atomics+ asset: 'usdc',+ payTo: { solana: 'YOUR_SOLANA_ADDRESS' },+ description: 'Document summarization',+ serviceName: 'Summarize',+ tags: ['nlp', 'summary'],+ },+ async (req, res) => {+ const { text } = req.body;+ res.json({ summary: await summarize(text) });+ },+);</code></pre>+ <p>That is a complete paid API. The wrapper builds the v2 challenge envelope, mirrors it into the <code>PAYMENT-REQUIRED</code> header for header-only clients, verifies the retry against a facilitator, runs your handler, settles, and attaches the receipt. It is framework agnostic: mount it as Express or Connect middleware, a Fastify hook, or a bare Node handler.</p>++ <h3>Two chains, one config</h3>+ <p>Add a second lane and the challenge advertises both accepts. The buyer picks whichever chain it holds funds on. Solana leads when both are present.</p>+ <pre><code>import { paid } from '@three-ws/x402-server';++export default paid(+ {+ price: '50000', // $0.05+ asset: 'usdc',+ payTo: {+ solana: 'YOUR_SOLANA_ADDRESS',+ base: '0xYourBaseAddress',+ },+ network: ['solana', 'base'],+ maxTimeoutSeconds: 60,+ onSettled: (receipt) => recordSale(receipt),+ },+ async (req, res, payment) => {+ const result = await render(req.body.prompt);+ res.json({ result, paidBy: payment.payer });+ },+);</code></pre>+ <p>Two details worth internalizing. The handler's third argument, <code>payment</code>, exists only on a paid call and carries <code>{ payer, network, accept, amount }</code>, which is your per-caller analytics key and your rate-limit key. And <strong>throwing from the handler skips settlement entirely</strong>: no funds move, the buyer gets a <code>500</code>, and the same signed payment can be retried. Let your errors throw. Do not catch them into a fake success.</p>++ <h3>Response ordering</h3>+ <p>By default the wrapper buffers your response, settles, then flushes the <code>200</code> with the receipt attached, so the buyer never receives the goods before payment lands. For responses you cannot buffer, a large file or an SSE stream, set <code>streaming: true</code> and settlement runs first, before your handler writes a byte.</p>++ <h3>Taking a platform fee without marking up the buyer</h3>+ <p>If you host other people's tools, <code>feeBps</code> splits your cut out of the listed price rather than adding to it. <code>feeSplit()</code> computes it as <code>floor(price × bps / 10000)</code>, and returns nothing when the fee would round to zero atomic units, in which case the creator receives the full amount. The buyer's total is whatever the challenge said. Surprise billing is how you lose a marketplace.</p>+ <pre><code>paid({+ price: '50000',+ asset: 'usdc',+ payTo: { solana: 'CREATOR_SOLANA_ADDRESS' },+ feeBps: 250, // 2.5%, capped at 1000 (10%)+ feeTo: 'YOUR_TREASURY_ADDRESS',+}, handler);</code></pre>++ <h2 id="inside">Step 4: charge inside a tool call</h2>+ <p>For shape B the payment rides in the MCP message itself. An unpaid <code>tools/call</code> returns a payment-required envelope quoting the price and the receiving address. The client signs, retries with the payload in <code>_meta["x402/payment"]</code>, and the settlement receipt comes back in <code>_meta["x402/payment-response"]</code>. x402-capable clients run that loop without asking the user anything.</p>+ <p>The same three primitives that back <code>paid()</code> are exported for this, so you keep one wire contract across both shapes:</p>+ <pre><code>import {+ buildChallenge,+ verifyPayment,+ settlePayment,+ NETWORK_SOLANA_MAINNET,+} from '@three-ws/x402-server';++const requirements = [{+ scheme: 'exact',+ network: NETWORK_SOLANA_MAINNET,+ asset: 'usdc',+ payTo: process.env.X402_PAY_TO_SOLANA,+ amount: '20000', // $0.02+ maxTimeoutSeconds: 60,+}];++server.registerTool('summarize_document', schema, async (args, extra) => {+ const header = extra?._meta?.['x402/payment'];++ if (!header) {+ const challenge = buildChallenge({+ price: '20000',+ asset: 'usdc',+ payTo: { solana: process.env.X402_PAY_TO_SOLANA },+ description: 'Document summarization',+ });+ return { isError: true, content: [{ type: 'text', text: JSON.stringify(challenge) }] };+ }++ const verified = await verifyPayment({ paymentHeader: header, requirements });+ if (!verified.ok) {+ return { isError: true, content: [{ type: 'text', text: JSON.stringify(verified.body) }] };+ }++ const summary = await summarize(args.text);+ const receipt = await settlePayment({ verified });++ return {+ content: [{ type: 'text', text: summary }],+ _meta: { 'x402/payment-response': receipt },+ };+});</code></pre>+ <p><strong>Ship one free tool alongside the paid ones.</strong> A tool named something like <code>getting_started</code> that returns your price list and explains the payment flow costs you nothing and removes the guesswork for a client that has never paid an MCP tool before. Every paid connector we run has one, and it is consistently the first tool a new caller invokes.</p>++ <h2 id="verify">Step 5: verify it against a real 402</h2>+ <p>Before trusting your own implementation, look at a working one. This is a live production endpoint, and the response below is what it returns right now to an unpaid request:</p>+ <pre><code>curl -s 'https://three.ws/api/x402/model-check?url=https://three.ws/avatars/cesium-man.glb'</code></pre>+ <pre><code>{+ "x402Version": 2,+ "error": "X-PAYMENT header is required",+ "accepts": [+ {+ "scheme": "exact",+ "network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",+ "amount": "1000",+ "payTo": "wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU",+ "asset": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",+ "maxTimeoutSeconds": 60,+ "resource": "https://three.ws/api/x402/model-check",+ "extra": { "name": "USDC", "decimals": 6, "feePayer": "WwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW" }+ }+ ]+}</code></pre>+ <p>Four things to copy from it. The status is <code>402</code>, not <code>400</code> or <code>403</code>, because buyer libraries branch on the code. The <code>network</code> is a CAIP-2 identifier, not a friendly name. The Solana accept carries <code>extra.feePayer</code>, which is mandatory on that lane and the single most common omission. And the same price is offered on more than one chain so a caller with the wrong balance is not turned away.</p>+ <p>Now check your own endpoint the same way, and confirm the unhappy paths: a malformed <code>X-PAYMENT</code> header returns a fresh <code>402</code> rather than a <code>500</code>, an underpayment is rejected, and a handler that throws leaves the buyer's balance untouched.</p>++ <h2 id="discovery">Step 6: get discovered</h2>+ <p>A paid endpoint nobody can find earns nothing. Three surfaces matter, in this order.</p>+ <ul>+ <li><strong>Facilitator discovery.</strong> Your challenge metadata (<code>serviceName</code>, <code>description</code>, <code>tags</code>, <code>iconUrl</code>) is what catalogs read. Fill all of it. A row that just says "paid endpoint" is a row no agent picks.</li>+ <li><strong>The bazaar.</strong> <a href="/docs/mcp-x402-bazaar" rel="noopener">three.ws/api/mcp-bazaar</a> is an MCP server over the merged live facilitator catalog, with <code>search_services</code>, <code>browse_services</code>, and <code>get_service</code>. Its listings come from live discovery, never a cached copy, so a correct challenge is all it takes to appear.</li>+ <li><strong>The MCP Registry.</strong> If you shipped shape B, publish a <code>server.json</code> manifest so clients can install your connector by name.</li>+ </ul>+ <p>One nuance about facilitators: PayAI is free, community run, and covers both Solana and Base. Coinbase CDP settlements additionally get indexed by catalogs that autonomous agents query. The protocol lets you advertise several networks in one challenge, so running both is normal and costs nothing architecturally.</p>++ <h2 id="buyer">Step 7: test the buyer side</h2>+ <p>The last mile is proving an assistant can find, price, and buy your tool without a human in the loop. Give Claude a self-custodial x402 wallet:</p>+ <pre><code>claude mcp add x402 --env SOLANA_SECRET_KEY=<base58> -- npx -y @three-ws/x402-mcp</code></pre>+ <p>That connector exposes four tools: <code>x402_wallet</code> (address and live balances), <code>find_services</code> (search the bazaar), <code>inspect_endpoint</code> (read a 402's requirements without paying), and <code>pay_and_call</code> (pay in USDC and return the result). The first three need no key at all, which makes <code>inspect_endpoint</code> the fastest way to see your own challenge exactly as a buyer sees it.</p>+ <p>Note how the spending controls are layered, because this is the pattern to imitate if you build your own payer. <code>pay_and_call</code> is annotated as destructive so the client prompts first. The server probes the 402 and refuses before any money moves if the price exceeds <code>MAX_PAY_USD</code>, which defaults to one dollar. And with <code>REQUIRE_CONFIRM</code> on, the call refuses until it is reissued with <code>confirm: true</code>. Three independent brakes, none of which trust the seller's quoted price.</p>++ <h2 id="rules">Production rules that keep you honest</h2>+ <ul>+ <li><strong>Verify, work, settle. In that order, every time.</strong> Any other order either gives away work or charges for failures.</li>+ <li><strong>Never mark up the listed price.</strong> Fees come out of what the challenge advertised. The buyer's total must equal the quote.</li>+ <li><strong>Make retries safe.</strong> A settled payment plus a failed response is the case that generates support mail. Key your work on the payment payload so a retry returns the same result instead of charging twice.</li>+ <li><strong>Log every settlement.</strong> <code>onSettled</code> gives you the receipt with network, payer, and transaction. That is your ledger, your fraud signal, and your revenue report.</li>+ <li><strong>Rate limit by payer.</strong> Payment is not authorization. A funded wallet can still hammer you.</li>+ <li><strong>Return real errors.</strong> Quota exhausted, upstream down, bad input: say so with a status the caller can act on. An agent that gets a clear <code>503</code> retries later. One that gets a vague <code>200</code> full of nonsense stops trusting the tool.</li>+ </ul>++ <h2 id="faq">FAQ</h2>+ <p class="faq-q">Do buyers need an account with me?</p>+ <p>No. That is the point. A wallet with USDC and an x402-capable client is the entire onboarding. There is no signup, no API key issuance, and no billing relationship to maintain.</p>++ <p class="faq-q">Which chain should I settle on?</p>+ <p>Solana first. Fees are negligible relative to a fraction-of-a-cent call, confirmation is fast enough to sit inside a request, and it is where the agent-payment volume is. Add Base as a second accept so EVM-funded callers are not excluded, and let the buyer choose.</p>++ <p class="faq-q">What stops an agent from paying for something worthless?</p>+ <p>Buyer-side caps, which is why every serious payer enforces them independently of the seller. A price ceiling per call, an explicit confirmation step, and a pre-payment probe of the 402 mean the wallet holder sets the risk, not the merchant.</p>++ <p class="faq-q">Can I charge different prices for different tools in one MCP server?</p>+ <p>Yes. In shape B the price is per tool call, so one connector can hold a free explainer tool, a half-cent lookup, and a five-cent inference call. Quote the price in each tool's own challenge.</p>++ <p class="faq-q">What happens if my handler crashes after the payment is verified?</p>+ <p>Nothing moves. Verification is not settlement. A thrown error skips settlement, the buyer keeps their funds, and the signed payment stays valid for a retry inside its timeout window.</p>++ <p class="faq-q">Is this only for AI tools?</p>+ <p>No. Any HTTP endpoint can take payment this way: data lookups, file conversion, rendering, scraping, geocoding. Agents are simply the first buyers with a wallet and no patience for signup forms.</p>++ <hr>++ <h2>Further reading</h2>+ <ul>+ <li><a href="/docs/x402-endpoints">x402 endpoints reference</a>: every paid route on the platform, with prices and payloads.</li>+ <li><a href="/tutorials/paid-x402-endpoint">Tutorial: build a paid x402 endpoint your agent calls</a>: the long-form walkthrough, from scaffold to production.</li>+ <li><a href="/tutorials/pay-for-x402-service">Tutorial: pay for an x402 service</a>: the buyer side, end to end.</li>+ <li><a href="/docs/mcp-x402-bazaar">The x402 bazaar MCP server</a>: how discovery works and what it indexes.</li>+ <li><a href="/docs/mcp">MCP on three.ws</a>: connectors, transports, and OAuth.</li>+ <li><a href="/blog/x402-stripe-for-agent-payments">Why x402 is Stripe for agent payments</a>: the argument behind the protocol.</li>+ </ul>++ <p>Packages used here: <a href="https://www.npmjs.com/package/@three-ws/x402-server" rel="noopener">@three-ws/x402-server</a> (seller), <a href="https://www.npmjs.com/package/@three-ws/x402-mcp" rel="noopener">@three-ws/x402-mcp</a> (buyer), and <a href="https://www.npmjs.com/package/@three-ws/x402-fetch" rel="noopener">@three-ws/x402-fetch</a> (a paying <code>fetch</code> for your own clients). Source for all three is in the <a href="https://github.com/nirholas/three.ws" rel="noopener">three.ws repository</a>.</p>++ <hr>+ <p><a href="/blog">← All posts</a></p>+ </main>+ <div id="footer-container"></div>+ <script src="/nav.js"></script>+ <script src="/footer.js"></script>+</body>+</html>diff --git a/data/changelog.json b/data/changelog.jsonindex eba6274ca..720dcfccf 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,14 @@{"$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-07-30",+ "title": "Paid requests stop being refused after they were already served",+ "summary": "When someone pays for one of our endpoints, we broadcast their payment to Solana and confirm it. Before broadcasting, we asked one of our own nodes to dry-run it first. But the payer builds and signs their payment against their own node, so if the node that answered us happened to be running a few slots behind, it had simply never seen the reference the payment was built against and rejected it as unknown. The payment was perfectly valid. Because that check runs after we have already done the paid work, the caller was charged effort and then handed an error. We now hand that decision to the network itself rather than to whichever of our nodes replied: if the payment is still live it goes through, and if it has genuinely expired it is dropped without landing and without a fee. Resending is safe because Solana ignores a duplicate of a payment it has already seen. Genuine faults, such as an underfunded account, are still refused on the first attempt as before.",+ "tags": [+ "fix"+ ]+ },{"date": "2026-07-30","title": "New engineering post: how our 3D generation runs on NVIDIA L4 and Blackwell GPUs",diff --git a/data/pages.json b/data/pages.jsonindex 20ec345f6..3446b266c 100644--- a/data/pages.json+++ b/data/pages.json@@ -3054,6 +3054,31 @@"lastmod": "2026-05-17","added": "2026-05-17"},+ {+ "path": "/blog/image-to-3d-on-nvidia-l4-and-blackwell",+ "title": "Image-to-3D on NVIDIA L4 and Blackwell: Shipping Hunyuan3D 2.1 on Cloud Run GPUs",+ "description": "A field report from the three.ws GPU fleet: why Hunyuan3D 2.1 could not load on an NVIDIA L4, why CUDA 12.4 wheels have no sm_120 kernels for RTX PRO 6000 Blackwell, and the regional quota that made the bigger card the available card.",+ "priority": 0.6,+ "changefreq": "monthly",+ "lastmod": "2026-07-30"+ },+ {+ "path": "/blog/monetize-mcp-server-x402-paid-tools",+ "title": "How to Monetize an MCP Server: Paid Tools with x402",+ "description": "A complete guide to charging for MCP tools with x402: price a tool in USDC, issue the 402 challenge, verify and settle on Solana, get discovered in the bazaar, and test the buyer side.",+ "priority": 0.6,+ "changefreq": "monthly",+ "lastmod": "2026-07-30"+ },+ {+ "path": "/blog/three-ws-openai-select-partner",+ "title": "three.ws Named an OpenAI Select Partner",+ "description": "three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.",+ "priority": 0.6,+ "changefreq": "monthly",+ "lastmod": "2026-07-25",+ "added": "2026-07-25"+ },{"path": "/blog/autonomous-trading-experiment","title": "We Gave 11 AI Agents Their Own Wallets and Real SOL. Here Are All 90 Trades.",@@ -3097,15 +3122,6 @@"lastmod": "2026-07-16","added": "2026-07-16"},- {- "path": "/blog/three-ws-openai-select-partner",- "title": "three.ws Named an OpenAI Select Partner",- "description": "three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.",- "priority": 0.6,- "changefreq": "monthly",- "lastmod": "2026-07-25",- "added": "2026-07-25"- },{"path": "/blog/three-ws-alibaba-cloud-partnership","title": "three.ws Joins the Alibaba Cloud Partner Network",diff --git a/docs/agent-economy-volume.md b/docs/agent-economy-volume.mdnew file mode 100644index 000000000..caf51c1d5--- /dev/null+++ b/docs/agent-economy-volume.md@@ -0,0 +1,227 @@+# Agent Economy Volume++[`/agent-economy-volume`](https://three.ws/agent-economy-volume) is the public+roll-up of the agent-to-agent economy: the total USDC that three.ws agents have+actually paid each other for paid skills over the x402 rails, plus who earns it,+who spends it, and how it moves day to day for the last 90 days.++Every number on the page is a live aggregate over one real ledger table. There is+no sample data and no mock path: when the ledger is empty the endpoint returns a+real zero shape and the page renders its empty states.++> Source: page+> [`pages/agent-economy-volume.html`](../pages/agent-economy-volume.html),+> frontend [`src/agent-economy-volume.js`](../src/agent-economy-volume.js),+> endpoint [`api/agent-economy/volume.js`](../api/agent-economy/volume.js),+> aggregation `platformEconomyStats()` in+> [`api/_lib/agent-economy.js`](../api/_lib/agent-economy.js), hire lifecycle+> [`api/agents/a2a-hire.js`](../api/agents/a2a-hire.js).++---++## What counts as volume++The ledger is `agent_hires`: one row per hire, written when one agent hires+another for a paid skill. **Only rows with `status = 'completed'` are counted.**+Every aggregate on this page carries a `FILTER (WHERE status = 'completed')`, so+pending and failed hires contribute nothing to volume, counts, averages,+leaderboards, or the feed.++That status is not cosmetic. In the hire path+([`api/agents/a2a-hire.js`](../api/agents/a2a-hire.js)) a row is inserted as+`pending`, the spend is reserved against the owner's policy, and the payment runs+over the real x402 rails. Because x402 verifies then settles, a failure means no+funds moved: the reservation is released and the row is flipped to `failed`. Only+after USDC has settled to the provider is the row flipped to `completed`, with+`completed_at` stamped and the settlement signature, payer address, and result+summary attached. So "completed" is exactly "real USDC moved on-chain, with the+signature on file".++The one place pending work appears is `totals.pending_hires`, a plain count shown+as the sub-label under "Settled hires". It never enters a money figure.++Each row's USD value comes from the `usd` column. In the recent feed only, a row+with a null `usd` falls back to `amount_atomics / 1e6` (USDC has 6 decimals). The+aggregates sum `usd` directly.++---++## Aggregation windows++Three different spans are in play at once, and mixing them up is the easiest way+to misread the page:++| Block | Span |+| ----------------------------------------- | ----------------------------------------------------------- |+| `totals.volume_usd`, `hires`, `unique_hirers`, `unique_providers`, `avg_hire_usd`, `pending_hires`, `last_hire_at` | **All time.** No date filter at all. |+| `totals.volume_24h_usd`, `hires_24h` | Trailing 24 hours on `completed_at`. |+| `totals.volume_7d_usd`, `hires_7d` | Trailing 7 days on `completed_at`. |+| `daily[]` | Trailing `window` days, grouped by `date_trunc('day', completed_at)`. |+| `top_providers[]`, `top_hirers[]` | Trailing `window` days. |+| `recent[]` | The latest `recent` completed hires, newest first, with no window. |++The `window` parameter therefore scopes the chart and both leaderboards, and+nothing else. The headline figure and the five stat cards other than the 7 day+card are lifetime numbers, which is what the page's "total volume settled between+agents" label means.++The page requests `?window=90&top=10&recent=14` once and drives its 7d / 30d /+90d toggle entirely client-side, re-slicing the cached 90 day series. The toggle+does not refetch, so switching windows is instant and costs no query. The series+is zero-filled per day in the browser so the chart shows a continuous timeline+rather than only days that had volume, and it renders on the native Canvas API+with no charting dependency. When no day in the visible window has volume, the+chart area is replaced with a plain "no settled agent-to-agent volume in this+window yet" line.++The page reloads on a 60 second interval while the tab is visible, and redraws the+canvas on resize and on a theme change.++---++## The API++```+GET /api/agent-economy/volume?window=90&top=10&recent=14+```++Public, read-only, no auth. `GET` and `OPTIONS` only, CORS open to any origin,+rate-limited per client IP through the shared public read limiter+(`limits.publicIp`). Responses carry+`Cache-Control: public, max-age=15, s-maxage=30, stale-while-revalidate=60`,+because these are heavy aggregate scans and 30 seconds of staleness is invisible+to a reader.++### Parameters++| Name | Range | Default | Effect |+| -------- | ------------- | ------- | -------------------------------------------------- |+| `window` | 1 to 365 days | 30 | Span for `daily[]` and both leaderboards. |+| `top` | 1 to 50 | 10 | Ranked agents per leaderboard. |+| `recent` | 1 to 50 | 12 | Settled hires in the feed. |++Values are parsed as integers, clamped to their range, and echoed back through+`window_days`. A non-numeric value falls back to the default.++### Response++```json+{+ "ok": true,+ "generated_at": "2026-07-30T00:00:00.000Z",+ "window_days": 90,+ "totals": {+ "volume_usd": 0,+ "hires": 0,+ "unique_hirers": 0,+ "unique_providers": 0,+ "avg_hire_usd": 0,+ "volume_24h_usd": 0,+ "hires_24h": 0,+ "volume_7d_usd": 0,+ "hires_7d": 0,+ "pending_hires": 0,+ "last_hire_at": null+ },+ "daily": [{ "day": "2026-07-30", "volume_usd": 0, "hires": 0 }],+ "top_providers": [+ {+ "agent_id": "<uuid>",+ "name": "Agent",+ "url": "/agent/<uuid>",+ "avatar_thumbnail_url": null,+ "earned_usd": 0,+ "hires": 0,+ "avg_rating": null+ }+ ],+ "top_hirers": [+ {+ "agent_id": "<uuid>",+ "name": "Agent",+ "url": "/agent/<uuid>",+ "avatar_thumbnail_url": null,+ "spent_usd": 0,+ "hires": 0+ }+ ],+ "recent": [+ {+ "id": "<uuid>",+ "skill_name": "Skill",+ "service_slug": "skill-slug",+ "usd": 0,+ "currency": "USDC",+ "network": "mainnet",+ "payment_signature": "<signature>",+ "completed_at": "2026-07-30T00:00:00.000Z",+ "hirer": { "agent_id": "<uuid>", "name": "Agent" },+ "provider": { "agent_id": "<uuid>", "name": "Agent" },+ "explorer_url": "https://solscan.io/tx/<signature>"+ }+ ]+}+```++### Field definitions++**`totals`** (all time unless the name says otherwise):++- `volume_usd`: `SUM(usd)` over completed hires. The headline number.+- `hires`: count of completed hires. Rendered as "Settled hires".+- `unique_hirers`: distinct `hirer_agent_id` across completed hires. Rendered as+ "Paying agents".+- `unique_providers`: distinct non-null `provider_agent_id` across completed+ hires. Rendered as "Earning agents".+- `avg_hire_usd`: `AVG(usd)` over completed hires, shown as "Avg hire value" and+ displayed as `$0` when there are no hires.+- `volume_24h_usd` / `hires_24h`: trailing 24 hours. The 24 hour volume drives the+ green delta pill next to the headline, which stays hidden at zero.+- `volume_7d_usd` / `hires_7d`: trailing 7 days, the "Volume, 7 days" card.+- `pending_hires`: count of rows still `pending`.+- `last_hire_at`: `MAX(completed_at)` over completed hires.++**`daily[]`**: one entry per day that had at least one completed hire inside the+window, as `YYYY-MM-DD` plus that day's `volume_usd` and `hires`. Days with no+activity are absent from the API and zero-filled by the page.++**`top_providers[]`**: grouped by `provider_agent_id` over the window, ordered by+`earned_usd` descending, limited to `top`. `earned_usd` is `SUM(usd)`, `hires` is+the row count, and `avg_rating` is the average of non-null hirer ratings (1 to 5,+one per hire, set by the hirer's owner) or `null` when nothing has been rated. The+page shows it as a star figure next to the hire count.++**`top_hirers[]`**: the same shape from the paying side, grouped by+`hirer_agent_id` and ordered by `spent_usd` descending.++Both leaderboards respect agent privacy: `url` is `null` when the agent's+identity is not public, which makes the page render an unlinked row, and+`avatar_thumbnail_url` is populated only when the linked avatar's visibility is+`public` or `unlisted`. A row with no avatar renders initials instead.++**`recent[]`**: the latest completed hires ordered by `completed_at` descending,+with the skill, the amount, the network, and the settlement signature.+`explorer_url` is the Solscan transaction link derived from that signature+(`?cluster=devnet` appended on devnet), so each row in the feed links to its+on-chain proof. It is `null` only when a completed row somehow carries no+signature.++### Degraded and error paths++If the `agent_hires` table is missing (an environment that has not run the+migration), the aggregation returns the zero shape above rather than an error, so+the dashboard renders empty states instead of a failure. Any other database error+propagates as a server error, and the page shows an inline error strip with a+Retry button that refetches. A network failure shows the same strip.++---++## Related++- [x402 revenue and receipts](x402-revenue.md): the other side of the ledger. This+ page counts agent-to-agent payments recorded in `agent_hires`; endpoint revenue+ paid **to** the platform's own paid endpoints is recorded separately in+ `x402_audit_log`. Do not add the two together.+- [The autonomous economy](autonomous-economy.md): how agents get wallets, spend+ policies, and paid skills in the first place, which is what produces the rows+ this page aggregates.diff --git a/docs/agent-identities.md b/docs/agent-identities.mdnew file mode 100644index 000000000..6bb2bfe75--- /dev/null+++ b/docs/agent-identities.md@@ -0,0 +1,158 @@+# Agent Identity Studio: a brand brief becomes a 3D identity++Every AI agent deserves a face. The Agent Identity Studio takes an agent's name and a plain-language brand brief and returns a complete visual identity: a rigged, animation-ready GLB avatar, a square profile picture that stays legible at thumbnail size, and a set of posed, studio-lit full-body renders. No manual modelling, no touch-ups, no human in the loop.++Page: [/agent-identities](https://three.ws/agent-identities) (the showcase) · Endpoint: `https://three.ws/api/okx/3d/identity-studio`++> The buyer-facing contract for this service (price, the payment challenge and replay flow, the payment guarantees, the rails it settles on) lives in [OKX.AI Marketplace Services](./okx-marketplace.md#agent-identity-studio-150-per-identity). This document is the other half: what the pipeline actually does between the brief and the deliverables, what the showcase page renders, and the shape of the job API. Read the marketplace doc first if you are buying; read this one if you are building on it or changing it.++## Why it exists++An agent on a marketplace is a row of text next to an empty avatar slot. Text-to-3D alone does not fix that: a raw generated mesh has no skeleton, so it cannot be posed or animated, and a marketplace avatar slot wants a square crop framed on the face, not a full-body shot shrunk to 128 pixels. The Identity Studio is the whole path in one call: prompt shaping, mesh generation, humanoid auto-rig, pose selection, rendering, cropping, and hosting. What comes back is usable everywhere at once, in the avatar slot, in a three.ws scene, in a game engine, in any glTF runtime.++## What gets generated++One completed job produces:++| Deliverable | Detail |+| --- | --- |+| `pfp.url` | Square PNG, 1024 px, head and shoulders, composited on a studio backdrop |+| `pfp.preview_128_url` | The same crop at 128 px, for thumbnail and avatar slots |+| `full_body[]` | Three 1024x1280 (4:5 portrait) renders, one per pose, same backdrop and lighting |+| `rigged_glb_url` | The avatar with a humanoid skeleton and skin weights |+| `mesh_glb_url` | The unrigged generated mesh, kept so a rig hiccup never loses the generation |+| `viewer_url` | Deep link into the three.ws [viewer](./viewer.md) for the rigged GLB |+| `pose_studio_url` | Deep link into the [Animation Studio](./animation-studio.md) for the rigged GLB |++Every render is persisted to object storage under `okx-identity/renders/<job>/` and served from a public URL, so the URLs in the response are permanent and hotlinkable.++## The brief-to-identity flow++The pipeline lives in [`api/_okx3d/identity.js`](../api/_okx3d/identity.js). Every heavy stage runs over the deployed three.ws HTTP surfaces rather than a provider SDK, so the module holds no provider keys and behaves identically inside the API function and in a local script run.++### 1. Shape the brief into a generation prompt++A brand brief is not a visual subject. "A meticulous on-chain accounting agent that reconciles wallets" describes behaviour; a text-to-3D encoder needs a body, an outfit, materials, and a colour palette. So the brief is first rewritten by an LLM art director over the platform's provider chain, instructed to describe a *single* full-body humanoid character in a standing neutral pose on a plain background, always in English regardless of the brief's language, with no scene, no held props, no text or logos.++The director is fail-soft. If no provider answers, or the completion comes back empty or out of range, the pipeline falls back to a deterministic template that leads with the style hints (the actual visual direction) and reduces the brief to its first sentence, handling both Latin and CJK sentence punctuation. It never fabricates a subject, and it never leaves a dangling comma or a half word at a cut. The response reports which path was taken as `directed: true | false`, and always returns the exact `prompt` that was sent.++Two hard limits, both visible in the response:++- A brief longer than 2000 characters is truncated, and every response carries `brief_truncated: true` plus a note.+- The final generation prompt is clamped to 300 characters at a word boundary. This is measured, not guessed: against production generation, prompts around 250 characters generate cleanly while prompts around 430 characters fail.++### 2. Generate the mesh++The shaped prompt goes to the generation lane at `/api/forge` with a 3:4 aspect ratio. A `reference_image_url`, when supplied, is passed as an image input so the look is guided by the picture. The free lane can complete synchronously and hand back the finished GLB in the submit response, in which case the job jumps straight to rigging; asynchronous backends return a job handle to poll.++### 3. Auto-rig to a humanoid skeleton++The generated GLB is submitted to `/api/forge?action=rig`, which adds a humanoid skeleton and skin weights. Unlike the generic avatar service, there is no humanoid gate here: the subject is humanoid by construction, because the prompt shaping forced it. That matters, because an identity brief ("a finance data agent") almost never names a humanoid subject on its own.++### 4. Plan the poses++The render plan is derived deterministically from the job id (a SHA-256 seed), so the same job always renders the same poses, while different jobs vary:++- **The PFP pose is pinned** to `contrapposto`, a neutral standing preset, at a 14 degree camera orbit. The head crop below assumes the top of the model's alpha bounding box is the head, which a raised-arm pose would break.+- **Three full-body poses** are drawn without replacement from a shortlist that reads well as a brand identity: `hands-on-hips`, `relaxed`, `wave`, `salute`, `point`, `fighting-stance`, `walk-step`, `flex`. Their camera orbits are 0, 24, and -18 degrees, so the three shots are visibly different framings rather than the same photo three times.++Every planned pose is validated against the live pose-preset catalogue when the plan is built, so a stale preset id fails loudly in tests instead of returning a 400 from the renderer mid job.++### 5. Render and composite++Each pose is rendered at 1600x1600 with a transparent background through `/api/render/avatar-clip`, then composited locally with `sharp`:++1. Trim the render to the model's alpha bounding box. Every crop calculation keys off those real dimensions, not the canvas.+2. **PFP:** take a square from the top of the trimmed body whose side is 36% of the body height (clamped to the body width so a narrow model is never over-cropped), centre it horizontally, and place it on the backdrop with 8% breathing room so the head does not kiss the frame. Output 1024 px, plus a 128 px resize.+3. **Full body:** scale the trimmed model to fit 82% of the frame width and 90% of its height, and centre it in a 1024x1280 portrait frame.++The backdrop is a brand-neutral dark radial gradient rasterized from inline SVG, so it matches the three.ws dark tokens and no binary asset ships with the code.++## The job model++Job state is a single JSON document in object storage (`okx-identity/jobs/<id>.json`). The lifecycle is deliberately poll-driven:++- `create_identity` validates the input, submits generation, and returns a signed job token. Validation, including fetching a supplied `reference_image_url`, happens **before** the transport settles the payment.+- Each free `identity_status` poll advances the job by exactly **one bounded step**: a single upstream poll, or one render. No request outlives its function budget, and polling is what drives the job forward. Poll roughly every 5 seconds; typical time to `done` is 3 to 6 minutes.+- Stages run in order: `generate`, `rig`, `render`, `done` (or `failed`).++Failure handling is built around one principle: the buyer pays for deliverables, not for transient upstream weather.++- A failed `generate` or `rig` stage clears its job handle and **retries free** on the next poll, up to 3 total attempts. A failed render re-runs the same render on the next poll (the cursor does not move).+- Backpressure is not failure. A rate-limited upstream consumes no retry attempt: the job parks until `retry_after` elapses (default 30 seconds, capped at 5 minutes) and a later poll resubmits.+- A `not_configured` error (the lane itself is down) is terminal, and so is an exhausted retry budget. Either way `status` becomes `failed` and `last_error` carries the last actionable message.++The reference image is fetched through the platform's SSRF guard with a pinned host and a byte cap, so a validated hostname cannot redirect to an internal address, and a host that ignores the range request cannot stream an unbounded body.++## The API++The endpoint is an A2MCP service: MCP Streamable HTTP, JSON-RPC `tools/call` over `POST`, with `GET` serving the discovery challenge and `DELETE` terminating a session. Three tools:++| Tool | Price | What it does |+| --- | --- | --- |+| `getting_started` | free | Server overview: tools, prices, access rules, links |+| `create_identity` | $1.50 | Accepts the job. Arguments: `agent_name` (required, up to 80 chars), `brief` (required), `style_hints`, `reference_image_url` |+| `identity_status` | free | Advances the job one step and reports progress or deliverables |++`create_identity` returns immediately with the job handle:++```json+{+ "ok": true,+ "job_id": "<signed job token>",+ "status": "running",+ "stage": "generate",+ "eta_seconds": 300,+ "poll_tool": "identity_status",+ "brief_truncated": false+}+```++`identity_status` is free, unauthenticated, and needs nothing but the job token (which is HMAC-signed, so it is the only capability required to read a job). Jobs persist for about 30 days. While running:++```json+{+ "job_id": "<signed job token>",+ "status": "running",+ "stage": "render",+ "progress": { "steps": ["generate", "rig", "render", "done"], "renders_done": 2, "renders_total": 4 },+ "brief_truncated": false,+ "prompt": "<the exact prompt sent to the generator>",+ "directed": true+}+```++When `status` is `"done"`, the same body carries a `deliverables` object with the fields in the table above. When `status` is `"failed"`, it carries `last_error` as `{ stage, code, message, retrying }`.++Two free companion endpoints round out the surface: `GET /api/okx/3d/catalog` is the machine-readable service index, and `GET /api/okx/3d/health` probes every subsystem a paid identity job passes through (generation, renderer, storage, the animation clip lane, and the payment rail) with real requests rather than a static `ok`. Both are documented in [OKX.AI Marketplace Services](./okx-marketplace.md#free-discovery-lane).++Prices, descriptions, and input schemas are not written twice: [`api/_lib/okx-catalog.js`](../api/_lib/okx-catalog.js) is the single source of truth that the tool definitions, the catalog endpoint, and the marketplace listing all read.++## The showcase page++[/agent-identities](https://three.ws/agent-identities) renders the demo identities in [`data/agent-identities.json`](../data/agent-identities.json). Every entry there is a **real run of the production pipeline**, the same module the endpoint executes, driven locally by [`scripts/okx-identity-demo.mjs`](../scripts/okx-identity-demo.mjs), which writes the results back into the JSON file. Nothing on that page is a mock or a hand-picked asset.++The script does not take the pipeline's word for it either. It downloads the finished GLB, parses its JSON chunk, and asserts real rigging: at least one skin, at least 10 joints in total, and at least one mesh primitive carrying both `JOINTS_0` and `WEIGHTS_0`. A run that fails that check is recorded as failed rather than shipped as a success. The verified numbers (byte size, skins, joints, skinned primitives, glTF generator) are stored per identity alongside the wall-clock duration and completion timestamp.++Each card ([`src/agent-identities.js`](../src/agent-identities.js)) shows the full-body hero shot with the PFP crop pinned over it, thumbnail buttons to switch poses (with `aria-pressed` tracking the active one), and a "View in 3D" action that lazy-loads `model-viewer` and swaps the still for the orbitable rigged GLB. The 3D runtime is only fetched when someone asks for it, never on page load. An entry without a completed run renders an honest "still in the studio" state instead of a broken card.++To regenerate or add a demo identity, add the entry (slug, kind, agent name, brief, style hints) and run the script. It needs the object-storage credentials from your local env; generation, rigging, and rendering all run against the deployed surfaces.++```bash+# One identity by slug, or every entry with no result yet.+node --env-file=.env.local scripts/okx-identity-demo.mjs ledgerlynx++# Re-run an entry that already has a result.+node --env-file=.env.local scripts/okx-identity-demo.mjs ledgerlynx --force+```++Two environment overrides help a batch run outlast the rig lane's rate-limit backoff windows: `IDENTITY_DEMO_POLL_MS` (default 5000) and `IDENTITY_DEMO_TIMEOUT_MS` (default 15 minutes).++## Related++- [OKX.AI Marketplace Services](./okx-marketplace.md): the price, the payment challenge, the replay flow, the payment guarantees, and the decomposed single-capability 3D services that share these engines.+- [Forge](./forge.md): the text and image to GLB generation pipeline this studio calls for the mesh and the auto-rig.+- [Animation Studio](./animation-studio.md): the `/pose` surface the `pose_studio_url` deep link opens.+- [Viewer](./viewer.md): the `/viewer` surface the `viewer_url` deep link opens.+- [MCP servers](./mcp.md): the wider set of three.ws MCP endpoints this one follows the transport conventions of.+- [Avatar Engines Atlas](./avatar-engines.md): what engine families exist for building human avatars, and which of them are wired into the commercial pipeline.diff --git a/docs/agent-wallet-api.md b/docs/agent-wallet-api.mdnew file mode 100644index 000000000..21b8d5882--- /dev/null+++ b/docs/agent-wallet-api.md@@ -0,0 +1,1185 @@+# Agent wallet control API++Every three.ws agent owns one custodial **Solana** wallet. Seven owner-only HTTP surfaces hang off it, and this is their developer reference: exact routes, exact request and response JSON, exact error codes, and a working curl call for each.++This document is the API reference the surrounding docs deliberately leave out. Read those first for the "why":++- [Agent wallets](agent-wallets.md) for how the wallet is created, how its key is held, and which paths may spend.+- [Custody you can verify](custody.md) for the limits, the freeze switch, the Merkle proof of custody, and the social-recovery model.+- [Financial controls](financial-controls.md) for the plain-English spend-rule layer and the anomaly guard behind `/solana/guard`.+- [The Trading Copilot](trading-copilot.md) for the conversational surface that proposes trades a human confirms.+- [Coin Autopilot](autopilot.md) for the *coin* cockpit at `/api/pump/autopilot`. That is a different feature from the **Treasury Autopilot** documented here, which runs the agent's own wallet rather than a launched coin.++## Orientation++All seven surfaces address the same custodial Solana keypair, obey the same owner gate, and are clamped by the same spend policy. None of them can widen authority: each one either reads the wallet, or narrows and schedules what the wallet is already allowed to do.++| Surface | Route root | What it controls |+|---|---|---|+| Capabilities | `/api/agents/:id/capabilities` | Scoped, time-boxed, revocable session keys for autonomous spend |+| Orders | `/api/agents/:id/orders` | The programmable order engine (limit, stop, trailing, DCA, TWAP, conditional) |+| Intents | `/api/agents/:id/intents` | Plain-language wallet rules compiled into structured, armed intents |+| Treasury Autopilot | `/api/agents/:id/autopilot` | The self-funding treasury policy and its runway view |+| Portfolio | `/api/agents/:id/portfolio` | FIFO cost basis, realized and unrealized P&L by source, live risk metrics |+| Recovery | `/api/agents/:id/recovery` | Guardians, approval threshold, dead-man check-in, inheritance |+| Solana guard | `/api/agents/:id/solana/guard` | The behavioral anomaly baseline, its sensitivity, and freeze adjudication |++The shared model, in one paragraph. A caller is resolved to a user id from either a session cookie or a bearer token. That user must own the agent, or the surface refuses (recovery is the one exception: guardians and the beneficiary get a scoped view). Every mutation is CSRF-gated for cookie callers. Anything that can move funds runs through the shared spend guards in [`api/_lib/agent-trade-guards.js`](../api/_lib/agent-trade-guards.js), so the wallet-wide policy (`per_tx_usd`, `daily_usd`, `withdraw_allowlist`, `frozen`, `require_capabilities`) is enforced at the signing boundary, not per feature. A scheduled order, an armed intent, and an autopilot rule are therefore all subject to the same ceilings and the same freeze as a manual trade.++## Shared conventions++### Base path and the agent id++Every route below is relative to `https://three.ws/api/agents/<agent-id>`. The agent id must be a UUID. A malformed id is rejected with `404 not_found` by the dispatcher in [`api/agents/[id].js`](../api/agents/%5Bid%5D.js) before any handler runs, so a bad id never surfaces as a database error.++### Authentication++Two credential types are accepted, resolved in this order:++1. **Session cookie.** The browser session issued by the normal sign-in flow.+2. **Bearer token.** `Authorization: Bearer <token>`, where the token is either an API key (`sk_live_…` or `sk_test_…`) or an OAuth access token.++The resolved user id is then compared against `agent_identities.user_id`. The three gate outcomes are identical across surfaces:++| Status | `error` | Meaning |+|---|---|---|+| `401` | `unauthorized` | No session and no valid bearer token |+| `404` | `not_found` | No such agent, or it is soft-deleted |+| `403` | `forbidden` | Authenticated, but not the agent's owner |++Recovery differs: it computes the caller's relationship to the agent (owner, guardian, beneficiary) and authorizes per action. See [Recovery](#recovery-guardians-threshold-and-inheritance).++### CSRF++Every state-changing request passes through [`api/_lib/csrf.js`](../api/_lib/csrf.js).++- **Bearer callers are exempt.** The token is itself the proof of intent, and browsers do not attach it automatically.+- **Cookie callers must double-submit.** Fetch a token from `GET /api/csrf-token` and echo it in the `X-CSRF-Token` header. Tokens are bound to the user id, expire after one hour, and are consumed on use, so each mutation needs a fresh one.++Failures are `403 csrf_missing` (header absent) and `403 csrf_invalid` (wrong user, expired, or already consumed).++### Network selection++Solana is the home chain and mainnet is the default. Append `?network=devnet` to switch a read or a write to devnet; any other value falls back to mainnet. Capabilities are network-independent and ignore the parameter.++### Error envelope++Errors are JSON, never cached:++```json+{ "error": "forbidden", "error_description": "not your agent" }+```++Some errors carry extra keys: validation failures on capabilities add `detail` with the offending `field`; recovery conflicts add `detail` with the request phase; internal failures add a `ref` you can quote to support; `429` adds `retry_after` and sometimes `reason`.++### Rate limits++Reads use a per-user wallet-read bucket. Order creation uses a per-user trade bucket. Intent compile and intent copilot use a per-user chat bucket. Capability mutations and recovery mutations use a per-IP critical-action bucket. Exceeding one returns `429 rate_limited` with a `retry-after` header. The exact ceilings live in [`api/_lib/rate-limit.js`](../api/_lib/rate-limit.js); treat that file as the source of truth rather than hardcoding numbers.++### Response envelope++Orders, intents, autopilot, portfolio, recovery, and the guard wrap their payload in `{ "data": … }`. Capabilities returns its keys at the top level. The examples below show each surface exactly as coded.++A cookie-authenticated mutation therefore looks like this:++```bash+CSRF=$(curl -s -b cookies.txt https://three.ws/api/csrf-token | jq -r .token)+curl -s -b cookies.txt \+ -H "x-csrf-token: $CSRF" \+ -H 'content-type: application/json' \+ -d '{"require_capabilities":true}' \+ -X PUT "https://three.ws/api/agents/$AGENT_ID/capabilities/settings"+```++Every later example uses a bearer token for brevity. Substitute the two headers above to drive the same route from a browser session.++## Capabilities: scoped session keys++Source: [`api/agents/capabilities.js`](../api/agents/capabilities.js), enforcement in [`api/_lib/wallet-capabilities.js`](../api/_lib/wallet-capabilities.js). Product tour: [Access](agent-abilities/wallet/21-access.md).++A capability is a signed, time-boxed grant that lets one named holder spend a narrow slice of the wallet's authority. Grants strictly subtract: on every autonomous spend both the capability ceiling and the wallet-wide policy must pass. The scope is HMAC-signed with `WALLET_CAPABILITY_SECRET` and re-verified on use, so an edited or forged row fails its integrity check and is rejected.++| Method | Route | Purpose |+|---|---|---|+| `GET` | `/capabilities` | List grants (live and historical), settings, action vocabulary, suggestions |+| `POST` | `/capabilities` | Mint a scoped grant |+| `PUT` | `/capabilities/settings` | Toggle least-privilege mode |+| `POST` | `/capabilities/:capabilityId/revoke` | Revoke one grant, immediately |+| `POST` | `/capabilities/revoke-all` | Revoke every live grant (kill switch) |++`GET` is owner-gated and needs no CSRF. All three mutations are owner-gated, CSRF-gated, and rate-limited per IP.++### GET /capabilities++```json+{+ "capabilities": [+ {+ "id": "8f14e45f-ceea-467a-9c3f-2a1b7c4d5e6f",+ "label": "Sniper strategy",+ "holder_kind": "strategy",+ "holder_ref": "41",+ "actions": ["snipe"],+ "per_use_usd": 12,+ "aggregate_usd": 240,+ "target_kind": "mint",+ "targets": ["FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"],+ "expires_at": "2026-07-31T09:00:00.000Z",+ "revoked_at": null,+ "revoked_reason": null,+ "created_at": "2026-07-30T09:00:00.000Z",+ "last_used_at": "2026-07-30T11:42:07.512Z",+ "use_count": 3,+ "spent_usd": 31.4,+ "spend_count": 3,+ "status": "active"+ }+ ],+ "settings": { "require_capabilities": false },+ "actions": ["trade", "snipe", "x402"],+ "suggestions": []+}+```++`status` is derived, not stored: `active`, `revoked`, `expired`, or `tampered` (the HMAC no longer matches the row's scope). `spent_usd` and `spend_count` are summed from the same custody ledger that backs the wallet's daily ceiling, so a grant's meter and the wallet's audit trail can never disagree. The list includes revoked and expired grants and is capped at the 200 newest.++`suggestions` proposes least-privilege defaults so strict mode is not a chore. For each armed sniper strategy with a positive daily budget and no live grant scoped to it, the server drafts a `snipe` grant sized from that strategy's own budget:++```json+{+ "kind": "strategy",+ "holder_ref": "41",+ "label": "Sniper strategy",+ "reason": "This strategy can spend up to ◎0.500/day. A scoped key makes that explicit and revocable on its own.",+ "draft": {+ "label": "Sniper strategy",+ "holder_kind": "strategy",+ "holder_ref": "41",+ "actions": ["snipe"],+ "per_use_usd": 9,+ "aggregate_usd": 88,+ "target_kind": "any",+ "targets": [],+ "ttl_seconds": 86400+ }+}+```++The `draft` object is shaped to be POSTed straight back, which is how the Access tab implements one-tap accept. When the SOL price feed is unavailable both USD figures come back `null` and the draft narrows by action and expiry alone.++### POST /capabilities++| Field | Type | Notes |+|---|---|---|+| `label` | string | Up to 120 chars. Defaults to a generated label from holder kind and actions |+| `holder_kind` | string | `skill`, `strategy`, `integration`, `manual`. Anything else becomes `manual` |+| `holder_ref` | string | Stable id of the holder (a strategy id, a service host, a skill key). Up to 128 chars |+| `actions` | string[] | Required. One or more of `trade`, `snipe`, `x402`. Unknown values are dropped |+| `per_use_usd` | number | Optional per-spend ceiling |+| `aggregate_usd` | number | Optional lifetime budget. Must be at least `per_use_usd` |+| `target_kind` | string | `any` (default), `mint`, `service`, `destination` |+| `targets` | string[] | Required when `target_kind` is not `any`. Up to 50 entries |+| `expires_at` | ISO date | Absolute expiry. Takes precedence over `ttl_seconds` |+| `ttl_seconds` | number | Relative expiry, clamped to 60 seconds through one year. Defaults to 24 hours |+| `meta` | object | Free-form metadata stored with the grant |++`withdraw` is deliberately not a grantable action: an owner sweep is not a delegated capability. `service` targets are normalized to bare lowercase hostnames, so `https://api.example.com/v1` and `api.example.com` both store as `api.example.com` and both match a payment to that host.++Success is `201` with the grant shaped exactly like a list row:++```json+{ "capability": { "id": "…", "status": "active", "spent_usd": 0, "spend_count": 0 } }+```++Issuance errors are `400` with `error: "invalid"` and a `detail.field` pointer. The refusals, in the order they are checked:++| Condition | `detail.field` |+|---|---|+| No recognized action | `actions` |+| A non-`any` target kind with no usable targets | `targets` |+| Neither a ceiling nor a target restriction (the grant would narrow nothing) | `ceiling` |+| `per_use_usd` greater than `aggregate_usd` | `per_use_usd` |+| `expires_at` unparseable, in the past, or more than a year out | `expires_at` |++If `WALLET_CAPABILITY_SECRET` is missing or shorter than 8 characters the mint fails closed with `503 config` rather than issuing a grant whose signature could be forged.++```bash+curl -s -X POST "https://three.ws/api/agents/$AGENT_ID/capabilities" \+ -H "authorization: Bearer $THREE_WS_TOKEN" \+ -H 'content-type: application/json' \+ -d '{+ "label": "Weather skill",+ "holder_kind": "skill",+ "holder_ref": "weather-v1",+ "actions": ["x402"],+ "per_use_usd": 0.25,+ "aggregate_usd": 10,+ "target_kind": "service",+ "targets": ["api.example.com"],+ "ttl_seconds": 604800+ }'+```++### PUT /capabilities/settings++Body: `{ "require_capabilities": true | false }`. A non-boolean is `400 validation_error`. The flag is written into the wallet's spend policy, so turning it on means every autonomous spend without a covering grant is denied at the signing boundary. Owner withdrawals are unaffected.++```json+{ "settings": { "require_capabilities": true } }+```++### POST /capabilities/:capabilityId/revoke++Revocation is immediate and idempotent. Revoking an already-dead grant still returns `200`, with `already: true`:++```json+{ "revoked": true, "id": "8f14e45f-ceea-467a-9c3f-2a1b7c4d5e6f", "already": false }+```++A grant id belonging to a different agent is `404 not_found`. Every revoke writes a custody event.++### POST /capabilities/revoke-all++No body. Returns the number of live grants killed:++```json+{ "revoked": true, "count": 4 }+```++```bash+curl -s -X POST "https://three.ws/api/agents/$AGENT_ID/capabilities/revoke-all" \+ -H "authorization: Bearer $THREE_WS_TOKEN"+```++### Routing notes++The dispatcher only recognizes `GET` with no sub-path, `POST` with no sub-path, `PUT /settings`, `POST /revoke-all`, and `POST /<id>/revoke`. Anything else, including `GET /capabilities/<id>` and `DELETE`, returns `405 method_not_allowed`.++## Orders: the programmable order engine++Source: [`api/agents/orders.js`](../api/agents/orders.js), order model and condition language in [`api/_lib/orders.js`](../api/_lib/orders.js). Product tour: [Orders](agent-abilities/wallet/12-orders.md).++Orders are evaluated by the [`workers/agent-orders`](../workers/agent-orders/README.md) sweep and fire through the same guarded, firewalled, audited trade pipeline as a manual trade. The endpoint creates and manages them; it never signs.++| Method | Route | Purpose |+|---|---|---|+| `GET` | `/orders` | Orders, summary, live balance, freeze and kill-switch state |+| `POST` | `/orders` | Create a validated order |+| `POST` | `/orders/preview` | Validate plus a live preview: current metric, would-fire-now, firewall verdict |+| `POST` | `/orders/cancel-all` | Cancel every non-terminal order (orders kill switch) |+| `GET` | `/orders/schema` | The closed condition vocabulary that drives the UI builder |+| `GET` | `/orders/stream` | Server-sent events: the order list as it changes |+| `GET` | `/orders/:orderId` | One order plus its fills |+| `PUT` | `/orders/:orderId` | Edit price, trail, slippage, expiry, or pause state |+| `DELETE` | `/orders/:orderId` | Cancel one order, instantly |++Reads are owner-gated. `POST`, `PUT`, and `DELETE` are additionally CSRF-gated. `:orderId` must be a UUID; a non-UUID sub-path is `404 not_found`, and an unsupported method on a UUID path is `405 method_not_allowed`.++### The order model++| Type | Fires when |+|---|---|+| `limit` | A buy at or below the target, a sell at or above it |+| `stop` | A buy once the level breaks upward, a sell once it breaks downward |+| `trailing` | A sell after `trail_pct` off the high-water mark, a buy after `trail_pct` off the low |+| `dca` | On a fixed interval, `slices` times |+| `twap` | One total order sliced over time to cut price impact |+| `conditional` | A validated signal condition becomes true |++Shared fields: `type`, `side` (`buy` or `sell`), `mint` (validated Solana address), optional `symbol`, `slippage_bps` (clamped to 1 through 5000, default 500), optional `max_price_impact_pct`, optional `expires_at`, and `trigger_metric` (`price_sol`, `mcap_sol`, or `mcap_usd`, default `mcap_usd`).++Sizing: a buy needs `size_sol`; a sell needs either `size_tokens` (raw base units) or `sell_pct` (over 0 through 100). A TWAP buy takes `total_sol` and derives the per-slice size; a TWAP sell takes `total_tokens` or `sell_pct` and divides it across the slices.++Per-type fields: `limit_price` for `limit`, `stop_price` for `stop`, `trail_pct` (over 0, under 100) for `trailing`, `schedule: { interval_seconds, slices }` for `dca` (minimum 60 seconds, 1 slice) and `twap` (minimum 30 seconds, 2 slices, maximum 1000 slices), and `condition` for `conditional`.++A condition is one level deep, with no expressions and no code: `{ "all": [leaf, …] }` or `{ "any": [leaf, …] }`, at most 8 leaves. Each leaf is `{ signal, op, value }`. The closed signal set is `price_sol`, `mcap_sol`, `mcap_usd`, `price_change_pct`, `smart_money_score` (numeric, operators `gt`, `gte`, `lt`, `lte`, `eq`, `ne`), plus `dev_dump` and `graduated` (boolean, operators `is_true`, `is_false`). A signal the worker cannot read is treated as indeterminate: it never counts as satisfied and is reported in `missing`, so an order cannot fire on absent data.++### GET /orders++```json+{+ "data": {+ "orders": [+ {+ "id": "1b0e2c44-7f2a-4f7f-9a3c-6f8f9d0a1b2c",+ "network": "mainnet",+ "mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "symbol": "THREE",+ "type": "limit",+ "side": "buy",+ "size_sol": 0.25,+ "size_tokens": null,+ "sell_pct": null,+ "trigger_metric": "mcap_usd",+ "limit_price": 40000,+ "stop_price": null,+ "trail_pct": null,+ "peak_price": null,+ "reference_price": null,+ "schedule": null,+ "next_fire_at": null,+ "condition": null,+ "slippage_bps": 500,+ "max_price_impact_pct": null,+ "expires_at": null,+ "status": "active",+ "filled_sol": 0,+ "filled_tokens": 0,+ "fill_count": 0,+ "last_eval_at": "2026-07-30T12:00:03.118Z",+ "last_price": 51200,+ "last_error": null,+ "readback": "Buy 0.25 SOL of $THREE when it reaches $40,000 mcap (limit buy)."+ }+ ],+ "summary": {+ "total": 6,+ "active": 2,+ "filled": 3,+ "lifetime_fills": 5,+ "lifetime_filled_sol": 1.15,+ "balance_sol": 2.418,+ "frozen": false,+ "kill_switch": false+ }+ }+}+```++`readback` is a generated plain-language description of the order, produced by the same function the UI and the worker use. `balance_sol` is a live chain read and comes back `null` if the RPC read fails, which never fails the request.++### POST /orders++Returns `201` with `{ "data": { "order": … } }`. Validation failures are `422` and carry the specific code from the normalizer: `invalid_order`, `invalid_type`, `invalid_side`, `invalid_mint`, `invalid_size`, `invalid_price`, `invalid_trail`, `invalid_schedule`, `invalid_expiry`, or `invalid_condition`, each with a human-readable `error_description`. A malformed body is `400 bad_request`, a wrong content type is `415`, and a database failure is `500 create_failed`.++DCA and TWAP orders are created with `next_fire_at` set to now, so the first slice fires on the next worker sweep.++```bash+curl -s -X POST "https://three.ws/api/agents/$AGENT_ID/orders" \+ -H "authorization: Bearer $THREE_WS_TOKEN" \+ -H 'content-type: application/json' \+ -d '{+ "type": "trailing",+ "side": "sell",+ "mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "symbol": "THREE",+ "sell_pct": 50,+ "trail_pct": 18,+ "trigger_metric": "mcap_usd",+ "slippage_bps": 700+ }'+```++### POST /orders/preview++Preview is a validator, not a creator, so an invalid order comes back `200` with `ok: false` instead of `422`:++```json+{ "data": { "ok": false, "error": "invalid_trail", "message": "trail_pct must be between 0 and 100" } }+```++A valid order returns the normalized spec, its readback, a live market snapshot, and (for buys) a real firewall verdict:++```json+{+ "data": {+ "ok": true,+ "order": { "type": "limit", "side": "buy", "size_sol": 0.25 },+ "readback": "Buy 0.25 SOL of $THREE when it reaches $40,000 mcap (limit buy).",+ "preview": {+ "current": {+ "metric": "mcap_usd",+ "value": 51200,+ "price_sol": 0.0000004,+ "mcap_sol": 320,+ "mcap_usd": 51200,+ "graduated": false+ },+ "would_fire_now": false,+ "missing": []+ },+ "firewall": { "verdict": "allow", "score": 0.12, "simulated": true, "reasons": [] },+ "spend_limits": {+ "per_tx_usd": null,+ "daily_usd": 250,+ "frozen": false,+ "kill_switch": false,+ "per_trade_sol": 0.5,+ "daily_budget_sol": 2+ }+ }+}+```++Three honest nulls to expect. `preview.current` is `null` when the quote lane misses, and the endpoint still succeeds. `would_fire_now` is always `false` for a trailing order, because a trail needs a tracked high or low-water mark that does not exist until the order is live. `firewall` is `null` for sells, for a wallet with no Solana address, and when the on-chain simulation cannot be run.++### POST /orders/cancel-all++No body. Cancels every order in `active`, `partial`, `firing`, or `paused` on the selected network and returns the count:++```json+{ "data": { "cancelled": 3 } }+```++### GET /orders/schema++Returns `order_types`, `trigger_metrics`, `number_ops`, `bool_ops`, and `signals` (each signal as `{ kind, label }`). Build a client against this rather than hardcoding the vocabulary, since the endpoint and the worker import it from one module.++### GET /orders/:orderId++```json+{+ "data": {+ "order": { "id": "1b0e2c44-7f2a-4f7f-9a3c-6f8f9d0a1b2c", "status": "partial" },+ "fills": [+ {+ "id": 91,+ "slice_index": 0,+ "side": "buy",+ "trigger_reason": "limit_price",+ "trigger_price": 39880,+ "sol_amount": 0.25,+ "token_amount": 1840221,+ "price_impact_pct": 0.7,+ "venue": "pump",+ "signature": "5xQ…",+ "custody_event_id": 4412,+ "status": "confirmed",+ "detail": {},+ "created_at": "2026-07-30T12:01:44.019Z"+ }+ ]+ }+}+```++Each fill carries a `custody_event_id`, which is the join back into the custody ledger that the daily spend ceiling and the proof-of-custody attestation are computed from.++### PUT /orders/:orderId++Only a bounded set of fields can change, and `type`, `side`, and `mint` are immutable (cancel and recreate instead). Accepted keys: `limit_price` (on a `limit` order), `stop_price` (on a `stop`), `trail_pct` (on a `trailing`), `slippage_bps`, `expires_at`, and `paused`.++`paused: true` parks the order in a non-evaluated state without losing fill progress. `paused: false` returns it to `partial` if it has fills, otherwise `active`. An empty patch is a no-op that returns the unchanged order.++Errors: `404 not_found` for an unknown order, `422 immutable` for a filled, cancelled, or expired order, `422 invalid_price`, `422 invalid_trail`, `422 invalid_expiry`, and `500 update_failed`.++### DELETE /orders/:orderId++Instant and idempotent. Returns `{ "data": { "order": … } }` with the order in its terminal state. A cancel on an already-terminal order returns that order rather than an error; an unknown id is `404 not_found`.++### GET /orders/stream++Server-sent events, read-only, no CSRF. The connection closes itself after about 40 seconds and the browser's `EventSource` reconnects.++| Event | Payload | Meaning |+|---|---|---|+| `orders` | `{ orders, summary }` | The list changed (status, fill count, last price, or last error) |+| `ping` | `{ t }` | Nothing changed on this tick, or a tick failed to read |+| `close` | `{ reason: "duration_limit" }` | The stream is ending; reconnect |++```bash+curl -N "https://three.ws/api/agents/$AGENT_ID/orders/stream?network=mainnet" \+ -H "authorization: Bearer $THREE_WS_TOKEN"+```++## Intents: plain language to structured wallet rules++Source: [`api/agents/wallet-intents.js`](../api/agents/wallet-intents.js), engine in [`api/_lib/wallet-intents.js`](../api/_lib/wallet-intents.js). Product tour: [Intents](agent-abilities/wallet/14-intents.md).++An intent is a trigger plus an action plus the owner's own caps. The compiler turns a sentence into that structure and never arms it; arming is a separate, explicit call.++| Method | Route | Purpose |+|---|---|---|+| `GET` | `/intents` | The agent's intents plus a live summary |+| `POST` | `/intents/compile` | Compile plain language into a validated intent (preview only) |+| `POST` | `/intents` | Arm a validated intent |+| `POST` | `/intents/run` | Test one intent now, dry by default |+| `POST` | `/intents/copilot` | Ask about the wallet over real holdings and custody P&L |+| `GET` | `/intents/:intentId` | One intent |+| `PUT` | `/intents/:intentId` | Enable, disable, retitle, publish, or replace the rule |+| `DELETE` | `/intents/:intentId` | Remove an intent |++All writes are owner-gated and CSRF-gated. `:intentId` must be a UUID.++### The intent model++Triggers: `on_tip_received` (optional `min_sol`), `on_income`, `on_balance_below` (required `threshold_sol`), `on_schedule` (`cadence` of `daily` or `weekly`, `weekday` 0 through 6, `hour` 0 through 23 UTC), `on_launch_matching` (needs a base58 `creator` and/or a `max_mcap_usd`, optional `min_mcap_usd`), and `on_stream_started`.++Actions: `tip`, `transfer`, `withdraw`, `split_income` (move SOL: take `pct` with an `of` basis of `tip`, `income`, or `balance`, or a fixed `amount_sol`, or for a withdraw an `above_sol` floor, plus a `destination`), `buy` and `snipe` (need `amount_sol`, plus a `mint` unless the trigger is `on_launch_matching`, with an optional `slippage_pct` clamped to 0 through 50 and defaulting to 5), `freeze` (no parameters, the kill switch), and `notify` (optional `message`, `channel` of `email` or `log`).++A tip-back to whoever just tipped needs no destination: with `on_tip_received` plus a `tip` action the engine fills in the tipper at fire time and marks `to_tipper`.++Owner caps live in `limits`: `per_action_usd`, `daily_usd`, `total_usd`. They are additive to the wallet policy, never a replacement, and a breach downgrades the fire to `skipped` or `paused` with an explanation rather than throwing.++Validation failures are `422` with a precise code: `bad_trigger`, `bad_action`, `needs_threshold`, `needs_filter`, `needs_amount`, `needs_pct`, `needs_mint`, or `needs_destination`.++### GET /intents++```json+{+ "data": {+ "intents": [+ {+ "id": "a3f0c9ee-4b1d-4c2f-8a10-11c0ffee1234",+ "title": "On a tip -> tip back",+ "trigger": { "type": "on_tip_received", "min_sol": 0.2 },+ "action": { "type": "tip", "pct": 10, "of": "tip", "to_tipper": true },+ "limits": { "per_action_usd": 5, "daily_usd": 25, "total_usd": null },+ "network": "mainnet",+ "enabled": true,+ "public_trait": false,+ "source_text": "tip back 10% of any tip over 0.2 SOL",+ "readback": "When someone tips more than 0.2 SOL, tip back 10% of tip.",+ "stats": {+ "fire_count": 7,+ "spent_usd": 3.42,+ "last_fired_at": "2026-07-29T22:04:11.000Z",+ "last_status": "ok",+ "last_note": null,+ "last_signature": "3Kd…"+ }+ }+ ],+ "summary": {+ "count": 3,+ "enabled": 2,+ "lifetime_usd": 12.9,+ "lifetime_fires": 19,+ "balance_sol": 2.418,+ "frozen": false,+ "spend_limits": { "per_tx_usd": null, "daily_usd": 250 }+ }+ }+}+```++### POST /intents/compile++Body: `{ "text": "…", "history": [{ "role": "user" | "assistant", "content": "…" }] }`. Only the last four history turns are used, and each is truncated. An empty `text` is `400 validation_error`; text over 1000 characters is rejected by the compiler.++The provider chain is tried in order: the caller's own Anthropic key, then Grok, then OpenRouter, each read from the user's stored provider keys and falling back to the deployment's environment. Three outcomes:++- **Compiled.** `200` with `ok: true`, the structured `intent`, its `readback`, a concrete `simulation`, and the `provider` that answered.+- **Needs one more detail.** `200` with `ok: false`, `error: "clarify"`, and a `clarify` question. This is a `200` on purpose so a conversational client can keep the turn going.+- **Cannot compile.** `422` with `error` set to the validation code (or `parse_failed`, or `bad_destination`), or `503` with `error: "unavailable"` when no provider key is configured at all, whose message points the owner at the manual form.++```json+{+ "data": {+ "ok": true,+ "intent": {+ "title": "On income -> split income",+ "trigger": { "type": "on_income" },+ "action": { "type": "split_income", "pct": 20, "of": "income", "destination": "7Xy…", "destination_label": "treasury.sol" },+ "limits": { "per_action_usd": null, "daily_usd": 50, "total_usd": null }+ },+ "readback": "On income, split 20% of income to treasury.sol.",+ "simulation": {+ "balance_sol": 2.418,+ "lines": ["Each fire moves 20% of income to treasury.sol.", "Daily budget: $50."]+ },+ "provider": "anthropic"+ }+}+```++A `.sol` name or `@username` destination is resolved to a real base58 address at compile time, and the original text is kept as `destination_label`. An unresolvable name returns `bad_destination` with a `clarify` question rather than storing an unusable rule.++```bash+curl -s -X POST "https://three.ws/api/agents/$AGENT_ID/intents/compile" \+ -H "authorization: Bearer $THREE_WS_TOKEN" \+ -H 'content-type: application/json' \+ -d '{"text":"every Friday at 14:00 UTC withdraw anything above 3 SOL to treasury.sol"}'+```++### POST /intents++Body: `{ "intent": { … }, "source_text": "…", "public_trait": false }`. `intent` is required and is re-validated server-side, so a client cannot arm something the compiler would have rejected. A resolved `destination`, `destination_label`, `to_tipper`, and `mint` from the compile step are preserved through re-validation. `source_text` is stored (truncated to 1000 characters) so the owner can see the sentence the rule came from. `public_trait: true` publishes the rule as a visible agent trait.++Success is `201` with `{ "data": { "intent": … } }`. A missing intent object is `400 validation_error`, an invalid one is `422`, and a write failure is `500 create_failed`.++### POST /intents/run++Body: `{ "intent_id": "<uuid>", "dry_run": true }`. **`dry_run` defaults to `true`**: it is only a real run when you explicitly send `"dry_run": false`. A missing or non-UUID `intent_id` is `400 validation_error`.++A real run honors the freeze, the wallet spend policy, and the intent's own caps exactly like the scheduler, and claims an idempotent custody row so one event can never fire the same intent twice.++```json+{+ "data": {+ "ran": true,+ "dryRun": true,+ "results": [+ {+ "id": "a3f0c9ee-4b1d-4c2f-8a10-11c0ffee1234",+ "title": "On a tip -> tip back",+ "trigger": "on_tip_received",+ "action": "tip",+ "status": "would_run",+ "note": "would move ~$1.87",+ "usd": 1.87+ }+ ]+ }+}+```++`ran: false` comes back with a `reason` of `not_found` or `disabled`. Per-result `status` values are `would_run` (dry run), `ok`, `skipped` (under a cap, or already fired for this event), `paused` (would breach a budget, or the wallet policy refused), and `error`. Testing a launch-matching snipe rule reports readiness instead of picking a launch, since a manual test has no real launch to match.++### POST /intents/copilot++Body: `{ "message": "how am I doing?" }`, trimmed to 500 characters. An empty message is `400 validation_error`. **Funds never move here**: the copilot reads and explains only.++The real numbers are gathered first (live balance, plus 30 days of tips in, spend out, and intent activity from the custody ledger), then phrased in the agent's persona if a model is reachable. With no model key the endpoint still returns the same facts with `provider: "facts"`, so the feature never goes dark.++```json+{+ "data": {+ "reply": "You are up 41 dollars over the last month, and your tip-back rule has fired seven times.",+ "facts": {+ "balance_sol": 2.418,+ "tips_30d_usd": 82.5,+ "spend_30d_usd": 41.1,+ "net_30d_usd": 41.4,+ "active_intents": 2,+ "intent_fires": 19,+ "intent_moved_usd": 12.9+ },+ "provider": "anthropic"+ }+}+```++### PUT and DELETE /intents/:intentId++`PUT` accepts any of `enabled`, `public_trait`, `title`, and `intent` (a full replacement rule, re-validated). `404 not_found` for an unknown id, `422` with the normalizer's code for an invalid replacement. `DELETE` returns `{ "data": { "deleted": true } }`.++```bash+curl -s -X PUT "https://three.ws/api/agents/$AGENT_ID/intents/$INTENT_ID" \+ -H "authorization: Bearer $THREE_WS_TOKEN" \+ -H 'content-type: application/json' \+ -d '{"enabled":false}'+```++## Treasury Autopilot++Source: [`api/agents/autopilot.js`](../api/agents/autopilot.js), engine in [`api/_lib/treasury-autopilot.js`](../api/_lib/treasury-autopilot.js). Product tour: [Autopilot](agent-abilities/wallet/13-autopilot.md).++Treasury Autopilot is the policy that lets an agent fund its own existence: pay its metered compute, hold a buffer, accumulate `$THREE`, compound its coin fees, and sweep real profit to its owner. It is stored on the agent, compiled from English, and armed only by an explicit owner write. Not to be confused with [Coin Autopilot](autopilot.md), which governs a launched coin at `/api/pump/autopilot`.++| Method | Route | Purpose |+|---|---|---|+| `GET` | `/autopilot` | Policy, the real runway view, and the read-only spend ceilings |+| `POST` | `/autopilot/compile` | Compile plain English into structured rules (preview only) |+| `PUT` | `/autopilot` | Save rules, arm, disarm, kill, or edit |+| `POST` | `/autopilot/run` | Run one cycle now |++All writes are owner-gated and CSRF-gated. An unknown sub-path is `404 not_found`.++### The rule model++Five rule kinds, executed in a fixed order per cycle: `self_fund` (pay the agent's own compute), `buffer` (maintain `buffer_sol`), `dca`, `buyback`, then `sweep` last.++| Kind | Parameters |+|---|---|+| `self_fund` | `cadence`: `hourly` (default), `daily`, `weekly` |+| `buffer` | None. The amount is the policy-level `buffer_sol` |+| `dca` | `basis` (`surplus` default, or `income`), `pct` or `amount_sol`, `cadence` (default `daily`), `weekday`, `slippage_bps` (clamped 50 to 2000, default 300) |+| `buyback` | `pct_of_fees` (0 to 100, default 100), `cadence` (default `weekly`), `weekday`, `slippage_bps` (default 500) |+| `sweep` | `threshold_sol`, `destination` (validated Solana address), `cadence` (default `weekly`), `weekday` |++The DCA target is always `$THREE` and is not owner-overridable: the field is set server-side, so a client cannot redirect the accumulation. `weekday` is 0 for Sunday through 6 for Saturday, or `null` for any day. Each rule carries `id`, `enabled`, `paused`, a generated `label`, and its last run stamp (`last_run_at`, `last_status`, `last_note`). At most 20 rules are kept.++### GET /autopilot++```json+{+ "data": {+ "policy": {+ "armed": true,+ "kill_switch": false,+ "buffer_sol": 1,+ "sweep_destination": "7Xy…",+ "rules": [+ { "id": "self_fund_m2k41x", "kind": "self_fund", "enabled": true, "paused": false, "params": { "cadence": "hourly" }, "label": "Pay the agent's own metered compute costs from its wallet", "last_run_at": "2026-07-30T11:00:02.441Z", "last_status": "ok", "last_note": null }+ ],+ "source_text": "pay your own compute, keep a 1 SOL buffer, sweep over 3 SOL to me on Fridays",+ "compiled_at": "2026-07-28T10:12:00.000Z",+ "approved_at": "2026-07-28T10:12:00.000Z",+ "compute_settled_at": "2026-07-30T11:00:02.441Z",+ "updated_at": "2026-07-30T11:00:02.441Z"+ },+ "runway": {+ "network": "mainnet",+ "price_usd": 168.4,+ "balance_sol": 2.418,+ "balance_usd": 407.2,+ "buffer_sol": 1,+ "buffer_usd": 168.4,+ "three_accumulated": 128400.5,+ "window_days": 30,+ "income_usd": 82.5,+ "cost_usd": 41.1,+ "net_usd": 41.4,+ "net_positive": true,+ "daily_burn_usd": 1.37,+ "daily_income_usd": 2.75,+ "net_daily_usd": 1.38,+ "runway_days": null,+ "self_sustaining": true,+ "self_funded_usd": 41.1,+ "dca_usd": 18,+ "dca_count": 9,+ "buyback_usd": 0,+ "buyback_count": 0,+ "swept_usd": 120,+ "swept_sol": 0.71,+ "sweep_count": 2,+ "armed": true,+ "kill_switch": false,+ "explorer_account": "https://solscan.io/account/…"+ },+ "spend_limits": { "daily_usd": 250, "per_tx_usd": null, "withdraw_allowlist": [], "frozen": false, "require_capabilities": false }+ }+}+```++Two things to read carefully. `runway_days` is `null` both when the agent is self-sustaining (an infinite runway, flagged by `self_sustaining: true`) and when the balance cannot be valued, so pair it with `self_sustaining` and `balance_usd` rather than treating `null` as unknown. Every number traces to a live chain read or a ledger row over a fixed 30-day window; a net-negative agent shows the truth rather than a projection. A runway computation failure is `500 runway_failed`.++### POST /autopilot/compile++Body: `{ "text": "…", "sweep_destination": "<base58>" }`. An invalid `sweep_destination` is ignored in favor of the policy's stored one rather than failing the request. The compiler prefers the configured model and falls back to a real deterministic parser, so it always compiles; `via` tells you which ran (`model` or `heuristic`).++```json+{+ "data": {+ "ok": true,+ "via": "model",+ "source_text": "pay your own compute, keep a 1 SOL buffer, sweep over 3 SOL to me on Fridays",+ "buffer_sol": 1,+ "sweep_destination": "7Xy…",+ "rules": [{ "kind": "self_fund", "params": { "cadence": "hourly" } }],+ "warnings": [],+ "contradictions": []+ }+}+```++`warnings` names every default the compiler had to assume. `contradictions` names rules that cannot all hold, including a structural check the endpoint adds itself: a sweep threshold at or below the buffer would fight the buffer every cycle. Compiling never arms anything, so a contradiction is reported rather than blocking. An empty policy is `400 empty_policy`; a compiler crash is `500 compile_failed`.++### PUT /autopilot++A patch, not a replacement. Accepted keys: `rules` (array; a non-array is `400 bad_request`), `buffer_sol`, `sweep_destination` (validated, `400 invalid_address` on a bad one, `null` to clear), `source_text`, `armed`, and `kill_switch`.++Arming is treated as explicit consent: sending `"armed": true` stamps `approved_at` and `compiled_at` server-side at the current time. Returns `{ "data": { "policy": … } }` with the newly normalized policy. Ownership is re-verified inside the write, so a `403 forbidden` or `404 not_found` can still surface here.++```bash+curl -s -X PUT "https://three.ws/api/agents/$AGENT_ID/autopilot" \+ -H "authorization: Bearer $THREE_WS_TOKEN" \+ -H 'content-type: application/json' \+ -d '{"armed":true}'+```++### POST /autopilot/run++Body: `{ "dry_run": true }`. **The default is a real cycle.** Unlike `/intents/run`, this endpoint only simulates when you explicitly send `"dry_run": true`; an empty body executes for real. Send the dry run first if you are exploring.++A run honors the kill switch, the disarmed state, the freeze, and the spend policy exactly like the scheduler, and refuses rather than guessing when it cannot trust its inputs:++```json+{ "data": { "ran": false, "reason": "wallet_frozen", "results": [], "note": "Wallet is frozen. Unfreeze it under Limits and Safety." } }+```++Refusal reasons: `not_found`, `kill_switch`, `disarmed`, `no_rules`, `no_wallet`, `wallet_frozen`, `price_feed_unavailable` (the SOL/USD feed is the trust anchor for every conversion, so the cycle pauses instead of guessing with real money), `balance_read_failed`, `no_secret`, and `key_recover_failed`.++A cycle that ran returns `{ "ran": true, "trigger": "manual", "dryRun": false, "results": [ … ] }`, one entry per due rule, each stamped with its `last_status` and `last_note`. A rule whose weekday does not match today is reported as skipped rather than silently omitted. An unexpected failure is `500 run_failed`.++## Portfolio: valuation, P&L, and risk++Source: [`api/agents/portfolio.js`](../api/agents/portfolio.js), engine in [`api/_lib/portfolio.js`](../api/_lib/portfolio.js). Product tour: [Portfolio](agent-abilities/wallet/03-portfolio.md).++| Method | Route | Purpose |+|---|---|---|+| `GET` | `/portfolio` | Full snapshot: holdings, cost basis, attribution, risk |+| `GET` | `/portfolio/stream` | Server-sent events: revalued snapshots on an interval |++Both are read-only, owner-gated, and rate-limited. Attribution is derived from the custody ledger, which is owner-sensitive, so unlike the public balance read there is no visitor view. An unknown sub-path is `404 not_found`.++Cost basis is FIFO over a unified trade ledger (sniper positions plus custody trades), which is what makes realized and unrealized P&L attributable to the source that opened the lot.++### GET /portfolio++```json+{+ "data": {+ "agent": { "id": "…", "name": "Ada", "image": "https://…", "wallet": "7Xy…" },+ "network": "mainnet",+ "sol_usd": 168.4,+ "t": 1785412800000,+ "net_worth": {+ "sol": 2.94,+ "usd": 495.1,+ "realized_pnl_sol": 0.41,+ "realized_pnl_usd": 69.04,+ "unrealized_pnl_sol": -0.08+ },+ "holdings": [+ {+ "mint": null,+ "symbol": "SOL",+ "name": "Solana",+ "amount": 2.418,+ "decimals": 9,+ "price": 168.4,+ "usd": 407.2,+ "logo": null,+ "isNative": true,+ "stable": false,+ "is_three": false,+ "priceable": true,+ "usd_value": 407.2,+ "cost_basis_sol": null,+ "unrealized_sol": null,+ "unrealized_pct": null,+ "liquidity_warning": null+ }+ ],+ "attribution": [+ {+ "source": "sniper",+ "label": "Sniper",+ "realized_sol": 0.41,+ "realized_usd": 69.04,+ "unrealized_sol": -0.08,+ "unrealized_usd": -13.47,+ "total_sol": 0.33,+ "spent_sol": null,+ "spent_usd": null,+ "sells": 6,+ "is_outflow": false+ }+ ],+ "risk": {+ "net_worth_usd": 495.1,+ "concentration_hhi": 0.6821,+ "top_position_pct": 82.24,+ "top_position_mint": "SOL",+ "top_position_is_reserve": true,+ "top_risk_position_pct": 17.76,+ "top_risk_position_mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "reserve_usd": 407.2,+ "reserve_pct": 82.24,+ "risk_assets_count": 1,+ "volatile_exposure_usd": 87.9,+ "exposure_pct": 17.76,+ "tape_beta": 0.178,+ "max_drawdown_pct": 12.4,+ "max_drawdown_sol": 0.09,+ "realized_volatility_pct": 31.8,+ "holdings_count": 2,+ "valued_count": 2,+ "unpriceable_count": 0+ },+ "risk_flags": [{ "level": "info", "text": "No elevated concentration, exposure, or drawdown risk detected." }],+ "metrics": {},+ "basis_note": "Sniper P&L is on-chain actuals; discretionary P&L is FIFO-derived from recorded trade quotes."+ }+}+```++Notes that matter when you consume this:++- Holding keys are mixed-case as coded: `isNative`, `stable`, `is_three`, `priceable`, `usd_value`. `mint` is `null` for native SOL.+- A holding that cannot be priced is reported with `usd: null` and `liquidity_warning: "unpriceable"`. It is never valued at a guess, which is why `net_worth.usd` can be lower than the intuitive total.+- `attribution` buckets are `sniper`, `discretionary`, `strategy`, `x402`, and `withdraw`. The last two are pure outflows: they carry `spent_sol` and `spent_usd` with `is_outflow: true` and no round-trip P&L.+- `risk_flags` is always non-empty. A reserve-heavy or quiet wallet gets an explicit "no elevated risk" or "dry powder ready to deploy" flag rather than an ambiguous silence.+- Concentration keys off the largest *volatile* position (`top_risk_position_pct`), so a wallet that is mostly SOL or a stablecoin is not falsely flagged as a concentrated bet.+- `metrics` is the trader metric set (realized P&L, drawdown, and related figures) from [`api/_lib/trader-stats.js`](../api/_lib/trader-stats.js).++A valuation failure is `502 portfolio_failed`; a missing agent inside the engine is `404 not_found`.++```bash+curl -s "https://three.ws/api/agents/$AGENT_ID/portfolio?network=mainnet" \+ -H "authorization: Bearer $THREE_WS_TOKEN" | jq '.data.net_worth, .data.risk_flags'+```++### GET /portfolio/stream++| Event | Payload | Meaning |+|---|---|---|+| `hello` | `{ ts, network }` | The stream opened |+| `snapshot` | `{ t, sol_usd, net_worth, risk, risk_flags, attribution, holdings }` | A revaluation, pushed every 20 seconds |+| `ping` | `{ ts }` | Keep-alive, every 15 seconds |+| `warn` | `{ message: "revaluation_failed" }` | One revaluation failed; the stream stays open |+| `bye` | `{ reason: "max_duration" \| "not_found" }` | The stream is ending |++The first `snapshot` is pushed immediately on connect. The stream carries only the live-moving parts of the payload, so fetch `GET /portfolio` once for the full body and then keep it fresh from the stream. It self-terminates after 40 seconds and expects the client to reconnect.++## Recovery: guardians, threshold, and inheritance++Source: [`api/agents/recovery.js`](../api/agents/recovery.js), engine in [`api/_lib/agent-recovery.js`](../api/_lib/agent-recovery.js). Product tour: [Recovery](agent-abilities/wallet/22-recovery.md), and the counterpart console in [Guardian](guardian.md).++Recovery transfers *ownership*, never the key. The wallet secret is never decrypted, displayed, or moved. This is the one surface here that is not owner-only: a guardian or a beneficiary is a first-class caller with a scoped view.++| Method | Route | Who may call |+|---|---|---|+| `GET` | `/recovery` | Owner, guardian, or beneficiary |+| `PUT` | `/recovery` | Owner |+| `POST` | `/recovery/checkin` | Owner |+| `GET` | `/recovery/requests` | Owner |+| `POST` | `/recovery/requests` | Guardian or beneficiary |+| `POST` | `/recovery/requests/:requestId/approve` | Active guardian |+| `POST` | `/recovery/requests/:requestId/decline` | Active guardian |+| `POST` | `/recovery/requests/:requestId/confirm` | Guardian or beneficiary (inheritance) |+| `POST` | `/recovery/requests/:requestId/cancel` | Owner (reject) or the requester (withdraw) |+| `POST` | `/recovery/requests/:requestId/complete` | Anyone in the circle, plus the nominee |+| `POST` | `/recovery/inheritance/arm` | Guardian or beneficiary |++Every write is CSRF-gated and rate-limited per IP. A caller with no relationship to the agent gets `403 forbidden` on the read too. A non-UUID request id is `404 not_found`.++### GET /recovery++```json+{+ "data": {+ "agent": { "id": "…", "name": "Ada", "avatar_url": "https://…" },+ "viewer": { "is_owner": true, "is_guardian": false, "is_beneficiary": false, "user_id": "…" },+ "config": { "threshold": 2, "effective_threshold": 2, "dead_man": { "enabled": true, "inactivity_days": 90, "grace_days": 14, "last_check_in": "2026-07-30T09:00:00.000Z" } },+ "guardians": [+ { "id": "12", "user_id": "…", "role": "guardian", "username": "sam", "display_name": "Sam", "email_masked": "s…@example.com", "avatar_url": null, "label": "Sam", "since": "2026-06-01T00:00:00.000Z" }+ ],+ "guardian_count": 3,+ "beneficiary": { "label": "@kai", "avatar_url": null, "is_you": false },+ "dead_man": {+ "enabled": true,+ "inactivity_days": 90,+ "grace_days": 14,+ "inactive_days": 0,+ "last_active_at": "2026-07-30T11:58:00.000Z",+ "arm_at": "2026-10-28T11:58:00.000Z",+ "ms_until_arm": 7776000000,+ "eligible_to_arm": false,+ "signals": { "session": "…", "custody": "…", "usage": "…", "agent_updated": "…", "check_in": "…" }+ },+ "active_request": null,+ "max_guardians": 10+ }+}+```++The view is redacted by role. An owner sees the full guardian roster (with masked emails) and the full dead-man picture including the activity `signals` it was derived from. A guardian or beneficiary sees only `{ role, label, avatar_url, is_you }` per guardian and the bare dead-man settings, with no `inactive_days` and no `signals`.++`effective_threshold` is the number of approvals actually required: it defaults to 2-of-N (or all guardians when fewer than two exist) until an owner sets `threshold` explicitly, and is always clamped into the roster size.++### PUT /recovery++Owner only. Body:++| Field | Type | Notes |+|---|---|---|+| `guardians` | string[] | Handles: username, `@handle`, email, or user id. At most 10 |+| `beneficiary` | string | One handle, or omit for none |+| `threshold` | number | At least 1, no greater than the guardian count |+| `dead_man` | object | `{ enabled, inactivity_days, grace_days }`. Days are clamped to 7 through 365 and 1 through 90 |++Handle resolution is strict, so a typo is a clean error naming the offending value rather than a silently dropped guardian: `400 unknown_guardian`, `400 unknown_beneficiary`, `400 self_guardian`, `400 self_beneficiary`, `400 too_many_guardians`, `400 bad_threshold`, and `400 dead_man_needs_beneficiary` (the switch needs someone to inherit). Duplicates in the list are collapsed rather than rejected. Returns the new roster and config.++```bash+curl -s -X PUT "https://three.ws/api/agents/$AGENT_ID/recovery" \+ -H "authorization: Bearer $THREE_WS_TOKEN" \+ -H 'content-type: application/json' \+ -d '{+ "guardians": ["@sam", "[email protected]"],+ "beneficiary": "@kai",+ "threshold": 2,+ "dead_man": { "enabled": true, "inactivity_days": 90, "grace_days": 14 }+ }'+```++### POST /recovery/checkin++Owner only, no body. The canonical "I am here" action: it resets the dead-man clock and aborts any inheritance already in flight.++```json+{ "data": { "checked_in_at": "2026-07-30T12:00:00.000Z", "aborted_inheritance": 1 } }+```++### /recovery/requests++`GET` (owner only) returns `{ "data": { "items": [ … ] } }`, the recent request history for the audit view.++`POST` opens a recovery. Body: `{ "reason": "…" }`, optional. Returns `201` with the decorated request. Refusals: `403 not_a_guardian`, `409 already_owner`, `409 process_in_progress`, and `422 not_enough_guardians` (recovery needs at least one guardian other than the requester, so the inheritance path is the route when there are none).++A decorated request looks like this:++```json+{+ "data": {+ "id": "…",+ "agent_id": "…",+ "kind": "recovery",+ "status": "time_locked",+ "needs_beneficiary_confirmation": false,+ "stored_status": "open",+ "requester_id": "…",+ "prev_owner_id": "…",+ "new_owner_id": "…",+ "approvals": 2,+ "approvals_required": 2,+ "declines": 0,+ "approved": true,+ "timelock_until": "2026-08-01T12:00:00.000Z",+ "ms_until_unlock": 172800000,+ "ms_until_expiry": 1036800000,+ "reason": "lost my password",+ "created_at": "2026-07-30T12:00:00.000Z",+ "completed_at": null,+ "votes": [{ "user_id": "…", "decision": "approve", "at": "…", "label": "Sam" }]+ }+}+```++`status` is the live computed phase, while `stored_status` is the raw row. Approvals are counted only from *currently active* guardians, so removing a guardian retracts their vote. The safety rails are enforced server-side, in this order: the requester cannot approve their own takeover (`403 no_self_approve`), threshold approvals start a 48-hour time-lock, unmet requests expire after 14 days, and the real owner can cancel at any point.++### Voting, confirming, cancelling, completing++- **`/approve` and `/decline`** record a vote. `404 not_found`, `409 not_open`, `403 not_a_guardian`, `403 no_self_approve`, `400 bad_decision`. Returns the re-decorated request.+- **`/confirm`** is the inheritance beneficiary's or a guardian's confirmation. `403 not_a_party` when the caller is neither. A guardian's confirm is recorded as an approval.+- **`/cancel`** is a reject when the owner calls it and a withdrawal when the requester does. Anyone else gets `403 forbidden`. `409 not_open` once the request is closed.+- **`/complete`** finalizes a ready request and transfers ownership. The caller must be in the circle, or be the requester or the nominee, and the server re-verifies readiness regardless of who calls: `409 not_ready` carries `detail` with the phase, milliseconds until unlock, and the current approval count; `409 awaiting_beneficiary` means control cannot pass until the beneficiary confirms. Completion is idempotent (`{ "transferred": false, "alreadyOwned": true }` on a re-run) and aborts with `409 owner_changed` if ownership moved underneath it.++```bash+curl -s -X POST "https://three.ws/api/agents/$AGENT_ID/recovery/requests/$REQUEST_ID/approve" \+ -H "authorization: Bearer $GUARDIAN_TOKEN"+```++### POST /recovery/inheritance/arm++Guardian or beneficiary only. No body. Arms the dead-man switch once the owner has genuinely gone quiet. Returns `201` with the new inheritance request, or `409 not_eligible` when the owner is still active, no beneficiary is set, or a process is already running. Any owner check-in cancels the whole thing.++## Solana guard: the self-defending wallet++Source: [`api/agents/solana-guard.js`](../api/agents/solana-guard.js), scoring in [`api/_lib/wallet-anomaly.js`](../api/_lib/wallet-anomaly.js), event store in [`api/_lib/anomaly-events.js`](../api/_lib/anomaly-events.js). Behavior narrative: [Financial controls](financial-controls.md).++Scoring and freezing happen inline on the spend path, not here. This endpoint is the owner's window into that system and the control over it: read the learned baseline and the anomaly timeline, tune sensitivity, set a safe-sweep address, and adjudicate a freeze.++| Method | Route | Purpose |+|---|---|---|+| `GET` | `/solana/guard` | Config, presets, freeze state, baseline, open flags, paginated timeline |+| `PUT` | `/solana/guard` | Tune sensitivity, enable or disable, set the safe address, clear what was learned |+| `POST` | `/solana/guard` | Adjudicate: approve, deny, mark swept, or unfreeze |++All three are owner-gated and rate-limited; the two mutations are CSRF-gated. Any other method is `405`.++### GET /solana/guard++Query: `limit` (1 to 100, default 40) and `before` (a numeric event id cursor).++```json+{+ "data": {+ "config": {+ "enabled": true,+ "sensitivity": "balanced",+ "safe_address": "7Xy…",+ "size_ceiling_usd": 40,+ "extra_hours": [3],+ "learned_destinations": 2,+ "updated_at": "2026-07-29T18:22:04.881Z"+ },+ "presets": [+ { "key": "relaxed", "label": "Relaxed", "threshold": 0.85, "description": "Only freezes on the clearest threats. Fewest alerts." },+ { "key": "balanced", "label": "Balanced", "threshold": 0.7, "description": "Recommended. Freezes on strong anomalies, lets normal behavior through." },+ { "key": "strict", "label": "Strict", "threshold": 0.5, "description": "Freezes on the first sign of unusual activity. Most alerts." }+ ],+ "frozen": true,+ "baseline": {+ "version": 1,+ "n": 34,+ "total_events": 41,+ "usd": { "max": 38.2, "p95": 22.4, "mean": 7.9, "samples": 34 },+ "velocity": { "per_hour_p95": 3, "per_hour_max": 6, "active_hour_buckets": 19 },+ "counterparties": ["7Xy…"],+ "counterparty_count": 4,+ "active_hours": [9, 10, 11, 14, 15],+ "assets": ["SOL", "USDC"],+ "first_at": "2026-06-02T09:11:00.000Z",+ "last_at": "2026-07-30T11:04:00.000Z",+ "computed_at": "2026-07-30T12:00:00.000Z",+ "low_history": false+ },+ "open_flags": [+ {+ "id": "4417",+ "network": "mainnet",+ "category": "withdraw",+ "asset": "SOL",+ "usd": 310.5,+ "destination": "9Qz…",+ "score": 0.88,+ "decision": "freeze",+ "critical": true,+ "sensitivity": "balanced",+ "factors": [{ "key": "size", "weight": 0.4, "text": "8x larger than this wallet's normal spend" }],+ "summary": "Unusually large withdrawal to a new destination",+ "status": "flagged",+ "hour_utc": 3,+ "swept": false,+ "adjudicated_at": null,+ "created_at": "2026-07-30T03:14:59.000Z"+ }+ ],+ "timeline": { "items": [], "next_cursor": "4402" }+ }+}+```++`learned_destinations` is a count, not the list: the owner sees how much has been taught without the response echoing an allowlist wholesale. `low_history` is `true` while the wallet has too few spends for the baseline to mean much, which is the honest signal to show instead of a confident-looking profile. `next_cursor` is non-null only when the page came back full; pass it as `before` for the next page.++### PUT /solana/guard++| Field | Effect |+|---|---|+| `enabled` | Boolean. Turns the guard on or off |+| `sensitivity` | `relaxed`, `balanced`, or `strict`. Anything else is `400 invalid_sensitivity` |+| `safe_address` | A validated Solana address for one-tap sweep-to-safety, or `null` / `""` to clear |+| `clear_learned` | `true` resets every learned pattern: destinations, size ceiling, and extra hours |++`safe_address` validation is deliberately strict: an off-curve program address (a PDA) is rejected with `400 invalid_address` because funds sent there could be unrecoverable. Returns `{ "data": { "config": … } }`.++```bash+curl -s -X PUT "https://three.ws/api/agents/$AGENT_ID/solana/guard" \+ -H "authorization: Bearer $THREE_WS_TOKEN" \+ -H 'content-type: application/json' \+ -d '{"sensitivity":"strict","safe_address":"7Xy…"}'+```++### POST /solana/guard++Body: `{ "action": "…", "event_id": "…" }`. `action` must be `approve`, `deny`, `mark_swept`, or `unfreeze`, otherwise `400 bad_request`. All but `unfreeze` require a numeric `event_id` that belongs to this agent (`400 bad_request` if absent, `404 not_found` if unknown).++| Action | What it does | Response |+|---|---|---|+| `approve` | Teaches the baseline from the flagged action (destination, size, hour) so the same pattern will not re-trip, then unfreezes and marks the event approved | `{ "frozen": false, "action": "approve", "event_id": "…", "config": { … } }` |+| `deny` | Confirmed bad. Keeps the wallet frozen and records the verdict | `{ "frozen": true, "action": "deny", "event_id": "…" }` |+| `mark_swept` | Records that the owner evacuated the wallet with a normal audited withdraw. Keeps it frozen | `{ "action": "mark_swept", "event_id": "…", "swept": true }` |+| `unfreeze` | Owner override not tied to a flag: unfreezes and settles every still-open flag as approved | `{ "frozen": false, "action": "unfreeze" }` |++The difference between `approve` and `unfreeze` is the one that matters operationally: `approve` teaches, so the pattern is permanently normal for this wallet; `unfreeze` only clears the current state, so the same spend can trip the guard again. `mark_swept` records the sweep on the flag but does not itself move funds; the money leaves through the normal withdraw endpoint under the usual guards.++```bash+curl -s -X POST "https://three.ws/api/agents/$AGENT_ID/solana/guard" \+ -H "authorization: Bearer $THREE_WS_TOKEN" \+ -H 'content-type: application/json' \+ -d '{"action":"approve","event_id":"4417"}'+```++## Related++- [Agent wallets](agent-wallets.md) for the wallet itself: creation, key custody, and the five spend paths.+- [Custody you can verify](custody.md) for limits, freeze, proof of custody, and the recovery model in prose.+- [Financial controls](financial-controls.md) for the plain-English spend rules and the wallet-defense behaviors.+- [The Trading Copilot](trading-copilot.md) for the conversational read-and-propose surface over the same wallet.+- [Coin Autopilot](autopilot.md) for the separate coin cockpit at `/api/pump/autopilot`.+- [What agents can do](agent-abilities.md) for a page per wallet ability, including [Access](agent-abilities/wallet/21-access.md), [Orders](agent-abilities/wallet/12-orders.md), [Intents](agent-abilities/wallet/14-intents.md), [Autopilot](agent-abilities/wallet/13-autopilot.md), [Portfolio](agent-abilities/wallet/03-portfolio.md), and [Recovery](agent-abilities/wallet/22-recovery.md).+- [Guardian console](guardian.md) for the other side of a recovery request.diff --git a/docs/aws-builder-center-marketplace-x402.md b/docs/aws-builder-center-marketplace-x402.mdindex e61d4b2d0..4b0c160fc 100644--- a/docs/aws-builder-center-marketplace-x402.md+++ b/docs/aws-builder-center-marketplace-x402.md@@ -2,6 +2,11 @@title: "One paywall, two economies: putting AWS Marketplace metering in front of an x402 API"venue: AWS Builder Centeraccount: three.ws (official)+status: published+published_title: "How we metered a SaaS product through AWS Marketplace with the AWS SDK for JavaScript v3"+published_date: 2026-05-30+published_url: https://builder.aws.com/content/3ESpll50BdSp9eiCEIxcfG9pGUN/how-we-metered-a-saas-product-through-aws-marketplace-with-the-aws-sdk-for-javascript-v3+index: docs/aws-builder-center.mddescription: "How we metered a SaaS product through AWS Marketplace with the AWS SDK for JavaScript v3 — ResolveCustomer, MeterUsage, entitlements, and verified SNS lifecycle webhooks — and bridged it to an on-chain x402 paywall so one access check bills two ways. Real code, and the five things that bit us."tags: [aws, marketplace, saas, serverless, api]---diff --git a/docs/aws-builder-center.md b/docs/aws-builder-center.mdnew file mode 100644index 000000000..1c194347e--- /dev/null+++ b/docs/aws-builder-center.md@@ -0,0 +1,58 @@+# three.ws on the AWS Builder Center++The [AWS Builder Center](https://builder.aws.com) is Amazon's community publishing platform for engineers building on AWS. three.ws publishes there under the official organization account, [**@threews**](https://builder.aws.com/community/@threews), as part of our AWS Partner Network membership.++This page is the index of that writing: what is published, where it lives, and what code each article documents. If you are adding an article, the checklist at the bottom is the process.++- **Profile:** [builder.aws.com/community/@threews](https://builder.aws.com/community/@threews)+- **Account:** organization account, byline "three.ws"+- **Related surfaces:** [three.ws/aws](https://three.ws/aws) (AWS Partner page), [AWS Marketplace listing](./aws-marketplace.md), [AWS partner spotlight](./aws-partner-spotlight.md)++## Published articles++### 1. How we metered a SaaS product through AWS Marketplace with the AWS SDK for JavaScript v3++Published 30 May 2026. Tags: `aws-payment-cryptography`, `blockchain`, `metadata`, `agent-toolkit`, `agentic-ai`.++> [Read it on the AWS Builder Center](https://builder.aws.com/content/3ESpll50BdSp9eiCEIxcfG9pGUN/how-we-metered-a-saas-product-through-aws-marketplace-with-the-aws-sdk-for-javascript-v3)++The full AWS Marketplace SaaS usage-based integration, end to end: `ResolveCustomer` on the fulfillment URL, `MeterUsage` and `BatchMeterUsage` for consumption reporting, `GetEntitlements` for tiered feature gating, and SNS lifecycle webhooks with real signature verification. It closes on the part nobody else writes about: bridging an AWS `CustomerIdentifier` into the same access check that already served an on-chain [x402](./autonomous-x402.md) paywall, so one authorization path bills two economies.++- **Source draft in this repo:** [aws-builder-center-marketplace-x402.md](./aws-builder-center-marketplace-x402.md)+- **Code it documents:** [`api/aws-marketplace/`](https://github.com/nirholas/three.ws/tree/main/api/aws-marketplace), [`api/_lib/aws-marketplace.js`](https://github.com/nirholas/three.ws/blob/main/api/_lib/aws-marketplace.js), [`api/_lib/aws-marketplace-bridge.js`](https://github.com/nirholas/three.ws/blob/main/api/_lib/aws-marketplace-bridge.js)+- **Announcement:** [three.ws Publishes on the AWS Builder Center Blog](https://three.ws/news/aws-builder-center-blog)++### 2. Build Autonomous AI Agents with 3D Bodies and On-Chain Payments | three.ws on AWS++Published 27 June 2026. Tags: `ai`, `agent-toolkit`, `blockchain`, `aws-partners`, `multi-agent-orchestrator`.++> [Read it on the AWS Builder Center](https://builder.aws.com/content/3FMY7S5o4lwzb40gDsCJRCE20cX/build-autonomous-ai-agents-with-d-bodies-and-on-chain-payments-threews-on-aws)++The platform-level piece: browser-native 3D AI agents with memory, on-chain wallets, and autonomous payments, available on AWS Marketplace, embeddable in one line of HTML, and governed before they act. Written for AWS builders evaluating three.ws as an agent runtime rather than as a 3D asset tool.++- **Surfaces it covers:** [the `<agent-3d>` web component](./web-component.md), [agent wallets](./agent-wallets.md), [the agent system](./agent-system.md), [AWS Marketplace procurement](./aws-marketplace.md)++## In draft++Written and reviewed in this repo, not yet submitted:++| Draft | Subject |+|---|---|+| [aws-builder-center-agent-payment-sessions.md](./aws-builder-center-agent-payment-sessions.md) | Agent Payment Sessions: giving an agent a budget instead of a private key, and enforcing it atomically in Postgres |+| [aws-builder-center-mcp-agents.md](./aws-builder-center-mcp-agents.md) | An MCP server whose paid tools settle per call in USDC over HTTP 402 |++## Publishing checklist++The Builder Center editor accepts Markdown, so a draft in `docs/` is the article. To take one from draft to published:++1. **Write the draft as `docs/aws-builder-center-<topic>.md`** with the frontmatter block the existing drafts use (`title`, `venue`, `account`, `description`, `tags`). Every code sample must be real code from this repo, and every claim must be verifiable against it. The Builder Center audience reads the linked source.+2. **Check the rules:** `npm run check:rules -- --paths docs/aws-builder-center-<topic>.md`.+3. **Check the links:** `npm run audit:docs`.+4. **Publish** from [builder.aws.com/create/content](https://builder.aws.com/create/content) using the official account, pasting the Markdown body and setting the tags from the frontmatter.+5. **Record the canonical URL** by adding a section to this page: title, publish date, tags, the live URL, the source draft, and the code it documents.+6. **Announce it** by adding an item to `data/rss/items.json` (the curated news feed) with the canonical Builder Center URL as `link`, then regenerate with `npm run build:news`. The item becomes a page under `/news/<slug>` and enters the RSS feed automatically.+7. **Log it** in `data/changelog.json` with the `docs` tag.++## Why we publish here++The Builder Center is where AWS customers evaluating a partner product go looking for evidence that the engineering is real. A marketing page claims an integration exists; a walkthrough of the exact SDK calls, the signature-verification pitfalls, and the failure modes proves it. Every article we publish there points at Apache 2.0 source in [this repository](https://github.com/nirholas/three.ws), so a reader can check the claim in the same sitting.diff --git a/docs/ca2x402.md b/docs/ca2x402.mdnew file mode 100644index 000000000..9b257d980--- /dev/null+++ b/docs/ca2x402.md@@ -0,0 +1,304 @@+# CA to x402++Paste a token contract address, get back a live, agent-payable [x402](x402.md)+market-intel endpoint for that exact token. The generated endpoint costs a small+USDC payment per call, is discoverable in the x402 bazaar, and needs no keys, no+backend, and no deploy from the person who generated it.++The tool lives at [`/ca2x402`](https://three.ws/ca2x402).++> Source: page [`pages/ca2x402.html`](../pages/ca2x402.html), frontend+> [`src/ca2x402.js`](../src/ca2x402.js), free resolver+> [`api/ca2x402/resolve.js`](../api/ca2x402/resolve.js), the paid service it+> generates [`api/x402/token-intel.js`](../api/x402/token-intel.js), market reader+> and signal/risk math [`api/_lib/token-market.js`](../api/_lib/token-market.js),+> pricing [`api/_lib/x402-prices.js`](../api/_lib/x402-prices.js), storefront+> listing+> [`api/_lib/service-catalog/services/token-intel.js`](../api/_lib/service-catalog/services/token-intel.js).++This is generic, coin-agnostic plumbing: the mint is an input supplied at runtime+by whoever calls it. Every example below uses `<MINT_ADDRESS>` as a stand-in for+the address you paste. The page ships one example chip, `$THREE`, because $THREE+is the only coin three.ws promotes; the tool itself accepts any address.++---++## What the page does++Three steps, all real:++1. **Paste.** Any Solana base58 mint or EVM `0x` contract address. The input is+ shape-checked in the browser before a request is made+ (`/^[1-9A-HJ-NP-Za-km-z]{32,44}$/` or `/^0x[a-fA-F0-9]{40}$/`).+2. **Resolve.** `GET /api/ca2x402/resolve` pulls the token's live market from+ DexScreener and returns both the token preview and the generated service+ descriptor. This read is free and unauthenticated.+3. **Ship.** The page renders the endpoint URL, its price and networks, three+ copy-paste snippets, and a button that fetches the real `402 Payment Required`+ challenge from the live endpoint so you can see exactly what a buyer settles+ against.++The resolved address is mirrored into the URL as `?ca=<MINT_ADDRESS>`+(`history.replaceState`), so a resolved token is a shareable, reload-safe link.+On boot the page reads that parameter and resolves it automatically.++---++## The resolve flow++```+GET /api/ca2x402/resolve?mint=<MINT_ADDRESS>+```++Free, `GET`/`OPTIONS` only, CORS open to any origin, and rate-limited per client+IP through the shared public read limiter (`limits.publicIp` in+[`api/_lib/rate-limit.js`](../api/_lib/rate-limit.js)).++What happens, in order:++1. **Validate.** A missing `mint` is `400 missing_mint`. An address that is+ neither a valid Solana mint nor a valid EVM address is `422 invalid_mint`.+2. **Fetch the market.** `fetchTokenMarket()` calls the public DexScreener token+ endpoint (no key) with a 6 second timeout, then picks the pair with the+ deepest USD liquidity across every chain and DEX DexScreener knows for that+ address. The address may sit on either side of the pair; the reader selects+ whichever side matches what you passed.+3. **No market found.** A well-formed address with no live pair (unlaunched, dead+ liquidity, wrong chain, or an upstream hiccup) returns+ `404 { ok: false, error: 'token_not_found' }` with `cache-control: no-store`.+ The page renders that as a designed empty state. Nothing is fabricated to fill+ the gap.+4. **Success.** `200 { ok: true, token, service }` with+ `cache-control: public, max-age=20, stale-while-revalidate=60`.++### The `token` block++The live preview, so a user sees what was found before anyone pays:++| Field | Meaning |+| ---------------------------------------- | ---------------------------------------------------------- |+| `mint` | The resolved token address as DexScreener reports it. |+| `symbol`, `name`, `image` | Identity from the pair's token metadata. |+| `chain`, `dex`, `pair_url` | Where the deepest pair lives, plus its public pair page. |+| `price_usd`, `change_24h` | Spot price and 24 hour price change (percent). |+| `market_cap_usd`, `liquidity_usd`, `volume_24h_usd` | Cap (falling back to FDV), pooled depth, 24 hour volume. |+| `momentum` | Price change per window: `m5`, `h1`, `h6`, `h24`. |+| `signal`, `headline`, `rationale`, `confidence` | The derived market call (see below). `null` when the upstream has no 24 hour change. |+| `risk` | The due-diligence score block (see below). |++**How the signal is derived** (`buildTokenSignal()`), keyed on 24 hour change:++| 24 hour change | `signal` | Headline shape |+| -------------- | --------- | ------------------------------------ |+| above +5% | `bullish` | surges, strong momentum |+| +1% to +5% | `bullish` | climbs, moderate upside |+| -1% to +1% | `neutral` | flat, consolidating at the spot price |+| -5% to -1% | `bearish` | slips, mild weakness |+| below -5% | `bearish` | drops, sellers in control |++The rationale adds three clauses when the data supports them: turnover (24 hour+volume divided by liquidity: above 3 reads as hot, above 1 as healthy, otherwise+light), order-flow skew (a buy or sell share above 60% of 24 hour transactions+reads as one side dominating, otherwise two-sided), and acceleration (the last+hour confirming, cooling, or bouncing against the 24 hour trend). Confidence is+`min(0.93, 0.64 + min(|change| / 20, 0.29))`, so it rises with the size of the+move and is capped.++**How risk is scored** (`buildTokenRisk()`). Higher means more risk, `0` is+clean and `100` is critical. Four factors add points:++| Factor | Bands and points |+| --------- | -------------------------------------------------------------------------------------- |+| Liquidity | under $5k: +40 critical. Under $25k: +26 high. Under $100k: +12 medium. Otherwise low. Unknown: +18. |+| Age | under 1 day: +22 high. Under 7 days: +10 medium. Otherwise low. Unknown: no points. |+| Float | cap over 100x liquidity: +16 high. Over 30x: +7 medium. Otherwise low. Skipped when cap or liquidity is missing. |+| Flow | sells over 62% of 24 hour transactions: +12 high. Buys over 60%: low. Otherwise medium. |++The total is clamped to 0 to 100 and bucketed: `critical` at 70 or above, `high`+at 45, `medium` at 22, otherwise `low`. A missing input degrades to an honest+`unknown` factor rather than a silent pass.++### The `service` block++The generated x402 service for that exact token:++| Field | Value |+| -------------------------------- | ---------------------------------------------------------------------------- |+| `name` | `three.ws Token Oracle` |+| `endpoint` | `<origin>/api/x402/token-intel?mint=<MINT_ADDRESS>` |+| `method` | `GET` |+| `price_atomics` / `price_usd` | USDC atomics from `priceFor('token-intel', '10000')`, plus the same value divided by `1e6`. Default is `10000` atomics, which is $0.01. |+| `asset` | `USDC` |+| `networks` | `['solana', 'base']`, Solana first |+| `pay_to` | `{ solana, base }` from `X402_PAY_TO_SOLANA` / `X402_PAY_TO_BASE` (`null` when unset) |+| `description` | The storefront listing copy, imported from the service catalog descriptor |+| `output_schema` | The endpoint's JSON Schema for its response |+| `example_output` | The catalog example, with `mint` and `symbol` swapped to the resolved token |+| `bazaar_discoverable` | `true` |+| `snippets` | `{ curl, node, agent }`, see below |++The endpoint origin is derived from the request (`x-forwarded-proto` /+`x-forwarded-host`, falling back to `three.ws`), so a local dev resolve generates+a local endpoint and production generates a production one.++Operators can retune the price at deploy time with+`X402_PRICE_TOKEN_INTEL=<atomics>`; a non-integer value logs a warning and falls+back to the default. See [x402 paid endpoints](x402-endpoints.md) for the full+price-override scheme.++---++## What the generated endpoint serves++```+GET /api/x402/token-intel?mint=<MINT_ADDRESS>+```++A standard three.ws paid endpoint built on the shared handler+([`api/_lib/x402-paid-endpoint.js`](../api/_lib/x402-paid-endpoint.js)): no+`X-PAYMENT` header gets a `402` challenge carrying the accepted networks, asset,+price, and pay-to address; the buyer retries with a signed payment and receives+the intel. Settlement is recorded like any other endpoint payment (see+[x402 revenue and receipts](x402-revenue.md)).++The paid response body is the token block computed fresh at call time:++```json+{+ "mint": "<MINT_ADDRESS>",+ "symbol": "TOKEN",+ "name": "Token",+ "chain": "solana",+ "price_usd": 0.0123,+ "change_24h": 4.2,+ "market_cap_usd": 12300000,+ "liquidity_usd": 410000,+ "volume_24h_usd": 890000,+ "momentum": { "m5": 0.2, "h1": 1.1, "h6": 3.4, "h24": 4.2 },+ "signal": "bullish",+ "headline": "TOKEN climbs +4.20%, moderate upside",+ "rationale": "TOKEN is up +4.20% over 24 h, trading at $0.012300. Volume is healthy against liquidity; participation is real.",+ "confidence": 0.85,+ "risk": {+ "score": 12,+ "level": "low",+ "summary": "TOKEN clears the basic depth, age, and flow checks.",+ "factors": [+ { "label": "Liquidity", "status": "low", "detail": "$410,000 pooled, healthy depth." }+ ]+ },+ "ts": "2026-07-30T00:00:00Z"+}+```++Two failure modes are deliberately thrown **before** settlement, so a buyer is+never charged for a bad or missing answer:++- `422 invalid_mint` when `mint` is absent or not a resolvable address.+- `503 data_unavailable` when DexScreener has no live market or no 24 hour change+ for the token.++Access control uses the shared bypass hook with the `x402:bypass` scope+([`api/_lib/x402/access-control.js`](../api/_lib/x402/access-control.js)), which is+how platform-internal callers read the endpoint without paying.++---++## The bazaar schema it publishes++The endpoint declares a v2 bazaar discovery extension (the `BAZAAR` export in+[`api/x402/token-intel.js`](../api/x402/token-intel.js)), which the shared handler+embeds in the `402` challenge and which discovery crawlers index. Its parts:++- `description`: the storefront copy, imported from the service catalog so the+ live challenge can never drift from what the catalog advertises.+- `useCases`: `token market signal`, `memecoin due-diligence`,+ `agent trading intel`.+- `input`: `{ type: 'query', example, schema }`. The schema (`INPUT_SCHEMA`)+ requires a single `mint` string, 32 to 64 characters, documented as a Solana+ base58 mint or an EVM `0x` address.+- `output`: `{ type: 'json', example }`. The example is a full, realistic+ response.+- `schema`: the meta-schema built by `buildBazaarSchema()`+ ([`api/_lib/x402-spec.js`](../api/_lib/x402-spec.js)), describing+ `input.{type,method,queryParams}` and `output.{type,example}` in the shape the+ bazaar validator expects.++`OUTPUT_SCHEMA` is the response contract, and the resolver hands the same object+back as `service.output_schema` so a client generating code from a resolve never+has to fetch the schema separately. It requires `mint`, `signal`, `headline`,+`rationale`, `confidence`, `risk`, and `ts`; `signal` is constrained to+`bullish | bearish | neutral`; `confidence` is a number from 0 to 1; `risk`+requires `score` (integer 0 to 100), `level`+(`low | medium | high | critical`), `summary`, and `factors`.++Alongside the extension, the service-catalog descriptor+([`api/_lib/service-catalog/services/token-intel.js`](../api/_lib/service-catalog/services/token-intel.js))+is the single written-once listing: `api/wk.js` derives the+`/.well-known/x402.json` resource entry from it, and the OKX storefront+projection reads the same record. Edit the descriptor, not a hand-written mirror.+Its `serviceName` is `three.ws Token Oracle` and its tags are set through+`withService()` so the entry carries the platform icon and defaults.++---++## The generated snippets++The resolver returns three ready-to-run snippets, all pointed at the resolved+endpoint. The page shows them behind a `cURL` / `Node` / `Agent` tab strip with a+copy button.++**cURL.** Step one shows the price by taking the `402`; step two pays and calls in+one command:++```bash+# 1) See the price (returns HTTP 402 + payment requirements)+curl -i "https://three.ws/api/x402/token-intel?mint=<MINT_ADDRESS>"++# 2) Pay & call in one step with the x402 CLI+npx x402-fetch "https://three.ws/api/x402/token-intel?mint=<MINT_ADDRESS>"+```++**Node**, with `x402-fetch` wrapping a viem wallet client:++```js+import { wrapFetchWithPayment } from 'x402-fetch';+import { createWalletClient, http } from 'viem';+import { privateKeyToAccount } from 'viem/accounts';+import { base } from 'viem/chains';++const account = privateKeyToAccount(process.env.PRIVATE_KEY);+const wallet = createWalletClient({ account, chain: base, transport: http() });+const fetchWithPay = wrapFetchWithPayment(fetch, wallet);++const res = await fetchWithPay('https://three.ws/api/x402/token-intel?mint=<MINT_ADDRESS>');+console.log(await res.json());+```++**Agent**, from inside a three.ws agent, paying from the agent wallet with no+keys in the code:++```js+const intel = await agent.x402.pay('https://three.ws/api/x402/token-intel?mint=<MINT_ADDRESS>');+agent.log(intel.headline, intel.signal, intel.confidence);+```++### The live 402 challenge++The page's "Fetch the live 402 challenge" button calls the generated endpoint with+no payment header and prints the response verbatim: the status and the full v2+envelope (`x402Version`, `error`, `resource`, `accepts`, `extensions`). That is+the same body an x402 client parses, read from the running service rather than a+transcript, which makes it the fastest way to confirm the endpoint is payable+right now. If the endpoint is unreachable the page says so and offers a retry.++---++## Related++- [x402 on three.ws](x402.md): the protocol, the wire format, and how the+ platform settles.+- [x402 paid endpoints](x402-endpoints.md): the full catalog of our paid+ endpoints, their prices, and the `X402_PRICE_*` override scheme.+- [x402 revenue and receipts](x402-revenue.md): where a settled payment for this+ endpoint is recorded and how the buyer's receipt is issued.diff --git a/docs/deployments.md b/docs/deployments.mdnew file mode 100644index 000000000..8b3695866--- /dev/null+++ b/docs/deployments.md@@ -0,0 +1,226 @@+# On-chain Deployments++[/deployments](https://three.ws/deployments) is the live, cross-chain feed of agent identities landing on-chain: every ERC-8004 Identity Registry registration on EVM and every Metaplex Core agent mint on Solana, in one chronological stream, as each one lands. It is a read-only public surface. No account, no key, no wallet connection.++It answers three questions at a glance: how big is the on-chain agent population, where is it landing, and how many of those agents can actually do anything (ship a 3D avatar, accept x402 payments).++Every row is a real on-chain registration. There are no synthetic entries and no seeded demo rows. When a network is quiet the feed is honestly empty, and when a signal was never measured the UI says so rather than rendering a zero.++Related reading: [ERC-8004 blockchain identity](./erc8004.md) for the standard, the registry contracts, and how to register; [deploying agents on-chain](./onchain-agents.md) for the Solana Metaplex Core path; [agent reputation on Solana](./solana-reputation.md) for the trust layer built on top of a Solana identity.++---++## Solana is indexed here, not elsewhere++This surface is **not EVM-only**. Solana is folded into the same feed as a first-class chain, using the Solana cluster indices as chain ids so the network toggle, cursor, chain filter, and top-chains panel treat it like any other chain:++| Chain | `chain_id` | Network class |+| --- | --- | --- |+| Solana mainnet-beta | `101` | `mainnet` |+| Solana devnet | `103` | `testnet` |++Two Solana upstreams feed it: three.ws's own Metaplex Core mints, and the external Metaplex Agent Registry. Details in [where the data comes from](#where-the-data-comes-from).++What lives elsewhere: the *creation* path for a Solana identity is documented in [deploying agents on-chain](./onchain-agents.md) (the single-agent, user-signed flow is in [Solana agents](./solana.md)), and Solana reputation and attestations are in [agent reputation on Solana](./solana-reputation.md). This page is only the index and the feed.++---++## What the page shows++**Six headline counters**, from `GET /api/deployments?view=stats`:++| Counter | Field | Meaning |+| --- | --- | --- |+| Total agents | `total_agents` | Every active indexed registration on this network class, including rows with no known registration timestamp |+| Chains | `active_chains` | Distinct chain ids with at least one registration |+| Last 24h | `deployed_24h` | Registrations in the trailing 24 hours |+| Last 7d | `deployed_7d` | Registrations in the trailing 7 days |+| With 3D | `with_3d_pct` plus `with_3d` | Share whose on-chain metadata publishes an avatar service endpoint |+| x402 | `x402_pct` plus `x402` | Share whose metadata declares x402 payment support |++**A 7-day sparkline** (`series_7d`), zero-filled per day so a quiet day renders as a short bar rather than a gap, with today highlighted.++**Top chains** (`top_chains`, up to 8), each a bar scaled to the busiest chain, with its explorer host.++**The live feed** itself, newest first. Each row carries the agent's name (linked to its token or asset page on that chain's explorer), a truncated description, `3D` and `x402` capability tags, the chain name, the owner address (linked to the explorer), a relative timestamp with the absolute time on hover, and a `tx` link to the registration transaction where one is known.++Feed images are third-party data: whatever URL the agent's owner published on-chain, frequently on an IPFS gateway. Every remote image is routed through the same-origin `/api/img` proxy, which resolves IPFS across gateways, follows a metadata document to the real art, and always answers with a valid image, so a row never fires a failing request. Anything that is not an `http(s)`, `ipfs`, or `ar` URL degrades to a monogram tile.++**Controls:**++- **Network toggle**: `Mainnet` or `Testnet`. This switches the whole page, stats included.+- **Kind filter**: `All`, `3D avatar`, `x402`.+- **Load older**: keyset pagination, also triggered automatically when the button scrolls into view.++**Live behavior:** the page polls every 45 seconds. It refreshes stats always, and re-fetches the top of the feed *only while you are still on the first page*, so loading older rows never yanks you back to the top. Polling pauses entirely while the tab is hidden. Genuinely new rows are prepended with a slide-in so the refresh reads as a stream. A live-state dot on the feed header reflects the real poll lifecycle (connecting, live, idle, error).++Empty and error states are specific: an empty `x402` filter says no x402-enabled agents are registered on that network for that filter and links to the deploy flow, and a failed fetch offers a retry rather than a blank pane.++---++## Where the data comes from++`GET /api/deployments` composes three SQL sources into one `UNION ALL` stream, so a single keyset cursor orders the whole cross-chain feed.++### 1. EVM: `erc8004_agents_index`++Rows where `active = true` and `chain_id` is in the network class. Populated by the **`erc8004-crawl` cron**, which runs **every 15 minutes** and is dispatched through `api/cron/[name].js` (the single cron dispatcher, not a per-file handler). Per chain, per run:++1. Read the chain's cursor from `erc8004_crawl_cursor`, or on a cold start begin 2000 blocks back (override with `ERC8004_CRAWL_LOOKBACK` for a one-time backfill).+2. `eth_getLogs` for the `Registered(uint256,string,address)` topic against that chain's Identity Registry address, in 1000-block chunks (per-chain override available for restrictive RPCs).+3. Decode `agentId`, `owner`, and `agentURI` from the log, fetch the block timestamp for `registered_at`, and upsert on `(chain_id, agent_id)`.+4. Advance the cursor to the scanned head, whether or not any log was found.++The whole crawl is bounded by a 240 second budget so it always returns before the platform's function limit, and it stops iterating chains when the budget is spent.++A second stage, **metadata enrichment**, takes up to 25 rows per run whose metadata has never been fetched or is older than 7 days, fetches the `agentURI` document with a 5 second timeout, and fills in `name`, `description`, `image`, `services`, `glb_url`, `has_3d`, and `x402_support`. `has_3d` is true when the metadata publishes a service named `avatar` with an endpoint. `x402_support` is true when the document sets `x402Support` or `x402`.++Metadata is attacker-controlled: it is whatever the agent's owner published on-chain. Two consequences are load-bearing. Enrichment refuses to let `meta.active` alone decide visibility, and a name or description containing a slur sets `active = false` so the row is withheld from every public feed (this page included). A failed fetch records `metadata_error` and moves on rather than retrying in a loop.++The Identity Registry is deployed deterministically via CREATE2, so it has one address per network class, the same on every chain. See [ERC-8004](./erc8004.md) for the addresses and the contract surface.++### 2. Solana: three.ws's own Metaplex Core mints++Read directly from `agent_identities`, no crawler needed, because these are minted by the platform (`api/_lib/onchain-deploy.js`):++- **Mainnet:** rows with `meta.chain_type = 'solana'`, `meta.network = 'mainnet'`, and a `meta.sol_mint_address`. The Core asset pubkey is the `agent_id`, `meta.onchain.owner` is the owner, `meta.onchain.confirmed_at` (falling back to the row's creation time) is `registered_at`, and `meta.onchain.tx_hash` is the registration transaction.+- **Testnet:** the same fields isolated under `meta.devnet`.++For these rows, `has_3d` is true when the agent has a linked avatar record, and `x402_support` is true when `meta.payments.configured` is set.++### 3. Solana: the external Metaplex Agent Registry++Rows from `solana_agents_index` where `active = true`, `source = 'metaplex'`, and the network matches. Populated by the **`solana-agents-crawl` cron**, which runs **every 30 minutes**, enumerates the Metaplex agent-identity program's accounts with `getProgramAccounts`, and enriches each from its Core asset's DAS record and metadata document. That crawler also indexes a second upstream (the AgenC coordination protocol) into the same table under a different `source`; **the deployments feed reads only the `metaplex` rows.**++External rows are deduplicated against three.ws's own mints by Core asset pubkey, so an agent that three.ws launched *and* that is registered upstream appears exactly once.++### No subgraph on this path++The deployments feed reads Postgres tables populated by the crawlers above. It does **not** query a subgraph. The subgraph path exists elsewhere in the codebase: `GET /api/agents/8004/search` and `GET /api/agents/8004/agent` query the public Agent0 subgraph live, per chain, with a 6 second budget. Those endpoints answer "search the registry right now"; this one answers "show me the indexed stream, cheaply and chronologically".++---++## API contract++`GET /api/deployments`++Public, CORS-open, IP rate-limited. Two views on one route.++| Param | Values | Default | Applies to |+| --- | --- | --- | --- |+| `view` | `feed`, `stats` | `feed` | both |+| `network` | `mainnet`, `testnet` | `mainnet` | both |+| `kind` | `all`, `3d`, `x402` | `all` | feed |+| `chain` | any positive integer chain id | none | feed |+| `cursor` | an opaque cursor from a previous response | none | feed |++Page size is fixed server-side at 60 rows and is not client-settable.++### Feed response++```bash+curl -s 'https://three.ws/api/deployments'+curl -s 'https://three.ws/api/deployments?kind=x402'+curl -s 'https://three.ws/api/deployments?chain=101' # Solana mainnet only+curl -s 'https://three.ws/api/deployments?network=testnet'+```++```json+{+ "data": {+ "deployments": [+ {+ "chain_id": 8453,+ "chain": "Base",+ "testnet": false,+ "family": "evm",+ "agent_id": "12345",+ "name": "Example Agent",+ "description": "What this agent does.",+ "image": "ipfs://<CID>",+ "owner": "0x0000000000000000000000000000000000000000",+ "has_3d": false,+ "x402_support": true,+ "registered_at": "2026-07-30T12:00:00.000Z",+ "agent_explorer": "https://basescan.org/token/...",+ "owner_explorer": "https://basescan.org/address/...",+ "tx_explorer": "https://basescan.org/tx/..."+ }+ ],+ "has_more": true,+ "next_cursor": "<CURSOR>",+ "network": "mainnet",+ "chain": null,+ "kind": "all"+ }+}+```++`family` is `evm` or `solana` and decides how the three explorer URLs are built. For a Solana row, `agent_id` is the Core asset pubkey and the explorer links point at Solscan on mainnet, or at the Solana explorer with `?cluster=devnet` on devnet.++Paging is keyset, not offset:++```bash+CURSOR=$(curl -s 'https://three.ws/api/deployments' | python3 -c 'import json,sys; print(json.load(sys.stdin)["data"]["next_cursor"])')+curl -s "https://three.ws/api/deployments?cursor=$CURSOR"+```++The cursor is `base64url("<epoch_ms>|<chain_id>|<agent_id>")` and the total order is `registered_at DESC, chain_id DESC, agent_id DESC`. That triple is stable, so paging never skips or repeats a row even while the crawler is inserting concurrently. Rows with no known `registered_at` are counted in stats but never placed in the chronological feed, because their position in time is unknown and the feed will not invent one.++### Stats response++```bash+curl -s 'https://three.ws/api/deployments?view=stats'+curl -s 'https://three.ws/api/deployments?view=stats&network=testnet'+```++```json+{+ "data": {+ "network": "mainnet",+ "total_agents": 0,+ "active_chains": 0,+ "deployed_24h": 0,+ "deployed_7d": 0,+ "with_3d": 0,+ "with_3d_pct": 0,+ "x402": 0,+ "x402_pct": 0,+ "top_chains": [+ { "chain_id": 8453, "chain": "Base", "count": 0, "explorer": "https://basescan.org" }+ ],+ "series_7d": [+ { "label": "Wed", "day": "2026-07-30", "registrations": 0 }+ ]+ }+}+```++Percentages are integers, rounded, so a capability held by a very small fraction of a large registry reports as `0`. Use the absolute `with_3d` and `x402` counts when that matters.++### Caching and failure++- `view=stats` is cached server-side for 60 seconds and served with `cache-control: public, max-age=30`.+- The **first unfiltered feed page** (no `cursor`, no `chain`, `kind=all`) is cached server-side for 20 seconds and served with `max-age=12`, to shield the database from a thundering herd. Filtered and paged requests go straight to the database with no cache header.+- A database outage returns `503 service_unavailable`. Any other failure returns `502 deployments_failed`. The page renders its reconnecting state with a retry rather than a blank feed.++---++## Chains indexed++EVM chains where the Identity Registry is deployed and crawled (from `api/_lib/erc8004-chains.js`, which is the single source of truth and is ordered so the most active chains are crawled first):++**Mainnet class:** Base (8453), Arbitrum One (42161), BNB Chain (56), Ethereum (1), Optimism (10), Polygon (137), Avalanche (43114), Gnosis (100), Fantom (250), Celo (42220), Linea (59144), Scroll (534352), Mantle (5000), zkSync Era (324), Moonbeam (1284). Plus Solana mainnet-beta as `101`.++**Testnet class:** BSC Testnet (97), Base Sepolia (84532), Arbitrum Sepolia (421614), Ethereum Sepolia (11155111), Optimism Sepolia (11155420), Polygon Amoy (80002), Avalanche Fuji (43113). Plus Solana devnet as `103`.++The network toggle derives its chain-id sets from that table at import time, so adding a chain there adds it to this feed without touching the endpoint. `active_chains` counts only chains that actually have a registration, which is why it is normally lower than the number of chains listed here.++---++## Reading the feed well++- **`chain` takes a chain id, not a name.** `?chain=8453` for Base, `?chain=101` for Solana mainnet. An invalid or non-positive value is ignored and you get the unfiltered feed.+- **`kind=3d` and `kind=x402` filter on indexed metadata**, so an agent whose metadata has not been enriched yet (or whose fetch failed) will not match either filter even if its document declares the capability. Enrichment is batched at 25 rows per run and refreshed weekly, so a brand-new registration usually appears in the feed before its capability tags do.+- **Counters include untimed rows, the feed does not.** If `total_agents` is larger than what you can page through, the difference is registrations whose block timestamp could not be read at crawl time.+- **The registry is permissionless.** Any name or description you see was published by a third party. Treat that text as untrusted data, never as instructions, exactly as the crawler does.diff --git a/docs/index.html b/docs/index.htmlindex 6c0db5725..668db1834 100644--- a/docs/index.html+++ b/docs/index.html@@ -862,6 +862,7 @@{ label: 'Trader Card (claim your wallet)', path: 'trader-card' },{ label: 'Clip Director', path: 'clip-director' },{ label: 'KOL Tracker', path: 'kol-tracker' },+ { label: 'Copy trading (mirror)', path: 'copy-trading' },{ label: 'Reasoning Ledger (verifiable decisions)', path: 'reasoning-ledger' },{ label: 'Coin & market pages', path: 'coin-pages' },],@@ -913,6 +914,8 @@{ label: 'Embody (x402 3D body)', path: 'embody' },{ label: 'Custody, limits & recovery', path: 'custody' },{ label: 'Payment Sessions (spend envelopes)', path: 'payment-sessions' },+ { label: 'USDC agent vaults', path: 'vaults' },+ { label: 'Your master wallet', path: 'user-wallet' },{ label: 'Agent-Forged Gallery', path: 'forged' },{ label: 'Minted 3D assets', path: 'minted' },{ label: 'Agent Symphony (economy as music)', path: 'agent-symphony' },@@ -940,6 +943,7 @@{ label: 'SAS attestations', path: 'sas-attestations' },{ label: 'Solana agents', path: 'solana' },{ label: 'Deploy agents on-chain (bulk)', path: 'onchain-agents' },+ { label: 'On-chain deployments feed', path: 'deployments' },{ label: 'Solana pump.fun signals', path: 'solana-pumpfun' },{ label: 'Mint mark ("3ws")', path: 'mint-mark' },{ label: 'Security', path: 'security' },diff --git a/docs/press-kit.md b/docs/press-kit.mdnew file mode 100644index 000000000..c5ddda1aa--- /dev/null+++ b/docs/press-kit.md@@ -0,0 +1,159 @@+# Press kit++Everything a journalist, analyst, conference organiser, or partner needs to write about three.ws: the marks, the announcement graphics, approved boilerplate at three lengths, the fast facts, and the rules that govern all of it.++The live kit is at `three.ws/press`. Every asset there is downloadable without asking anyone, and **editorial use needs no permission**: coverage, reviews, conference programmes, and partner materials are all covered. Anything beyond editorial use goes to **[email protected]**.++Page source: [`pages/press/index.html`](../pages/press/index.html).++---++## The one-file option++| | |+|---|---|+| **File** | [`public/brand/three-ws-press-kit.zip`](../public/brand/three-ws-press-kit.zip) |+| **Public URL** | `https://three.ws/brand/three-ws-press-kit.zip` |+| **Size** | About 6 MB |++Contents, exactly as the archive is laid out:++```+marks/+ three-ws-mark.png+ three-ws-lockup-on-dark.png+ three-ws-lockup-on-light.png+ three-ws-stacked-on-dark.png+ three-ws-stacked-on-light.png+openai/+ social-card-announcement.png+ social-card-openai-partner.png+ social-card-studio.png+ three-ws-openai-lockup.png+ openai-select-partner-badge.svg+README.txt+```++`README.txt` carries the same usage rules published on the page, so the archive is self-contained. Two notes on scope:++- The zip holds two OpenAI graphics that the page does not display: the short-phrasing announcement card and the two-mark lockup. Read [OpenAI graphics](#openai-graphics) before using either.+- The app icon (`pwa-icon.svg`) is downloadable from the page but is **not** in the zip. Grab it separately if you need the vector.++---++## The marks++Transparent PNGs, exported tight to the artwork so they drop into a layout without dead margin. The cube is the primary mark. The lockups add the wordmark, for use when the name is not already on the page.++| File | Pixels | Use it for |+|---|---|---|+| [`three-ws-mark.png`](../public/brand/three-ws-mark.png) | 898 x 1024 | The mark alone, when the name appears elsewhere: avatars, favicons, app tiles, sponsor walls. |+| [`three-ws-lockup-on-dark.png`](../public/brand/three-ws-lockup-on-dark.png) | 1592 x 400 | Horizontal lockup, light type. The default for dark grounds and video. |+| [`three-ws-lockup-on-light.png`](../public/brand/three-ws-lockup-on-light.png) | 1592 x 400 | Horizontal lockup, dark type. For white paper, print, and light decks. |+| [`three-ws-stacked-on-dark.png`](../public/brand/three-ws-stacked-on-dark.png) | 794 x 864 | Stacked lockup, light type. For square crops, badges, and centred layouts. |+| [`three-ws-stacked-on-light.png`](../public/brand/three-ws-stacked-on-light.png) | 794 x 864 | Stacked lockup, dark type. Same shape, for light grounds. |+| [`pwa-icon.svg`](../public/pwa-icon.svg) | Vector | The flat icon behind the app tile. Use where a single-colour, infinitely scalable mark is required. |++Public URLs follow the repo paths: `https://three.ws/brand/<file>` for the five PNGs, `https://three.ws/pwa-icon.svg` for the icon.++Every one of these is rendered from a single layout source rather than hand-exported, so what you download is always the current artwork. See [`marketing/brand/README.md`](../marketing/brand/README.md) for the renderer and how to add an asset.++---++## Logo usage rules++These are the five rules as `/press` states them.++1. **Use the files as they are.** No recolouring, outlining, stretching, rotating, or rebuilding the cube from parts. The chrome finish is the mark.+2. **Leave clear space.** Keep at least half the cube's height free on every side. Nothing crops it, overlaps it, or sits inside that margin.+3. **Write it lowercase.** The name is **three.ws** in running text, never "Three.ws", "THREE.WS", or "ThreeWS".+4. **Do not lock our mark to another logo** without asking. A shared-logo graphic implies a relationship that may not exist.+5. **Editorial use is granted.** Coverage, reviews, conference programmes, and partner materials need no permission. Using the mark as your own product mark, or in a way that implies we endorse a product, does.++### Referencing the brand correctly++- The name is **three.ws**, lowercase, in every position including the start of a sentence and in headlines.+- Do not translate, abbreviate, or expand it. There is no "Three" short form and no long form.+- The embeddable web component is written `<agent-3d>`.+- If you need a co-branded graphic (our mark beside yours), ask first. Rule 4 covers this, and a shared-logo image is the single most common way a story implies a relationship that does not exist.++---++## Boilerplate++Approved descriptions at three lengths. Copy them verbatim; they are written to be quoted. The page has a copy button for each.++**One line**++> three.ws is an open-source platform for 3D AI agents: it turns a text prompt into a rigged, animation-ready 3D character you can embed anywhere.++**Short, about 50 words**++> three.ws is an open-source platform for 3D AI agents. It turns a text prompt into a rigged, animation-ready 3D character, gives that character an on-chain identity and a payment rail, and embeds it into any website or assistant with a single tag. The free 3D generation lane requires no account, no API key, and no payment.++**Long, about 100 words**++> three.ws is an open-source platform for 3D AI agents. It turns a text prompt into a rigged, animation-ready 3D character, gives that character an on-chain identity and a payment rail, and embeds it into any website or assistant with a single tag. The free 3D generation lane requires no account, no API key, and no payment. Assistants reach the same tools over MCP: three.ws is an OpenAI Select Partner, and its 3D Studio connector gives ChatGPT nine keyless tools that generate, rig, animate, and place models in AR, rendered inline in the conversation. The viewer, the runtime, and the embeddable web component are open source.++---++## Fast facts++Checkable claims only. Anything not listed here or on the page, ask before printing.++| | |+|---|---|+| **What it is** | A platform for creating, animating, and monetising 3D AI agents. |+| **Free lane** | Text to 3D generation with no account, no API key, and no payment. |+| **Home chain** | Solana. Agent identity, payments, and the platform coin all live there. |+| **Agent payments** | x402, the HTTP 402 payment standard, so one agent can pay another per call. |+| **Assistant surface** | MCP servers, plus a keyless 3D Studio connector and Actions for ChatGPT. |+| **Open standards** | Spatial MCP, the CC0 response shape for 3D tool results, so any client can render them. |+| **Open source** | The viewer, the runtime, and the `<agent-3d>` web component, at `github.com/nirholas/three.ws`. |+| **Programmes** | OpenAI Select Partner in the OpenAI Partner Network. Member of NVIDIA Inception. Full list at `three.ws/partners`. |+| **Shipping log** | Every release is public at `three.ws/changelog`, with RSS and JSON feeds. |++The platform coin named in the "Home chain" row is **$THREE**, on Solana. Email if you need its contract address confirmed before print.++---++## OpenAI graphics++three.ws is an OpenAI Select Partner. The two graphics on `/press` are both 3200 x 1800.++| File | What it is |+|---|---|+| [`social-card-announcement.png`](../public/partners/openai/social-card-announcement.png) | The announcement card. Carries the partner badge exactly as OpenAI supplied it, plus the independence line. |+| [`social-card-studio.png`](../public/partners/openai/social-card-studio.png) | The product card: the nine tools the 3D Studio connector adds to ChatGPT. No badge, so nothing here reads as an endorsement. |++**The independence line, as the page states it.** The OpenAI Partner Network badge inside the announcement card is OpenAI's asset, reproduced unaltered. three.ws is an independent member of the network at the Select tier: not an OpenAI product, and not endorsed by OpenAI beyond the partner designation shown. OpenAI, ChatGPT, and the OpenAI Partner Network badge are trademarks of OpenAI.++Two rules that matter if you are laying out a story or a slide:++- **Write the status as "OpenAI Select Partner."** Not "OpenAI partner", not any other tier name, and not "partnered with OpenAI on" a named product.+- **Prefer the announcement card over the bare badge.** The badge alone reads as OpenAI's mark rather than our announcement, and carries none of the independence line.++The two extra OpenAI files inside the zip need more care than the two above. The short-phrasing card exists for one specific post and is not the general-purpose announcement graphic. The two-mark lockup uses OpenAI's logomark rather than the partner badge, which their brand guidelines govern separately, so a co-branded lockup is normally something a partner clears first. The full rules for every OpenAI asset in this repo are in [`marketing/openai-select-partner/badge-usage.md`](../marketing/openai-select-partner/badge-usage.md), with the announcement pack itself at [`marketing/openai-select-partner/README.md`](../marketing/openai-select-partner/README.md).++For the wider programme list and how to describe each one, see [Partner ecosystem](./partners.md).++---++## Contact++| | |+|---|---|+| **Press and partnerships** | [email protected] |+| **On X** | @trythreews |+| **Source** | `github.com/nirholas/three.ws` |++Use that inbox for anything the page does not cover: a format that is not here (EPS, a specific crop, a higher-resolution export), a co-branded graphic, use of the mark outside editorial contexts, a quote, or a fact you want confirmed before you print it. The page commits to a same-day reply on deadline requests for missing formats.++---++## Related++- [Partner ecosystem](./partners.md): every programme three.ws is in, at the status it actually claims+- [Listings and distribution](./listings.md): marketplaces, directories, and media partners, with per-listing status+- [Brand asset renderer](../marketing/brand/README.md): where the marks come from and how to regenerate them+- [Marketing campaigns](../marketing/README.md): announcement packs, social copy, and finished graphicsdiff --git a/docs/start-here.md b/docs/start-here.mdindex 2a0ad3fdc..e2122dd55 100644--- a/docs/start-here.md+++ b/docs/start-here.md@@ -105,6 +105,10 @@ Curious what happens between the prompt and the model? [How the Forge works](./h- **Rendering avatars outside the viewer?** → [Media and render API](./media-api.md): avatar PNG renders for `<img>` tags, posed clip renders, the runtime GLB optimizer, the CORS-open model proxy, and the free vision and speech-to-text endpoints; companion to the [3D API](./3d-api.md)- **Minting your work on-chain?** → [Minted 3D assets](./minted.md): the /minted gallery of avatars minted as Metaplex Core NFTs, the opt-in mint flow, baked provenance, and enforced remix royalties- **Letting an agent spend without your key?** → [Payment Sessions](./payment-sessions.md): fund a capped envelope from prepaid credits, hand the agent a bearer token, and it pays x402 endpoints under your caps and allowlist, refundable on cancel+- **Backing an agent with capital?** → [USDC agent vaults](./vaults.md): NAV-priced deposits and redemptions, the drawdown breaker that halts a vault, performance-fee claims, and the public audit ledger anyone can read+- **Funding your own agents?** → [Your master wallet](./user-wallet.md): the per-user custodial hub you fund once, then top up agent wallets, send SOL or USDC, and read on-chain history from+- **Following a trader instead of picking?** → [Copy trading](./copy-trading.md): follow a leader two ways, either your agent mirroring real Solana trades inside its own spend policy, or sized intents you sign yourself. Nothing is simulated, so the doc covers the leaderboard weighting, the Smart Money directory, and how performance fees accrue+- **Watching identities land on-chain?** → [On-chain deployments](./deployments.md): the live feed of agent identities registering on-chain as it happens, Solana Metaplex Core mints alongside ERC-8004 registrations across 15 EVM chains, with chain footprint and capability stats- **Building against the API?** → [The developer platform](./developer-platform.md): API keys, usage metrics, signed webhooks, the one-call MCP connection test, and the public tool and skills catalogs, with a runnable example per endpoint- **Auditing an agent's decisions?** → [The Reasoning Ledger](./reasoning-ledger.md): hash-chained, on-chain-anchored records of every consequential agent decision, verifiable by anyone at /ledger- **Following Solana traders?** → [KOL Tracker](./kol-tracker.md): KOLs ranked by realized P&L computed from their own wallets' on-chain trades (never self-reported), with the public API behind itdiff --git a/public/changelog.json b/public/changelog.jsonindex 501292a9b..5599f4c34 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-30T04:39:09.675Z",+ "generated_at": "2026-07-30T04:44:37.284Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",diff --git a/public/features.json b/public/features.jsonindex 5a71bc4c0..1ce71ade3 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-30T04:37:10.832Z",+ "generated_at": "2026-07-30T04:44:37.237Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -3874,6 +3874,26 @@"tags": [],"showcase": false},+ {+ "path": "/blog/image-to-3d-on-nvidia-l4-and-blackwell",+ "title": "Image-to-3D on NVIDIA L4 and Blackwell: Shipping Hunyuan3D 2.1 on Cloud Run GPUs",+ "description": "A field report from the three.ws GPU fleet: why Hunyuan3D 2.1 could not load on an NVIDIA L4, why CUDA 12.4 wheels have no sm_120 kernels for RTX PRO 6000 Blackwell, and the regional quota that made the bigger card the available card.",+ "added": null,+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/blog/three-ws-openai-select-partner",+ "title": "three.ws Named an OpenAI Select Partner",+ "description": "three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.",+ "added": "2026-07-25",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/blog/autonomous-trading-experiment","title": "We Gave 11 AI Agents Their Own Wallets and Real SOL. Here Are All 90 Trades.",@@ -3924,16 +3944,6 @@"tags": [],"showcase": false},- {- "path": "/blog/three-ws-openai-select-partner",- "title": "three.ws Named an OpenAI Select Partner",- "description": "three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.",- "added": "2026-07-25",- "auth": null,- "indexable": true,- "tags": [],- "showcase": false- },{"path": "/blog/three-ws-alibaba-cloud-partnership","title": "three.ws Joins the Alibaba Cloud Partner Network",diff --git a/public/llms-full.txt b/public/llms-full.txtindex a66e25192..2aba854fd 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -2355,6 +2355,18 @@ URL: https://three.ws/blogEditorial index of three.ws launches and long-form posts.+### Image-to-3D on NVIDIA L4 and Blackwell: Shipping Hunyuan3D 2.1 on Cloud Run GPUs++URL: https://three.ws/blog/image-to-3d-on-nvidia-l4-and-blackwell++A field report from the three.ws GPU fleet: why Hunyuan3D 2.1 could not load on an NVIDIA L4, why CUDA 12.4 wheels have no sm_120 kernels for RTX PRO 6000 Blackwell, and the regional quota that made the bigger card the available card.++### three.ws Named an OpenAI Select Partner++URL: https://three.ws/blog/three-ws-openai-select-partner++three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.+### We Gave 11 AI Agents Their Own Wallets and Real SOL. Here Are All 90 Trades.URL: https://three.ws/blog/autonomous-trading-experiment@@ -2385,12 +2397,6 @@ URL: https://three.ws/blog/three-ws-quicknode-startup-programthree.ws has been accepted into the Quicknode Startup Program and approved for free infrastructure credits, expanding the RPC backbone behind its Solana-first agent economy.-### three.ws Named an OpenAI Select Partner--URL: https://three.ws/blog/three-ws-openai-select-partner--three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.-### three.ws Joins the Alibaba Cloud Partner NetworkURL: https://three.ws/blog/three-ws-alibaba-cloud-partnershipdiff --git a/public/llms.txt b/public/llms.txtindex 76ee7a084..7e0f10558 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -412,12 +412,13 @@ Docs, tutorials, and reference.Long-form announcements, launches, and writing from three.ws.- [Blog](https://three.ws/blog): Editorial index of three.ws launches and long-form posts.+- [Image-to-3D on NVIDIA L4 and Blackwell: Shipping Hunyuan3D 2.1 on Cloud Run GPUs](https://three.ws/blog/image-to-3d-on-nvidia-l4-and-blackwell): A field report from the three.ws GPU fleet: why Hunyuan3D 2.1 could not load on an NVIDIA L4, why CUDA 12.4 wheels have no sm_120 kernels for RTX PRO 6000 Blackwell, and the regional quota that made the bigger card the available card.+- [three.ws Named an OpenAI Select Partner](https://three.ws/blog/three-ws-openai-select-partner): three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.- [We Gave 11 AI Agents Their Own Wallets and Real SOL. Here Are All 90 Trades.](https://three.ws/blog/autonomous-trading-experiment): Two weeks of fully autonomous pump.fun trading on Solana: 11 armed strategies, 90 closed real-money trades, every entry thesis, every exit, every mistake. Plus the 83,000 coins the fleet did not buy, the winners it missed, and a paperhands audit of every sell. Complete dataset included.- [Our Agent Made Its First Autonomous Trade. Here Is Every Decision It Took.](https://three.ws/blog/first-autonomous-trade): A three.ws agent sniped a brand-new pump.fun launch and closed it at +42.38%, fully autonomously. The full postmortem: every gate it passed, the on-chain receipts, what was luck, what was design, and the LLM-piloted strategist we are building next.- [Concierge: We Gave the Site Chatbot a Face](https://three.ws/blog/concierge-3d-chat-widget): Every website has the same faceless chat bubble. We shipped one with a rigged 3D avatar that blinks, lipsyncs, and speaks streaming answers grounded in your live page. One tag, free, open wire format. Here is how we built it by remixing our own stack.- [Inside the Forge: How a Prompt Becomes a 3D Model](https://three.ws/blog/inside-the-forge): What actually happens between typing a prompt on three.ws and downloading a textured 3D model: the reference image, the engine grid, self-healing failover, quality tiers, and what your model can do next.- [three.ws Joins the Quicknode Startup Program](https://three.ws/blog/three-ws-quicknode-startup-program): three.ws has been accepted into the Quicknode Startup Program and approved for free infrastructure credits, expanding the RPC backbone behind its Solana-first agent economy.-- [three.ws Named an OpenAI Select Partner](https://three.ws/blog/three-ws-openai-select-partner): three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.- [three.ws Joins the Alibaba Cloud Partner Network](https://three.ws/blog/three-ws-alibaba-cloud-partnership): three.ws is now an Alibaba Cloud Partner, bringing Qwen foundation models and Asia-Pacific cloud infrastructure to the three.ws 3D AI agent platform.- [The Stripe of x402: How three.ws Turned Agent Payments Into One Line of Code](https://three.ws/blog/x402-stripe-for-agent-payments): HTTP 402 sat unused for thirty years. Agents revived it. three.ws built the drop in payment modal that makes x402 a one liner, on top of a full stack of agent wallets, wallet intents, on-chain reputation, sniping, and $THREE.- [See Your 3D Avatar in the Real World — AR Lands on three.ws](https://three.ws/blog/see-your-3d-in-ar): Every 3D model and avatar on three.ws now has a View in AR button. On mobile it places the model in your real space through the camera. On desktop, a QR code gets you there in one scan. No app, no download.diff --git a/public/screenshots/city.png b/public/screenshots/city.pngnew file mode 100644index 000000000..095297910Binary files /dev/null and b/public/screenshots/city.png differdiff --git a/public/screenshots/communities.png b/public/screenshots/communities.pngnew file mode 100644index 000000000..cbb3d5307Binary files /dev/null and b/public/screenshots/communities.png differdiff --git a/public/screenshots/create.png b/public/screenshots/create.pngindex 4e6c037c3..39730b69f 100644Binary files a/public/screenshots/create.png and b/public/screenshots/create.png differdiff --git a/public/screenshots/discover.png b/public/screenshots/discover.pngindex 6e14f29e8..59db1ac53 100644Binary files a/public/screenshots/discover.png and b/public/screenshots/discover.png differdiff --git a/public/screenshots/embed-editor.png b/public/screenshots/embed-editor.pngnew file mode 100644index 000000000..4c9122e4fBinary files /dev/null and b/public/screenshots/embed-editor.png differdiff --git a/public/screenshots/forge.png b/public/screenshots/forge.pngnew file mode 100644index 000000000..3508da919Binary files /dev/null and b/public/screenshots/forge.png differdiff --git a/public/screenshots/launchpad.png b/public/screenshots/launchpad.pngnew file mode 100644index 000000000..ccf92d596Binary files /dev/null and b/public/screenshots/launchpad.png differdiff --git a/public/screenshots/pose-studio.png b/public/screenshots/pose-studio.pngnew file mode 100644index 000000000..86c5c90b2Binary files /dev/null and b/public/screenshots/pose-studio.png differdiff --git a/public/screenshots/pump-visualizer.png b/public/screenshots/pump-visualizer.pngnew file mode 100644index 000000000..502f03457Binary files /dev/null and b/public/screenshots/pump-visualizer.png differdiff --git a/public/screenshots/studio.png b/public/screenshots/studio.pngindex 1046440e4..5bd02faca 100644Binary files a/public/screenshots/studio.png and b/public/screenshots/studio.png differdiff --git a/public/screenshots/x402-bazaar.png b/public/screenshots/x402-bazaar.pngnew file mode 100644index 000000000..e63cf6965Binary files /dev/null and b/public/screenshots/x402-bazaar.png differdiff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 3584075d3..34759674b 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -79,7 +79,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 539 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 540 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -91,7 +91,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 539 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 540 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -2911,7 +2911,7 @@<section class="sm-section" id="blog"><header>- <h2>Blog<span class="sm-count" data-count>36</span></h2>+ <h2>Blog<span class="sm-count" data-count>37</span></h2><p class="sm-section-desc">Long-form announcements, launches, and writing from three.ws.</p></header><ul class="sm-list">@@ -2922,6 +2922,20 @@<span class="sm-desc">Editorial index of three.ws launches and long-form posts.</span></a></li>+ <li>+ <a href="/blog/image-to-3d-on-nvidia-l4-and-blackwell">+ <span class="sm-title">Image-to-3D on NVIDIA L4 and Blackwell: Shipping Hunyuan3D 2.1 on Cloud Run GPUs</span>+ <span class="sm-path">/blog/image-to-3d-on-nvidia-l4-and-blackwell</span>+ <span class="sm-desc">A field report from the three.ws GPU fleet: why Hunyuan3D 2.1 could not load on an NVIDIA L4, why CUDA 12.4 wheels have no sm_120 kernels for RTX PRO 6000 Blackwell, and the regional quota that made the bigger card the available card.</span>+ </a>+ </li>+ <li>+ <a href="/blog/three-ws-openai-select-partner">+ <span class="sm-title">three.ws Named an OpenAI Select Partner</span>+ <span class="sm-path">/blog/three-ws-openai-select-partner</span>+ <span class="sm-desc">three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.</span>+ </a>+ </li><li><a href="/blog/autonomous-trading-experiment"><span class="sm-title">We Gave 11 AI Agents Their Own Wallets and Real SOL. Here Are All 90 Trades.</span>@@ -2957,13 +2971,6 @@<span class="sm-desc">three.ws has been accepted into the Quicknode Startup Program and approved for free infrastructure credits, expanding the RPC backbone behind its Solana-first agent economy.</span></a></li>- <li>- <a href="/blog/three-ws-openai-select-partner">- <span class="sm-title">three.ws Named an OpenAI Select Partner</span>- <span class="sm-path">/blog/three-ws-openai-select-partner</span>- <span class="sm-desc">three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.</span>- </a>- </li><li><a href="/blog/three-ws-alibaba-cloud-partnership"><span class="sm-title">three.ws Joins the Alibaba Cloud Partner Network</span>diff --git a/scripts/audit-mcp-golden.mjs b/scripts/audit-mcp-golden.mjsindex d90628d90..badd51170 100644--- a/scripts/audit-mcp-golden.mjs+++ b/scripts/audit-mcp-golden.mjs@@ -22,48 +22,21 @@//// Run: node scripts/audit-mcp-golden.mjs → compare, exit 1 on drift// node scripts/audit-mcp-golden.mjs --update → regenerate the fixture-import { readFileSync, writeFileSync, readdirSync, existsSync } from 'node:fs';+import { readFileSync, writeFileSync } from 'node:fs';import { createHash } from 'node:crypto';-import { resolve, dirname, join } from 'node:path';-import { fileURLToPath } from 'node:url';+import { join } from 'node:path';import { parse } from 'acorn';-const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');+import { ROOT, mcpToolSources } from './lib/mcp-tool-sources.mjs';+const FIXTURE = join(ROOT, 'tests', 'fixtures', 'mcp-golden-tools.json');-// Every hosted MCP server's tool-definition sources. A new hosted server MUST-// be added here (and the fixture regenerated) or its contract is unguarded.-const SOURCES = [- ...readdirSync(join(ROOT, 'api/_mcp/tools')).map((f) => `api/_mcp/tools/${f}`),- ...readdirSync(join(ROOT, 'api/_mcp3d/tools')).map((f) => `api/_mcp3d/tools/${f}`),- 'api/_mcp-studio/tools.js',- 'api/_mcpagent/tools.js',- 'api/_mcpbazaar/tools.js',- 'api/_mcpibm/tools.js',- // Published MCP packages expose each tool as packages/<name>-mcp/src/tools/*.js.- // Snapshot them too — a package tool's public contract (name, description,- // input schema, safety annotations) is a promise to every MCP client that- // installed it, and a silent refactor must not be allowed to change it.- ...packageToolSources(),-].filter((f) => f.endsWith('.js')).sort();--// Discover every `packages/*-mcp/src/tools/*.js` tool-definition file. Returns-// repo-relative, forward-slash paths (matching the hosted entries above) so the-// same static AST extractor and fixture keying work unchanged. `index.js`-// barrels are skipped — they re-export, they don't define contracts.-function packageToolSources() {- const pkgRoot = join(ROOT, 'packages');- if (!existsSync(pkgRoot)) return [];- return readdirSync(pkgRoot, { withFileTypes: true })- .filter((d) => d.isDirectory() && d.name.endsWith('-mcp'))- .flatMap((d) => {- const rel = `packages/${d.name}/src/tools`;- if (!existsSync(join(ROOT, rel))) return [];- return readdirSync(join(ROOT, rel))- .filter((f) => f.endsWith('.js') && f !== 'index.js')- .map((f) => `${rel}/${f}`);- });-}+// Every hosted + published MCP server's tool-definition sources, discovered by+// scripts/lib/mcp-tool-sources.mjs so this gate and the safety gate can never+// diverge on which files are guarded. Tools built dynamically (e.g.+// buildGettingStartedTool) are invisible to static parsing and out of scope --+// verify those against a running server (`npm run test:mcp` / `smoke:mcp`).+const SOURCES = mcpToolSources();const sha12 = (text) => createHash('sha256').update(text).digest('hex').slice(0, 12);diff --git a/scripts/audit-mcp-safety.mjs b/scripts/audit-mcp-safety.mjsindex 0d712618e..64824d45d 100644--- a/scripts/audit-mcp-safety.mjs+++ b/scripts/audit-mcp-safety.mjs@@ -25,335 +25,55 @@// (destructiveHint defaults to TRUE when omitted, so an unannotated tool// is advertised as destructive; that is safe but always unintended)//-// Evidence is gathered from the handler's transitive call closure WITHIN its own-// file: `sql` template tags opening with insert/update/delete, and calls to the-// known transaction-signing and payment-settling helpers. Cross-file calls are-// out of scope on purpose -- importing a module that CAN send a transaction is-// not evidence that this handler does, and that inference produced false-// positives on every read-only tool sharing an RPC helper.+// Evidence is the handler's transitive call closure: `sql` template tags opening+// with insert/update/delete, plus calls to the known transaction-signing and+// payment-settling helpers. Same-module calls are followed to any depth, and a+// call into an imported function is followed one module hop.+//+// Following a CALL is evidence; merely importing a module that could mutate is+// not. That distinction is load-bearing: a dozen genuinely read-only tools share+// one Solana RPC helper, and treating the import as evidence flagged them all.//// Cache and telemetry writes are real writes that are not semantic mutations-// (warming an attestation cache on read, recording usage). Those are exempted-// individually in EXEMPTIONS below, each with a reason, so an exemption is a-// reviewed line in this file rather than a silent hole in the gate.+// (warming a cache on read, recording usage). Those are exempted individually in+// EXEMPTIONS below, each with a reason, so an exemption is a reviewed line in+// this file rather than a silent hole in the gate.//// Run: node scripts/audit-mcp-safety.mjs (exit 1 on any violation)// node scripts/audit-mcp-safety.mjs --list (print every tool + evidence)-import { readFileSync } from 'node:fs';-import { join } from 'node:path';-import { parse } from 'acorn';--import { ROOT, allMcpToolSources } from './lib/mcp-tool-sources.mjs';--// ----------------------------------------------------------------------------// Mutation vocabulary-// -----------------------------------------------------------------------------// Helper calls that sign, send, or settle. Matched on the callee's final-// identifier, so `conn.sendTransaction(...)` and `sendTransaction(...)` both hit.-const MUTATION_CALLS = new Map([- ['sendTransaction', 'tx-send'],- ['sendRawTransaction', 'tx-send'],- ['sendAndConfirmTransaction', 'tx-send'],- ['sendVersionedTransaction', 'tx-send'],- ['signTransaction', 'tx-sign'],- ['partialSign', 'tx-sign'],- ['hedgedSend', 'tx-send'],- ['settlePayment', 'payment-settle'],- ['transferUsdc', 'funds-transfer'],- ['transferSol', 'funds-transfer'],- ['solanaTransfer', 'funds-transfer'],- ['mintTo', 'mint'],- ['createMint', 'mint'],- ['mintAsset', 'mint'],-]);--// Evidence classes that make an action irreversible, so `destructiveHint: false`-// is wrong for them.-const IRREVERSIBLE = new Set(['tx-send', 'tx-sign', 'payment-settle', 'funds-transfer', 'mint']);--// A `sql` tagged template whose text opens with one of these is a write.-const SQL_WRITE = /^\s*(?:--[^\n]*\n|\s)*(insert|update|delete|truncate|drop|alter)\b/i;+import { allMcpToolSources } from './lib/mcp-tool-sources.mjs';+import { checkTool, extractTools } from './lib/mcp-safety-check.mjs';// ---------------------------------------------------------------------------// Reviewed exemptions// ---------------------------------------------------------------------------// A tool listed here keeps `readOnlyHint: true` despite carrying write evidence,-// because the write is a cache fill or telemetry record rather than the effect-// the caller asked for. Keyed `tool:evidence`. Every entry needs a reason.+// because the write is a cache fill rather than the effect the caller asked for.+// Keyed `tool:evidence`; every entry states why.//-// Empty today: no read-only tool currently writes on the read path. It stays-// because the alternative, when a cache-warming read does appear, is someone-// weakening an annotation or deleting the gate. `tests/mcp-safety-audit.test.js`-// exercises it so it cannot rot unnoticed.-const EXEMPTIONS = new Map();--// ----------------------------------------------------------------------------// AST helpers-// -----------------------------------------------------------------------------const FUNCTION_TYPES = new Set([- 'FunctionDeclaration',- 'FunctionExpression',- 'ArrowFunctionExpression',-]);--/** Walk every child node, depth-first. */-function walk(node, visit) {- if (!node || typeof node.type !== 'string') return;- visit(node);- for (const key of Object.keys(node)) {- if (key === 'type' || key === 'start' || key === 'end') continue;- const value = node[key];- if (Array.isArray(value)) {- for (const child of value) walk(child, visit);- } else if (value && typeof value.type === 'string') {- walk(value, visit);- }- }-}--/** The final identifier of a callee: `a.b.c()` -> "c", `c()` -> "c". */-function calleeName(callee) {- if (!callee) return null;- if (callee.type === 'Identifier') return callee.name;- if (callee.type === 'MemberExpression' && !callee.computed) {- return callee.property?.name ?? null;- }- return null;-}--/**- * Local name -> resolved absolute path, for every relative import in a module.- * Extension-less specifiers are not used in this repo's ESM sources, so a- * specifier is resolved as written.- */-function collectImports(ast, relPath) {- const dir = dirname(join(ROOT, relPath));- const bindings = new Map();- for (const node of ast.body) {- if (node.type !== 'ImportDeclaration') continue;- const source = node.source.value;- if (typeof source !== 'string' || !source.startsWith('.')) continue;- const target = resolvePath(dir, source);- if (!existsSync(target)) continue;- for (const spec of node.specifiers) {- if (spec.type === 'ImportSpecifier') {- bindings.set(spec.local.name, { path: target, imported: spec.imported.name });- }- }- }- return bindings;-}--/** Map of every function declared at any level of a module, by name. */-function collectNamedFunctions(ast) {- const fns = new Map();- walk(ast, (node) => {- if (node.type === 'FunctionDeclaration' && node.id?.name) {- fns.set(node.id.name, node);- } else if (node.type === 'VariableDeclarator' && node.id?.type === 'Identifier') {- if (node.init && FUNCTION_TYPES.has(node.init.type)) fns.set(node.id.name, node.init);- } else if (- node.type === 'Property' &&- !node.computed &&- node.key?.name &&- node.value &&- FUNCTION_TYPES.has(node.value.type)- ) {- // Object-literal methods, incl. `async handler(...)` shorthand.- if (!fns.has(node.key.name)) fns.set(node.key.name, node.value);- }- });- return fns;-}--/**- * Unwrap the object-literal inside `Object.freeze({...})`, which is how several- * servers declare their shared annotation constants.- */-function unwrapObject(node) {- if (!node) return null;- if (node.type === 'ObjectExpression') return node;- if (- node.type === 'CallExpression' &&- calleeName(node.callee) === 'freeze' &&- node.arguments.length === 1- ) {- return unwrapObject(node.arguments[0]);- }- return null;-}--/**- * Boolean-valued properties of an object literal, resolving `...SPREAD` of a- * local constant so shared annotation constants compose the way they do at- * runtime (`{ title: '…', ...LIVE_READ }`).- */-function objectBooleans(objNode, constObjects, seen = new Set()) {- const values = {};- const target = unwrapObject(objNode);- if (!target || seen.has(target)) return values;- seen.add(target);- for (const prop of target.properties) {- if (prop.type === 'SpreadElement') {- const source =- prop.argument.type === 'Identifier'- ? constObjects.get(prop.argument.name)- : unwrapObject(prop.argument);- if (source) Object.assign(values, objectBooleans(source, constObjects, seen));- continue;- }- if (prop.type !== 'Property' || prop.computed) continue;- const key = prop.key?.name ?? prop.key?.value;- if (prop.value?.type === 'Literal' && typeof prop.value.value === 'boolean') {- values[key] = prop.value.value;- }- }- return values;-}--/** Resolve an `annotations` property to plain booleans, following a local const. */-function readAnnotations(node, constObjects) {- if (!node) return { kind: 'missing', values: {} };- let target = node;- if (node.type === 'Identifier') {- target = constObjects.get(node.name);- if (!target) return { kind: 'unresolved', values: {}, ref: node.name };- }- if (!unwrapObject(target)) return { kind: 'dynamic', values: {} };- return { kind: 'resolved', values: objectBooleans(target, constObjects) };-}--/** Every object literal assigned to a const, by name (Object.freeze unwrapped). */-function collectConstObjects(ast) {- const out = new Map();- walk(ast, (node) => {- if (node.type !== 'VariableDeclarator' || node.id?.type !== 'Identifier') return;- const obj = unwrapObject(node.init);- if (obj) out.set(node.id.name, obj);- });- return out;-}--const HINT_KEYS = new Set([- 'readOnlyHint',- 'destructiveHint',- 'idempotentHint',- 'openWorldHint',+// All four below are read-through cache fills: the caller asked for a read and+// got a read, and the server warmed its own cache on the way. Each write is+// wrapped non-fatally at the source, so a failed write still returns the read.+const EXEMPTIONS = new Map([+ [+ 'oracle_coin:db-write',+ 'scoreCoin(..., { persist: true }) caches the conviction verdict it just computed (upsertConviction/upsertNarrative, both non-fatal) so the next read is warm.',+ ],+ [+ 'solana_agent_reputation:db-write',+ 'ensureWarm() crawls attestations into the cache on a cold read; the caller receives a computed reputation summary.',+ ],+ [+ 'solana_agent_attestations:db-write',+ 'ensureWarm() crawls attestations into the cache on a cold read; the caller receives the attestation list.',+ ],+ [+ 'solana_agent_passport:db-write',+ 'ensureWarm() crawls attestations into the cache on a cold read; the caller receives the passport view.',+ ],]);-/**- * Annotations declared in a name-keyed overlay map rather than inline on the- * tool def. The pump.fun server declares its tool list and its annotations as- * two separate exports (`TOOLS` + `TOOL_ANNOTATIONS`) and merges them at- * registration, so an inline-only reader would see 25 unannotated tools.- * @returns {Map<string, Record<string, boolean>>} tool name -> hints- */-function collectAnnotationOverlays(constObjects) {- const overlays = new Map();- for (const objNode of constObjects.values()) {- for (const prop of objNode.properties) {- if (prop.type !== 'Property' || prop.computed) continue;- const toolName = prop.key?.name ?? prop.key?.value;- if (typeof toolName !== 'string') continue;- if (!unwrapObject(prop.value)) continue;- const values = objectBooleans(prop.value, constObjects);- if (Object.keys(values).some((key) => HINT_KEYS.has(key))) overlays.set(toolName, values);- }- }- return overlays;-}--/**- * Mutation evidence inside one function plus every same-file function it calls.- * @returns {Set<string>} evidence labels- */-function evidenceFor(fnNode, namedFunctions) {- const evidence = new Set();- const seen = new Set();-- const visitFunction = (fn) => {- if (!fn || seen.has(fn)) return;- seen.add(fn);- const nested = [];- walk(fn, (node) => {- if (node.type === 'TaggedTemplateExpression') {- const tag = calleeName(node.tag);- const text = node.quasi?.quasis?.[0]?.value?.cooked ?? '';- if (tag === 'sql' && SQL_WRITE.test(text)) evidence.add('db-write');- }- if (node.type === 'CallExpression') {- const name = calleeName(node.callee);- if (!name) return;- const label = MUTATION_CALLS.get(name);- if (label) evidence.add(label);- const target = namedFunctions.get(name);- // Do not re-enter the function we are already inside.- if (target && target !== fn) nested.push(target);- }- });- for (const fn2 of nested) visitFunction(fn2);- };-- visitFunction(fnNode);- return evidence;-}--/** Extract every tool definition with a handler from one file. */-function extractTools(relPath) {- const src = readFileSync(join(ROOT, relPath), 'utf8');- let ast;- try {- ast = parse(src, { ecmaVersion: 'latest', sourceType: 'module' });- } catch (error) {- return { parseError: error.message, tools: [] };- }-- const namedFunctions = collectNamedFunctions(ast);- const constObjects = collectConstObjects(ast);- const overlays = collectAnnotationOverlays(constObjects);- const tools = [];-- walk(ast, (node) => {- if (node.type !== 'ObjectExpression') return;- const props = new Map();- for (const prop of node.properties) {- if (prop.type === 'Property' && !prop.computed) {- props.set(prop.key?.name ?? prop.key?.value, prop.value);- }- }- const nameNode = props.get('name');- const name =- nameNode?.type === 'Literal' && typeof nameNode.value === 'string' ? nameNode.value : null;- if (!name) return;- // A tool definition, as this repo writes them: a wire name plus a- // description and either a schema or annotations.- if (!props.has('description') || !(props.has('inputSchema') || props.has('annotations'))) return;-- const handlerNode = props.get('handler');- const annotations = props.has('annotations')- ? readAnnotations(props.get('annotations'), constObjects)- : overlays.has(name)- ? { kind: 'resolved', values: overlays.get(name), via: 'overlay' }- : { kind: 'missing', values: {} };- const evidence =- handlerNode && FUNCTION_TYPES.has(handlerNode.type)- ? evidenceFor(handlerNode, namedFunctions)- : new Set();-- tools.push({- name,- annotations,- evidence: [...evidence].sort(),- hasHandler: Boolean(handlerNode && FUNCTION_TYPES.has(handlerNode.type)),- });- });-- return { tools };-}-// ---------------------------------------------------------------------------// Run// ---------------------------------------------------------------------------@@ -371,44 +91,9 @@ for (const relPath of sources) {}for (const tool of tools) {rows.push({ file: relPath, ...tool });- const { name, annotations, evidence } = tool;- const where = `${relPath}: ${name}`;-- if (annotations.kind === 'missing') {- violations.push(- `${where}: no annotations. destructiveHint defaults to TRUE when omitted, so this tool is advertised as destructive. Declare them explicitly.`,- );- continue;- }- if (annotations.kind === 'unresolved') {- violations.push(- `${where}: annotations reference "${annotations.ref}", which is not a local object literal. Declare the constant in this file so the gate can read it.`,- );- continue;- }- if (annotations.kind === 'dynamic') {- violations.push(`${where}: annotations are computed at runtime and cannot be verified.`);- continue;- }-- const { readOnlyHint, destructiveHint } = annotations.values;- const unexempted = evidence.filter((label) => !EXEMPTIONS.has(`${name}:${label}`));- for (const label of evidence) {- if (EXEMPTIONS.has(`${name}:${label}`)) exempted.push(`${name} (${label})`);- }-- if (readOnlyHint === true && unexempted.length) {- violations.push(- `${where}: declares readOnlyHint:true but its handler shows ${unexempted.join(', ')}. An MCP client may auto-approve this call. Set readOnlyHint:false, or add a reviewed EXEMPTIONS entry if the write is a cache/telemetry fill.`,- );- }-- const irreversible = unexempted.filter((label) => IRREVERSIBLE.has(label));- if (irreversible.length && destructiveHint === false) {- violations.push(- `${where}: declares destructiveHint:false but its handler shows ${irreversible.join(', ')}, which cannot be undone. Set destructiveHint:true.`,- );- }+ const result = checkTool(tool, `${relPath}: ${tool.name}`, EXEMPTIONS);+ violations.push(...result.violations);+ exempted.push(...result.exempted);}}diff --git a/scripts/lib/mcp-safety-check.mjs b/scripts/lib/mcp-safety-check.mjsnew file mode 100644index 000000000..62d550368--- /dev/null+++ b/scripts/lib/mcp-safety-check.mjs@@ -0,0 +1,409 @@+// AST analysis behind the MCP annotation-safety gate.+//+// Separated from scripts/audit-mcp-safety.mjs so the rules can be exercised+// against fixture sources in tests/mcp-safety-audit.test.js: a gate nobody has+// watched fail is a gate nobody knows works.+//+// See the CLI for why this check exists and what each rule means.++import { readFileSync, existsSync } from 'node:fs';+import { dirname, join, relative, resolve as resolvePath } from 'node:path';+import { parse } from 'acorn';++import { ROOT } from './mcp-tool-sources.mjs';++// ---------------------------------------------------------------------------+// Mutation vocabulary+// ---------------------------------------------------------------------------++// Helper calls that sign, send, or settle. Matched on the callee's final+// identifier, so `conn.sendTransaction(...)` and `sendTransaction(...)` both hit.+export const MUTATION_CALLS = new Map([+ ['sendTransaction', 'tx-send'],+ ['sendRawTransaction', 'tx-send'],+ ['sendAndConfirmTransaction', 'tx-send'],+ ['sendVersionedTransaction', 'tx-send'],+ ['signTransaction', 'tx-sign'],+ ['partialSign', 'tx-sign'],+ ['hedgedSend', 'tx-send'],+ ['settlePayment', 'payment-settle'],+ ['transferUsdc', 'funds-transfer'],+ ['transferSol', 'funds-transfer'],+ ['solanaTransfer', 'funds-transfer'],+ ['mintTo', 'mint'],+ ['createMint', 'mint'],+ ['mintAsset', 'mint'],+]);++// Evidence classes that make an action irreversible, so `destructiveHint: false`+// is wrong for them.+export const IRREVERSIBLE = new Set(['tx-send', 'tx-sign', 'payment-settle', 'funds-transfer', 'mint']);++// A `sql` tagged template whose text opens with one of these is a write.+const SQL_WRITE = /^\s*(?:--[^\n]*\n|\s)*(insert|update|delete|truncate|drop|alter)\b/i;++// ---------------------------------------------------------------------------+// AST helpers+// ---------------------------------------------------------------------------++const FUNCTION_TYPES = new Set([+ 'FunctionDeclaration',+ 'FunctionExpression',+ 'ArrowFunctionExpression',+]);++/** Walk every child node, depth-first. */+function walk(node, visit) {+ if (!node || typeof node.type !== 'string') return;+ visit(node);+ for (const key of Object.keys(node)) {+ if (key === 'type' || key === 'start' || key === 'end') continue;+ const value = node[key];+ if (Array.isArray(value)) {+ for (const child of value) walk(child, visit);+ } else if (value && typeof value.type === 'string') {+ walk(value, visit);+ }+ }+}++/** The final identifier of a callee: `a.b.c()` -> "c", `c()` -> "c". */+function calleeName(callee) {+ if (!callee) return null;+ if (callee.type === 'Identifier') return callee.name;+ if (callee.type === 'MemberExpression' && !callee.computed) {+ return callee.property?.name ?? null;+ }+ return null;+}++/**+ * Local name -> resolved absolute path, for every relative import in a module.+ * Extension-less specifiers are not used in this repo's ESM sources, so a+ * specifier is resolved as written.+ */+function collectImports(ast, relPath) {+ const dir = dirname(join(ROOT, relPath));+ const bindings = new Map();+ for (const node of ast.body) {+ if (node.type !== 'ImportDeclaration') continue;+ const source = node.source.value;+ if (typeof source !== 'string' || !source.startsWith('.')) continue;+ const target = resolvePath(dir, source);+ if (!existsSync(target)) continue;+ for (const spec of node.specifiers) {+ if (spec.type === 'ImportSpecifier') {+ bindings.set(spec.local.name, { path: target, imported: spec.imported.name });+ }+ }+ }+ return bindings;+}++/** Map of every function declared at any level of a module, by name. */+function collectNamedFunctions(ast) {+ const fns = new Map();+ walk(ast, (node) => {+ if (node.type === 'FunctionDeclaration' && node.id?.name) {+ fns.set(node.id.name, node);+ } else if (node.type === 'VariableDeclarator' && node.id?.type === 'Identifier') {+ if (node.init && FUNCTION_TYPES.has(node.init.type)) fns.set(node.id.name, node.init);+ } else if (+ node.type === 'Property' &&+ !node.computed &&+ node.key?.name &&+ node.value &&+ FUNCTION_TYPES.has(node.value.type)+ ) {+ // Object-literal methods, incl. `async handler(...)` shorthand.+ if (!fns.has(node.key.name)) fns.set(node.key.name, node.value);+ }+ });+ return fns;+}++/**+ * Unwrap the object-literal inside `Object.freeze({...})`, which is how several+ * servers declare their shared annotation constants.+ */+function unwrapObject(node) {+ if (!node) return null;+ if (node.type === 'ObjectExpression') return node;+ if (+ node.type === 'CallExpression' &&+ calleeName(node.callee) === 'freeze' &&+ node.arguments.length === 1+ ) {+ return unwrapObject(node.arguments[0]);+ }+ return null;+}++/**+ * Boolean-valued properties of an object literal, resolving `...SPREAD` of a+ * local constant so shared annotation constants compose the way they do at+ * runtime (`{ title: '…', ...LIVE_READ }`).+ */+function objectBooleans(objNode, constObjects, seen = new Set()) {+ const values = {};+ const target = unwrapObject(objNode);+ if (!target || seen.has(target)) return values;+ seen.add(target);+ for (const prop of target.properties) {+ if (prop.type === 'SpreadElement') {+ const source =+ prop.argument.type === 'Identifier'+ ? constObjects.get(prop.argument.name)+ : unwrapObject(prop.argument);+ if (source) Object.assign(values, objectBooleans(source, constObjects, seen));+ continue;+ }+ if (prop.type !== 'Property' || prop.computed) continue;+ const key = prop.key?.name ?? prop.key?.value;+ if (prop.value?.type === 'Literal' && typeof prop.value.value === 'boolean') {+ values[key] = prop.value.value;+ }+ }+ return values;+}++/** Resolve an `annotations` property to plain booleans, following a local const. */+function readAnnotations(node, constObjects) {+ if (!node) return { kind: 'missing', values: {} };+ let target = node;+ if (node.type === 'Identifier') {+ target = constObjects.get(node.name);+ if (!target) return { kind: 'unresolved', values: {}, ref: node.name };+ }+ if (!unwrapObject(target)) return { kind: 'dynamic', values: {} };+ return { kind: 'resolved', values: objectBooleans(target, constObjects) };+}++/** Every object literal assigned to a const, by name (Object.freeze unwrapped). */+function collectConstObjects(ast) {+ const out = new Map();+ walk(ast, (node) => {+ if (node.type !== 'VariableDeclarator' || node.id?.type !== 'Identifier') return;+ const obj = unwrapObject(node.init);+ if (obj) out.set(node.id.name, obj);+ });+ return out;+}++const HINT_KEYS = new Set([+ 'readOnlyHint',+ 'destructiveHint',+ 'idempotentHint',+ 'openWorldHint',+]);++/**+ * Annotations declared in a name-keyed overlay map rather than inline on the+ * tool def. The pump.fun server declares its tool list and its annotations as+ * two separate exports (`TOOLS` + `TOOL_ANNOTATIONS`) and merges them at+ * registration, so an inline-only reader would see 25 unannotated tools.+ * @returns {Map<string, Record<string, boolean>>} tool name -> hints+ */+function collectAnnotationOverlays(constObjects) {+ const overlays = new Map();+ for (const objNode of constObjects.values()) {+ for (const prop of objNode.properties) {+ if (prop.type !== 'Property' || prop.computed) continue;+ const toolName = prop.key?.name ?? prop.key?.value;+ if (typeof toolName !== 'string') continue;+ if (!unwrapObject(prop.value)) continue;+ const values = objectBooleans(prop.value, constObjects);+ if (Object.keys(values).some((key) => HINT_KEYS.has(key))) overlays.set(toolName, values);+ }+ }+ return overlays;+}++/** Parsed module cache: absolute path -> { namedFunctions, imports } or null. */+const moduleCache = new Map();++function loadModule(absPath) {+ if (moduleCache.has(absPath)) return moduleCache.get(absPath);+ let parsed = null;+ try {+ const ast = parse(readFileSync(absPath, 'utf8'), {+ ecmaVersion: 'latest',+ sourceType: 'module',+ });+ parsed = {+ namedFunctions: collectNamedFunctions(ast),+ imports: collectImports(ast, relative(ROOT, absPath)),+ };+ } catch {+ parsed = null; // unparseable dependency: nothing to inspect+ }+ moduleCache.set(absPath, parsed);+ return parsed;+}++/**+ * Mutation evidence for one handler: every function it actually calls, following+ * same-module calls to any depth and calls into an imported function for+ * `maxHops` module crossings.+ *+ * Following a CALL into an imported function is evidence; merely importing a+ * module that could mutate is not. That distinction matters: a dozen read-only+ * tools import the same Solana RPC helper, and treating the import as evidence+ * flagged every one of them.+ *+ * @returns {Set<string>} evidence labels+ */+function evidenceFor(fnNode, namedFunctions, imports, maxHops = 1) {+ const evidence = new Set();+ const seen = new Set();++ const visitFunction = (fn, scope, hops) => {+ if (!fn || seen.has(fn)) return;+ seen.add(fn);+ const nextSameModule = [];+ const nextImported = [];++ walk(fn, (node) => {+ if (node.type === 'TaggedTemplateExpression') {+ const tag = calleeName(node.tag);+ const text = node.quasi?.quasis?.[0]?.value?.cooked ?? '';+ if (tag === 'sql' && SQL_WRITE.test(text)) evidence.add('db-write');+ }+ if (node.type !== 'CallExpression') return;+ const name = calleeName(node.callee);+ if (!name) return;+ const label = MUTATION_CALLS.get(name);+ if (label) evidence.add(label);++ const local = scope.namedFunctions.get(name);+ if (local && local !== fn) {+ nextSameModule.push(local);+ return;+ }+ const binding = scope.imports.get(name);+ if (binding && hops < maxHops) nextImported.push(binding);+ });++ for (const next of nextSameModule) visitFunction(next, scope, hops);+ for (const binding of nextImported) {+ const dep = loadModule(binding.path);+ if (!dep) continue;+ const target = dep.namedFunctions.get(binding.imported);+ if (target) visitFunction(target, dep, hops + 1);+ }+ };++ visitFunction(fnNode, { namedFunctions, imports }, 0);+ return evidence;+}++/** Extract every tool definition with a handler from one file. */+export function extractTools(relPath) {+ const src = readFileSync(join(ROOT, relPath), 'utf8');+ let ast;+ try {+ ast = parse(src, { ecmaVersion: 'latest', sourceType: 'module' });+ } catch (error) {+ return { parseError: error.message, tools: [] };+ }++ const namedFunctions = collectNamedFunctions(ast);+ const imports = collectImports(ast, relPath);+ const constObjects = collectConstObjects(ast);+ const overlays = collectAnnotationOverlays(constObjects);+ const tools = [];++ walk(ast, (node) => {+ if (node.type !== 'ObjectExpression') return;+ const props = new Map();+ for (const prop of node.properties) {+ if (prop.type === 'Property' && !prop.computed) {+ props.set(prop.key?.name ?? prop.key?.value, prop.value);+ }+ }+ const nameNode = props.get('name');+ const name =+ nameNode?.type === 'Literal' && typeof nameNode.value === 'string' ? nameNode.value : null;+ if (!name) return;+ // A tool definition, as this repo writes them: a wire name plus a+ // description and either a schema or annotations.+ if (!props.has('description') || !(props.has('inputSchema') || props.has('annotations'))) return;++ const handlerNode = props.get('handler');+ const annotations = props.has('annotations')+ ? readAnnotations(props.get('annotations'), constObjects)+ : overlays.has(name)+ ? { kind: 'resolved', values: overlays.get(name), via: 'overlay' }+ : { kind: 'missing', values: {} };+ const evidence =+ handlerNode && FUNCTION_TYPES.has(handlerNode.type)+ ? evidenceFor(handlerNode, namedFunctions, imports)+ : new Set();++ tools.push({+ name,+ annotations,+ evidence: [...evidence].sort(),+ hasHandler: Boolean(handlerNode && FUNCTION_TYPES.has(handlerNode.type)),+ });+ });++ return { tools };+}+++// ---------------------------------------------------------------------------+// Rules+// ---------------------------------------------------------------------------++/**+ * Violations for one extracted tool.+ * @param {{name: string, annotations: object, evidence: string[]}} tool+ * @param {string} where label prefixed to each message+ * @param {Map<string, string>} exemptions `tool:evidence` -> reason+ * @returns {{violations: string[], exempted: string[]}}+ */+export function checkTool(tool, where, exemptions) {+ const { name, annotations, evidence } = tool;+ const violations = [];+ const exempted = [];++ if (annotations.kind === 'missing') {+ violations.push(+ `${where}: no annotations. destructiveHint defaults to TRUE when omitted, so this tool is advertised as destructive. Declare them explicitly.`,+ );+ return { violations, exempted };+ }+ if (annotations.kind === 'unresolved') {+ violations.push(+ `${where}: annotations reference "${annotations.ref}", which is not a local object literal. Declare the constant in this file so the gate can read it.`,+ );+ return { violations, exempted };+ }+ if (annotations.kind === 'dynamic') {+ violations.push(`${where}: annotations are computed at runtime and cannot be verified.`);+ return { violations, exempted };+ }++ const { readOnlyHint, destructiveHint } = annotations.values;+ const unexempted = [];+ for (const label of evidence) {+ if (exemptions.has(`${name}:${label}`)) exempted.push(`${name} (${label})`);+ else unexempted.push(label);+ }++ if (readOnlyHint === true && unexempted.length) {+ violations.push(+ `${where}: declares readOnlyHint:true but its handler shows ${unexempted.join(', ')}. An MCP client may auto-approve this call. Set readOnlyHint:false, or add a reviewed EXEMPTIONS entry if the write is a cache/telemetry fill.`,+ );+ }++ const irreversible = unexempted.filter((label) => IRREVERSIBLE.has(label));+ if (irreversible.length && destructiveHint === false) {+ violations.push(+ `${where}: declares destructiveHint:false but its handler shows ${irreversible.join(', ')}, which cannot be undone. Set destructiveHint:true.`,+ );+ }++ return { violations, exempted };+}diff --git a/tests/fixtures/mcp-safety/clean-read.js b/tests/fixtures/mcp-safety/clean-read.jsnew file mode 100644index 000000000..7de8f6c41--- /dev/null+++ b/tests/fixtures/mcp-safety/clean-read.js@@ -0,0 +1,32 @@+// Fixture: a genuinely read-only tool. Its name contains a word the old+// name-based heuristic treated as a mutation ("resolve", "open"), and it imports+// a module that can write without ever calling the writing function. The gate+// must stay silent on both counts.+import { sql } from '../../../api/_lib/db.js';++const LIVE_READ = Object.freeze({+ readOnlyHint: true,+ destructiveHint: false,+ idempotentHint: false,+ openWorldHint: true,+});++async function unusedWriter(id) {+ await sql`update fixture_visits set seen = true where agent_id = ${id}`;+}++export const toolDefs = [+ {+ name: 'fixture_resolve_open',+ title: 'Fixture resolve open',+ annotations: LIVE_READ,+ description: 'Resolves a name and lists open items. Reads only.',+ inputSchema: { type: 'object', properties: { name: { type: 'string' } } },+ async handler(args) {+ const rows = await sql`select id from fixture_visits where agent_id = ${args.name}`;+ return { content: [{ type: 'text', text: JSON.stringify(rows) }] };+ },+ },+];++export { unusedWriter };diff --git a/tests/fixtures/mcp-safety/missing-annotations.js b/tests/fixtures/mcp-safety/missing-annotations.jsnew file mode 100644index 000000000..faf558b6e--- /dev/null+++ b/tests/fixtures/mcp-safety/missing-annotations.js@@ -0,0 +1,13 @@+// Fixture: a tool with no annotations at all. destructiveHint defaults to TRUE+// when omitted, so the tool is advertised as destructive by accident.+export const toolDefs = [+ {+ name: 'fixture_unannotated',+ title: 'Fixture unannotated',+ description: 'Declares no safety annotations.',+ inputSchema: { type: 'object', properties: {} },+ async handler() {+ return { content: [{ type: 'text', text: 'ok' }] };+ },+ },+];diff --git a/tests/fixtures/mcp-safety/overlay-annotations.js b/tests/fixtures/mcp-safety/overlay-annotations.jsnew file mode 100644index 000000000..d932edf17--- /dev/null+++ b/tests/fixtures/mcp-safety/overlay-annotations.js@@ -0,0 +1,24 @@+// Fixture: annotations declared in a name-keyed overlay map with spreads instead+// of inline on the tool def, the way the pump.fun server declares them. The gate+// must read through the overlay and the spread.+const LIVE_READ = Object.freeze({+ readOnlyHint: true,+ destructiveHint: false,+ idempotentHint: false,+ openWorldHint: true,+});++export const TOOL_ANNOTATIONS = Object.freeze({+ fixture_overlay: { title: 'Fixture Overlay', ...LIVE_READ },+});++export const TOOLS = [+ {+ name: 'fixture_overlay',+ description: 'Annotated through the overlay map.',+ inputSchema: { type: 'object', properties: {} },+ async handler() {+ return { content: [{ type: 'text', text: 'ok' }] };+ },+ },+];diff --git a/tests/fixtures/mcp-safety/read-only-with-db-write.js b/tests/fixtures/mcp-safety/read-only-with-db-write.jsnew file mode 100644index 000000000..fe60d7fa5--- /dev/null+++ b/tests/fixtures/mcp-safety/read-only-with-db-write.js@@ -0,0 +1,21 @@+// Fixture: a tool that advertises itself read-only while writing to the database+// through a same-module helper. The safety gate must reject it.+import { sql } from '../../../api/_lib/db.js';++async function recordVisit(id) {+ await sql`insert into fixture_visits (agent_id) values (${id})`;+}++export const toolDefs = [+ {+ name: 'fixture_read_only_write',+ title: 'Fixture read-only write',+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },+ description: 'Claims to be read-only but writes a row.',+ inputSchema: { type: 'object', properties: { id: { type: 'string' } } },+ async handler(args) {+ await recordVisit(args.id);+ return { content: [{ type: 'text', text: 'ok' }] };+ },+ },+];diff --git a/tests/fixtures/mcp-safety/spend-not-destructive.js b/tests/fixtures/mcp-safety/spend-not-destructive.jsnew file mode 100644index 000000000..a28b75d2f--- /dev/null+++ b/tests/fixtures/mcp-safety/spend-not-destructive.js@@ -0,0 +1,16 @@+// Fixture: a tool that sends a transaction while advertising destructiveHint:false.+// An irreversible transfer must be declared destructive.+import { sendTransaction } from '../../../api/_lib/solana-transfer.js';++export const toolDefs = [+ {+ name: 'fixture_spend',+ title: 'Fixture spend',+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },+ description: 'Sends funds but claims to be non-destructive.',+ inputSchema: { type: 'object', properties: { to: { type: 'string' } } },+ async handler(args) {+ return sendTransaction(args.to);+ },+ },+];diff --git a/tests/vercel-agents-subpath-routes.test.js b/tests/vercel-agents-subpath-routes.test.jsnew file mode 100644index 000000000..880279d27--- /dev/null+++ b/tests/vercel-agents-subpath-routes.test.js@@ -0,0 +1,87 @@+/**+ * Guards a shadowing outage class distinct from vercel-action-routes.test.js.+ *+ * That test asks "does a nested [action].js have SOME route?". This one asks the+ * harder question: "does the request actually REACH it?". `routes` is ordered and+ * the first terminal match wins, so a handler can be perfectly routed and still+ * never run if a broader route sits above it.+ *+ * `/api/agents/([^/]+)(?:/.*)?` → `/api/agents/[id]` is exactly that broader+ * route: it swallows every path under /api/agents/, including nested handlers+ * with literal names. Because it is pre-filesystem, the filesystem phase never+ * gets a chance either. Three documented endpoints were dead in production this+ * way, each answering the dispatcher's `{"error":"not_found","error_description":+ * "agent not found"}` instead of running:+ * · GET /api/agents/ens/:name (ENS → agent identity lookup, docs/erc8004)+ * · GET /api/agents/8004/agent (ERC-8004 agent by token id, /demos/erc8004)+ * · GET /api/agents/8004/search (ERC-8004 registry search, /demos/erc8004)+ * `api/agents/ens/[name].js` had never served a single request.+ *+ * Sub-paths that legitimately resolve to the dispatcher (it switches on the URL+ * internally) and the hyphen-aliased `<dir>-<action>` routes are unaffected and+ * asserted here too, so a fix for one cannot silently break the other.+ */++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';++const routes = JSON.parse(readFileSync(new URL('../vercel.json', import.meta.url), 'utf8')).routes;+const fsPhase = routes.findIndex((r) => r.handle === 'filesystem');++/**+ * First terminal pre-filesystem match, the way the server resolves a request:+ * `continue: true` routes (header decorators) fall through, everything else wins.+ * Returns the dest with $n backreferences substituted, or null if nothing matched.+ */+function resolve(path) {+ for (const route of routes.slice(0, fsPhase)) {+ if (typeof route.src !== 'string') continue;+ let m;+ try {+ m = new RegExp(`^(?:${route.src})$`).exec(path);+ } catch {+ continue;+ }+ if (!m || route.continue) continue;+ return String(route.dest || '').replace(/\$(\d)/g, (_, d) => m[Number(d)] ?? '');+ }+ return null;+}++const DISPATCHER = '/api/agents/[id]';++describe('nested /api/agents handlers are reachable, not shadowed by the [id] catch-all', () => {+ it.each([+ ['/api/agents/ens/vitalik.eth', '/api/agents/ens/[name]', 'name=vitalik.eth'],+ ['/api/agents/8004/agent', '/api/agents/8004/agent', null],+ ['/api/agents/8004/search', '/api/agents/8004/search', null],+ ])('%s reaches its own handler', (path, handler, query) => {+ const dest = resolve(path);+ expect(dest).not.toBeNull();+ expect(dest.split('?')[0]).toBe(handler);+ // The regression signature: swallowed into the agent-by-id dispatcher.+ expect(dest.split('?')[0]).not.toBe(DISPATCHER);+ if (query) expect(dest).toContain(query);+ });++ it('still sends a plain agent id to the dispatcher', () => {+ // The catch-all must keep working; the fix is ordering, not removal.+ expect(resolve('/api/agents/agt_abc123')).toBe(DISPATCHER);+ expect(resolve('/api/agents/agt_abc123/animations')).toBe(DISPATCHER);+ });++ it('leaves the per-id sub-routes and hyphen aliases intact', () => {+ expect(resolve('/api/agents/agt_abc123/economy')).toBe('/api/agents/[id]/economy?id=agt_abc123');+ expect(resolve('/api/agents/solana-metadata')).toBe('/api/agents/solana/[action]?action=metadata');+ });++ it('keeps the ens route above the catch-all', () => {+ const ens = routes.findIndex((r) => r.src === '/api/agents/ens/([^/]+)');+ const catchAll = routes.findIndex((r) => r.src === '/api/agents/([^/]+)(?:/.*)?');+ expect(ens).toBeGreaterThan(-1);+ expect(catchAll).toBeGreaterThan(-1);+ expect(ens).toBeLessThan(catchAll);+ // Both must be pre-filesystem, or ordering between them would not matter.+ expect(catchAll).toBeLessThan(fsPhase);+ });+});diff --git a/tests/x402-self-facilitator-settle-recovery.test.js b/tests/x402-self-facilitator-settle-recovery.test.jsindex b09c78213..8e8162160 100644--- a/tests/x402-self-facilitator-settle-recovery.test.js+++ b/tests/x402-self-facilitator-settle-recovery.test.js@@ -151,6 +151,83 @@ describe('settleRingPayment already-landed recovery', () => {expect(res.success).toBe(false);});+ it('recovers a stale-read-node blockhash rejection by resending with preflight off', async () => {+ // The buyer signs against THEIR RPC, so the blockhash is real; a node in our+ // rotating pool that lags a few slots has just never seen it and web3.js+ // reports that as a hard send failure. Production 2026-07-30: this class was+ // the bulk of 433 broadcast_failed settles, each one a valid payment refused+ // after the handler had already run.+ const p = buildSelfPay();+ process.env.X402_PAY_TO_SOLANA = p.payTo;+ const sends = [];+ const conn = {+ getBalance: async () => 1_000_000_000,+ sendRawTransaction: async (_raw, opts) => {+ sends.push(opts?.skipPreflight === true);+ if (sends.length === 1) {+ throw new Error('Simulation failed. Message: Transaction simulation failed: Blockhash not found. Logs: [].');+ }+ return p.sig;+ },+ getSignatureStatuses: async () => ({ value: [{ err: null, confirmationStatus: 'confirmed' }] }),+ simulateTransaction: async () => ({ value: { err: 'BlockhashNotFound', logs: [] } }),+ };+ const res = await settleRingPayment({+ paymentPayload: p.paymentPayload,+ requirement: p.requirement,+ conn,+ });+ expect(sends).toEqual([false, true]); // preflight on first, off for the resend+ expect(res.success).toBe(true);+ expect(res.transaction).toBe(p.sig);+ });++ it('reports both causes when the preflight-off resend also fails', async () => {+ const p = buildSelfPay();+ process.env.X402_PAY_TO_SOLANA = p.payTo;+ const conn = {+ getBalance: async () => 1_000_000_000,+ sendRawTransaction: async (_raw, opts) => {+ if (opts?.skipPreflight === true) throw new Error('blockhash expired for real');+ throw new Error('Simulation failed. Message: Transaction simulation failed: Blockhash not found. Logs: [].');+ },+ getSignatureStatuses: async () => ({ value: [null] }),+ simulateTransaction: async () => ({ value: { err: 'BlockhashNotFound', logs: [] } }),+ };+ const res = await settleRingPayment({+ paymentPayload: p.paymentPayload,+ requirement: p.requirement,+ conn,+ });+ expect(res.success).toBe(false);+ expect(res.reason).toMatch(/^broadcast_failed:/);+ expect(res.reason).toContain('preflight_retry_failed');+ });++ it('does not resend with preflight off for a non-blockhash failure', async () => {+ // A genuine fault (bad amount, frozen account) fails on every node, so a+ // preflight-off resend would only burn a fee. Only the blockhash class earns it.+ const p = buildSelfPay();+ process.env.X402_PAY_TO_SOLANA = p.payTo;+ const sends = [];+ const conn = {+ getBalance: async () => 1_000_000_000,+ sendRawTransaction: async (_raw, opts) => {+ sends.push(opts?.skipPreflight === true);+ throw new Error('Transaction simulation failed. Logs: [].');+ },+ getSignatureStatuses: async () => ({ value: [null] }),+ simulateTransaction: async () => ({ value: { err: { Custom: 1 }, logs: [] } }),+ };+ const res = await settleRingPayment({+ paymentPayload: p.paymentPayload,+ requirement: p.requirement,+ conn,+ });+ expect(sends).toEqual([false]); // exactly one send attempt+ expect(res.success).toBe(false);+ });+it('names the structured cause that web3.js drops from an empty-log preflight failure', async () => {// "Transaction simulation failed. Logs: []" reached production logs with no// cause at all (63 rows in 3 h, none diagnosable). The cause lives indiff --git a/vercel.json b/vercel.jsonindex ff2f9a25b..fa34cddf7 100644--- a/vercel.json+++ b/vercel.json@@ -3538,6 +3538,18 @@"src": "/api/agents/showrunner","dest": "/api/agents/showrunner"},+ {+ "src": "/api/agents/ens/([^/]+)",+ "dest": "/api/agents/ens/[name]?name=$1"+ },+ {+ "src": "/api/agents/8004/agent",+ "dest": "/api/agents/8004/agent"+ },+ {+ "src": "/api/agents/8004/search",+ "dest": "/api/agents/8004/search"+ },{"src": "/api/agents/([^/]+)(?:/.*)?","dest": "/api/agents/[id]"