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(x402): port x402-books as a native Solana x402 service
nirholas0ecc3007ce75
diff --git a/api/_lib/service-catalog/services/books-read.js b/api/_lib/service-catalog/services/books-read.jsnew file mode 100644index 000000000..5813c50ea--- /dev/null+++ b/api/_lib/service-catalog/services/books-read.js@@ -0,0 +1,36 @@+// Service-catalog descriptor: see news-pulse.js for the contract notes.+// Do not re-add a hand-written mirror for this route in api/wk.js.++export default {+ slug: 'books-read',+ title: 'Book Read',+ category: 'live-data',+ useCase: 'three.ws Book Read: $0.01 USDC per call delivers a complete public-domain Project Gutenberg book, boilerplate stripped and split into chapters, as markdown JSON.',+ path: '/api/x402/books-read',+ method: 'GET',+ free: false,+ status: 'live',+ priceAtomics: '10000',+ acceptsBuilder: 'standard',+ serviceName: 'three.ws Books',+ tags: ['books', 'live-data', 'gutenberg', 'full-text'],+ description: 'three.ws Book Read: pay $0.01 USDC per call to receive the complete text of a public-domain Project Gutenberg book, with the licence boilerplate stripped and the text split into chapters, delivered as markdown JSON in the response body. Find a gutenbergId with Book Search first.',+ input: { gutenbergId: 1342 },+ inputSchema: {+ type: 'object',+ required: ['gutenbergId'],+ properties: {+ gutenbergId: { type: 'integer', description: 'Project Gutenberg ebook id, from Book Search.' },+ },+ },+ outputExample: {+ source: 'gutenberg',+ gutenbergId: 1342,+ title: 'Pride and Prejudice',+ authors: ['Jane Austen'],+ chapterCount: 61,+ wordCount: 122000,+ chapters: [{ index: 1, title: 'Chapter I', markdown: 'It is a truth universally acknowledged...', wordCount: 450 }],+ },+ storefronts: ['x402scan'],+};diff --git a/api/_lib/service-catalog/services/books-search.js b/api/_lib/service-catalog/services/books-search.jsnew file mode 100644index 000000000..d7b3fedbe--- /dev/null+++ b/api/_lib/service-catalog/services/books-search.js@@ -0,0 +1,46 @@+// Service-catalog descriptor: see news-pulse.js for the contract notes.+// Do not re-add a hand-written mirror for this route in api/wk.js.++export default {+ slug: 'books-search',+ title: 'Book Search',+ category: 'live-data',+ useCase: 'three.ws Book Search: $0.001 USDC per call returns OpenLibrary editions for a title, each annotated with whether a clean Project Gutenberg full text is available to buy.',+ path: '/api/x402/books-search',+ method: 'GET',+ free: true,+ status: 'live',+ priceAtomics: '1000',+ acceptsBuilder: 'standard',+ serviceName: 'three.ws Books',+ tags: ['books', 'live-data', 'openlibrary', 'gutenberg'],+ description: 'three.ws Book Search: live public-data endpoint, no API key anywhere in the chain. Pay $0.001 USDC (or use the free daily per-IP quota) to search OpenLibrary editions by title (and optionally author) and get each edition annotated with whether a cleaned Project Gutenberg full text can be bought from Book Read, resolved live via Gutendex with a gutenberg.org fallback.',+ input: { q: 'pride and prejudice', limit: 5 },+ inputSchema: {+ type: 'object',+ required: ['q'],+ properties: {+ q: { type: 'string', description: 'Title to search for.' },+ author: { type: 'string', description: 'Optional author filter.' },+ limit: { type: 'integer', minimum: 1, maximum: 25, default: 5, description: 'Max editions to return.' },+ },+ },+ outputExample: {+ source: 'openlibrary+gutenberg',+ query: { q: 'pride and prejudice', author: null, limit: 5 },+ totalFound: 120,+ count: 1,+ editions: [+ {+ key: '/works/OL66554W',+ title: 'Pride and Prejudice',+ authors: ['Jane Austen'],+ firstPublishYear: 1813,+ ebookAccess: 'public',+ gutenberg: { available: true, gutenbergId: 1342, readPath: '/read/1342' },+ },+ ],+ retrievedAt: '2026-10-14T00:00:00Z',+ },+ storefronts: ['x402scan'],+};diff --git a/api/_lib/service-catalog/services/index.js b/api/_lib/service-catalog/services/index.jsindex e057accbd..ca5ee333e 100644--- a/api/_lib/service-catalog/services/index.js+++ b/api/_lib/service-catalog/services/index.js@@ -83,6 +83,8 @@ import domainsBulk from './domains-bulk.js';import researchSearch from './research-search.js';import researchPaper from './research-paper.js';import researchBibliography from './research-bibliography.js';+import booksSearch from './books-search.js';+import booksRead from './books-read.js';export const PAID_SERVICES = Object.freeze([modelCheck,@@ -155,4 +157,6 @@ export const PAID_SERVICES = Object.freeze([researchSearch,researchPaper,researchBibliography,+ booksSearch,+ booksRead,]);diff --git a/api/_lib/x402-services/books.js b/api/_lib/x402-services/books.jsnew file mode 100644index 000000000..1655786aa--- /dev/null+++ b/api/_lib/x402-services/books.js@@ -0,0 +1,293 @@+// Entirely keyless and entirely live:+// - Editions and availability from the OpenLibrary Search API.+// - Public-domain full text from Project Gutenberg, cleaned and chaptered.+// - Gutenberg availability from Gutendex, with a fallback to gutenberg.org's+// own search when Gutendex is unreachable.+// No fixture mode: every response is fetched live.++const THREE_WS_UA = 'three.ws/1.0 (+https://three.ws; [email protected])';+const OPENLIBRARY_BASE = 'https://openlibrary.org';+const GUTENDEX_BASE = 'https://gutendex.com';+const GUTENBERG_BASE = 'https://www.gutenberg.org';+const TIMEOUT_MS = 30_000;++async function get(url, accept = 'application/json') {+ return fetch(url, {+ headers: { 'user-agent': THREE_WS_UA, accept },+ signal: AbortSignal.timeout(TIMEOUT_MS),+ redirect: 'follow',+ });+}++function normalizeTitle(t) {+ return t+ .toLowerCase()+ .replace(/[^a-z0-9 ]+/g, ' ')+ .replace(/\b(the|a|an|or|and|of)\b/g, ' ')+ .replace(/\s+/g, ' ')+ .trim();+}++async function gutendexSearch(query) {+ try {+ const res = await get(`${GUTENDEX_BASE}/books?search=${encodeURIComponent(query)}`);+ if (!res.ok) return null;+ const body = await res.json();+ return body.results ?? [];+ } catch {+ return null;+ }+}++async function gutenbergSiteSearch(query) {+ try {+ const res = await get(`${GUTENBERG_BASE}/ebooks/search/?query=${encodeURIComponent(query)}`, 'text/html');+ if (!res.ok) return null;+ const html = await res.text();+ const out = [];+ const re = /href="\/ebooks\/(\d+)"[\s\S]{0,600}?<span class="title">([^<]*)<\/span>/g;+ let m;+ while ((m = re.exec(html)) !== null && out.length < 25) {+ out.push({ id: Number(m[1]), title: m[2].trim() });+ }+ return out;+ } catch {+ return null;+ }+}++async function gutenbergIndex(query) {+ const build = (entries) => {+ const index = new Map();+ for (const e of entries) {+ const key = normalizeTitle(e.title);+ if (!index.has(key)) index.set(key, e.id);+ }+ return index;+ };++ const viaGutendex = await gutendexSearch(query);+ if (viaGutendex) {+ return {+ index: build(viaGutendex.filter((b) => b.id != null && typeof b.title === 'string').map((b) => ({ id: b.id, title: b.title }))),+ };+ }+ const viaSite = await gutenbergSiteSearch(query);+ if (viaSite) {+ return { index: build(viaSite), note: 'Gutendex unreachable; availability resolved via gutenberg.org search.' };+ }+ return { index: new Map(), note: 'Gutenberg availability could not be determined (both Gutendex and gutenberg.org were unreachable).' };+}++function matchGutenberg(title, index) {+ const norm = normalizeTitle(title);+ if (index.has(norm)) return index.get(norm) ?? null;+ for (const [key, id] of index) {+ if (key.startsWith(norm) || norm.startsWith(key)) return id;+ }+ return null;+}++export async function searchBooks(q, author, limit) {+ const params = new URLSearchParams({+ q,+ limit: String(limit),+ fields: 'key,title,author_name,first_publish_year,edition_count,language,subject,cover_i,ebook_access,ia',+ });+ if (author) params.set('author', author);++ const res = await get(`${OPENLIBRARY_BASE}/search.json?${params.toString()}`);+ if (!res.ok) {+ const err = new Error(`OpenLibrary search failed: ${res.status} ${(await res.text()).slice(0, 200)}`);+ err.status = 502;+ err.code = 'upstream_error';+ throw err;+ }+ const body = await res.json();+ const docs = body.docs ?? [];++ const { index, note } = await gutenbergIndex(author ? `${q} ${author}` : q);++ const editions = docs.map((d) => {+ const title = d.title ?? '(untitled)';+ const gutenbergId = matchGutenberg(title, index);+ return {+ key: d.key ?? '',+ title,+ authors: d.author_name ?? [],+ firstPublishYear: d.first_publish_year ?? null,+ editionCount: d.edition_count ?? 0,+ languages: d.language ?? [],+ subjects: (d.subject ?? []).slice(0, 8),+ coverUrl: d.cover_i != null ? `https://covers.openlibrary.org/b/id/${d.cover_i}-M.jpg` : null,+ ebookAccess: d.ebook_access ?? null,+ internetArchiveIds: (d.ia ?? []).slice(0, 5),+ openLibraryUrl: d.key ? `${OPENLIBRARY_BASE}${d.key}` : OPENLIBRARY_BASE,+ gutenberg:+ gutenbergId != null+ ? { available: true, gutenbergId, readPath: `/read/${gutenbergId}` }+ : { available: false, gutenbergId: null, readPath: null, ...(note ? { note } : {}) },+ };+ });++ return {+ source: 'openlibrary+gutenberg',+ query: { q, author, limit },+ totalFound: body.numFound ?? editions.length,+ count: editions.length,+ editions,+ retrievedAt: new Date().toISOString(),+ };+}++async function gutenbergMetadata(id) {+ try {+ const res = await get(`${GUTENDEX_BASE}/books/${id}`);+ if (res.ok) {+ const b = await res.json();+ if (b.id != null) {+ return {+ title: b.title ?? `Project Gutenberg eBook ${id}`,+ authors: (b.authors ?? []).map((a) => a.name ?? '').filter(Boolean),+ languages: b.languages ?? [],+ subjects: (b.subjects ?? []).slice(0, 10),+ };+ }+ }+ } catch {+ // fall through to the RDF+ }++ try {+ const res = await get(`${GUTENBERG_BASE}/cache/epub/${id}/pg${id}.rdf`, 'application/rdf+xml');+ if (!res.ok) return null;+ const xml = await res.text();+ const one = (re) => re.exec(xml)?.[1]?.trim() ?? null;+ const all = (re) => [...xml.matchAll(re)].map((m) => m[1].trim());+ const title = one(/<dcterms:title>([\s\S]*?)<\/dcterms:title>/);+ if (!title) return null;+ return {+ title,+ authors: all(/<pgterms:name>([\s\S]*?)<\/pgterms:name>/g),+ languages: all(/<rdf:value[^>]*>([a-z]{2,3})<\/rdf:value>/g).slice(0, 2),+ subjects: all(/<rdf:value>([^<]{3,})<\/rdf:value>/g)+ .filter((v) => !/^[a-z]{2,3}$/.test(v))+ .slice(0, 10),+ };+ } catch {+ return null;+ }+}++function textUrls(id) {+ return [`${GUTENBERG_BASE}/cache/epub/${id}/pg${id}.txt`, `${GUTENBERG_BASE}/files/${id}/${id}-0.txt`, `${GUTENBERG_BASE}/ebooks/${id}.txt.utf-8`];+}++const START_MARKER = /^\*\*\*\s*START OF (?:THE|THIS) PROJECT GUTENBERG EBOOK[\s\S]*?\*\*\*$/im;+const END_MARKER = /^\*\*\*\s*END OF (?:THE|THIS) PROJECT GUTENBERG EBOOK[\s\S]*?\*\*\*$/im;++function stripBoilerplate(raw) {+ let text = raw.replace(/\r\n/g, '\n');+ const start = START_MARKER.exec(text);+ if (start) text = text.slice(start.index + start[0].length);+ const end = END_MARKER.exec(text);+ if (end) text = text.slice(0, end.index);+ return text.replace(/^\s*\n+/, '').replace(/\n{4,}/g, '\n\n\n');+}++const HEADING = /^\s{0,8}((?:chapter|letter|part|book|canto|act|scene|volume)\s+[a-z0-9ivxlcdm]+\.?)\s*$/i;++function toMarkdown(lines) {+ const paragraphs = [];+ let current = [];+ for (const line of lines) {+ if (line.trim().length === 0) {+ if (current.length > 0) {+ paragraphs.push(current.join(' ').replace(/\s+/g, ' ').trim());+ current = [];+ }+ } else {+ current.push(line.trim());+ }+ }+ if (current.length > 0) paragraphs.push(current.join(' ').replace(/\s+/g, ' ').trim());+ return paragraphs.filter((p) => p.length > 0).join('\n\n');+}++function countWords(s) {+ const m = s.match(/\S+/g);+ return m ? m.length : 0;+}++function chapterize(text) {+ const lines = text.split('\n');+ const marks = [];+ for (let i = 0; i < lines.length; i++) {+ const m = HEADING.exec(lines[i]);+ const prevBlank = i === 0 || lines[i - 1].trim() === '';+ const nextBlank = i + 1 >= lines.length || lines[i + 1].trim() === '';+ if (m && prevBlank && nextBlank) {+ marks.push({ line: i, title: m[1].replace(/\.$/, '').trim() });+ }+ }++ if (marks.length === 0) {+ const markdown = toMarkdown(lines);+ return { frontMatter: null, chapters: [{ index: 1, title: 'Full text', markdown, wordCount: countWords(markdown) }] };+ }++ const frontLines = lines.slice(0, marks[0].line);+ const frontMarkdown = toMarkdown(frontLines);++ const chapters = marks.map((mark, i) => {+ const from = mark.line + 1;+ const to = i + 1 < marks.length ? marks[i + 1].line : lines.length;+ const markdown = toMarkdown(lines.slice(from, to));+ return { index: i + 1, title: mark.title, markdown, wordCount: countWords(markdown) };+ });++ return { frontMatter: frontMarkdown.length > 0 ? frontMarkdown : null, chapters };+}++export async function readBook(gutenbergId) {+ let raw = null;+ let usedUrl = '';+ for (const url of textUrls(gutenbergId)) {+ try {+ const res = await get(url, 'text/plain');+ if (res.ok) {+ const body = await res.text();+ if (body.length > 2000 && !body.trimStart().startsWith('<')) {+ raw = body;+ usedUrl = url;+ break;+ }+ }+ } catch {+ // try the next candidate URL+ }+ }+ if (raw == null) return null;++ const meta = await gutenbergMetadata(gutenbergId);+ const cleaned = stripBoilerplate(raw);+ const { frontMatter, chapters } = chapterize(cleaned);+ const wordCount = chapters.reduce((n, c) => n + c.wordCount, 0) + countWords(frontMatter ?? '');++ return {+ source: 'gutenberg',+ gutenbergId,+ title: meta?.title ?? `Project Gutenberg eBook ${gutenbergId}`,+ authors: meta?.authors ?? [],+ languages: meta?.languages ?? [],+ subjects: meta?.subjects ?? [],+ textUrl: usedUrl,+ gutenbergUrl: `${GUTENBERG_BASE}/ebooks/${gutenbergId}`,+ rights: 'Public domain in the USA. Project Gutenberg licence applies to the source file; the cleaned text is derived from it.',+ chapterCount: chapters.length,+ wordCount,+ frontMatter,+ chapters,+ retrievedAt: new Date().toISOString(),+ };+}diff --git a/api/x402/books-read.js b/api/x402/books-read.jsnew file mode 100644index 000000000..01ca99c8b--- /dev/null+++ b/api/x402/books-read.js@@ -0,0 +1,67 @@+// GET /api/x402/books-read?gutenbergId=1342+//+// Book Read: $0.01 USDC per call, always paid (the free quota lives on+// books-search). Cleaned, chaptered Project Gutenberg full text.++import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema } from '../_lib/x402-spec.js';+import { installAccessControl } from '../_lib/x402/access-control.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import { priceFor } from '../_lib/x402-prices.js';+import { readBook } from '../_lib/x402-services/books.js';+import listing from '../_lib/service-catalog/services/books-read.js';++const ROUTE = '/api/x402/books-read';+const DESCRIPTION = listing.description;++export const INPUT_SCHEMA = { $schema: 'https://json-schema.org/draft/2020-12/schema', ...listing.inputSchema };+export const OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['source', 'gutenbergId', 'title', 'chapters'],+ properties: {+ source: { type: 'string' },+ gutenbergId: { type: 'integer' },+ title: { type: 'string' },+ chapterCount: { type: 'integer' },+ wordCount: { type: 'integer' },+ chapters: { type: 'array' },+ },+};++export const BAZAAR = {+ description: DESCRIPTION,+ useCases: ['reading agents', 'text analysis', 'public-domain archiving'],+ input: { type: 'query', example: listing.input, schema: INPUT_SCHEMA },+ output: { type: 'json', example: listing.outputExample },+ schema: buildBazaarSchema({ method: 'GET', queryParamsSchema: INPUT_SCHEMA, outputSchema: OUTPUT_SCHEMA }),+};++export default paidEndpoint({+ route: ROUTE,+ method: 'GET',+ priceAtomics: priceFor('books-read', '10000'), // $0.01 USDC+ networks: ['solana', 'base'],+ description: DESCRIPTION,+ bazaar: BAZAAR,+ service: withService({ serviceName: listing.serviceName, tags: listing.tags }),+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),+ async handler({ req }) {+ const params = new URL(req.url, 'http://x').searchParams;+ const idRaw = Number(params.get('gutenbergId'));+ if (!Number.isFinite(idRaw) || idRaw <= 0) {+ const err = new Error('query param "gutenbergId" must be a positive integer');+ err.status = 400;+ err.code = 'invalid_gutenberg_id';+ throw err;+ }+ const book = await readBook(Math.floor(idRaw));+ if (!book) {+ const err = new Error(`no readable Project Gutenberg text found for id ${idRaw}`);+ err.status = 404;+ err.code = 'not_found';+ throw err;+ }+ return book;+ },+});diff --git a/api/x402/books-search.js b/api/x402/books-search.jsnew file mode 100644index 000000000..64a584fbc--- /dev/null+++ b/api/x402/books-search.js@@ -0,0 +1,97 @@+// GET /api/x402/books-search?q=pride+and+prejudice&limit=5+//+// Book Search: $0.001 USDC per call (free daily per-IP quota runs first).+// Live OpenLibrary editions annotated with Gutenberg full-text availability.++import { cors, method, error, json, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema } from '../_lib/x402-spec.js';+import { installAccessControl } from '../_lib/x402/access-control.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import { priceFor } from '../_lib/x402-prices.js';+import { searchBooks } from '../_lib/x402-services/books.js';+import listing from '../_lib/service-catalog/services/books-search.js';++const ROUTE = '/api/x402/books-search';+const DESCRIPTION = listing.description;++export const INPUT_SCHEMA = { $schema: 'https://json-schema.org/draft/2020-12/schema', ...listing.inputSchema };+export const OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['source', 'count', 'editions'],+ properties: {+ source: { type: 'string' },+ totalFound: { type: 'integer' },+ count: { type: 'integer' },+ editions: { type: 'array' },+ tier: { type: 'string', enum: ['free', 'paid'] },+ free_remaining_today: { type: 'integer' },+ },+};++export const BAZAAR = {+ description: DESCRIPTION,+ useCases: ['book discovery', 'reading list building', 'library agents'],+ input: { type: 'query', example: listing.input, schema: INPUT_SCHEMA },+ output: { type: 'json', example: listing.outputExample },+ schema: buildBazaarSchema({ method: 'GET', queryParamsSchema: INPUT_SCHEMA, outputSchema: OUTPUT_SCHEMA }),+};++function parseParams(req) {+ const params = new URL(req.url, 'http://x').searchParams;+ const q = String(params.get('q') || '').trim();+ const author = params.get('author');+ const limitRaw = Number(params.get('limit') || '5');+ const limit = Math.min(25, Math.max(1, Number.isFinite(limitRaw) ? limitRaw : 5));+ return { q, author: author && author.trim() ? author.trim() : null, limit };+}++let _paid = null;+function paidHandler() {+ if (_paid) return _paid;+ _paid = paidEndpoint({+ route: ROUTE,+ method: 'GET',+ priceAtomics: priceFor('books-search', '1000'), // $0.001 USDC+ networks: ['solana', 'base'],+ description: DESCRIPTION,+ bazaar: BAZAAR,+ service: withService({ serviceName: listing.serviceName, tags: listing.tags }),+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),+ async handler({ req }) {+ const { q, author, limit } = parseParams(req);+ if (!q) {+ const err = new Error('query param "q" is required');+ err.status = 400;+ err.code = 'missing_query';+ throw err;+ }+ const data = await searchBooks(q, author, limit);+ return { ...data, tier: 'paid' };+ },+ });+ return _paid;+}++export default wrap(async function handler(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const paymentPresent = Boolean(req.headers['x-payment'] || req.headers['payment-signature']);+ if (paymentPresent) return paidHandler()(req, res);++ const rl = await limits.booksFreeIp(clientIp(req));+ if (!rl.success) return paidHandler()(req, res);++ const { q, author, limit } = parseParams(req);+ if (!q) return error(res, 400, 'missing_query', 'query param "q" is required');++ try {+ const data = await searchBooks(q, author, limit);+ return json(res, 200, { ...data, 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);+ }+});