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-carbon as a native Solana x402 service
nirholas228dafe28d65
diff --git a/api/_lib/service-catalog/services/carbon-best-window.js b/api/_lib/service-catalog/services/carbon-best-window.jsnew file mode 100644index 000000000..18fd33f0a--- /dev/null+++ b/api/_lib/service-catalog/services/carbon-best-window.js@@ -0,0 +1,35 @@+// 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: 'carbon-best-window',+ title: 'Grid Carbon: Best Window',+ category: 'live-data',+ useCase: 'three.ws Grid Carbon best window: $0.002 USDC per call scans the 48h UK grid carbon forecast and returns the lowest-carbon window to run a flexible load, plus runners-up, the worst window, and a plain-language recommendation.',+ path: '/api/x402/carbon-best-window',+ method: 'GET',+ free: false,+ status: 'live',+ priceAtomics: '2000',+ acceptsBuilder: 'standard',+ serviceName: 'three.ws Grid Carbon',+ tags: ['carbon', 'energy', 'live-data', 'uk-grid'],+ description: 'three.ws Grid Carbon best window: pay $0.002 USDC per call to scan the live 48h National Grid ESO carbon-intensity forecast for the lowest-carbon window of a given length (1 to 12 hours), nationally or for one GB postcode region. Returns the best window (mean + peak intensity), up to 3 non-overlapping runner-up windows, the worst window, and a plain-language recommendation, including a near-zero-carbon call-out and a marginal-savings warning when the forecast barely varies.',+ input: { hours: 4 },+ inputSchema: {+ type: 'object',+ properties: {+ hours: { type: 'number', minimum: 1, maximum: 12, default: 4, description: 'Length of the window to find, in hours.' },+ postcode: { type: 'string', description: 'GB postcode outcode, e.g. "SW1A". Omit for the national forecast.' },+ },+ },+ outputExample: {+ scope: 'national',+ hoursRequested: 4,+ best: { from: '2026-10-15T03:00Z', to: '2026-10-15T07:00Z', meanIntensity: 62, peakIntensity: 80 },+ worst: { from: '2026-10-14T18:00Z', to: '2026-10-14T22:00Z', meanIntensity: 210, peakIntensity: 240 },+ runnersUp: [{ from: '2026-10-15T08:00Z', to: '2026-10-15T12:00Z', meanIntensity: 75, peakIntensity: 95 }],+ recommendation: 'Best window 2026-10-15T03:00Z to 2026-10-15T07:00Z averages 62 gCO2/kWh, about 54% below the current reading.',+ },+ storefronts: ['x402scan'],+};diff --git a/api/_lib/service-catalog/services/carbon-now.js b/api/_lib/service-catalog/services/carbon-now.jsnew file mode 100644index 000000000..4731b9790--- /dev/null+++ b/api/_lib/service-catalog/services/carbon-now.js@@ -0,0 +1,33 @@+// 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: 'carbon-now',+ title: 'Grid Carbon: Now',+ category: 'live-data',+ useCase: 'three.ws Grid Carbon now: $0.001 USDC per call returns the current UK electricity grid carbon intensity (gCO2/kWh) and live generation mix, nationally or for one GB postcode region.',+ path: '/api/x402/carbon-now',+ method: 'GET',+ free: true,+ status: 'live',+ priceAtomics: '1000',+ acceptsBuilder: 'standard',+ serviceName: 'three.ws Grid Carbon',+ tags: ['carbon', 'energy', 'live-data', 'uk-grid'],+ description: 'three.ws Grid Carbon now: live public-data endpoint, no API key anywhere in the chain. Pay $0.001 USDC (or use the free daily per-IP quota) for the current UK national grid carbon intensity in gCO2/kWh with its forecast/actual/index reading and full generation mix, live from the National Grid ESO Carbon Intensity API. Pass a GB postcode outcode (e.g. "SW1A") to get the regional reading for that DNO region instead of the national figure.',+ input: {},+ inputSchema: {+ type: 'object',+ properties: {+ postcode: { type: 'string', description: 'GB postcode outcode, e.g. "SW1A". Omit for the national reading.' },+ },+ },+ outputExample: {+ scope: 'national',+ from: '2026-10-14T22:00Z',+ to: '2026-10-14T22:30Z',+ intensity: { forecast: 118, actual: 121, index: 'moderate' },+ generationmix: [{ fuel: 'wind', perc: 34.2 }, { fuel: 'gas', perc: 28.1 }, { fuel: 'nuclear', perc: 14.6 }],+ },+ storefronts: ['x402scan'],+};diff --git a/api/_lib/service-catalog/services/index.js b/api/_lib/service-catalog/services/index.jsindex 46a8549d8..b09645ffb 100644--- a/api/_lib/service-catalog/services/index.js+++ b/api/_lib/service-catalog/services/index.js@@ -76,6 +76,8 @@ import knock from './knock.js';// Scholar, OpenLibrary/Gutenberg, GDELT, MBTA GTFS, OSM Overpass).import weatherGuardForecast from './weather-guard-forecast.js';import weatherGuardDecision from './weather-guard-decision.js';+import carbonNow from './carbon-now.js';+import carbonBestWindow from './carbon-best-window.js';export const PAID_SERVICES = Object.freeze([modelCheck,@@ -141,4 +143,6 @@ export const PAID_SERVICES = Object.freeze([knock,weatherGuardForecast,weatherGuardDecision,+ carbonNow,+ carbonBestWindow,]);diff --git a/api/_lib/x402-services/carbon.js b/api/_lib/x402-services/carbon.jsnew file mode 100644index 000000000..f40480565--- /dev/null+++ b/api/_lib/x402-services/carbon.js@@ -0,0 +1,139 @@+// Live UK grid carbon intensity over the keyless National Grid ESO Carbon+// Intensity API (api.carbonintensity.org.uk). No API key, no fixture mode.+// National by default; regional when a GB postcode outcode is supplied.++const THREE_WS_UA = 'three.ws/1.0 (+https://three.ws; [email protected])';+const API_BASE = 'https://api.carbonintensity.org.uk';+const TIMEOUT_MS = 10_000;++function upstreamError(message, status, code, cause) {+ const err = new Error(message);+ err.status = status;+ err.code = code;+ if (cause) err.cause = cause;+ return err;+}++async function fetchJson(url) {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);+ try {+ const res = await fetch(url, { headers: { accept: 'application/json', 'user-agent': THREE_WS_UA }, signal: controller.signal });+ const text = await res.text();+ let data;+ try {+ data = text ? JSON.parse(text) : null;+ } catch {+ data = null;+ }+ if (!res.ok) {+ throw upstreamError(`carbon intensity API returned ${res.status}`, res.status >= 500 ? 502 : res.status, res.status === 429 ? 'upstream_rate_limited' : 'upstream_error');+ }+ return data;+ } catch (err) {+ if (err?.status) throw err;+ throw upstreamError('carbon intensity API is unreachable', 504, 'upstream_unreachable', err);+ } finally {+ clearTimeout(timer);+ }+}++function validateOutcode(postcode) {+ const v = String(postcode || '').trim().toUpperCase();+ // Outcode only (e.g. "SW1A", "EH1"), per the upstream API's own contract.+ if (!/^[A-Z]{1,2}[0-9][A-Z0-9]?$/.test(v)) {+ throw upstreamError('postcode must be a GB outcode, e.g. "SW1A" or "EH1"', 400, 'bad_request');+ }+ return v;+}++export async function now(postcode) {+ if (postcode) {+ const outcode = validateOutcode(postcode);+ const data = await fetchJson(`${API_BASE}/regional/postcode/${encodeURIComponent(outcode)}`);+ const region = data?.data?.[0];+ if (!region) throw upstreamError('no regional data for this postcode', 404, 'not_found');+ return {+ scope: 'regional',+ postcode: outcode,+ region: region.shortname,+ from: region.data?.[0]?.from,+ to: region.data?.[0]?.to,+ intensity: region.data?.[0]?.intensity,+ generationmix: region.data?.[0]?.generationmix,+ };+ }+ const [intensity, generation] = await Promise.all([+ fetchJson(`${API_BASE}/intensity`),+ fetchJson(`${API_BASE}/generation`),+ ]);+ const point = intensity?.data?.[0];+ if (!point) throw upstreamError('carbon intensity API returned no current reading', 502, 'upstream_error');+ return {+ scope: 'national',+ from: point.from,+ to: point.to,+ intensity: point.intensity,+ generationmix: generation?.data?.generationmix,+ };+}++function windowStats(points) {+ const values = points.map((p) => p.intensity?.forecast).filter((v) => typeof v === 'number');+ const mean = values.reduce((a, b) => a + b, 0) / (values.length || 1);+ const peak = Math.max(...values);+ return { mean: Number(mean.toFixed(1)), peak, from: points[0]?.from, to: points[points.length - 1]?.to };+}++export async function bestWindow({ hours = 4, postcode } = {}) {+ const slots = Math.max(1, Math.min(24, Math.round(Number(hours) * 2))); // half-hour slots+ const from = new Date().toISOString().slice(0, 16) + 'Z';+ let forecast;+ if (postcode) {+ const outcode = validateOutcode(postcode);+ const data = await fetchJson(`${API_BASE}/regional/intensity/${from}/fw48h/postcode/${encodeURIComponent(outcode)}`);+ forecast = data?.data?.data;+ } else {+ const data = await fetchJson(`${API_BASE}/intensity/${from}/fw48h`);+ forecast = data?.data;+ }+ if (!Array.isArray(forecast) || forecast.length < slots) {+ throw upstreamError('carbon intensity API returned an incomplete forecast window', 502, 'upstream_error');+ }++ const candidates = [];+ for (let i = 0; i + slots <= forecast.length; i++) {+ candidates.push({ startIdx: i, ...windowStats(forecast.slice(i, i + slots)) });+ }+ candidates.sort((a, b) => a.mean - b.mean);+ const best = candidates[0];+ const worst = candidates[candidates.length - 1];+ const runnersUp = [];+ for (const c of candidates.slice(1)) {+ if (runnersUp.length >= 3) break;+ const overlaps = runnersUp.some((r) => Math.abs(r.startIdx - c.startIdx) < slots) || Math.abs(best.startIdx - c.startIdx) < slots;+ if (!overlaps) runnersUp.push(c);+ }++ const nowPoint = forecast[0];+ const nowIntensity = nowPoint?.intensity?.forecast;+ const savingsPct = nowIntensity ? Math.round(((nowIntensity - best.mean) / nowIntensity) * 100) : null;+ let recommendation;+ if (best.mean <= 50) {+ recommendation = `Grid is near-zero carbon in the best window (${best.from} to ${best.to}, avg ${best.mean} gCO2/kWh). Run flexible loads then.`;+ } else if (savingsPct != null && savingsPct < 10) {+ recommendation = `Little variation ahead: the best window (${best.from} to ${best.to}) only saves about ${savingsPct}% over now. Timing shift is marginal.`;+ } else {+ recommendation = `Best window ${best.from} to ${best.to} averages ${best.mean} gCO2/kWh${savingsPct != null ? `, about ${savingsPct}% below the current reading` : ''}.`;+ }++ return {+ scope: postcode ? 'regional' : 'national',+ postcode: postcode ? validateOutcode(postcode) : undefined,+ hoursRequested: hours,+ best: { from: best.from, to: best.to, meanIntensity: best.mean, peakIntensity: best.peak },+ worst: { from: worst.from, to: worst.to, meanIntensity: worst.mean, peakIntensity: worst.peak },+ runnersUp: runnersUp.map((r) => ({ from: r.from, to: r.to, meanIntensity: r.mean, peakIntensity: r.peak })),+ recommendation,+ };+}diff --git a/api/x402/carbon-best-window.js b/api/x402/carbon-best-window.jsnew file mode 100644index 000000000..f661a0918--- /dev/null+++ b/api/x402/carbon-best-window.js@@ -0,0 +1,58 @@+// GET /api/x402/carbon-best-window?hours=4&postcode=SW1A+//+// Grid Carbon: Best Window: $0.002 USDC per call, always paid (the free+// quota lives on carbon-now). Scans the live 48h National Grid ESO forecast+// for the lowest-carbon window.++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 { bestWindow } from '../_lib/x402-services/carbon.js';+import listing from '../_lib/service-catalog/services/carbon-best-window.js';++const ROUTE = '/api/x402/carbon-best-window';+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: ['scope', 'best', 'worst', 'runnersUp', 'recommendation'],+ properties: {+ scope: { type: 'string', enum: ['national', 'regional'] },+ postcode: { type: 'string' },+ hoursRequested: { type: 'number' },+ best: { type: 'object' },+ worst: { type: 'object' },+ runnersUp: { type: 'array' },+ recommendation: { type: 'string' },+ },+};++export const BAZAAR = {+ description: DESCRIPTION,+ useCases: ['load scheduling', 'ev charging', 'battery dispatch'],+ 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('carbon-best-window', '2000'), // $0.002 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 hoursRaw = Number(params.get('hours') || '4');+ const hours = Math.min(12, Math.max(1, Number.isFinite(hoursRaw) ? hoursRaw : 4));+ const postcode = params.get('postcode');+ return bestWindow({ hours, postcode: postcode && postcode.trim() ? postcode.trim() : undefined });+ },+});diff --git a/api/x402/carbon-now.js b/api/x402/carbon-now.jsnew file mode 100644index 000000000..ec9a9022b--- /dev/null+++ b/api/x402/carbon-now.js@@ -0,0 +1,89 @@+// GET /api/x402/carbon-now?postcode=SW1A+//+// Grid Carbon: Now: $0.001 USDC per call (free daily per-IP quota runs+// first). Live UK grid carbon intensity + generation mix from the National+// Grid ESO Carbon Intensity API. No API key, no fixture mode.++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 { now as carbonNow } from '../_lib/x402-services/carbon.js';+import listing from '../_lib/service-catalog/services/carbon-now.js';++const ROUTE = '/api/x402/carbon-now';+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: ['scope', 'intensity'],+ properties: {+ scope: { type: 'string', enum: ['national', 'regional'] },+ postcode: { type: 'string' },+ region: { type: 'string' },+ from: { type: 'string' },+ to: { type: 'string' },+ intensity: { type: 'object' },+ generationmix: { type: 'array' },+ tier: { type: 'string', enum: ['free', 'paid'] },+ free_remaining_today: { type: 'integer' },+ },+};++export const BAZAAR = {+ description: DESCRIPTION,+ useCases: ['load scheduling', 'carbon reporting', 'grid-aware automation'],+ 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 readPostcode(params) {+ const raw = params.get('postcode');+ return raw && raw.trim() ? raw.trim() : undefined;+}++let _paid = null;+function paidHandler() {+ if (_paid) return _paid;+ _paid = paidEndpoint({+ route: ROUTE,+ method: 'GET',+ priceAtomics: priceFor('carbon-now', '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 params = new URL(req.url, 'http://x').searchParams;+ const data = await carbonNow(readPostcode(params));+ 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.carbonFreeIp(clientIp(req));+ if (!rl.success) return paidHandler()(req, res);++ try {+ const params = new URL(req.url, 'http://x').searchParams;+ const data = await carbonNow(readPostcode(params));+ 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);+ }+});