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
feat: speech package — ASR + TTS as agent products over x402
nich5901cbed6318
diff --git a/api/_lib/ai-speech.js b/api/_lib/ai-speech.jsnew file mode 100644index 000000000..e06cafc3f--- /dev/null+++ b/api/_lib/ai-speech.js@@ -0,0 +1,269 @@+// Shared core for the productized speech package (api/v1/ai/asr, api/v1/ai/tts).+//+// The versioned /api/v1/ai/* endpoints and their x402 paid twins run the SAME+// synthesis / recognition here, so a free-quota caller and a paying caller hit+// identical lane code. This module owns:+// • input parsing + validation (typed errors carrying { status, code })+// • the tier limits (free-tier char/duration caps, hard body caps)+// • the calls into the free NVIDIA NIM lanes (tts-nvidia.js / asr-nvidia.js),+// with their gRPC error codes mapped to HTTP once, in one place.+//+// It deliberately pulls in NO x402 dependencies — the route files wire the+// billing rail. The NIM lanes are the only synthesis backend here (no OpenAI+// backstop): these endpoints productize the free NVIDIA lanes, and env gating+// answers 503 not_configured (never a fake response) when the key is absent.++import {+ synthesizeNvidiaTts,+ nvidiaTtsConfigured,+} from './tts-nvidia.js';+import {+ transcribeNvidiaAsr,+ nvidiaAsrConfigured,+ resolveAsrEncoding,+ parseWav,+} from './asr-nvidia.js';+import { TTS_VOICES, TTS_VOICE_IDS, DEFAULT_VOICE } from './tts-voices.js';++export { nvidiaTtsConfigured, nvidiaAsrConfigured };++// ── Tier limits ──────────────────────────────────────────────────────────────+// Free tier is tight on purpose: the NIM lanes cost real GPU credit. Above these+// the caller falls through to the x402 402 challenge (pay-per-call).+export const FREE_TTS_MAX_CHARS = 500;+export const PAID_TTS_MAX_CHARS = 4096; // matches api/tts/speak.js+export const FREE_ASR_MAX_SECONDS = 60;++// Hard memory bounds (both tiers). ASR audio is buffered in full per request.+export const ASR_MAX_AUDIO_BYTES = 8 * 1024 * 1024; // 8 MiB of decoded audio+// Base64 in a JSON body inflates ~33%, so allow a larger raw read then bound the+// decoded audio to ASR_MAX_AUDIO_BYTES.+export const ASR_MAX_BODY_BYTES = Math.ceil(ASR_MAX_AUDIO_BYTES * 1.4);+export const TTS_MAX_BODY_BYTES = 64 * 1024; // 64 KiB JSON is plenty for 4096 chars++const TTS_TIMEOUT_MS = 30_000;+const ASR_TIMEOUT_MS = 25_000;++// Encodings the ASR lane accepts, advertised on the capability probe.+export const ASR_ACCEPTED_ENCODINGS = ['wav', 'pcm', 'flac', 'ogg'];++function httpError(status, code, message) {+ const err = new Error(message);+ err.status = status;+ err.code = code;+ return err;+}++// Map a NIM lane error (Error with .code from tts-nvidia/asr-nvidia) to an HTTP+// status once, so the free route and the paid handler answer identically.+function laneErrorToHttp(e, label) {+ const code = e?.code || 'provider_error';+ const status =+ code === 'not_configured' ? 503 :+ code === 'invalid_argument' ? 400 :+ code === 'rate_limited' ? 429 :+ code === 'timeout' ? 504 :+ 502; // invalid_key / provider_unreachable / provider_error+ return httpError(status, code, `${label} failed: ${e?.message || 'unknown error'}`);+}++// ── TTS ────────────────────────────────────────────────────────────────────────++// The voices catalog (mirrors /api/tts/voices) — free, public metadata. Only the+// NVIDIA lane is reported here; `enabled` reflects whether synthesis is live.+export function ttsVoicesPayload() {+ const configured = nvidiaTtsConfigured();+ return {+ enabled: configured,+ default: DEFAULT_VOICE,+ voices: TTS_VOICES,+ formats: ['wav', 'pcm'],+ providers: { nvidia: configured },+ };+}++// Parse + validate a TTS request body. `maxChars` differs by tier (free 500,+// paid 4096). Throws typed { status, code } errors on bad input.+export function readTtsInput(raw, { maxChars = PAID_TTS_MAX_CHARS } = {}) {+ let body;+ try {+ body = JSON.parse(Buffer.isBuffer(raw) ? raw.toString('utf8') : String(raw || ''));+ } catch {+ throw httpError(400, 'bad_request', 'request body must be valid JSON');+ }+ if (!body || typeof body !== 'object') {+ throw httpError(400, 'bad_request', 'request body must be a JSON object');+ }+ const text = typeof body.text === 'string' ? body.text.trim() : '';+ if (!text) throw httpError(400, 'bad_request', '"text" is required');+ if (text.length > maxChars) {+ throw httpError(400, 'text_too_long', `"text" exceeds the ${maxChars}-character limit (got ${text.length})`);+ }+ const voice = typeof body.voice === 'string' && body.voice ? body.voice : DEFAULT_VOICE;+ // Magpie honestly emits only WAV/PCM (see tts-nvidia.js), so those are the+ // only formats we advertise; anything else is coerced to WAV by the lane.+ const format = body.format === 'pcm' ? 'pcm' : 'wav';+ const language = typeof body.language === 'string' && body.language ? body.language : 'en-US';+ return { text, voice, format, language };+}++// Synthesize on the free NVIDIA NIM Magpie lane. Returns a JSON-serializable+// payload with base64 audio (uniform across the free + paid lanes so settlement+// on the paid rail always emits JSON). Throws an HTTP-typed error on lane failure.+export async function ttsSynthesize({ text, voice, format, language }) {+ let out;+ try {+ out = await synthesizeNvidiaTts({ text, voice, language, format, timeoutMs: TTS_TIMEOUT_MS });+ } catch (e) {+ throw laneErrorToHttp(e, 'Speech synthesis');+ }+ return {+ audio: out.audio.toString('base64'),+ encoding: 'base64',+ format: out.format,+ content_type: out.contentType,+ sample_rate: out.sampleRateHz,+ voice: out.voiceName,+ model: out.model,+ characters: text.length,+ bytes: out.audio.length,+ };+}++// ── ASR ────────────────────────────────────────────────────────────────────────++// Content-Type → friendly encoding alias. WebM/Opus is intentionally absent:+// Riva rejects the WebM container, so callers must decode to PCM/WAV first.+export function asrEncodingFromContentType(ct) {+ const type = String(ct || '').split(';')[0].trim().toLowerCase();+ switch (type) {+ case 'audio/wav':+ case 'audio/x-wav':+ case 'audio/wave':+ return 'wav';+ case 'audio/l16':+ case 'audio/pcm':+ case 'audio/x-pcm':+ return 'pcm';+ case 'audio/flac':+ case 'audio/x-flac':+ return 'flac';+ case 'audio/ogg':+ case 'audio/opus':+ return 'opus';+ default:+ return null;+ }+}++// Parse an ASR request from either transport:+// • application/json → { audio: <base64>, format?, language?, sampleRate?, words?, model? }+// • audio/* → raw bytes in the body, encoding from Content-Type+// Returns the lane-ready shape { audio, encoding, sampleRateHz, language,+// wantWords, model, durationSec|null }. `durationSec` is exact for WAV, estimated+// for raw PCM, and null for compressed formats (bounded only by the byte cap).+// Throws typed { status, code } errors on bad/oversize/unsupported input.+export function parseAsrRequest({ contentType, url, buf }) {+ const q = safeQuery(url);+ const isJson = String(contentType || '').split(';')[0].trim().toLowerCase() === 'application/json';++ let audio;+ let format;+ let language = q.language || q.lang || 'en-US';+ let sampleRate = Number(q.rate || q.sampleRate) || 0;+ let wantWords = q.words === '1' || q.words === 'true';+ let model = q.model || '';++ if (isJson) {+ let body;+ try {+ body = JSON.parse(buf.toString('utf8'));+ } catch {+ throw httpError(400, 'bad_request', 'request body must be valid JSON');+ }+ const b64 = typeof body?.audio === 'string' ? body.audio.replace(/^data:[^,]*,/, '') : '';+ if (!b64) throw httpError(400, 'bad_request', '"audio" (base64) is required');+ audio = Buffer.from(b64, 'base64');+ format = body.format || 'wav';+ if (typeof body.language === 'string') language = body.language;+ if (Number(body.sampleRate)) sampleRate = Number(body.sampleRate);+ if (body.words === true || body.words === '1') wantWords = true;+ if (typeof body.model === 'string') model = body.model;+ } else {+ format = asrEncodingFromContentType(contentType);+ if (!format) {+ throw httpError(+ 415,+ 'unsupported_media_type',+ `unsupported audio Content-Type "${String(contentType || '').split(';')[0] || 'none'}". ` ++ 'Send audio/wav, audio/pcm (with ?rate=), audio/flac, audio/ogg, or a JSON body ' ++ '{ "audio": "<base64>" } — WebM/Opus must be decoded to PCM/WAV client-side first.',+ );+ }+ audio = buf;+ }++ if (!audio?.length) throw httpError(400, 'bad_request', 'no audio bytes received');+ if (audio.length > ASR_MAX_AUDIO_BYTES) {+ throw httpError(413, 'payload_too_large', `audio exceeds the ${ASR_MAX_AUDIO_BYTES}-byte limit`);+ }++ let encoding = resolveAsrEncoding(format);+ let durationSec = null;++ // A WAV carries its own rate and a 44-byte header Riva's LINEAR_PCM must not+ // see — strip to raw PCM, trust the header's rate, and compute exact duration.+ if (encoding === 'LINEAR_PCM') {+ const wav = parseWav(audio);+ if (wav) {+ audio = wav.pcm;+ sampleRate = wav.sampleRateHz;+ const bytesPerSample = 2 * (wav.channels || 1);+ durationSec = wav.pcm.length / (wav.sampleRateHz * bytesPerSample);+ } else {+ if (!sampleRate) sampleRate = 16000; // Riva model default + common capture rate+ durationSec = audio.length / (sampleRate * 2); // raw mono s16 estimate+ }+ } else if (!sampleRate) {+ sampleRate = 16000;+ }++ return { audio, encoding, sampleRateHz: sampleRate, language, wantWords, model, durationSec };+}++// Transcribe on the free NVIDIA NIM Riva lane. Returns a JSON-serializable+// payload; throws an HTTP-typed error on lane failure.+export async function asrTranscribe({ audio, encoding, sampleRateHz, language, wantWords, model }) {+ let out;+ try {+ out = await transcribeNvidiaAsr({+ audio,+ encoding,+ sampleRateHz,+ language,+ wordTimeOffsets: wantWords,+ model,+ timeoutMs: ASR_TIMEOUT_MS,+ });+ } catch (e) {+ throw laneErrorToHttp(e, 'Speech recognition');+ }+ return {+ text: out.text,+ confidence: out.confidence,+ duration: out.audioProcessed,+ language: out.language,+ model: out.model,+ ...(wantWords ? { words: out.words } : {}),+ };+}++// Parse a request URL's query into a plain object without throwing on garbage.+function safeQuery(url) {+ try {+ const u = new URL(url || '/', 'http://internal');+ return Object.fromEntries(u.searchParams);+ } catch {+ return {};+ }+}diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 3fdbc6c4a..776ee7700 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -489,6 +489,12 @@ export const limits = {// /api/x402/forge tiers rather than paywalling silently. Non-critical: a Redis// blip degrades to the per-instance memory limiter, never blocks generation.aiTextTo3d: (ip) => getLimiter('ai:text-to-3d', { limit: 10, window: '24 h' }).limit(ip),+ // Free token security check (api/v1/token/security) — reads getAccountInfo ++ // getTokenLargestAccounts off the shared RPC and DexScreener, all cached 60s at+ // the edge, so this only gates cache-miss origin hits. 20/min per IP is generous+ // for an agent screening a watchlist while capping a scripted enumeration flood.+ // Non-critical: a Redis blip degrades to the per-instance memory limiter.+ tokenSecurityIp: (ip) => getLimiter('token:security:ip', { limit: 20, window: '1 m' }).limit(ip),// Diorama composer (api/diorama action:compose) — one free-first LLM// completion per call that decomposes a sentence into a placed object set.// Paid upstream egress, so cap per IP and add a global hourly circuit breaker.@@ -679,6 +685,14 @@ export const limits = {// (which caching can't stop). One bucket across all DAS endpoints.heliusDasGlobal: () =>getLimiter('helius-das:global', { limit: 3000, window: '1 h' }).limit('global'),+ // Free Crypto Data API family (api/crypto/*). Keyless, no-account reads an agent+ // makes mid-task (wallet portfolio, token snapshots). Some paths fan out to the+ // keyed Helius/public-RPC upstreams, so a generous-but-bounded per-IP burst keeps+ // interactive use snappy while a shared global hourly ceiling is the hard cost cap+ // against one caller (or many) draining the upstream quota. One bucket for the family.+ cryptoDataIp: (ip) => getLimiter('crypto-data:ip', { limit: 60, window: '1 m' }).limit(ip),+ cryptoDataGlobal: () =>+ getLimiter('crypto-data:global', { limit: 6000, window: '1 h' }).limit('global'),// Agent-to-agent economy demo (api/agent-economy/transact). Each call can send// a tiny real SOL payment from the server wallet, so cap per-IP and add a// global daily ceiling as a hard spend cap independent of wallet balance.@@ -841,6 +855,17 @@ export const limits = {getLimiter('asr:user', { limit: 60, window: '1 h', critical: true }).limit(userId),asrIp: (ip) =>getLimiter('asr:ip', { limit: 15, window: '1 h', critical: true }).limit(ip),+ // Productized speech package free tier (api/v1/ai/tts, api/v1/ai/asr). A tight+ // per-IP DAILY quota that gates the free NIM lane before the x402 402+ // fall-through — the free tier is the funnel, x402 is the metered overage.+ // Kept low to protect the credit-metered NIM GPU allocation. Critical so a+ // Redis outage in prod fails closed: an over-quota caller is routed to PAY+ // (the route sends a denied free check to the 402 challenge) rather than the+ // free GPU lane being silently uncapped across serverless instances.+ aiTtsFreeIp: (ip) =>+ getLimiter('ai:tts:free:ip', { limit: 10, window: '1 d', critical: true }).limit(ip),+ aiAsrFreeIp: (ip) =>+ getLimiter('ai:asr:free:ip', { limit: 5, window: '1 d', critical: true }).limit(ip),// NVIDIA Audio2Face-3D (api/a2f) — free upstream but credit-metered, and each// call streams a full speech clip through a bidirectional gRPC stream the// server holds in memory while collecting the blendshape track. Meter perdiff --git a/api/healthz.js b/api/healthz.jsindex 155b8ed9b..18ea4bdd7 100644--- a/api/healthz.js+++ b/api/healthz.js@@ -10,6 +10,7 @@import { cors, json, method, wrap } from './_lib/http.js';import { countRecentPayments } from './_lib/x402/audit-log.js';import { gatherSubsystemHealth } from './_lib/ops/subsystem-health.js';+import { nvidiaTtsConfigured, nvidiaAsrConfigured } from './_lib/ai-speech.js';const STARTED_AT = Date.now();const VERSION = process.env.VERCEL_GIT_COMMIT_SHA || process.env.npm_package_version || 'dev';@@ -348,5 +349,16 @@ export default wrap(async (req, res) => {// probe can't see (Redis on memory-fallback, ring half-armed, Helius// throttled, DB slow, world unprotected). See api/_lib/ops/subsystem-health.js.subsystems,+ // Productized speech package (api/v1/ai/tts, api/v1/ai/asr). Honest env-gate+ // status so a missing NVIDIA key shows here instead of only surfacing as a+ // 503 on the endpoint. Sync env reads — no upstream probe, no key material.+ speech: {+ tts: { configured: nvidiaTtsConfigured(), route: '/api/v1/ai/tts', requires: ['NVIDIA_API_KEY'] },+ asr: {+ configured: nvidiaAsrConfigured(),+ route: '/api/v1/ai/asr',+ requires: ['NVIDIA_API_KEY', 'NVIDIA_ASR_FUNCTION_ID'],+ },+ },}, { 'cache-control': 'public, max-age=2, s-maxage=2' });});diff --git a/api/v1/_catalog.js b/api/v1/_catalog.jsindex e2b8db839..3b7b47454 100644--- a/api/v1/_catalog.js+++ b/api/v1/_catalog.js@@ -60,6 +60,20 @@ export const CATALOG = ['per-IP quota of 10/day, then 429 pointing at the paid /api/x402/forge tiers.',params: { prompt: 'string — describe a single object or character (3–1000 chars, required)' },},+ {+ id: 'v1.ai.image',+ method: 'POST',+ path: '/api/v1/ai/image',+ auth: 'public',+ summary:+ 'Text→image for agents over x402 — 5 free images/day per IP, then $0.02 USDC/image, ' ++ 'no API key. Runs on NVIDIA NIM / Google Vertex lanes; returns a durable image URL.',+ params: {+ prompt: 'string — image description (required, 3–2000 chars)',+ aspect_ratio: 'string — 1:1 | 16:9 | 9:16 | 4:3 | 3:4 | 3:2 | 2:3 (default 1:1)',+ seed: 'number — optional deterministic seed (honored on NIM/Replicate lanes)',+ },+ },{id: 'v1.sentiment',method: 'POST',@@ -105,4 +119,47 @@ export const CATALOG = ['(eip155:<chainId>:<registry>/<tokenId>, URL-encoded).',params: { caip: 'path — URL-encoded CAIP agent ref (required)' },},+ {+ id: 'v1.ai.tts',+ method: 'POST',+ path: '/api/v1/ai/tts',+ auth: 'public',+ summary:+ 'Text-to-speech (neural Magpie voices) — 10 free calls/day per IP (≤500 chars), ' ++ 'then $0.005 USDC/call via x402. GET ?voices=1 lists voices. Returns base64 WAV/PCM.',+ params: {+ text: 'string — text to synthesize (required, ≤4096 chars; free tier ≤500)',+ voice: 'string — voice id (optional, default nova)',+ format: 'string — "wav" | "pcm" (optional, default wav)',+ language: 'string — BCP-47 tag (optional, default en-US)',+ },+ },+ {+ id: 'v1.ai.asr',+ method: 'POST',+ path: '/api/v1/ai/asr',+ auth: 'public',+ summary:+ 'Speech-to-text (NVIDIA Riva) — 5 free clips/day per IP (≤60s), then $0.01 USDC/clip ' ++ 'via x402. Accepts base64 JSON or raw audio/* bytes; returns transcript + confidence.',+ params: {+ audio: 'string — base64 audio in a JSON body, or raw bytes with an audio/* Content-Type (required)',+ format: 'string — wav | pcm | flac | ogg (optional)',+ language: 'string — BCP-47 tag (optional, default en-US)',+ words: 'string — "1" for word-level timestamps (optional)',+ },+ },+ {+ id: 'v1.token.security',+ method: 'GET',+ path: '/api/v1/token/security',+ auth: 'public',+ summary:+ 'Rug-check any Solana token in one free call: authority status, holder concentration, ' ++ 'liquidity depth — on-chain facts, no invented scores. Composes getAccountInfo + ' ++ 'getTokenLargestAccounts + DexScreener into a report agents weigh themselves; 20/min per IP.',+ params: {+ address: 'string — base58 Solana mint address (required; EVM 0x… returns 400)',+ },+ },];diff --git a/api/v1/ai/asr.js b/api/v1/ai/asr.jsnew file mode 100644index 000000000..4ee1bbee1--- /dev/null+++ b/api/v1/ai/asr.js@@ -0,0 +1,218 @@+// POST /api/v1/ai/asr — speech-to-text for agents (free daily quota → x402).+// GET /api/v1/ai/asr — capability probe (free, public).+//+// Productizes the platform's free NVIDIA NIM Riva lane (api/_lib/asr-nvidia.js)+// as a versioned, agent-callable endpoint. Nobody else in the x402 ecosystem+// sells ASR — this is the differentiated listing.+// • Free tier: 5 calls/day per IP, audio ≤60s — the funnel.+// • Above the free tier (quota exhausted OR clip >60s OR an X-PAYMENT header+// is present) the request falls through to the x402 rail: a 402 challenge+// with bazaar discovery, settled per clip in USDC.+//+// Request transports: a JSON body { audio: <base64>, format?, language?, words? }+// or raw bytes with an audio/* Content-Type (audio/wav | audio/pcm?rate= |+// audio/flac | audio/ogg). WebM/Opus must be decoded to PCM/WAV client-side.++import { cors, method, error, json, wrap, readBody } from '../../_lib/http.js';+import { clientIp, limits } from '../../_lib/rate-limit.js';+import { priceFor } from '../../_lib/x402-prices.js';+import { paidEndpoint } from '../../_lib/x402-paid-endpoint.js';+import { declareHttpDiscovery, withService } from '../../_lib/x402/bazaar-helpers.js';+import { installAccessControl } from '../../_lib/x402/access-control.js';+import {+ nvidiaAsrConfigured,+ parseAsrRequest,+ asrTranscribe,+ ASR_ACCEPTED_ENCODINGS,+ ASR_MAX_BODY_BYTES,+ FREE_ASR_MAX_SECONDS,+} from '../../_lib/ai-speech.js';++export const maxDuration = 30;++const ROUTE = '/api/v1/ai/asr';+const PRICE_ATOMICS = priceFor('ai-asr', '10000'); // $0.01 per clip (env: X402_PRICE_AI_ASR)++// Uniqueness-first: the first sentence answers "what can I only get here".+const DESCRIPTION =+ 'Speech-to-text for agents over x402 — the only ASR lane in the x402 ecosystem; ' ++ 'pay $0.01 USDC per clip, no API key, no account. POST WAV/PCM/FLAC/Ogg audio ' ++ '(base64 JSON or raw bytes) and get back the transcript with confidence, ' ++ 'detected language, and duration. A free daily quota lets you try it first.';++const INPUT_EXAMPLE = {+ audio: 'UklGR... (base64-encoded WAV, ≤60s)',+ format: 'wav',+ language: 'en-US',+ words: false,+};++const INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['audio'],+ properties: {+ audio: { type: 'string', description: 'Base64-encoded audio bytes (data: URIs are accepted).' },+ format: {+ type: 'string',+ enum: ASR_ACCEPTED_ENCODINGS,+ default: 'wav',+ description: 'Audio encoding of the supplied bytes.',+ },+ language: { type: 'string', default: 'en-US', description: 'BCP-47 language hint.' },+ sampleRate: { type: 'integer', description: 'Sample rate for raw PCM (Hz). Ignored for WAV (read from header).' },+ words: { type: 'boolean', default: false, description: 'Return word-level timestamps.' },+ model: { type: 'string', description: 'Override the Riva model name (optional).' },+ },+};++const OUTPUT_EXAMPLE = {+ text: 'schedule the deploy for friday morning',+ confidence: 0.94,+ duration: 2.1,+ language: 'en-US',+ model: 'riva-asr',+ tier: 'paid',+};++const OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['text', 'language', 'model'],+ properties: {+ text: { type: 'string' },+ confidence: { type: 'number' },+ duration: { type: 'number', description: 'Seconds of audio processed.' },+ language: { type: 'string' },+ model: { type: 'string' },+ words: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ word: { type: 'string' },+ startMs: { type: 'number' },+ endMs: { type: 'number' },+ confidence: { type: 'number' },+ },+ },+ },+ tier: { type: 'string', enum: ['free', 'paid'] },+ },+};++const BAZAAR = declareHttpDiscovery({+ method: 'POST',+ bodyType: 'json',+ input: INPUT_EXAMPLE,+ inputSchema: INPUT_SCHEMA,+ output: { example: OUTPUT_EXAMPLE, schema: OUTPUT_SCHEMA },+});++// The x402 paid twin — built once, lazily. Reused for every over-quota / paying+// request.+let _paid = null;+function paidHandler() {+ if (_paid) return _paid;+ _paid = paidEndpoint({+ route: ROUTE,+ method: 'POST',+ priceAtomics: PRICE_ATOMICS,+ networks: ['base', 'solana'],+ description: DESCRIPTION,+ bazaar: BAZAAR,+ service: withService({+ serviceName: 'three.ws Speech-to-Text',+ tags: ['asr', 'speech', 'transcription', 'audio', 'ai'],+ }),+ requiredScope: 'x402:bypass',+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),+ async handler({ req }) {+ const buf = req._aiSpeechBody ?? (await readBody(req, ASR_MAX_BODY_BYTES));+ const prepared = parseAsrRequest({ contentType: req.headers['content-type'], url: req.url, buf });+ const payload = await asrTranscribe(prepared);+ return { ...payload, tier: 'paid' };+ },+ });+ return _paid;+}++export default wrap(async function handler(req, res) {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ // ── Capability probe (free, public) ──────────────────────────────────────+ if (req.method === 'GET') {+ return json(+ res,+ 200,+ {+ data: {+ endpoint: ROUTE,+ configured: nvidiaAsrConfigured(),+ encodings: ASR_ACCEPTED_ENCODINGS,+ sampleRate: 16000,+ free_tier: { per_day: 5, max_seconds: FREE_ASR_MAX_SECONDS },+ paid: { price_usdc: Number(PRICE_ATOMICS) / 1e6, networks: ['base', 'solana'] },+ },+ },+ { 'cache-control': 'public, max-age=300' },+ );+ }++ // ── POST: transcribe ──────────────────────────────────────────────────────+ if (!nvidiaAsrConfigured()) {+ return error(+ res,+ 503,+ 'not_configured',+ 'Speech-to-text is not configured (set NVIDIA_API_KEY and NVIDIA_ASR_FUNCTION_ID — ' ++ 'discover the id with scripts/verify-nvidia-asr.mjs --list)',+ );+ }++ // Buffer the body once, then decide the lane — the paid rail reads the same+ // bytes (req._aiSpeechBody) so the stream is never consumed twice.+ let buf;+ try {+ buf = await readBody(req, ASR_MAX_BODY_BYTES);+ } catch (e) {+ if (e?.status === 413) return error(res, 413, 'payload_too_large', `request body exceeds the ${ASR_MAX_BODY_BYTES}-byte limit`);+ return error(res, 400, 'bad_request', e?.message || 'could not read request body');+ }+ req._aiSpeechBody = buf;++ // A payment header means the caller is on the paid rail already.+ const paymentPresent = Boolean(req.headers['x-payment'] || req.headers['payment-signature']);+ if (paymentPresent) return paidHandler()(req, res);++ // Parse/validate against the boundary (bad body 400, oversize 413, bad type+ // 415) so genuinely broken input never becomes a payment prompt.+ let prepared;+ try {+ prepared = parseAsrRequest({ contentType: req.headers['content-type'], url: req.url, buf });+ } catch (e) {+ return error(res, e.status || 400, e.code || 'bad_request', e.message);+ }++ // Beyond the free-tier duration cap (measurable for WAV/PCM) → pay per clip.+ if (prepared.durationSec != null && prepared.durationSec > FREE_ASR_MAX_SECONDS) {+ return paidHandler()(req, res);+ }++ // Free daily quota (per IP). Exhausted → the 402 challenge.+ const rl = await limits.aiAsrFreeIp(clientIp(req));+ if (!rl.success) return paidHandler()(req, res);++ try {+ const payload = await asrTranscribe(prepared);+ return json(+ res,+ 200,+ { data: { ...payload, tier: 'free', free_remaining_today: Math.max(0, rl.remaining) } },+ { 'cache-control': 'no-store' },+ );+ } catch (e) {+ return error(res, e.status || 502, e.code || 'provider_error', e.message);+ }+});diff --git a/api/v1/ai/tts.js b/api/v1/ai/tts.jsnew file mode 100644index 000000000..2dce25275--- /dev/null+++ b/api/v1/ai/tts.js@@ -0,0 +1,223 @@+// POST /api/v1/ai/tts — text-to-speech for agents (free daily quota → x402).+// GET /api/v1/ai/tts?voices=1 — list the available voices (free, public).+//+// Productizes the platform's free NVIDIA NIM Magpie lane (api/_lib/tts-nvidia.js)+// as a versioned, agent-callable endpoint:+// • Free tier: 10 calls/day per IP, text ≤500 chars — the funnel.+// • Above the free tier (quota exhausted OR text >500 chars OR an X-PAYMENT+// header is present) the request falls through to the x402 rail: a 402+// challenge with bazaar discovery, settled per call in USDC.+//+// Both tiers run the SAME synthesis (api/_lib/ai-speech.js) and return the SAME+// JSON shape (base64 audio) — the paid rail must return JSON so settlement runs,+// so the free lane matches for a uniform contract.++import { cors, method, error, json, wrap, readBody } from '../../_lib/http.js';+import { clientIp, limits } from '../../_lib/rate-limit.js';+import { priceFor } from '../../_lib/x402-prices.js';+import { paidEndpoint } from '../../_lib/x402-paid-endpoint.js';+import { declareHttpDiscovery, withService } from '../../_lib/x402/bazaar-helpers.js';+import { installAccessControl } from '../../_lib/x402/access-control.js';+import { TTS_VOICE_IDS, DEFAULT_VOICE } from '../../_lib/tts-voices.js';+import {+ nvidiaTtsConfigured,+ ttsVoicesPayload,+ readTtsInput,+ ttsSynthesize,+ FREE_TTS_MAX_CHARS,+ PAID_TTS_MAX_CHARS,+ TTS_MAX_BODY_BYTES,+} from '../../_lib/ai-speech.js';++export const maxDuration = 45;++const ROUTE = '/api/v1/ai/tts';+const PRICE_ATOMICS = priceFor('ai-tts', '5000'); // $0.005 per call (env: X402_PRICE_AI_TTS)++// Uniqueness-first: the first sentence answers "what can I only get here".+const DESCRIPTION =+ 'Text-to-speech for agents over x402 — a keyless neural TTS lane you can call ' ++ 'with no account and no API key; pay $0.005 USDC per call for multilingual ' ++ 'Magpie voices (English, Spanish, French, German, Italian, Hindi, Chinese, ' ++ 'Vietnamese, Japanese). POST { text, voice? } and receive base64 WAV/PCM audio. ' ++ 'A free daily quota lets you try it before paying.';++const INPUT_EXAMPLE = {+ text: 'Your deploy finished — three services are green and latency is nominal.',+ voice: 'nova',+ format: 'wav',+ language: 'en-US',+};++const INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['text'],+ properties: {+ text: {+ type: 'string',+ minLength: 1,+ maxLength: PAID_TTS_MAX_CHARS,+ description: `Text to synthesize (≤${PAID_TTS_MAX_CHARS} chars; free tier ≤${FREE_TTS_MAX_CHARS}).`,+ },+ voice: {+ type: 'string',+ enum: TTS_VOICE_IDS,+ default: DEFAULT_VOICE,+ description: 'Voice id. Unknown values fall back to the default persona.',+ },+ format: {+ type: 'string',+ enum: ['wav', 'pcm'],+ default: 'wav',+ description: 'Audio container. Magpie emits WAV or raw PCM.',+ },+ language: {+ type: 'string',+ default: 'en-US',+ description: 'BCP-47 language tag (en-US, es-US, fr-FR, de-DE, it-IT, hi-IN, zh-CN, vi-VN, ja-JP).',+ },+ },+};++const OUTPUT_EXAMPLE = {+ audio: 'UklGR... (base64-encoded WAV)',+ encoding: 'base64',+ format: 'wav',+ content_type: 'audio/wav',+ sample_rate: 44100,+ voice: 'Magpie-Multilingual.EN-US.Aria',+ model: 'magpie-tts-multilingual',+ characters: 71,+ bytes: 132_344,+ tier: 'paid',+};++const OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['audio', 'format', 'content_type', 'sample_rate', 'voice', 'model'],+ properties: {+ audio: { type: 'string', description: 'Base64-encoded audio in `format`.' },+ encoding: { type: 'string', const: 'base64' },+ format: { type: 'string' },+ content_type: { type: 'string' },+ sample_rate: { type: 'integer' },+ voice: { type: 'string' },+ model: { type: 'string' },+ characters: { type: 'integer' },+ bytes: { type: 'integer' },+ tier: { type: 'string', enum: ['free', 'paid'] },+ },+};++const BAZAAR = declareHttpDiscovery({+ method: 'POST',+ bodyType: 'json',+ input: INPUT_EXAMPLE,+ inputSchema: INPUT_SCHEMA,+ output: { example: OUTPUT_EXAMPLE, schema: OUTPUT_SCHEMA },+});++// The x402 paid twin — built once, lazily (constructing it touches env-derived+// pay-to config). Reused for every over-quota / paying request.+let _paid = null;+function paidHandler() {+ if (_paid) return _paid;+ _paid = paidEndpoint({+ route: ROUTE,+ method: 'POST',+ priceAtomics: PRICE_ATOMICS,+ networks: ['base', 'solana'],+ description: DESCRIPTION,+ bazaar: BAZAAR,+ service: withService({+ serviceName: 'three.ws Text-to-Speech',+ tags: ['tts', 'speech', 'voice', 'audio', 'ai'],+ }),+ requiredScope: 'x402:bypass',+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),+ async handler({ req }) {+ const raw = req._aiSpeechBody ?? (await readBody(req, TTS_MAX_BODY_BYTES));+ const input = readTtsInput(raw, { maxChars: PAID_TTS_MAX_CHARS });+ const payload = await ttsSynthesize(input);+ return { ...payload, tier: 'paid' };+ },+ });+ return _paid;+}++export default wrap(async function handler(req, res) {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ // ── Voices / capability probe (free, public) ─────────────────────────────+ if (req.method === 'GET') {+ const url = new URL(req.url, 'http://localhost');+ if (url.searchParams.has('voices')) {+ return json(res, 200, { data: ttsVoicesPayload() }, { 'cache-control': 'public, max-age=3600' });+ }+ return json(+ res,+ 200,+ {+ data: {+ endpoint: ROUTE,+ description: 'POST text to synthesize speech. GET ?voices=1 lists voices.',+ configured: nvidiaTtsConfigured(),+ free_tier: { per_day: 10, max_chars: FREE_TTS_MAX_CHARS },+ paid: { price_usdc: Number(PRICE_ATOMICS) / 1e6, max_chars: PAID_TTS_MAX_CHARS, networks: ['base', 'solana'] },+ },+ },+ { 'cache-control': 'public, max-age=300' },+ );+ }++ // ── POST: synthesize ──────────────────────────────────────────────────────+ if (!nvidiaTtsConfigured()) {+ return error(res, 503, 'not_configured', 'Text-to-speech is not configured (set NVIDIA_API_KEY)');+ }++ // Buffer the body once, then decide the lane — the paid rail reads the same+ // bytes (req._aiSpeechBody) so the stream is never consumed twice.+ let raw;+ try {+ raw = await readBody(req, TTS_MAX_BODY_BYTES);+ } catch (e) {+ if (e?.status === 413) return error(res, 413, 'payload_too_large', `request body exceeds ${TTS_MAX_BODY_BYTES} bytes`);+ return error(res, 400, 'bad_request', e?.message || 'could not read request body');+ }+ req._aiSpeechBody = raw;++ // A payment header means the caller is on the paid rail already.+ const paymentPresent = Boolean(req.headers['x-payment'] || req.headers['payment-signature']);+ if (paymentPresent) return paidHandler()(req, res);++ // Validate against the paid ceiling first, so genuinely bad input (empty / too+ // long) is a clean 400 rather than a payment prompt.+ let input;+ try {+ input = readTtsInput(raw, { maxChars: PAID_TTS_MAX_CHARS });+ } catch (e) {+ return error(res, e.status || 400, e.code || 'bad_request', e.message);+ }++ // Beyond the free-tier char cap → pay per call.+ if (input.text.length > FREE_TTS_MAX_CHARS) return paidHandler()(req, res);++ // Free daily quota (per IP). Exhausted → the 402 challenge.+ const rl = await limits.aiTtsFreeIp(clientIp(req));+ if (!rl.success) return paidHandler()(req, res);++ try {+ const payload = await ttsSynthesize(input);+ return json(+ res,+ 200,+ { data: { ...payload, tier: 'free', free_remaining_today: Math.max(0, rl.remaining) } },+ { 'cache-control': 'no-store' },+ );+ } catch (e) {+ return error(res, e.status || 502, e.code || 'provider_error', e.message);+ }+});diff --git a/data/changelog.json b/data/changelog.jsonindex 2865eb4b6..a24a1d882 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,181 @@{"$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-07",+ "title": "Speech for agents: keyless text-to-speech and speech-to-text over x402",+ "summary": "Two new AI endpoints give agents a voice and an ear with no account and no API key. POST /api/v1/ai/tts turns text into natural multilingual speech (nine languages on the NVIDIA Magpie lane); POST /api/v1/ai/asr transcribes audio to text with confidence and duration — the only speech-to-text lane anywhere in the x402 ecosystem. Both are free to try — 10 TTS calls and 5 ASR clips per day per IP — and past that quota each call is a tiny USDC micropayment settled on Solana or Base ($0.005 per TTS call, $0.01 per ASR clip). The response looks the same whether it was free or paid, so an agent writes one integration for both. Full reference with runnable curls lives at /docs/api-reference.",+ "tags": [+ "feature"+ ],+ "link": "/docs/api-reference"+ },+ {+ "date": "2026-07-07",+ "title": "On-chain identity verification now works cross-platform for any claim",+ "summary": "The Identity Verifier is no longer three.ws-only. Give it any claim that an identity controls an address — an ENS name (vitalik.eth), an SNS name (bonfida.sol), an EVM or Solana wallet, an ERC-8004 agent id, or a three.ws agent_id — and it returns real on-chain evidence the link is genuine: ENS/SNS resolution, a contract's deploy transaction and deployer, a token's mint and metadata authorities, an ERC-8004 registry entry, or the three.ws deploy record. Every verdict is true, false, or unverifiable — and it never reports true without concrete on-chain proof, so an insufficient read is honestly labeled instead of guessed. An agent can now verify whoever it's about to pay, trade, or delegate to, whatever platform they came from. Pair it with cross-chain Agent Reputation: verify who they are, then score whether to trust them. Full evidence model at /docs/trust-primitives.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/docs/trust-primitives"+ },+ {+ "date": "2026-07-07",+ "title": "Forge listing sharpened: clear 3D generation tiers for agents",+ "summary": "Forge — our text→3D and image→3D generation — now reads like the crown jewel it is on the x402 agent marketplaces. The listing leads with what agents actually build (game assets, NFT collections, 3D scenes, product viz), spells out the three quality tiers and their flat USDC prices (draft $0.05 / standard $0.15 / high $0.50), and points newcomers to the free keyless draft lane as an on-ramp. The input and output schemas are now complete enough for an agent to call it blind — the prompt, the reference-image mode, the free job-token poll, and the finished GLB — and it's tagged so it surfaces under 3D, AI, and Utility. Under the hood the discovery listing and the live payment challenge now share one source of truth, so what an agent sees can never drift from what it pays for.",+ "tags": [+ "improvement"+ ],+ "link": "/docs/3d-api"+ },+ {+ "date": "2026-07-07",+ "title": "three.ws Crypto Data API: one free, keyless crypto data bundle for AI agents",+ "summary": "The free crypto endpoints are now one product with a single front door. GET /api/crypto lists the whole bundle — bonding-curve status, whale activity, trending tokens, wallet portfolios, and symbol availability — each with its inputs, outputs, and a live example, so an agent discovers everything in one call (ask for HTML and it renders a browsable page instead of JSON). GET /api/crypto/openapi.json is a real OpenAPI 3.1 spec generated straight from that catalog, so LangChain, openapi-generator, and Swagger UI produce typed clients and callable tools with no key and no account. New endpoints join the index and the spec automatically the moment they ship, and a zero-endpoint state is a valid \"coming soon\", never an error. Full reference lives at /docs/crypto-api.",+ "tags": [+ "feature",+ "sdk"+ ],+ "link": "/docs/crypto-api"+ },+ {+ "date": "2026-07-07",+ "title": "three.ws 3D API: free text→3D + inspection for AI agents, with pro tiers",+ "summary": "One URL now discovers the whole free, keyless 3D API for agents. GET /api/3d returns every free endpoint — turn a text prompt into a real GLB (/api/3d/generate) and validate/optimize any glTF/GLB (/api/3d/inspect) — with a live example each, plus the paid ladder it graduates to. GET /api/3d/openapi.json is a real OpenAPI 3.1 spec generated straight from the catalog, so LangChain, openapi-generator, and Swagger UI get typed tools with no key and no account. A new docs page at /3d shows a hero, a live endpoint table, a runnable quickstart with a \"run it live\" inspection console, an embedded 3D viewer of a real model, and a clear free→paid path: free draft + inspect → Forge Pro quality tiers → animation-ready Rigged Avatars. No other agent-payments platform gives away 3D generation and inspection.",+ "tags": [+ "feature",+ "docs"+ ],+ "link": "/3d"+ },+ {+ "date": "2026-07-07",+ "title": "Free trending-tokens API for crypto agents",+ "summary": "New free, keyless endpoint GET /api/crypto/trending gives any AI agent a ranked \"what's hot right now\" list in one call — no account, no key. Tokens are ranked by momentum (a 0–100 score blending windowed trade volume, buy pressure, a volume-spike signal, and short-window price change), fused live across pump.fun, DexScreener's boosted board, and GMGN smart money. Pick a window (5m, 1h, or 24h) and a source (pump.fun only or all), and get back each token's mint, symbol, market cap, volume, price change, score, and link. If an upstream is down it returns whatever ranked data it has with a note instead of failing.",+ "tags": [+ "feature"+ ],+ "link": "/docs/crypto-api"+ },+ {+ "date": "2026-07-07",+ "title": "One x402 call runs the whole 3D asset pipeline",+ "summary": "New endpoint POST /api/x402/pipeline runs a full chain of 3D stages — generate → rig → remesh → gameready → stylize — as a single paid job with one price. Describe what you want (a text prompt or an existing GLB) and get back a rigged, game-ready GLB: text or GLB in, finished asset out. You pick the stages as an ordered chain, the 402 challenge quotes the exact sum of just those stages, and you poll the job for free at /api/forge?job=<id> while it advances, watching each stage's progress. Only stages whose lane is live on the deployment are offered, and if a stage fails mid-chain the job is marked failed at that stage with every completed stage's output still delivered — honest partial value, never a silent dead-end. It's the only end-to-end asset pipeline in the x402 ecosystem.",+ "tags": [+ "feature"+ ],+ "link": "/docs/3d-pipeline"+ },+ {+ "date": "2026-07-07",+ "title": "Free token security check answers \"is this a rug?\" in one call",+ "summary": "New free, keyless endpoint: GET /api/v1/token/security turns any Solana mint into an on-chain security report — the first question every trading agent asks before touching a token. It reports whether the mint and freeze authorities are still active (supply can be inflated / accounts frozen), how concentrated the top holders are, how deep the liquidity is, and how old the trading pair is, composing Solana RPC and DexScreener into one answer. There's no invented 'risk score' — just factual flags like mint_authority_active, top1_holder_over_20pct, liquidity_under_10k, and pair_younger_than_24h that agents weigh themselves. Every field is always present (null when a source can't resolve it, never faked), each section degrades independently, and an EVM address gets an honest 'Solana only' 400. Capped at 20 calls/min per IP.",+ "tags": [+ "feature"+ ],+ "link": "/docs/api-reference"+ },+ {+ "date": "2026-07-07",+ "title": "Agent reputation now scores any wallet or agent on any chain",+ "summary": "The paid Agent Reputation endpoint no longer only works on three.ws agents — pass ANY counterparty and get a deterministic 0–100 trust score before you pay, trade, or delegate to it. It auto-detects the type — a Solana wallet, an EVM 0x address, a pump.fun mint, an ERC-8004 agent id, or a three.ws agent_id — and scores it from real on-chain evidence: transaction history, account age, distinct counterparties, holdings, settlement reliability, prior settled agent payments, and ERC-8004 feedback. Every score comes with the underlying evidence links and a clear list of what couldn't be read; an unknown or unscannable subject returns score:null, never a fabricated number. A new batch mode scores up to 25 counterparties in one call. It's a genuine pre-transaction trust primitive that works across chains, not just on our own platform.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/docs/trust-primitives"+ },+ {+ "date": "2026-07-07",+ "title": "The 3D asset pipeline is now purchasable stage-by-stage",+ "summary": "Every working stage of the platform's 3D pipeline is now its own pay-per-call x402 endpoint, so an agent can buy exactly the step it needs and get a finished asset URL back in one call — no account, no API key. Rig a static model into an animation-ready one ($0.05), remesh or retopologize to a clean topology ($0.03), make a mesh game-ready to a poly budget ($0.03), geometrically restyle it — voxel, brick, voronoi, low-poly ($0.03), or strip an image's background to a transparent PNG for image→3D ($0.01). Each call validates your input, runs the real worker, checks the output is a valid asset, and hands back a durable first-party URL — and if anything fails, you're never charged. Nobody else in the x402 ecosystem sells a 3D asset pipeline.",+ "tags": [+ "feature"+ ],+ "link": "/docs/3d-pipeline"+ },+ {+ "date": "2026-07-07",+ "title": "Free wallet portfolio API for agents",+ "summary": "New free, keyless endpoint: GET /api/crypto/wallet returns any wallet's native balance, every token it holds, and a rough USD valuation in one call — no account, no API key. It's built for agents that need to size up a wallet before they act: a treasury agent checking its own runway, a copy-trade agent reading a leader's holdings, or a pre-trade check on a counterparty. Solana works with no key at all (it falls back to the public RPC plus Jupiter and pump.fun pricing); tokens that can't be priced are still listed with their balance, never dropped or faked.",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-07-07",+ "title": "Symbol-availability check is now free",+ "summary": "Checking whether a token ticker is already taken is now free and keyless at /api/crypto/symbol — no account, no payment. Send up to 20 candidate tickers in one call and get back, for each, whether it's available plus any exact collisions and fuzzy look-alikes (e.g. MOONZ vs MOONS) already live across the market, so your name won't get lost among clones. It's the natural first step before minting: clear the name here for free, then launch through the Pump Launcher. Previously this was a paid endpoint; it's now a free discovery utility with exact + fuzzy matching across live registries, and it degrades gracefully (never a false 'available') if a data source is down.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/docs/crypto-api"+ },+ {+ "date": "2026-07-07",+ "title": "Pump Launcher listing sharpened + wired to the free symbol & launches APIs",+ "summary": "The paid Pump Launcher (/api/x402/pump-launch) now sells what it actually does: deploy a brand-new pump.fun token in one call with no SOL, no wallet, and no account — you pay $5 in USDC and the platform fronts the deploy cost, optionally grinds a vanity mint, and signs the create transaction. The discovery listing and its schema were rewritten so an agent can call it blind — every input (name, symbol, a pre-pinned metadataUri or an imageUrl we pin for you, creator-rewards wallet, optional vanity prefix/suffix) and every output (mint, tx signature, metadata URI, pump.fun URL) is now spelled out. It's also wired into the free Crypto Data API: check your ticker is free first with /api/crypto/symbol, then confirm your deploy landed on the live /api/crypto/launches feed. A new docs page walks the whole flow.",+ "tags": [+ "improvement"+ ],+ "link": "/docs/pump-launcher"+ },+ {+ "date": "2026-07-07",+ "title": "Text→image API for agents — 5 free a day, then pay per image",+ "summary": "Agents can now turn a text prompt into a real image with one call to /api/v1/ai/image — no API key, no account. The first 5 images a day per IP are free; after that each image is a single $0.02 USDC micropayment over x402, settled on Solana or Base, with nothing to sign up for. It runs on the same subsidized lanes as the 3D forge (NVIDIA NIM FLUX and the Google Vertex/Gemini image lane) and returns a durable URL to the rendered image. Pick an aspect ratio, pass an optional seed for reproducible results, and check lane health at /api/v1/ai/image?health=1. A quota slot is only spent when an image actually ships — a bad prompt or a provider content refusal never costs you a free generation.",+ "tags": [+ "feature"+ ],+ "link": "/docs/api-reference"+ },+ {+ "date": "2026-07-07",+ "title": "New: three.ws Crypto Data API docs",+ "summary": "One page now documents the whole free, keyless Crypto Data API for AI agents — live at /crypto. It lays out all nine reads an agent needs mid-trade (token snapshot, security/rug signals, holders & concentration, live pump.fun launches, bonding-curve status, whale activity, symbol availability, wallet portfolio, trending) with a copy-paste quickstart in curl, JavaScript and Python, a real request/response example for each, and a live 'Try it' console right in the browser. Every endpoint is free with no key and no account. The page probes production in real time and marks each endpoint Live or Coming soon, so it stays honest as the API rolls out — and points you to the paid uniques (Pump Launcher, Vanity, Forge) when your agent is ready to act on the data.",+ "tags": [+ "feature",+ "docs"+ ],+ "link": "/crypto"+ },+ {+ "date": "2026-07-07",+ "title": "3D model inspection is now free",+ "summary": "Validating and optimizing a glTF/GLB no longer costs anything. The new free, keyless /api/3d/inspect takes a model URL (or a raw upload) and returns whether it's spec-valid, its full structural stats — vertices, triangles, materials, textures, animations, extensions — and a severity-ranked list of exactly what to fix to make it smaller and faster for the web. It runs the official Khronos glTF-Validator plus the same inspection core the platform's paid pipelines use. This capability used to be a paid x402 endpoint (model-check); a validation utility should be free — it builds trust and points agents at the paid Forge Pro, Rigged Avatar, and optimization tiers when they need the heavy lifting done for them.",+ "tags": [+ "feature",+ "improvement"+ ]+ },+ {+ "date": "2026-07-07",+ "title": "Free text→3D generation API for agents",+ "summary": "Any AI agent can now turn a text prompt into a real 3D model with one call to /api/3d/generate — free, keyless, no account, no wallet. Describe a single object and get back a textured GLB (inline when it finishes fast, otherwise a job token you poll at /api/3d/generate?job=<id>). It runs on the free draft lane (NVIDIA NIM TRELLIS): draft-fidelity geometry, GLB only, no rigging — honest about being a prototyping tier, with a generous per-IP rate limit protecting the shared GPU. Need denser meshes with PBR textures, or an animation-ready rigged character? The response and docs point straight at paid Forge Pro and Rigged Avatars. No other agent-payments platform gives away 3D generation.",+ "tags": [+ "feature",+ "sdk"+ ]+ },+ {+ "date": "2026-07-07",+ "title": "Free whale-activity API for crypto agents",+ "summary": "A new free, keyless endpoint tells an AI agent whether big money is moving before it trades. Call /api/crypto/whales with a token mint to see the large buys of that coin, or without one to see the top whale wallets active across pump.fun right now. Each response carries a plain bullish/bearish/neutral signal derived from net whale flow — the SOL whales bought minus the SOL they sold — with no black-box scoring. No account, no key, no payment.",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-07-07",+ "title": "Free text→3D now has a first-class API endpoint",+ "summary": "The free text-to-3D lane — the only text-to-mesh service in the agent-payments ecosystem — finally has a clean, versioned endpoint instead of being buried under forge job plumbing. POST a prompt to /api/v1/ai/text-to-3d and get back a textured GLB and a viewer link: no key, no wallet, nothing to sign. It runs on the free NVIDIA NIM TRELLIS lane with a per-IP quota of 10 generations a day; past that it returns a clear rate-limit notice pointing at the paid forge tiers for higher volume and quality, never a silent paywall. The GLB either comes back inline or as a job you poll to completion.",+ "tags": [+ "feature"+ ],+ "link": "/docs/api-reference"+ },{"date": "2026-07-06","title": "3D generation, rigging, and export — now individually-priced services for AI agents",diff --git a/docs/api-reference.md b/docs/api-reference.mdindex 81001a74d..5a13f9352 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -653,6 +653,430 @@ Responses are cached in R2 by `sha256(voiceId + text + modelId)` for 30 days —---+## AI API — text→3D++The only text→mesh lane in the x402 / agent-payments ecosystem. Turn a text+prompt into a textured, downloadable GLB — no key, no wallet. The draft tier runs+free on the NVIDIA NIM TRELLIS lane (the same pipeline behind the `forge_free`+MCP tool and [/forge](https://three.ws/forge)). Higher quality/volume lives on+the paid [x402 forge tiers](#x402-paid-endpoints--sign-in-with-x-siwx).++### Text→3D (free)++```+POST /api/v1/ai/text-to-3d+```++Public, CORS-open, no auth. Free with a per-IP quota of **10 generations/day**+(the GPU quota is real). Above the quota the endpoint returns `429` with+`X-RateLimit-Reset` and a pointer to the paid forge tiers — it never paywalls+silently.++**Request body**++```json+{ "prompt": "a small ceramic robot figurine" }+```++| Field | Type | Description |+|-------|------|-------------|+| `prompt` | string | Describe a single object or character. 3–1000 characters. Required. |++**Response — finished inline** (the NIM often completes inside the request window):++```json+{+ "data": {+ "status": "done",+ "glb_url": "https://cdn.three.ws/forge/anon/<id>.glb",+ "viewer_url": "https://three.ws/viewer?src=https%3A%2F%2Fcdn.three.ws%2Fforge%2Fanon%2F%3Cid%3E.glb",+ "creation_id": "<uuid>",+ "backend": "nvidia",+ "tier": "draft"+ }+}+```++**Response — queued** (poll the existing free job endpoint until `status: "done"`):++```json+{+ "data": {+ "status": "pending",+ "job": "f1.<signed-token>",+ "poll_url": "/api/forge?job=f1.<signed-token>",+ "viewer_url": null,+ "backend": "nvidia",+ "tier": "draft"+ }+}+```++Poll with `GET /api/forge?job=<job>` — it returns `{ status: "queued" | "done" | "failed", glb_url? }`.++**Example**++```bash+curl -s -X POST https://three.ws/api/v1/ai/text-to-3d \+ -H 'content-type: application/json' \+ -d '{"prompt":"a small ceramic robot figurine"}'+```++**Errors**++| Status | Code | Meaning |+|--------|------|---------|+| `400` | `validation_error` | `prompt` missing, shorter than 3 chars, or over 1000 |+| `429` | `quota_exceeded` | Daily free quota spent; see `X-RateLimit-Reset` and `upgrade.endpoint` (`/api/x402/forge`) |+| `503` | `not_configured` | The NVIDIA NIM lane isn't configured on this deployment (`NVIDIA_API_KEY`) |+| `502`/`504` | `lane_error` / `lane_timeout` | The generation lane failed or timed out — retry |++---++## AI API — text→image++Text→image for agents over x402 — no API key, no account. The first **5 images/day+per IP are free**; past the quota each image is a single USDC micropayment+(`$0.02`) settled on Solana or Base via the [x402](#x402-paid-endpoints--sign-in-with-x-siwx)+rail. It runs on the same subsidized lanes as the 3D forge (NVIDIA NIM FLUX and+the Google Vertex/Gemini image lane), and returns a durable https URL to the+rendered image.++### Text→image++```+POST /api/v1/ai/image+```++Public, CORS-open. Unauthenticated callers get the free daily quota first; once+it's spent the endpoint answers with a standard `402 Payment Required` challenge+(pay with any x402 client to receive the image). A quota slot is spent only when+an image is actually delivered — a validation error, a content refusal, or a lane+outage never burns a free generation.++**Request body**++```json+{ "prompt": "a brass owl figurine on a plain white background", "aspect_ratio": "1:1" }+```++| Field | Type | Description |+|-------|------|-------------|+| `prompt` | string | Image description. 3–2000 characters. Required. |+| `aspect_ratio` | string | One of `1:1`, `16:9`, `9:16`, `4:3`, `3:4`, `3:2`, `2:3`. Default `1:1`. |+| `seed` | integer | Optional deterministic seed (0–4294967295). Honored on the NIM / Replicate flux lanes; the Vertex/Gemini lane has no seed parameter and ignores it. |++**Response — 200**++```json+{+ "url": "https://cdn.three.ws/forge/refs/<id>.jpg",+ "provider": "nvidia-nim",+ "model": "black-forest-labs/flux.1-schnell",+ "width": 1024,+ "height": 1024,+ "aspect_ratio": "1:1",+ "seed": null,+ "free": true,+ "quota": { "used": 1, "limit": 5, "remaining": 4, "resetAt": "2026-07-08T00:00:00.000Z" }+}+```++`provider` is the lane that served the image (`nvidia-nim` | `vertex` | `replicate`).+`width`/`height` are the nominal target dimensions for the requested aspect ratio.++**Example — free tier**++```bash+curl -s -X POST https://three.ws/api/v1/ai/image \+ -H 'content-type: application/json' \+ -d '{"prompt":"a brass owl figurine on a plain white background"}'+```++**Example — paid (past the free quota), with an x402 client**++```bash+# The x402 CLI pays the 402 challenge and returns the settled response body.+npx x402 curl -X POST https://three.ws/api/v1/ai/image \+ -H 'content-type: application/json' \+ -d '{"prompt":"a neon koi swimming, dark background","aspect_ratio":"16:9"}'+```++**Lane health** (no quota burn):++```bash+curl -s 'https://three.ws/api/v1/ai/image?health=1'+```++Returns per-lane `configured`/`status` (`ok` | `down` | `degraded` | `unconfigured`)+and `missing_env` when nothing is wired. A plain `GET /api/v1/ai/image` returns a+discovery doc (price, free-tier width, which lanes are configured).++**Errors**++| Status | Code | Meaning |+|--------|------|---------|+| `400` | `invalid_prompt` / `prompt_too_long` / `invalid_aspect_ratio` / `invalid_seed` | Request validation failed |+| `402` | — | Free quota spent — pay the x402 challenge to continue |+| `422` | `content_refused` | The provider blocked the prompt on content-policy grounds (not retried) |+| `429` | `rate_limited` | Lane briefly busy — retry after `retryAfter` seconds |+| `503` | `not_configured` | No image lane is configured (`NVIDIA_API_KEY`, `GOOGLE_CLOUD_PROJECT` + `GCP_SERVICE_ACCOUNT_JSON`, or `REPLICATE_API_TOKEN`) |+| `503` | `lane_unavailable` | The configured lane is temporarily down — retry |+| `502` | `generation_failed` | The lane returned no usable image — retry |++---++## AI API — speech (TTS + ASR)++Text-to-speech and speech-to-text for agents over x402 — no API key, no account.+Both run on the platform's subsidized **NVIDIA NIM** lanes (Magpie multilingual TTS+and Riva ASR) and both follow the same shape: a **free daily per-IP quota** first,+then a single USDC micropayment settled on Solana or Base via the+[x402](#x402-paid-endpoints--sign-in-with-x-siwx) rail. Nobody else in the x402+ecosystem sells ASR, so `/api/v1/ai/asr` is a one-of-a-kind lane.++Both endpoints return the **same JSON shape whether served free or paid** (the paid+rail must return JSON so settlement can run), so a caller writes one parser for+both tiers. The `tier` field reports which lane served the response.++### Text→speech++```+POST /api/v1/ai/tts+```++Public, CORS-open. **10 free calls/day per IP** for text ≤500 characters; beyond the+quota (or for text 501–4096 characters, or when an `X-PAYMENT` header is present)+the endpoint answers a `402 Payment Required` challenge priced at **`$0.005` USDC**+per call. Synthesis runs on the free Magpie lane in all cases — the payment is for+access, not a different model.++**Request body**++```json+{ "text": "Your deploy finished — three services are green.", "voice": "nova", "format": "wav" }+```++| Field | Type | Description |+|-------|------|-------------|+| `text` | string | Text to synthesize. Required. ≤4096 chars (free tier ≤500). |+| `voice` | string | Voice id (`nova`, `alloy`, `shimmer`, `onyx`, …). Unknown values fall back to the default persona. Default `nova`. |+| `format` | string | `wav` or `pcm`. Magpie emits WAV or raw PCM. Default `wav`. |+| `language` | string | BCP-47 tag: `en-US`, `es-US`, `fr-FR`, `de-DE`, `it-IT`, `hi-IN`, `zh-CN`, `vi-VN`, `ja-JP`. Default `en-US`. |++**Response — 200**++```json+{+ "data": {+ "audio": "UklGR... (base64)",+ "encoding": "base64",+ "format": "wav",+ "content_type": "audio/wav",+ "sample_rate": 44100,+ "voice": "Magpie-Multilingual.EN-US.Aria",+ "model": "magpie-tts-multilingual",+ "characters": 47,+ "bytes": 132344,+ "tier": "free",+ "free_remaining_today": 9+ }+}+```++`audio` is the base64-encoded clip in `content_type`. Decode it to bytes to play or+save. `tier` is `free` or `paid`.++**List voices** (free, no quota):++```bash+curl -s 'https://three.ws/api/v1/ai/tts?voices=1'+```++**Example — free tier**++```bash+curl -s -X POST https://three.ws/api/v1/ai/tts \+ -H 'content-type: application/json' \+ -d '{"text":"Hello from three.ws","voice":"nova"}' \+ | jq -r '.data.audio' | base64 -d > hello.wav+```++**Example — paid (past the free quota), with an x402 client**++```bash+npx x402 curl -X POST https://three.ws/api/v1/ai/tts \+ -H 'content-type: application/json' \+ -d '{"text":"This one is billed at half a cent.","voice":"onyx"}'+```++### Speech→text++```+POST /api/v1/ai/asr+```++Public, CORS-open. **5 free clips/day per IP** for audio ≤60 seconds; beyond the+quota (or for clips >60s, or when an `X-PAYMENT` header is present) the endpoint+answers a `402 Payment Required` challenge priced at **`$0.01` USDC** per clip.++Send audio one of two ways:++- **JSON** — `{ "audio": "<base64>", "format": "wav" }`+- **Raw bytes** — the audio as the request body with an `audio/*` `Content-Type`+ (`audio/wav`, `audio/pcm` with `?rate=`, `audio/flac`, `audio/ogg`).++WebM/Opus is not accepted — decode it to PCM/WAV client-side first.++| Field | Type | Description |+|-------|------|-------------|+| `audio` | string | Base64 audio in a JSON body (data: URIs accepted). Required for the JSON transport. |+| `format` | string | `wav` \| `pcm` \| `flac` \| `ogg`. Default `wav`. |+| `language` | string | BCP-47 language hint. Default `en-US`. |+| `sampleRate` | integer | Sample rate (Hz) for raw PCM. Ignored for WAV (read from the header). |+| `words` | boolean | Return word-level timestamps. Default `false`. |++**Response — 200**++```json+{+ "data": {+ "text": "schedule the deploy for friday morning",+ "confidence": 0.94,+ "duration": 2.1,+ "language": "en-US",+ "model": "riva-asr",+ "tier": "free",+ "free_remaining_today": 4+ }+}+```++`duration` is the seconds of audio processed. `confidence` is the mean top-alternative+confidence. Pass `words: true` to also receive a `words` array of+`{ word, startMs, endMs, confidence }`.++**Example — free tier (base64 JSON)**++```bash+AUDIO=$(base64 -w0 clip.wav)+curl -s -X POST https://three.ws/api/v1/ai/asr \+ -H 'content-type: application/json' \+ -d "{\"audio\":\"$AUDIO\",\"format\":\"wav\"}"+```++**Example — raw bytes**++```bash+curl -s -X POST https://three.ws/api/v1/ai/asr \+ -H 'content-type: audio/wav' \+ --data-binary @clip.wav+```++**Example — paid (past the free quota), with an x402 client**++```bash+npx x402 curl -X POST https://three.ws/api/v1/ai/asr \+ -H 'content-type: application/json' \+ -d "{\"audio\":\"$(base64 -w0 clip.wav)\",\"format\":\"wav\"}"+```++A plain `GET /api/v1/ai/asr` returns a capability probe (accepted encodings,+sample rate, whether the lane is configured).++**Errors** (both endpoints)++| Status | Code | Meaning |+|--------|------|---------|+| `400` | `bad_request` / `text_too_long` | Request validation failed (empty/invalid body, or text over 4096 chars) |+| `402` | — | Free quota spent (or over the free size limit) — pay the x402 challenge |+| `413` | `payload_too_large` | Audio exceeds the 8 MB limit |+| `415` | `unsupported_media_type` | Unrecognized audio `Content-Type` (ASR) |+| `429` | `rate_limited` | Upstream credit metering hit — retry shortly |+| `503` | `not_configured` | TTS needs `NVIDIA_API_KEY`; ASR needs `NVIDIA_API_KEY` + `NVIDIA_ASR_FUNCTION_ID` |+| `502` | `provider_error` / `invalid_key` | The NIM lane failed — retry |++---++## Token API — security++Rug-check any Solana token in one free call. Instead of an invented "risk score",+this returns the **on-chain facts** an agent needs to decide for itself: whether+the mint and freeze authorities are still active, how concentrated the top holders+are, how deep the liquidity is, and how old the pair is. It composes+`getAccountInfo` + `getTokenLargestAccounts` (Solana RPC) with DexScreener — data+you could gather yourself from three sources, in one keyless request.++### Token security check++```+GET /api/v1/token/security?address=<mint>+```++Public, CORS-open, no auth. Rate limited to **20 requests/min per IP**; responses+are edge-cached for 60s. Solana only — an EVM `0x…` address returns `400`.++| Query param | Type | Description |+|-------------|------|-------------|+| `address` | string | Base58 Solana mint address. Required. |++**Response**++Every field is always present — `null` when a source couldn't resolve it, never+omitted and never faked. `sources` names which upstreams answered; `flags` are+factual conditions (an empty array means none tripped).++```json+{+ "data": {+ "address": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "chain": "solana",+ "mint_authority": { "revoked": true, "address": null },+ "freeze_authority": { "revoked": true, "address": null },+ "supply": "999683523471616",+ "decimals": 6,+ "top_holders": { "top1_pct": 6.6, "top5_pct": 14.7, "top10_pct": 22.3, "holders_sampled": 20 },+ "liquidity": { "usd": 196695.93, "largest_pair": "three/SOL", "pair_created_at": 1777446541000 },+ "flags": [],+ "sources": ["solana-rpc", "dexscreener"],+ "ts": 1783382400000+ }+}+```++**Flags** (emitted only when the underlying facts are known):++| Flag | Condition |+|------|-----------|+| `mint_authority_active` | The mint authority is not revoked — supply can still be inflated |+| `freeze_authority_active` | The freeze authority is not revoked — accounts can be frozen |+| `top1_holder_over_20pct` | The single largest account holds > 20% of supply |+| `top10_holders_over_80pct` | The top 10 accounts hold > 80% of supply |+| `liquidity_under_10k` | Deepest-pair liquidity is under $10,000 |+| `pair_younger_than_24h` | The deepest pair was created less than 24h ago |++**Example**++```bash+curl -s 'https://three.ws/api/v1/token/security?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump'+```++**Degradation & errors**++Each section resolves independently. If one upstream is down, only that section+is nulled and it drops out of `sources` — the call still succeeds (`200`) as long+as any section resolved.++| Status | Code | Meaning |+|--------|------|---------|+| `400` | `validation_error` | `address` missing or not a base58 Solana address |+| `400` | `unsupported_chain` | An EVM `0x…` address — this endpoint is Solana-only |+| `404` | `not_found` | Sources answered but no on-chain mint or market exists for this address |+| `429` | `rate_limited` | Over 20 requests/min from this IP — back off per `retry_after` |+| `503` | `sources_unavailable` | Every upstream failed — transient, retry shortly |++---+## Authentication APIAuthentication is covered in detail in the [Authentication documentation](authentication.md). Quick reference:diff --git a/tests/api/v1-ai-speech.test.js b/tests/api/v1-ai-speech.test.jsnew file mode 100644index 000000000..f679bf00c--- /dev/null+++ b/tests/api/v1-ai-speech.test.js@@ -0,0 +1,362 @@+// Tests for the productized speech package: POST /api/v1/ai/tts + /api/v1/ai/asr.+//+// Contract under test:+// • Free tier: a per-IP DAILY quota (10 TTS / 5 ASR) served on the free NVIDIA+// NIM lanes; above it the request falls through to the x402 402 challenge.+// • Env gating is honest: a missing NVIDIA key answers 503 not_configured+// naming the exact var — never a 500, never a fake response.+// • Input is validated at the boundary (bad body 400, oversize 413, bad+// Content-Type 415) BEFORE any lane is tried or any payment is prompted.+// • The catalog (api/v1/_catalog.js) lists both endpoints.+//+// The NIM boundary (the @grpc/grpc-js transport) is fixtured with captured Riva+// response shapes — none of OUR code (ai-speech, asr-nvidia, tts-nvidia, the+// routes) is mocked.++import { describe, it, expect, vi, beforeEach, afterEach, beforeAll } from 'vitest';+import { Readable } from 'node:stream';++// ── NIM transport (gRPC) fixture ──────────────────────────────────────────────+const grpcState = vi.hoisted(() => ({+ synthesize: null, // (req, md, opts, cb)+ recognize: null, // (req, md, opts, cb)+ synthCalls: [],+ recogCalls: [],+}));++vi.mock('@grpc/grpc-js', () => {+ class Metadata {+ constructor() {+ this.map = {};+ }+ set(k, v) {+ this.map[k] = v;+ }+ get(k) {+ return this.map[k];+ }+ }+ class RivaSpeechSynthesis {+ synthesize(request, metadata, opts, cb) {+ grpcState.synthCalls.push({ request, metadata });+ grpcState.synthesize(request, metadata, opts, cb);+ }+ }+ class RivaSpeechRecognition {+ recognize(request, metadata, opts, cb) {+ grpcState.recogCalls.push({ request, metadata });+ grpcState.recognize(request, metadata, opts, cb);+ }+ }+ const grpc = {+ Metadata,+ credentials: { createSsl: () => ({ ssl: true }) },+ loadPackageDefinition: () => ({+ nvidia: { riva: { tts: { RivaSpeechSynthesis }, asr: { RivaSpeechRecognition } } },+ }),+ };+ return { default: grpc };+});++vi.mock('@grpc/proto-loader', () => ({+ default: { fromJSON: () => ({ mockPackageDefinition: true }) },+}));++// Captured Riva shapes.+const PCM_BYTES = Buffer.alloc(2000, 0x42); // clearly not RIFF+function grpcTtsSuccess() {+ grpcState.synthesize = (_r, _m, _o, cb) => cb(null, { audio: PCM_BYTES });+}+function grpcAsrSuccess(transcript = 'schedule the deploy for friday') {+ grpcState.recognize = (_r, _m, _o, cb) =>+ cb(null, {+ results: [+ {+ alternatives: [{ transcript, confidence: 0.94, language_code: ['en-US'] }],+ audio_processed: 2.1,+ },+ ],+ });+}++// ── env ───────────────────────────────────────────────────────────────────────+const ENV_KEYS = [+ 'NVIDIA_API_KEY',+ 'NVIDIA_ASR_FUNCTION_ID',+ 'X402_PAY_TO_SOLANA',+ 'X402_ASSET_MINT_SOLANA',+ 'X402_FEE_PAYER_SOLANA',+];+const ORIGINAL_ENV = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));++// ── request/response harness ──────────────────────────────────────────────────+function makeReq({ method = 'POST', url = '/api/v1/ai/tts', headers = {}, body }) {+ const buf = body == null ? Buffer.alloc(0) : Buffer.isBuffer(body) ? body : Buffer.from(body);+ const req = Readable.from(buf.length ? [buf] : []);+ req.method = method;+ req.url = url;+ req.headers = { 'content-length': String(buf.length), ...headers };+ return req;+}++function makeRes() {+ const chunks = [];+ return {+ statusCode: 200,+ _h: {},+ writableEnded: false,+ headersSent: false,+ setHeader(k, v) {+ this._h[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this._h[k.toLowerCase()];+ },+ write(c) {+ chunks.push(Buffer.from(c));+ },+ end(c) {+ if (c) chunks.push(Buffer.from(c));+ this.writableEnded = true;+ },+ body() {+ return Buffer.concat(chunks);+ },+ json() {+ return JSON.parse(this.body().toString('utf8'));+ },+ };+}++let ttsHandler;+let asrHandler;+async function callTts(req) {+ const res = makeRes();+ await ttsHandler(req, res);+ return res;+}+async function callAsr(req) {+ const res = makeRes();+ await asrHandler(req, res);+ return res;+}++function jsonReq(url, obj, extraHeaders = {}) {+ return makeReq({+ method: 'POST',+ url,+ headers: { 'content-type': 'application/json', ...extraHeaders },+ body: JSON.stringify(obj),+ });+}++let ipCounter = 0;+function freshIp() {+ return { 'x-vercel-forwarded-for': `10.20.30.${++ipCounter}` };+}++beforeAll(async () => {+ // Warm the cold import of the x402-heavy route modules once (see vitest.config.js).+ ttsHandler = (await import('../../api/v1/ai/tts.js')).default;+ asrHandler = (await import('../../api/v1/ai/asr.js')).default;+}, 240_000);++beforeEach(() => {+ grpcState.synthesize = () => {+ throw new Error('grpc synthesize called without a test stub');+ };+ grpcState.recognize = () => {+ throw new Error('grpc recognize called without a test stub');+ };+ grpcState.synthCalls.length = 0;+ grpcState.recogCalls.length = 0;+ process.env.NVIDIA_API_KEY = 'nvapi-test-key';+ process.env.NVIDIA_ASR_FUNCTION_ID = 'test-asr-fn-id';+ // Minimal x402 config so the 402 fall-through can build a Solana accept.+ process.env.X402_PAY_TO_SOLANA = 'THREEsynthetic1111111111111111111111111PayTo';+ process.env.X402_ASSET_MINT_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+ process.env.X402_FEE_PAYER_SOLANA = 'THREEsynthetic1111111111111111111111111PayTo';+});++afterEach(() => {+ for (const k of ENV_KEYS) {+ if (ORIGINAL_ENV[k] === undefined) delete process.env[k];+ else process.env[k] = ORIGINAL_ENV[k];+ }+});++// ── TTS ─────────────────────────────────────────────────────────────────────+describe('POST /api/v1/ai/tts', () => {+ it('GET ?voices=1 lists voices free (no lane call)', async () => {+ const res = await callTts(makeReq({ method: 'GET', url: '/api/v1/ai/tts?voices=1', headers: freshIp() }));+ expect(res.statusCode).toBe(200);+ const data = res.json().data;+ expect(Array.isArray(data.voices)).toBe(true);+ expect(data.voices.length).toBeGreaterThan(0);+ expect(data.default).toBe('nova');+ expect(grpcState.synthCalls).toHaveLength(0);+ });++ it('serves the free tier on the NIM lane and returns base64 WAV', async () => {+ grpcTtsSuccess();+ const res = await callTts(jsonReq('/api/v1/ai/tts', { text: 'Deploy finished', voice: 'nova' }, freshIp()));+ expect(res.statusCode).toBe(200);+ const data = res.json().data;+ expect(data.tier).toBe('free');+ expect(data.content_type).toBe('audio/wav');+ expect(data.characters).toBe('Deploy finished'.length);+ const audio = Buffer.from(data.audio, 'base64');+ expect(audio.subarray(0, 4).toString('ascii')).toBe('RIFF');+ expect(audio.length).toBe(44 + PCM_BYTES.length);+ expect(grpcState.synthCalls).toHaveLength(1);+ });++ it('rejects empty text with 400 before any lane call', async () => {+ const res = await callTts(jsonReq('/api/v1/ai/tts', { text: ' ' }, freshIp()));+ expect(res.statusCode).toBe(400);+ expect(res.json().error).toBe('bad_request');+ expect(grpcState.synthCalls).toHaveLength(0);+ });++ it('rejects invalid JSON with 400', async () => {+ const res = await callTts(+ makeReq({ url: '/api/v1/ai/tts', headers: { 'content-type': 'application/json', ...freshIp() }, body: '{not json' }),+ );+ expect(res.statusCode).toBe(400);+ expect(grpcState.synthCalls).toHaveLength(0);+ });++ it('rejects text over the paid ceiling with 400 text_too_long', async () => {+ const res = await callTts(jsonReq('/api/v1/ai/tts', { text: 'a'.repeat(5000) }, freshIp()));+ expect(res.statusCode).toBe(400);+ expect(res.json().error).toBe('text_too_long');+ });++ it('text over the free char cap (≤4096) falls through to the 402 challenge', async () => {+ const res = await callTts(jsonReq('/api/v1/ai/tts', { text: 'b'.repeat(600) }, freshIp()));+ expect(res.statusCode).toBe(402);+ expect(grpcState.synthCalls).toHaveLength(0);+ });++ it('falls through to 402 once the daily free quota is exhausted', async () => {+ grpcTtsSuccess();+ const ip = { 'x-vercel-forwarded-for': '10.99.99.10' };+ for (let i = 0; i < 10; i++) {+ const ok = await callTts(jsonReq('/api/v1/ai/tts', { text: `call ${i}` }, ip));+ expect(ok.statusCode).toBe(200);+ }+ const over = await callTts(jsonReq('/api/v1/ai/tts', { text: 'one too many' }, ip));+ expect(over.statusCode).toBe(402);+ });++ it('returns 503 not_configured (naming NVIDIA_API_KEY) when the lane is absent', async () => {+ delete process.env.NVIDIA_API_KEY;+ const res = await callTts(jsonReq('/api/v1/ai/tts', { text: 'anyone there?' }, freshIp()));+ expect(res.statusCode).toBe(503);+ expect(res.json().error).toBe('not_configured');+ expect(res.json().error_description).toContain('NVIDIA_API_KEY');+ expect(grpcState.synthCalls).toHaveLength(0);+ });+});++// ── ASR ─────────────────────────────────────────────────────────────────────+describe('POST /api/v1/ai/asr', () => {+ // Build a tiny valid WAV from raw PCM so parseWav strips it correctly.+ async function wavClip(pcmBytes = 3200, sampleRate = 16000) {+ const { pcmToWav } = await import('../../api/_lib/tts-nvidia.js');+ return pcmToWav(Buffer.alloc(pcmBytes, 0x01), { sampleRateHz: sampleRate });+ }++ it('GET returns the capability probe', async () => {+ const res = await callAsr(makeReq({ method: 'GET', url: '/api/v1/ai/asr', headers: freshIp() }));+ expect(res.statusCode).toBe(200);+ const data = res.json().data;+ expect(data.configured).toBe(true);+ expect(data.encodings).toEqual(expect.arrayContaining(['wav', 'pcm', 'flac', 'ogg']));+ });++ it('transcribes a base64 WAV on the free tier', async () => {+ grpcAsrSuccess('hello world');+ const wav = await wavClip();+ const res = await callAsr(jsonReq('/api/v1/ai/asr', { audio: wav.toString('base64'), format: 'wav' }, freshIp()));+ expect(res.statusCode).toBe(200);+ const data = res.json().data;+ expect(data.tier).toBe('free');+ expect(data.text).toBe('hello world');+ expect(data.confidence).toBeCloseTo(0.94, 5);+ expect(data.duration).toBeCloseTo(2.1, 5);+ expect(grpcState.recogCalls).toHaveLength(1);+ });++ it('rejects a JSON body with no audio (400)', async () => {+ const res = await callAsr(jsonReq('/api/v1/ai/asr', { language: 'en-US' }, freshIp()));+ expect(res.statusCode).toBe(400);+ expect(res.json().error).toBe('bad_request');+ expect(grpcState.recogCalls).toHaveLength(0);+ });++ it('rejects an unsupported audio Content-Type (415)', async () => {+ const res = await callAsr(+ makeReq({ url: '/api/v1/ai/asr', headers: { 'content-type': 'audio/webm', ...freshIp() }, body: Buffer.alloc(500, 1) }),+ );+ expect(res.statusCode).toBe(415);+ expect(res.json().error).toBe('unsupported_media_type');+ expect(grpcState.recogCalls).toHaveLength(0);+ });++ it('rejects oversize audio with 413', async () => {+ const big = Buffer.alloc(8 * 1024 * 1024 + 1024, 0x00); // > 8 MiB decoded cap+ const res = await callAsr(+ makeReq({ url: '/api/v1/ai/asr', headers: { 'content-type': 'audio/wav', ...freshIp() }, body: big }),+ );+ expect(res.statusCode).toBe(413);+ expect(res.json().error).toBe('payload_too_large');+ expect(grpcState.recogCalls).toHaveLength(0);+ });++ it('audio longer than the free 60s cap falls through to the 402 challenge', async () => {+ // 16 kHz mono s16 → 60s = 1,920,000 PCM bytes; make it clearly longer.+ const longWav = await wavClip(2_100_000, 16000);+ const res = await callAsr(jsonReq('/api/v1/ai/asr', { audio: longWav.toString('base64'), format: 'wav' }, freshIp()));+ expect(res.statusCode).toBe(402);+ expect(grpcState.recogCalls).toHaveLength(0);+ });++ it('falls through to 402 once the daily free quota is exhausted', async () => {+ grpcAsrSuccess('ok');+ const wav = await wavClip();+ const ip = { 'x-vercel-forwarded-for': '10.99.99.20' };+ const b64 = wav.toString('base64');+ for (let i = 0; i < 5; i++) {+ const ok = await callAsr(jsonReq('/api/v1/ai/asr', { audio: b64, format: 'wav' }, ip));+ expect(ok.statusCode).toBe(200);+ }+ const over = await callAsr(jsonReq('/api/v1/ai/asr', { audio: b64, format: 'wav' }, ip));+ expect(over.statusCode).toBe(402);+ });++ it('returns 503 not_configured (naming the ASR env) when the lane is absent', async () => {+ delete process.env.NVIDIA_ASR_FUNCTION_ID;+ const wav = await wavClip();+ const res = await callAsr(jsonReq('/api/v1/ai/asr', { audio: wav.toString('base64'), format: 'wav' }, freshIp()));+ expect(res.statusCode).toBe(503);+ expect(res.json().error).toBe('not_configured');+ expect(res.json().error_description).toContain('NVIDIA_ASR_FUNCTION_ID');+ expect(grpcState.recogCalls).toHaveLength(0);+ });+});++// ── Catalog ───────────────────────────────────────────────────────────────────+describe('catalog registration', () => {+ it('lists both speech endpoints in api/v1/_catalog.js', async () => {+ const { CATALOG } = await import('../../api/v1/_catalog.js');+ const tts = CATALOG.find((e) => e.id === 'v1.ai.tts');+ const asr = CATALOG.find((e) => e.id === 'v1.ai.asr');+ expect(tts).toBeTruthy();+ expect(tts.path).toBe('/api/v1/ai/tts');+ expect(tts.method).toBe('POST');+ expect(asr).toBeTruthy();+ expect(asr.path).toBe('/api/v1/ai/asr');+ expect(asr.method).toBe('POST');+ });+});