Skip to content

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

feat(x402): port x402-weather-guard as a native Solana x402 service

nirholasb239cb926e43
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index d3ef97c89..5cf507cc7 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -1940,6 +1940,31 @@ export const limits = {
// a Redis outage fails closed to the paid rail rather than opening the chain.
factCheckFreeIp: (ip) =>
getLimiter('fact-check:free:ip', { limit: 3, window: '1 d', critical: true }).limit(ip),
+ // Keyless x402 services (api/x402/{weather-guard,carbon,domains,research,
+ // books,news-wire,transit,places}): each ports a live public-data API with
+ // no API key at all, so the free lane costs us nothing but the upstream's
+ // goodwill. Quotas are sized to each upstream's own tolerance, tightest
+ // for the ones that actively rate-limit or ask for restraint (GDELT's
+ // 5.1s min-gap, Overpass's shared community infra), loosest for the ones
+ // built for exactly this kind of polling (Open-Meteo, UK Carbon Intensity,
+ // MBTA's public GTFS feed). Critical: a Redis outage fails closed to the
+ // paid rail rather than opening an unmetered proxy to the upstream.
+ weatherGuardFreeIp: (ip) =>
+ getLimiter('weather-guard:free:ip', { limit: 20, window: '1 d', critical: true }).limit(ip),
+ carbonFreeIp: (ip) =>
+ getLimiter('carbon:free:ip', { limit: 20, window: '1 d', critical: true }).limit(ip),
+ domainsFreeIp: (ip) =>
+ getLimiter('domains:free:ip', { limit: 15, window: '1 d', critical: true }).limit(ip),
+ researchFreeIp: (ip) =>
+ getLimiter('research:free:ip', { limit: 10, window: '1 d', critical: true }).limit(ip),
+ booksFreeIp: (ip) =>
+ getLimiter('books:free:ip', { limit: 10, window: '1 d', critical: true }).limit(ip),
+ newsWireFreeIp: (ip) =>
+ getLimiter('news-wire:free:ip', { limit: 5, window: '1 d', critical: true }).limit(ip),
+ transitFreeIp: (ip) =>
+ getLimiter('transit:free:ip', { limit: 20, window: '1 d', critical: true }).limit(ip),
+ placesFreeIp: (ip) =>
+ getLimiter('places:free:ip', { limit: 15, 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 per
diff --git a/api/_lib/service-catalog/services/index.js b/api/_lib/service-catalog/services/index.js
index a4218e5eb..46a8549d8 100644
--- a/api/_lib/service-catalog/services/index.js
+++ b/api/_lib/service-catalog/services/index.js
@@ -71,6 +71,11 @@ import walletConnect from './wallet-connect.js';
import robinhoodPortfolio from './robinhood-portfolio.js';
import printOrder from './print-order.js';
import knock from './knock.js';
+// Keyless x402 suite: live public-data ports, no API key anywhere in the
+// chain (Open-Meteo/NWS, UK Carbon Intensity, RDAP, arXiv/Crossref/Semantic
+// Scholar, OpenLibrary/Gutenberg, GDELT, MBTA GTFS, OSM Overpass).
+import weatherGuardForecast from './weather-guard-forecast.js';
+import weatherGuardDecision from './weather-guard-decision.js';
export const PAID_SERVICES = Object.freeze([
modelCheck,
@@ -134,4 +139,6 @@ export const PAID_SERVICES = Object.freeze([
robinhoodPortfolio,
printOrder,
knock,
+ weatherGuardForecast,
+ weatherGuardDecision,
]);
diff --git a/api/_lib/service-catalog/services/weather-guard-decision.js b/api/_lib/service-catalog/services/weather-guard-decision.js
new file mode 100644
index 000000000..380c4394f
--- /dev/null
+++ b/api/_lib/service-catalog/services/weather-guard-decision.js
@@ -0,0 +1,38 @@
+// 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: 'weather-guard-decision',
+ title: 'Weather Guard: Activity Decision',
+ category: 'live-data',
+ useCase: 'three.ws Weather Guard decision: $0.002 USDC per call turns a live forecast into a go / caution / no-go verdict for a specific outdoor activity (running, cycling, outdoor-event, drone-flight, photography), with the exact reasons behind the call.',
+ path: '/api/x402/weather-guard-decision',
+ method: 'GET',
+ free: false,
+ status: 'live',
+ priceAtomics: '2000',
+ acceptsBuilder: 'standard',
+ serviceName: 'three.ws Weather Guard',
+ tags: ['weather', 'decision', 'live-data', 'open-meteo'],
+ description: 'three.ws Weather Guard decision: pay $0.002 USDC per call to turn the next 6 hours of live forecast at any lat/lon into a go / caution / no-go verdict for a named activity. Each activity (running, cycling, outdoor-event, drone-flight, photography) carries its own wind, precipitation and weather-code thresholds; the response lists every reason a threshold was crossed, the live forecast window it judged, and any active NWS severe-weather alert that forced a no-go. Same live Open-Meteo/NWS sourcing as weather-guard-forecast.',
+ input: { lat: 42.3601, lon: -71.0589, activity: 'running' },
+ inputSchema: {
+ type: 'object',
+ required: ['lat', 'lon', 'activity'],
+ properties: {
+ lat: { type: 'number', minimum: -90, maximum: 90, description: 'Latitude.' },
+ lon: { type: 'number', minimum: -180, maximum: 180, description: 'Longitude.' },
+ activity: { type: 'string', enum: ['running', 'cycling', 'outdoor-event', 'drone-flight', 'photography'] },
+ },
+ },
+ outputExample: {
+ activity: 'running',
+ verdict: 'caution',
+ reasons: ['wind 38 km/h exceeds 35 km/h at 2026-10-14T15:00'],
+ source: 'open-meteo',
+ failedOver: false,
+ window: [{ time: '2026-10-14T12:00', tempC: 14.2, precipProbPct: 10, windKph: 11.4, weatherCode: 2, conditions: 'partly cloudy' }],
+ alerts: [],
+ },
+ storefronts: ['x402scan'],
+};
diff --git a/api/_lib/service-catalog/services/weather-guard-forecast.js b/api/_lib/service-catalog/services/weather-guard-forecast.js
new file mode 100644
index 000000000..e41a16878
--- /dev/null
+++ b/api/_lib/service-catalog/services/weather-guard-forecast.js
@@ -0,0 +1,37 @@
+// 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: 'weather-guard-forecast',
+ title: 'Weather Guard: Forecast',
+ category: 'live-data',
+ useCase: 'three.ws Weather Guard forecast: $0.001 USDC per call returns a 24h hourly forecast (temperature, wind, precipitation chance, WMO conditions) plus active severe-weather alerts for any lat/lon, live from Open-Meteo with a US National Weather Service fallback.',
+ path: '/api/x402/weather-guard-forecast',
+ method: 'GET',
+ free: true,
+ status: 'live',
+ priceAtomics: '1000',
+ acceptsBuilder: 'standard',
+ serviceName: 'three.ws Weather Guard',
+ tags: ['weather', 'forecast', 'live-data', 'open-meteo'],
+ description: 'three.ws Weather Guard forecast: 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 next 24 hours of hourly temperature, wind speed, precipitation probability and WMO weather conditions at any latitude/longitude, sourced live from Open-Meteo. Falls over to the US National Weather Service automatically if Open-Meteo is unreachable, and always layers in active NWS severe-weather alerts for US coordinates. Real upstream calls only; a dead upstream refuses before settlement rather than serving stale or fabricated data.',
+ input: { lat: 42.3601, lon: -71.0589 },
+ inputSchema: {
+ type: 'object',
+ required: ['lat', 'lon'],
+ properties: {
+ lat: { type: 'number', minimum: -90, maximum: 90, description: 'Latitude.' },
+ lon: { type: 'number', minimum: -180, maximum: 180, description: 'Longitude.' },
+ },
+ },
+ outputExample: {
+ source: 'open-meteo',
+ lat: 42.3601,
+ lon: -71.0589,
+ failedOver: false,
+ current: { tempC: 14.2, windKph: 11.4, weatherCode: 2, conditions: 'partly cloudy' },
+ hourly: [{ time: '2026-10-14T12:00', tempC: 14.2, precipProbPct: 10, windKph: 11.4, weatherCode: 2, conditions: 'partly cloudy' }],
+ alerts: [],
+ },
+ storefronts: ['x402scan'],
+};
diff --git a/api/_lib/x402-services/weather-guard.js b/api/_lib/x402-services/weather-guard.js
new file mode 100644
index 000000000..4d9bc1a2c
--- /dev/null
+++ b/api/_lib/x402-services/weather-guard.js
@@ -0,0 +1,244 @@
+// Live weather + go/no-go activity verdicts over two keyless public sources:
+// Open-Meteo (global, primary) and the US National Weather Service (fallback
+// when Open-Meteo is unreachable, and the only source for active alerts).
+// No API key, no fixture mode: every call hits the real upstream.
+//
+// Both upstreams are free and ask only for a polite, identifiable User-Agent
+// (NWS actively 403s a request that omits one): see THREE_WS_UA below.
+
+const THREE_WS_UA = 'three.ws/1.0 (+https://three.ws; [email protected])';
+const TIMEOUT_MS = 10_000;
+
+// WMO weather codes (shared by Open-Meteo's `current_weather`/`hourly.weathercode`).
+// https://open-meteo.com/en/docs: "WMO Weather interpretation codes"
+const WMO_CODES = {
+ 0: 'clear sky', 1: 'mainly clear', 2: 'partly cloudy', 3: 'overcast',
+ 45: 'fog', 48: 'depositing rime fog',
+ 51: 'light drizzle', 53: 'moderate drizzle', 55: 'dense drizzle',
+ 56: 'light freezing drizzle', 57: 'dense freezing drizzle',
+ 61: 'slight rain', 63: 'moderate rain', 65: 'heavy rain',
+ 66: 'light freezing rain', 67: 'heavy freezing rain',
+ 71: 'slight snow', 73: 'moderate snow', 75: 'heavy snow', 77: 'snow grains',
+ 80: 'slight rain showers', 81: 'moderate rain showers', 82: 'violent rain showers',
+ 85: 'slight snow showers', 86: 'heavy snow showers',
+ 95: 'thunderstorm', 96: 'thunderstorm with slight hail', 99: 'thunderstorm with heavy hail',
+};
+
+// Per-activity thresholds a verdict is checked against. Each threshold is the
+// upper bound the activity still tolerates; crossing any one drops the
+// verdict a notch (go -> caution -> no-go).
+const ACTIVITY_PROFILES = {
+ running: { maxWindKph: 35, maxPrecipProb: 60, badCodes: new Set([65, 67, 75, 82, 86, 95, 96, 99]) },
+ cycling: { maxWindKph: 25, maxPrecipProb: 40, badCodes: new Set([61, 63, 65, 66, 67, 71, 73, 75, 80, 81, 82, 85, 86, 95, 96, 99]) },
+ 'outdoor-event': { maxWindKph: 30, maxPrecipProb: 30, badCodes: new Set([61, 63, 65, 66, 67, 71, 73, 75, 77, 80, 81, 82, 85, 86, 95, 96, 99]) },
+ 'drone-flight': { maxWindKph: 20, maxPrecipProb: 20, badCodes: new Set([45, 48, 51, 53, 55, 56, 57, 61, 63, 65, 66, 67, 71, 73, 75, 77, 80, 81, 82, 85, 86, 95, 96, 99]) },
+ photography: { maxWindKph: 40, maxPrecipProb: 50, badCodes: new Set([65, 67, 75, 95, 96, 99]) },
+};
+
+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, { timeoutMs = TIMEOUT_MS } = {}) {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
+ 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(
+ `upstream returned ${res.status}`,
+ res.status >= 500 ? 502 : res.status,
+ res.status === 429 ? 'upstream_rate_limited' : 'upstream_error',
+ );
+ }
+ return data;
+ } catch (err) {
+ clearTimeout(timer);
+ if (err?.status) throw err;
+ throw upstreamError('upstream is unreachable', 504, 'upstream_unreachable', err);
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+function validateCoords(lat, lon) {
+ const latNum = Number(lat);
+ const lonNum = Number(lon);
+ if (!Number.isFinite(latNum) || latNum < -90 || latNum > 90) {
+ throw upstreamError('lat must be a number between -90 and 90', 400, 'bad_request');
+ }
+ if (!Number.isFinite(lonNum) || lonNum < -180 || lonNum > 180) {
+ throw upstreamError('lon must be a number between -180 and 180', 400, 'bad_request');
+ }
+ return { lat: latNum, lon: lonNum };
+}
+
+function isInContinentalUsRoughly(lat, lon) {
+ // NWS only covers the US + territories. A rough bounding check avoids
+ // burning the fallback path on an upstream that would 404 anyway.
+ return lat >= 18 && lat <= 72 && lon >= -180 && lon <= -65;
+}
+
+async function fromOpenMeteo(lat, lon) {
+ const url = new URL('https://api.open-meteo.com/v1/forecast');
+ url.searchParams.set('latitude', String(lat));
+ url.searchParams.set('longitude', String(lon));
+ url.searchParams.set('current_weather', 'true');
+ url.searchParams.set('hourly', 'temperature_2m,precipitation_probability,windspeed_10m,weathercode');
+ url.searchParams.set('forecast_days', '2');
+ url.searchParams.set('timezone', 'auto');
+ const data = await fetchJson(url);
+ const hourly = data?.hourly;
+ if (!hourly?.time) throw upstreamError('open-meteo returned no hourly series', 502, 'upstream_error');
+ const nowIso = new Date().toISOString().slice(0, 13);
+ const startIdx = Math.max(0, hourly.time.findIndex((t) => t.startsWith(nowIso)));
+ const slice = (arr) => arr.slice(startIdx, startIdx + 24);
+ return {
+ source: 'open-meteo',
+ timezone: data.timezone,
+ current: {
+ tempC: data.current_weather?.temperature ?? null,
+ windKph: data.current_weather?.windspeed != null ? data.current_weather.windspeed : null,
+ weatherCode: data.current_weather?.weathercode ?? null,
+ conditions: WMO_CODES[data.current_weather?.weathercode] || 'unknown',
+ },
+ hourly: slice(hourly.time).map((t, i) => ({
+ time: t,
+ tempC: slice(hourly.temperature_2m)[i] ?? null,
+ precipProbPct: slice(hourly.precipitation_probability)[i] ?? null,
+ windKph: slice(hourly.windspeed_10m)[i] ?? null,
+ weatherCode: slice(hourly.weathercode)[i] ?? null,
+ conditions: WMO_CODES[slice(hourly.weathercode)[i]] || 'unknown',
+ })),
+ };
+}
+
+// NWS fallback: only reachable (and only useful) for US coordinates. Two hops
+// are required by the API itself: /points resolves the forecast office +
+// gridpoint, then that URL serves the actual forecast periods.
+async function fromNws(lat, lon) {
+ if (!isInContinentalUsRoughly(lat, lon)) {
+ throw upstreamError('NWS has no coverage outside the US', 502, 'upstream_error');
+ }
+ const point = await fetchJson(`https://api.weather.gov/points/${lat.toFixed(4)},${lon.toFixed(4)}`);
+ const forecastUrl = point?.properties?.forecastHourly;
+ if (!forecastUrl) throw upstreamError('NWS returned no forecast grid for this point', 502, 'upstream_error');
+ const forecast = await fetchJson(forecastUrl);
+ const periods = Array.isArray(forecast?.properties?.periods) ? forecast.properties.periods : [];
+ return {
+ source: 'nws',
+ timezone: point?.properties?.timeZone || null,
+ current: periods[0]
+ ? {
+ tempC: typeof periods[0].temperature === 'number'
+ ? (periods[0].temperatureUnit === 'F' ? (periods[0].temperature - 32) / 1.8 : periods[0].temperature)
+ : null,
+ windKph: periods[0].windSpeed ? parseFloat(periods[0].windSpeed) * 1.60934 : null,
+ weatherCode: null,
+ conditions: periods[0].shortForecast || 'unknown',
+ }
+ : null,
+ hourly: periods.slice(0, 24).map((p) => ({
+ time: p.startTime,
+ tempC: typeof p.temperature === 'number'
+ ? (p.temperatureUnit === 'F' ? (p.temperature - 32) / 1.8 : p.temperature)
+ : null,
+ precipProbPct: p.probabilityOfPrecipitation?.value ?? null,
+ windKph: p.windSpeed ? parseFloat(p.windSpeed) * 1.60934 : null,
+ weatherCode: null,
+ conditions: p.shortForecast || 'unknown',
+ })),
+ };
+}
+
+// Active NWS alerts for a point (watches/warnings). US-only; returns an empty
+// list (not an error) outside NWS coverage, since this is an enrichment, not
+// the primary payload.
+async function nwsAlerts(lat, lon) {
+ if (!isInContinentalUsRoughly(lat, lon)) return [];
+ try {
+ const data = await fetchJson(`https://api.weather.gov/alerts/active?point=${lat.toFixed(4)},${lon.toFixed(4)}`);
+ return (data?.features || []).map((f) => ({
+ event: f.properties?.event,
+ severity: f.properties?.severity,
+ headline: f.properties?.headline,
+ expires: f.properties?.expires,
+ }));
+ } catch {
+ return [];
+ }
+}
+
+export async function forecast(lat, lon) {
+ const coords = validateCoords(lat, lon);
+ let base;
+ let failedOver = false;
+ try {
+ base = await fromOpenMeteo(coords.lat, coords.lon);
+ } catch (err) {
+ if (!isInContinentalUsRoughly(coords.lat, coords.lon)) throw err;
+ base = await fromNws(coords.lat, coords.lon);
+ failedOver = true;
+ }
+ const alerts = await nwsAlerts(coords.lat, coords.lon);
+ return { ...base, lat: coords.lat, lon: coords.lon, failedOver, alerts };
+}
+
+export async function decision(lat, lon, activity) {
+ const profile = ACTIVITY_PROFILES[activity];
+ if (!profile) {
+ throw upstreamError(
+ `unknown activity "${activity}": choose one of ${Object.keys(ACTIVITY_PROFILES).join(', ')}`,
+ 400,
+ 'bad_request',
+ );
+ }
+ const data = await forecast(lat, lon);
+ const window = data.hourly.slice(0, 6);
+ const reasons = [];
+ let verdict = 'go';
+ const worsen = (to, reason) => {
+ reasons.push(reason);
+ if (to === 'no-go' || verdict === 'no-go') verdict = 'no-go';
+ else if (to === 'caution') verdict = 'caution';
+ };
+ for (const hour of window) {
+ if (profile.badCodes.has(hour.weatherCode)) {
+ worsen('no-go', `${hour.conditions} expected at ${hour.time}`);
+ }
+ if (hour.windKph != null && hour.windKph > profile.maxWindKph) {
+ worsen('caution', `wind ${hour.windKph.toFixed(0)} km/h exceeds ${profile.maxWindKph} km/h at ${hour.time}`);
+ }
+ if (hour.precipProbPct != null && hour.precipProbPct > profile.maxPrecipProb) {
+ worsen('caution', `${hour.precipProbPct}% precipitation chance exceeds ${profile.maxPrecipProb}% at ${hour.time}`);
+ }
+ }
+ if (data.alerts.some((a) => /warning/i.test(a.severity || '') || /extreme|severe/i.test(a.severity || ''))) {
+ worsen('no-go', `active NWS alert: ${data.alerts[0].event}`);
+ }
+ return {
+ activity,
+ verdict,
+ reasons: reasons.length ? reasons : ['no threshold exceeded in the next 6 hours'],
+ source: data.source,
+ failedOver: data.failedOver,
+ window,
+ alerts: data.alerts,
+ };
+}
+
+export const WEATHER_GUARD_ACTIVITIES = Object.keys(ACTIVITY_PROFILES);
diff --git a/api/x402/weather-guard-decision.js b/api/x402/weather-guard-decision.js
new file mode 100644
index 000000000..e8132040b
--- /dev/null
+++ b/api/x402/weather-guard-decision.js
@@ -0,0 +1,67 @@
+// GET /api/x402/weather-guard-decision?lat=..&lon=..&activity=running
+//
+// Weather Guard: Activity Decision: $0.002 USDC per call, always paid (the
+// free quota lives on weather-guard-forecast). Turns the live forecast into
+// a go/caution/no-go verdict for a named outdoor activity.
+
+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 { decision, WEATHER_GUARD_ACTIVITIES } from '../_lib/x402-services/weather-guard.js';
+import listing from '../_lib/service-catalog/services/weather-guard-decision.js';
+
+const ROUTE = '/api/x402/weather-guard-decision';
+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: ['activity', 'verdict', 'reasons', 'source', 'window', 'alerts'],
+ properties: {
+ activity: { type: 'string' },
+ verdict: { type: 'string', enum: ['go', 'caution', 'no-go'] },
+ reasons: { type: 'array', items: { type: 'string' } },
+ source: { type: 'string', enum: ['open-meteo', 'nws'] },
+ failedOver: { type: 'boolean' },
+ window: { type: 'array' },
+ alerts: { type: 'array' },
+ },
+};
+
+export const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['go/no-go planning', 'drone operations', 'event logistics'],
+ 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('weather-guard-decision', '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 lat = params.get('lat');
+ const lon = params.get('lon');
+ const activity = (params.get('activity') || '').trim();
+ if (lat == null || lon == null || lat === '' || lon === '') {
+ throw Object.assign(new Error('lat and lon query params are required'), { status: 400, code: 'bad_request' });
+ }
+ if (!WEATHER_GUARD_ACTIVITIES.includes(activity)) {
+ throw Object.assign(
+ new Error(`activity must be one of: ${WEATHER_GUARD_ACTIVITIES.join(', ')}`),
+ { status: 422, code: 'invalid_activity' },
+ );
+ }
+ return decision(lat, lon, activity);
+ },
+});
diff --git a/api/x402/weather-guard-forecast.js b/api/x402/weather-guard-forecast.js
new file mode 100644
index 000000000..ab3af77dc
--- /dev/null
+++ b/api/x402/weather-guard-forecast.js
@@ -0,0 +1,108 @@
+// GET /api/x402/weather-guard-forecast?lat=..&lon=..
+//
+// Weather Guard: Forecast: $0.001 USDC per call (free daily per-IP quota
+// runs first). Live 24h hourly forecast from Open-Meteo, failing over to the
+// US National Weather Service when Open-Meteo is unreachable, with active
+// NWS severe-weather alerts layered in for US coordinates. No API key
+// anywhere in the chain; 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 { forecast } from '../_lib/x402-services/weather-guard.js';
+import listing from '../_lib/service-catalog/services/weather-guard-forecast.js';
+
+const ROUTE = '/api/x402/weather-guard-forecast';
+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', 'lat', 'lon', 'current', 'hourly', 'alerts'],
+ properties: {
+ source: { type: 'string', enum: ['open-meteo', 'nws'] },
+ lat: { type: 'number' },
+ lon: { type: 'number' },
+ failedOver: { type: 'boolean' },
+ current: { type: ['object', 'null'] },
+ hourly: { type: 'array' },
+ alerts: { type: 'array' },
+ tier: { type: 'string', enum: ['free', 'paid'] },
+ free_remaining_today: { type: 'integer' },
+ },
+};
+
+export const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['go/no-go planning', 'agronomy', 'logistics routing', 'outdoor events'],
+ 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 parseCoords(params) {
+ const lat = params.get('lat');
+ const lon = params.get('lon');
+ if (lat == null || lon == null || lat === '' || lon === '') {
+ throw Object.assign(new Error('lat and lon query params are required'), { status: 400, code: 'bad_request' });
+ }
+ return { lat, lon };
+}
+
+let _paid = null;
+function paidHandler() {
+ if (_paid) return _paid;
+ _paid = paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ priceAtomics: priceFor('weather-guard-forecast', '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 { lat, lon } = parseCoords(params);
+ const data = await forecast(lat, lon);
+ 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 params = new URL(req.url, 'http://x').searchParams;
+ let coords;
+ try {
+ coords = parseCoords(params);
+ } catch (e) {
+ return error(res, e.status || 400, e.code || 'bad_request', e.message);
+ }
+
+ const paymentPresent = Boolean(req.headers['x-payment'] || req.headers['payment-signature']);
+ if (paymentPresent) return paidHandler()(req, res);
+
+ const rl = await limits.weatherGuardFreeIp(clientIp(req));
+ if (!rl.success) return paidHandler()(req, res);
+
+ try {
+ const data = await forecast(coords.lat, coords.lon);
+ 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);
+ }
+});