Skip to content

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

Aggregator engine + provider registry, /api/v1/x dynamic route, discovery + changelog updates

nirholas0cb0ec08eb5a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3b609c4d9..cef6eb987 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,7 +17,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Getting-started progress now follows you across the whole platform** — Your setup checklist no longer forgets what you've done. The floating "Getting started" guide and the dashboard's onboarding panel now share one source of truth: the moment you create an avatar, give an agent a personality, or embed a widget, every checklist on the site ticks that step — no more seeing "2 of 4 done" in one place and "0 of 3" in another on the same visit. Visiting your dashboard reconciles your real progress automatically, and saving a persona to an agent now completes the "give it a brain" step the instant it happens. `[improvement]`
- **Hardened the widget custom-brain proxy against internal-network abuse** — Chat widgets configured with a custom AI "brain" endpoint now route that request through our SSRF guard, so a widget owner can no longer point it at a private/internal address to probe our network. No change for legitimate public endpoints. We also tightened a few backend read paths so a temporary database or price-feed hiccup surfaces as "temporarily unavailable" instead of silently looking like empty data. `[security, improvement]`
- **IBM sites can now embed three.ws pages** — We extended the sitewide clickjacking protection to allow IBM properties to frame three.ws. Any page on ibm.com (and its subdomains) may now load three.ws pages inside an iframe — useful for the IBM x402 demo and other IBM-hosted integrations — while every other external site is still refused by default. Sign-in, wallet, dashboard and OAuth consent pages remain hard-locked and cannot be framed by anyone, including IBM. The avatar, widget and walk embeds continue to work on any site as before. `[security, improvement]`
-- **One API for the whole platform: three.ws API v1** — Everything three.ws can do is now reachable through a single, versioned API at /api/v1 — one key, one rate-limit budget, and one usage ledger across every capability. Hit GET /api/v1 to discover the full endpoint catalog (each one's auth, scope, and parameters) in a single call. The first endpoints are live: text sentiment scoring (POST /api/v1/sentiment), market and narrative intelligence (GET /api/v1/market/intel and /api/v1/market/projects), and verified agent-card resolution (GET /api/v1/agents/{caip}). Authenticate with a developer API key (Authorization: Bearer sk_live_…) created in your developer dashboard, an OAuth token, or a signed-in session; every response uses one consistent shape and standard RateLimit headers. More of the platform's capabilities will land under this same API over the coming releases. `[feature, sdk]`
+- **One API, many services: the three.ws API gateway** — We bundled a stack of popular third-party APIs behind a single three.ws API so you can reach them all with one integration, one key, and one bill. The first providers are live at /api/v1/x — CoinGecko (live prices and ranked market data), DefiLlama (protocol TVL across all of DeFi), and any OpenAI-compatible LLM — with more landing over the coming releases. Discover everything with one call to GET /api/v1, which returns the full catalog: every provider, endpoint, parameter, and price. You can pay three ways, your choice per call: bring your own upstream key (we just route it, no markup), use a three.ws API key on your plan, or pay-per-call in USDC with no account at all. Every response uses one consistent shape with standard rate-limit headers, and the platform's own capabilities — text sentiment, market and narrative intelligence, and verified agent-card lookups — live under the same /api/v1 surface. `[feature, sdk]`
- **Paid market-intel never charges you for unavailable data** — The pay-per-call market-intel endpoints (the $THREE Town Oracle and the crypto-intel kiosk) used to hand back an estimated "neutral" reading — and still take the payment — when their live price feed was rate-limited. They now return a clean "temporarily unavailable, retry shortly" instead, and crucially the payment is never settled when live data is missing. You only pay when you get a real, live signal. `[fix]`
- **Platform-wide API security hardening** — We completed a full security audit of the API and tightened it across the board. Server errors no longer echo internal details back to callers — they return a short reference code you can quote to support, while the real diagnostics stay server-side (this also closes a path where a backend service key could surface in an error message). Account-changing actions made from the website — updating preferences, managing webhooks and payout wallets, marking notifications read, scheduling posts, setting skill prices — now carry cross-site request-forgery protection, so a malicious page can't act on your behalf. Sign-in, wallet-linking, GitHub connect and sensitive admin actions gained rate limits, and image-analysis requests are now screened so a supplied URL can't be used to probe internal systems. API access via developer keys is unaffected. `[security]`
- **Premium avatar cosmetics are now buyable right in the character creator** — Locked premium headwear, eyewear, dyes and auras in the character creator no longer dead-end on a placeholder — clicking one now opens the real wallet checkout and unlocks it the moment the USDC payment settles, then equips it on your live preview. Anything you already own loads pre-unlocked, and the price you see is the true checkout amount pulled from the catalog. (`/create`) `[feature, fix]`
diff --git a/api/_lib/aggregator.js b/api/_lib/aggregator.js
new file mode 100644
index 000000000..d513fe53d
--- /dev/null
+++ b/api/_lib/aggregator.js
@@ -0,0 +1,196 @@
+// Aggregator engine — runs a registered third-party API endpoint
+// (api/v1/_providers.js) as part of the unified three.ws API.
+//
+// One function does the real upstream work (executeUpstream); the catch-all
+// route picks the billing model and calls it. The x402 pay-per-call path is
+// delegated to the platform's existing paidEndpoint rail (api/_lib/
+// x402-paid-endpoint.js) so aggregated endpoints settle real USDC and appear
+// in the x402 bazaar — no second payment implementation.
+
+import { paidEndpoint } from './x402-paid-endpoint.js';
+import { buildBazaarSchema } from './x402-spec.js';
+import { installAccessControl } from './x402/access-control.js';
+import { withService } from './x402/bazaar-helpers.js';
+
+const UPSTREAM_TIMEOUT_MS = 20_000;
+
+/**
+ * Resolve the upstream key to use for a call.
+ * BYOK (caller-supplied) wins; else the platform env key; else null.
+ * @returns {{ key: string|null, source: 'byok'|'platform'|'none' }}
+ */
+export function resolveUpstreamKey(provider, byokKey) {
+ if (byokKey) return { key: byokKey, source: 'byok' };
+ const envKey = provider.envVar ? process.env[provider.envVar] : null;
+ if (envKey) return { key: envKey, source: 'platform' };
+ return { key: null, source: 'none' };
+}
+
+/**
+ * Perform the real upstream request and return the normalized payload.
+ * Throws an Error with `.status` + `.code` on any failure (mapped by wrap()).
+ *
+ * @param {object} args
+ * @param {object} args.provider provider descriptor
+ * @param {object} args.endpoint endpoint descriptor
+ * @param {Record<string,any>} args.query request query params
+ * @param {any} [args.body] parsed request body (POST)
+ * @param {string|null} args.apiKey resolved upstream key (or null)
+ */
+export async function executeUpstream({ provider, endpoint, query = {}, body, apiKey }) {
+ if (provider.requiresKey && !apiKey) {
+ const err = new Error(
+ `${provider.name} requires an API key — supply your own via the "${provider.byokHeader}" header, ` +
+ `or this deployment must set ${provider.envVar}`,
+ );
+ err.status = 503;
+ err.code = 'not_configured';
+ throw err;
+ }
+
+ const path = typeof endpoint.path === 'function' ? endpoint.path(query) : endpoint.path;
+ const url = new URL(provider.base + path);
+
+ if (endpoint.method === 'GET' && endpoint.query) {
+ for (const [k, v] of Object.entries(endpoint.query(query))) {
+ if (v != null && v !== '') url.searchParams.set(k, String(v));
+ }
+ }
+
+ const headers = { accept: 'application/json' };
+ let outBody;
+ if (endpoint.method === 'POST') {
+ outBody = endpoint.body ? endpoint.body(body) : body;
+ headers['content-type'] = 'application/json';
+ }
+ provider.applyKey(headers, url, apiKey);
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), UPSTREAM_TIMEOUT_MS);
+ let res;
+ try {
+ res = await fetch(url, {
+ method: endpoint.method,
+ headers,
+ body: outBody != null ? JSON.stringify(outBody) : undefined,
+ signal: controller.signal,
+ });
+ } catch (err) {
+ clearTimeout(timer);
+ const e = new Error(`${provider.name} is unreachable`);
+ e.status = 504;
+ e.code = 'upstream_unreachable';
+ e.cause = err;
+ throw e;
+ }
+ clearTimeout(timer);
+
+ const text = await res.text();
+ let data;
+ try {
+ data = text ? JSON.parse(text) : null;
+ } catch {
+ data = text;
+ }
+
+ if (!res.ok) {
+ const e = new Error(
+ `${provider.name} returned ${res.status} for ${endpoint.id}`,
+ );
+ // Map upstream 5xx to 502 (we're the proxy); pass client-fault 4xx through.
+ e.status = res.status >= 500 ? 502 : res.status;
+ e.code = res.status === 429 ? 'upstream_rate_limited' : 'upstream_error';
+ e.detail = typeof data === 'object' ? data : { message: String(data).slice(0, 300) };
+ throw e;
+ }
+
+ return endpoint.transform ? endpoint.transform(data) : data;
+}
+
+// ── x402 pay-per-call path ────────────────────────────────────────────────────
+// Lazily build (and cache) one paidEndpoint handler per descriptor. The handler
+// runs the SAME executeUpstream with the platform key, so a paying caller and a
+// plan/BYOK caller hit identical upstream logic.
+const _paidHandlers = new Map();
+
+export function getPaidHandler(provider, endpoint) {
+ const key = `${provider.id}/${endpoint.id}`;
+ if (_paidHandlers.has(key)) return _paidHandlers.get(key);
+
+ const route = `/api/v1/x/${provider.id}/${endpoint.id}`;
+ const description =
+ `three.ws API — ${provider.name}: ${endpoint.summary} ` +
+ `Pay per call in USDC, or use a three.ws API key / your own ${provider.name} key.`;
+
+ const bazaar = {
+ discoverable: true,
+ info: {
+ input: { type: 'http', method: endpoint.method, queryParams: endpoint.params || {} },
+ output: { type: 'json', example: {} },
+ },
+ schema: buildBazaarSchema({
+ method: endpoint.method,
+ queryParamsSchema: { type: 'object' },
+ outputSchema: { type: 'object' },
+ }),
+ };
+
+ const handler = paidEndpoint({
+ route,
+ method: endpoint.method,
+ priceAtomics: endpoint.priceAtomics,
+ networks: ['base', 'solana'],
+ description,
+ bazaar,
+ service: withService({
+ serviceName: `three.ws · ${provider.name}`,
+ tags: ['aggregator', provider.category, provider.id],
+ }),
+ requiredScope: endpoint.scope || 'agents:read',
+ accessControl: installAccessControl({ requiredScope: endpoint.scope || 'agents:read' }),
+ async handler({ req, bypass }) {
+ const query = req.query || {};
+ let body;
+ if (endpoint.method === 'POST') body = await readJsonStream(req);
+ const { key } = resolveUpstreamKey(provider, null); // pay path uses platform key
+ const out = await executeUpstream({ provider, endpoint, query, body, apiKey: key });
+ return {
+ data: out,
+ _meta: {
+ provider: provider.id,
+ endpoint: endpoint.id,
+ billing: bypass ? 'plan' : 'x402',
+ },
+ };
+ },
+ });
+
+ _paidHandlers.set(key, handler);
+ return handler;
+}
+
+// Minimal JSON body reader for the paid POST path (paidEndpoint leaves the
+// stream untouched). Mirrors http.js readJson but without its content-type
+// hard-fail, since the x402 dance has already consumed headers.
+function readJsonStream(req, limit = 1_000_000) {
+ return new Promise((resolve, reject) => {
+ const chunks = [];
+ let total = 0;
+ req.on('data', (c) => {
+ total += c.length;
+ if (total > limit) {
+ req.destroy();
+ reject(Object.assign(new Error('payload too large'), { status: 413 }));
+ } else chunks.push(c);
+ });
+ req.on('end', () => {
+ if (!chunks.length) return resolve(undefined);
+ try {
+ resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));
+ } catch {
+ reject(Object.assign(new Error('invalid JSON body'), { status: 400, code: 'validation_error' }));
+ }
+ });
+ req.on('error', reject);
+ });
+}
diff --git a/api/v1/_providers.js b/api/v1/_providers.js
new file mode 100644
index 000000000..0daa6c151
--- /dev/null
+++ b/api/v1/_providers.js
@@ -0,0 +1,215 @@
+// Upstream provider registry for the three.ws aggregator (/api/v1/x/*).
+//
+// This is the single source of truth for every THIRD-PARTY API three.ws
+// bundles and re-offers as one API. Adding a new upstream — or a new endpoint
+// on an existing one — is a descriptor here; no new route file, no new
+// plumbing. The catch-all route (api/v1/x/[...slug].js) resolves a request
+// against this registry and the aggregator engine (api/_lib/aggregator.js)
+// runs it through one auth / rate-limit / metering / billing path.
+//
+// Provider descriptor:
+// id url-safe slug (first path segment under /api/v1/x)
+// name human label
+// category grouping for discovery
+// base upstream base URL (no trailing slash)
+// requiresKey true when the upstream needs an API key to function at all
+// envVar env var holding three.ws's platform key for this upstream
+// byokHeader request header a caller uses to supply THEIR OWN upstream key
+// applyKey (headers, url, key) => void — places a key where the upstream wants it
+// endpoints array of endpoint descriptors:
+// id url-safe slug (second path segment)
+// method 'GET' | 'POST'
+// path string, or (query) => string for path params
+// query (query) => object of upstream query params (GET)
+// body (body) => object forwarded as the upstream JSON body (POST)
+// transform (data) => normalized response (default: passthrough)
+// priceAtomics x402 price in USDC atomics (6 decimals; "1000" = $0.001)
+// scope three.ws OAuth scope required for the plan-billing path
+// summary one line for discovery
+// params documented inputs for discovery
+
+function required(value, name) {
+ const v = value == null ? '' : String(value).trim();
+ if (!v) {
+ const err = new Error(`query param "${name}" is required`);
+ err.status = 400;
+ err.code = 'missing_param';
+ throw err;
+ }
+ return v;
+}
+
+export const PROVIDERS = [
+ {
+ id: 'coingecko',
+ name: 'CoinGecko',
+ category: 'crypto-market-data',
+ base: 'https://api.coingecko.com/api/v3',
+ requiresKey: false,
+ // CoinGecko's optional Pro key lifts rate limits; works key-free otherwise.
+ envVar: 'COINGECKO_API_KEY',
+ byokHeader: 'x-provider-key',
+ applyKey: (headers, _url, key) => {
+ if (key) headers['x-cg-pro-api-key'] = key;
+ },
+ endpoints: [
+ {
+ id: 'price',
+ method: 'GET',
+ path: '/simple/price',
+ query: (q) => ({
+ ids: required(q.ids, 'ids'),
+ vs_currencies: q.vs_currencies || 'usd',
+ include_24hr_change: q.include_24hr_change,
+ include_market_cap: q.include_market_cap,
+ }),
+ priceAtomics: '1000',
+ scope: 'agents:read',
+ summary: 'Spot price for one or more coins in any fiat/crypto.',
+ params: {
+ ids: 'comma-separated CoinGecko coin ids, e.g. "solana,bitcoin" (required)',
+ vs_currencies: 'comma-separated quote currencies (default "usd")',
+ include_24hr_change: 'true to include 24h change',
+ include_market_cap: 'true to include market cap',
+ },
+ },
+ {
+ id: 'markets',
+ method: 'GET',
+ path: '/coins/markets',
+ query: (q) => ({
+ vs_currency: q.vs_currency || 'usd',
+ ids: q.ids,
+ order: q.order || 'market_cap_desc',
+ per_page: Math.min(Math.max(1, Number(q.per_page) || 20), 100),
+ page: Number(q.page) || 1,
+ price_change_percentage: q.price_change_percentage,
+ }),
+ priceAtomics: '2000',
+ scope: 'agents:read',
+ summary: 'Ranked market data (price, market cap, volume, change) per coin.',
+ params: {
+ vs_currency: 'quote currency (default "usd")',
+ ids: 'comma-separated coin ids to filter (optional)',
+ order: 'sort order (default "market_cap_desc")',
+ per_page: 'number 1–100 (default 20)',
+ page: 'page number (default 1)',
+ },
+ },
+ ],
+ },
+ {
+ id: 'defillama',
+ name: 'DefiLlama',
+ category: 'defi-data',
+ base: 'https://api.llama.fi',
+ requiresKey: false,
+ envVar: null,
+ byokHeader: null,
+ applyKey: () => {},
+ endpoints: [
+ {
+ id: 'protocols',
+ method: 'GET',
+ path: '/protocols',
+ query: () => ({}),
+ // DefiLlama returns ~3k protocols; slim to the fields callers actually
+ // use so one call doesn't ship a multi-MB payload.
+ transform: (data) =>
+ Array.isArray(data)
+ ? data
+ .map((p) => ({
+ name: p.name,
+ symbol: p.symbol,
+ category: p.category,
+ chains: p.chains,
+ tvl: p.tvl,
+ change_1d: p.change_1d,
+ change_7d: p.change_7d,
+ mcap: p.mcap,
+ }))
+ .sort((a, b) => (b.tvl || 0) - (a.tvl || 0))
+ : data,
+ priceAtomics: '1000',
+ scope: 'agents:read',
+ summary: 'All DeFi protocols with current TVL, ranked.',
+ params: {},
+ },
+ {
+ id: 'tvl',
+ method: 'GET',
+ path: (q) => `/tvl/${encodeURIComponent(required(q.protocol, 'protocol'))}`,
+ query: () => ({}),
+ transform: (data) => ({ tvl_usd: typeof data === 'number' ? data : Number(data) }),
+ priceAtomics: '1000',
+ scope: 'agents:read',
+ summary: 'Current total value locked (USD) for a single protocol.',
+ params: { protocol: 'DefiLlama protocol slug, e.g. "uniswap" (required)' },
+ },
+ ],
+ },
+ {
+ id: 'openai',
+ name: 'OpenAI-compatible LLM',
+ category: 'ai-inference',
+ base: 'https://api.openai.com/v1',
+ requiresKey: true,
+ envVar: 'OPENAI_API_KEY',
+ byokHeader: 'x-provider-key',
+ applyKey: (headers, _url, key) => {
+ if (key) headers['authorization'] = `Bearer ${key}`;
+ },
+ endpoints: [
+ {
+ id: 'chat',
+ method: 'POST',
+ path: '/chat/completions',
+ body: (b) => {
+ if (!b || typeof b !== 'object' || !Array.isArray(b.messages)) {
+ const err = new Error('body must include a "messages" array');
+ err.status = 400;
+ err.code = 'validation_error';
+ throw err;
+ }
+ return b;
+ },
+ priceAtomics: '5000',
+ scope: 'agents:write',
+ summary: 'Chat completions against any OpenAI-compatible model (BYOK supported).',
+ params: {
+ model: 'model id (required)',
+ messages: 'array of {role, content} (required)',
+ '…': 'any other OpenAI chat-completions parameter is forwarded',
+ },
+ },
+ ],
+ },
+];
+
+// Flat lookup map: "provider/endpoint" → { provider, endpoint }.
+export const ENDPOINT_INDEX = new Map();
+for (const provider of PROVIDERS) {
+ for (const endpoint of provider.endpoints) {
+ ENDPOINT_INDEX.set(`${provider.id}/${endpoint.id}`, { provider, endpoint });
+ }
+}
+
+/** Machine-readable catalog of every aggregated endpoint, for discovery. */
+export function providerCatalog() {
+ return PROVIDERS.map((p) => ({
+ id: p.id,
+ name: p.name,
+ category: p.category,
+ key: p.requiresKey ? 'required (platform key or BYOK)' : 'optional',
+ byok: Boolean(p.byokHeader),
+ endpoints: p.endpoints.map((e) => ({
+ id: e.id,
+ method: e.method,
+ path: `/api/v1/x/${p.id}/${e.id}`,
+ scope: e.scope,
+ price_usdc_atomics: e.priceAtomics,
+ summary: e.summary,
+ params: e.params,
+ })),
+ }));
+}
diff --git a/api/v1/index.js b/api/v1/index.js
index ed71699a3..00ac48aa7 100644
--- a/api/v1/index.js
+++ b/api/v1/index.js
@@ -7,6 +7,7 @@
import { defineEndpoint } from '../_lib/gateway.js';
import { API_META, CATALOG } from './_catalog.js';
+import { providerCatalog } from './_providers.js';
export default defineEndpoint({
name: 'v1.index',
@@ -15,6 +16,13 @@ export default defineEndpoint({
handler: () => ({
...API_META,
endpoints: CATALOG,
+ // Aggregated third-party APIs — many endpoints behind one key/bill, each
+ // callable via BYOK, a three.ws plan, or x402 pay-per-call. See /api/v1/x.
+ aggregator: {
+ base_url: '/api/v1/x',
+ billing: ['byok', 'plan', 'x402'],
+ providers: providerCatalog(),
+ },
docs: '/dashboard/developers',
openapi: '/openapi.json',
}),
diff --git a/api/v1/x/[...slug].js b/api/v1/x/[...slug].js
new file mode 100644
index 000000000..6d8c4c30b
--- /dev/null
+++ b/api/v1/x/[...slug].js
@@ -0,0 +1,173 @@
+// /api/v1/x/<provider>/<endpoint> — the aggregator front door.
+//
+// One catch-all route exposes every third-party API registered in
+// api/v1/_providers.js. Per request, it selects a billing model and runs the
+// call through the aggregator engine:
+//
+// • BYOK — caller supplies their own upstream key (e.g. "x-provider-key").
+// Pure pass-through: no markup, no key custody. Rate-limited + metered.
+// • plan — caller authenticates with a three.ws API key / OAuth token / session.
+// Uses the platform's upstream key; counts against their plan.
+// • x402 — no credentials → pay-per-call in USDC via the real paidEndpoint
+// rail (also makes the endpoint discoverable in the x402 bazaar).
+//
+// GET /api/v1/x (no provider) returns the machine-readable provider catalog.
+
+import { cors, json, error, rateLimited, wrap, readJson, setRateLimitHeaders } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { authenticateBearer, extractBearer, getSessionUser, hasScope } from '../../_lib/auth.js';
+import { recordEvent } from '../../_lib/usage.js';
+import { ENDPOINT_INDEX, providerCatalog } from '../_providers.js';
+import { executeUpstream, getPaidHandler, resolveUpstreamKey } from '../../_lib/aggregator.js';
+
+function parseSlug(req) {
+ // Prefer the platform-provided param; fall back to parsing the path so the
+ // route also works under runtimes that don't populate req.query.slug.
+ const fromQuery = req.query?.slug;
+ if (Array.isArray(fromQuery)) return fromQuery.filter(Boolean);
+ if (typeof fromQuery === 'string' && fromQuery) return fromQuery.split('/').filter(Boolean);
+ const path = new URL(req.url, 'http://internal').pathname;
+ const m = path.match(/\/api\/v1\/x\/?(.*)$/);
+ return m && m[1] ? m[1].split('/').filter(Boolean) : [];
+}
+
+function parseQuery(req) {
+ const q = { ...(req.query || {}) };
+ delete q.slug;
+ // Ensure path-only deployments still get query params.
+ for (const [k, v] of new URL(req.url, 'http://internal').searchParams) {
+ if (!(k in q)) q[k] = v;
+ }
+ return q;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
+
+ const slug = parseSlug(req);
+
+ // Discovery: GET /api/v1/x → list every aggregated provider + endpoint.
+ if (slug.length === 0) {
+ return json(res, 200, {
+ data: {
+ base_url: '/api/v1/x',
+ billing: {
+ byok: 'send your own upstream key via the provider\'s BYOK header — pass-through, no markup',
+ plan: 'authenticate with a three.ws API key / OAuth token — uses the platform key',
+ x402: 'send no credentials — pay per call in USDC (HTTP 402)',
+ },
+ providers: providerCatalog(),
+ },
+ });
+ }
+
+ if (slug.length !== 2) {
+ return error(
+ res,
+ 404,
+ 'not_found',
+ 'use /api/v1/x/<provider>/<endpoint> — GET /api/v1/x lists every available pair',
+ );
+ }
+
+ const ref = ENDPOINT_INDEX.get(`${slug[0]}/${slug[1]}`);
+ if (!ref) {
+ return error(
+ res,
+ 404,
+ 'unknown_endpoint',
+ `no aggregated endpoint "${slug[0]}/${slug[1]}" — GET /api/v1/x lists what's available`,
+ );
+ }
+ const { provider, endpoint } = ref;
+
+ const isHead = req.method === 'HEAD' && endpoint.method === 'GET';
+ if (req.method !== endpoint.method && !isHead) {
+ res.setHeader('allow', `${endpoint.method}, OPTIONS`);
+ return error(res, 405, 'method_not_allowed', `use ${endpoint.method}`);
+ }
+
+ // ── billing model selection ──────────────────────────────────────────────
+ const byokKey = provider.byokHeader ? req.headers[provider.byokHeader] : null;
+ let principal = null;
+ if (!byokKey) {
+ const session = await getSessionUser(req);
+ if (session) principal = { userId: session.id, source: 'session', scope: 'all' };
+ else {
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer)
+ principal = {
+ userId: bearer.userId,
+ source: bearer.source,
+ scope: bearer.scope || '',
+ apiKeyId: bearer.apiKeyId,
+ clientId: bearer.clientId,
+ };
+ }
+ }
+
+ // No BYOK key and no three.ws credentials → pay-per-call via the x402 rail.
+ if (!byokKey && !principal) return getPaidHandler(provider, endpoint)(req, res);
+
+ const billing = byokKey ? 'byok' : 'plan';
+
+ // Plan callers must hold the endpoint's scope (session owners hold all).
+ if (
+ billing === 'plan' &&
+ principal.source !== 'session' &&
+ endpoint.scope &&
+ !hasScope(principal.scope, endpoint.scope)
+ ) {
+ return error(res, 403, 'insufficient_scope', `this endpoint requires the "${endpoint.scope}" scope`);
+ }
+
+ // ── rate limit (per principal › IP) ──────────────────────────────────────
+ const ip = clientIp(req);
+ const rlKey = principal?.apiKeyId
+ ? `key:${principal.apiKeyId}`
+ : principal?.userId
+ ? `user:${principal.userId}`
+ : `ip:${ip}`;
+ const rl = await limits.apiV1(rlKey);
+ setRateLimitHeaders(res, rl);
+ if (!rl.success) return rateLimited(res, rl);
+
+ // ── execute ──────────────────────────────────────────────────────────────
+ const query = parseQuery(req);
+ const body = endpoint.method === 'POST' ? await readJson(req) : undefined;
+ const { key, source } = resolveUpstreamKey(provider, billing === 'byok' ? byokKey : null);
+
+ const started = Date.now();
+ let out;
+ try {
+ out = await executeUpstream({ provider, endpoint, query, body, apiKey: key });
+ } catch (err) {
+ recordEvent({
+ kind: 'api',
+ tool: `v1.x.${provider.id}.${endpoint.id}`,
+ userId: principal?.userId,
+ apiKeyId: principal?.apiKeyId,
+ clientId: principal?.clientId,
+ status: 'error',
+ latencyMs: Date.now() - started,
+ meta: { billing, key_source: source, code: err?.code },
+ });
+ throw err;
+ }
+
+ recordEvent({
+ kind: 'api',
+ tool: `v1.x.${provider.id}.${endpoint.id}`,
+ userId: principal?.userId,
+ apiKeyId: principal?.apiKeyId,
+ clientId: principal?.clientId,
+ status: 'ok',
+ latencyMs: Date.now() - started,
+ meta: { billing, key_source: source },
+ });
+
+ return json(res, 200, {
+ data: out,
+ _meta: { provider: provider.id, endpoint: endpoint.id, billing },
+ });
+});
diff --git a/data/changelog.json b/data/changelog.json
index 325fc2fd5..5238e82f5 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -3,8 +3,8 @@
"entries": [
{
"date": "2026-06-19",
- "title": "One API for the whole platform: three.ws API v1",
- "summary": "Everything three.ws can do is now reachable through a single, versioned API at /api/v1 — one key, one rate-limit budget, and one usage ledger across every capability. Hit GET /api/v1 to discover the full endpoint catalog (each one's auth, scope, and parameters) in a single call. The first endpoints are live: text sentiment scoring (POST /api/v1/sentiment), market and narrative intelligence (GET /api/v1/market/intel and /api/v1/market/projects), and verified agent-card resolution (GET /api/v1/agents/{caip}). Authenticate with a developer API key (Authorization: Bearer sk_live_…) created in your developer dashboard, an OAuth token, or a signed-in session; every response uses one consistent shape and standard RateLimit headers. More of the platform's capabilities will land under this same API over the coming releases.",
+ "title": "One API, many services: the three.ws API gateway",
+ "summary": "We bundled a stack of popular third-party APIs behind a single three.ws API so you can reach them all with one integration, one key, and one bill. The first providers are live at /api/v1/x — CoinGecko (live prices and ranked market data), DefiLlama (protocol TVL across all of DeFi), and any OpenAI-compatible LLM — with more landing over the coming releases. Discover everything with one call to GET /api/v1, which returns the full catalog: every provider, endpoint, parameter, and price. You can pay three ways, your choice per call: bring your own upstream key (we just route it, no markup), use a three.ws API key on your plan, or pay-per-call in USDC with no account at all. Every response uses one consistent shape with standard rate-limit headers, and the platform's own capabilities — text sentiment, market and narrative intelligence, and verified agent-card lookups — live under the same /api/v1 surface.",
"tags": [
"feature",
"sdk"
diff --git a/public/changelog.json b/public/changelog.json
index b85b9b449..45fcbb9a2 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T03:32:31.125Z",
+ "generated_at": "2026-06-19T04:01:15.347Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -123,8 +123,8 @@
{
"date": "2026-06-19",
"type": "update",
- "title": "One API for the whole platform: three.ws API v1",
- "summary": "Everything three.ws can do is now reachable through a single, versioned API at /api/v1 — one key, one rate-limit budget, and one usage ledger across every capability. Hit GET /api/v1 to discover the full endpoint catalog (each one's auth, scope, and parameters) in a single call. The first endpoints are live: text sentiment scoring (POST /api/v1/sentiment), market and narrative intelligence (GET /api/v1/market/intel and /api/v1/market/projects), and verified agent-card resolution (GET /api/v1/agents/{caip}). Authenticate with a developer API key (Authorization: Bearer sk_live_…) created in your developer dashboard, an OAuth token, or a signed-in session; every response uses one consistent shape and standard RateLimit headers. More of the platform's capabilities will land under this same API over the coming releases.",
+ "title": "One API, many services: the three.ws API gateway",
+ "summary": "We bundled a stack of popular third-party APIs behind a single three.ws API so you can reach them all with one integration, one key, and one bill. The first providers are live at /api/v1/x — CoinGecko (live prices and ranked market data), DefiLlama (protocol TVL across all of DeFi), and any OpenAI-compatible LLM — with more landing over the coming releases. Discover everything with one call to GET /api/v1, which returns the full catalog: every provider, endpoint, parameter, and price. You can pay three ways, your choice per call: bring your own upstream key (we just route it, no markup), use a three.ws API key on your plan, or pay-per-call in USDC with no account at all. Every response uses one consistent shape with standard rate-limit headers, and the platform's own capabilities — text sentiment, market and narrative intelligence, and verified agent-card lookups — live under the same /api/v1 surface.",
"link": null,
"tags": [
"feature",
diff --git a/public/changelog.xml b/public/changelog.xml
index 0c766e63f..86f70a3fa 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -95,12 +95,12 @@
<description>We extended the sitewide clickjacking protection to allow IBM properties to frame three.ws. Any page on ibm.com (and its subdomains) may now load three.ws pages inside an iframe — useful for the IBM x402 demo and other IBM-hosted integrations — while every other external site is still refused by default. Sign-in, wallet, dashboard and OAuth consent pages remain hard-locked and cannot be framed by anyone, including IBM. The avatar, widget and walk embeds continue to work on any site as before.</description>
</item>
<item>
- <title>One API for the whole platform: three.ws API v1</title>
+ <title>One API, many services: the three.ws API gateway</title>
<link>https://three.ws/changelog</link>
- <guid isPermaLink="false">2026-06-19:One API for the whole platform: three.ws API v1</guid>
+ <guid isPermaLink="false">2026-06-19:One API, many services: the three.ws API gateway</guid>
<pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>
<category>feature</category>
- <description>Everything three.ws can do is now reachable through a single, versioned API at /api/v1 — one key, one rate-limit budget, and one usage ledger across every capability. Hit GET /api/v1 to discover the full endpoint catalog (each one's auth, scope, and parameters) in a single call. The first endpoints are live: text sentiment scoring (POST /api/v1/sentiment), market and narrative intelligence (GET /api/v1/market/intel and /api/v1/market/projects), and verified agent-card resolution (GET /api/v1/agents/{caip}). Authenticate with a developer API key (Authorization: Bearer sk_live_…) created in your developer dashboard, an OAuth token, or a signed-in session; every response uses one consistent shape and standard RateLimit headers. More of the platform's capabilities will land under this same API over the coming releases.</description>
+ <description>We bundled a stack of popular third-party APIs behind a single three.ws API so you can reach them all with one integration, one key, and one bill. The first providers are live at /api/v1/x — CoinGecko (live prices and ranked market data), DefiLlama (protocol TVL across all of DeFi), and any OpenAI-compatible LLM — with more landing over the coming releases. Discover everything with one call to GET /api/v1, which returns the full catalog: every provider, endpoint, parameter, and price. You can pay three ways, your choice per call: bring your own upstream key (we just route it, no markup), use a three.ws API key on your plan, or pay-per-call in USDC with no account at all. Every response uses one consistent shape with standard rate-limit headers, and the platform's own capabilities — text sentiment, market and narrative intelligence, and verified agent-card lookups — live under the same /api/v1 surface.</description>
</item>
<item>
<title>Paid market-intel never charges you for unavailable data</title>
diff --git a/public/features.json b/public/features.json
index 14518c5d3..140c88503 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T03:32:31.105Z",
+ "generated_at": "2026-06-19T04:01:15.335Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",