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-news-wire, x402-transit, x402-places as native Solana x402 services

nirholas48d05d9a7349
diff --git a/api/_lib/service-catalog/services/index.js b/api/_lib/service-catalog/services/index.js
index ca5ee333e..430a29079 100644
--- a/api/_lib/service-catalog/services/index.js
+++ b/api/_lib/service-catalog/services/index.js
@@ -85,6 +85,12 @@ import researchPaper from './research-paper.js';
import researchBibliography from './research-bibliography.js';
import booksSearch from './books-search.js';
import booksRead from './books-read.js';
+import newsWireQuery from './news-wire-query.js';
+import newsWirePulse from './news-wire-pulse.js';
+import transitPlan from './transit-plan.js';
+import transitDelays from './transit-delays.js';
+import placesSearch from './places-search.js';
+import placesDetail from './places-detail.js';
export const PAID_SERVICES = Object.freeze([
modelCheck,
@@ -159,4 +165,10 @@ export const PAID_SERVICES = Object.freeze([
researchBibliography,
booksSearch,
booksRead,
+ newsWireQuery,
+ newsWirePulse,
+ transitPlan,
+ transitDelays,
+ placesSearch,
+ placesDetail,
]);
diff --git a/api/_lib/service-catalog/services/news-wire-pulse.js b/api/_lib/service-catalog/services/news-wire-pulse.js
new file mode 100644
index 000000000..3fb84a93b
--- /dev/null
+++ b/api/_lib/service-catalog/services/news-wire-pulse.js
@@ -0,0 +1,43 @@
+// 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.
+// Slug is "news-wire-*" (not "news-*") to avoid colliding with the
+// unrelated pre-existing "news-pulse" ticker-sentiment service.
+
+export default {
+ slug: 'news-wire-pulse',
+ title: 'Global News Wire Pulse',
+ category: 'live-data',
+ useCase: 'three.ws Global News Wire Pulse: $0.002 USDC per call returns only the GDELT articles indexed since a cursor, with a fresh cursor for the next poll, for building a live news feed without re-fetching.',
+ path: '/api/x402/news-wire-pulse',
+ method: 'GET',
+ free: false,
+ status: 'live',
+ priceAtomics: '2000',
+ acceptsBuilder: 'standard',
+ serviceName: 'three.ws News Wire',
+ tags: ['news', 'live-data', 'gdelt', 'media-monitoring', 'polling'],
+ description: 'three.ws Global News Wire Pulse: pay $0.002 USDC per call to get only the GDELT articles that have appeared for your query since a cursor you supply, plus a fresh cursor for the next poll. Built for agents running a repeated poll loop against Global News Wire Search without re-fetching the same articles. Start with News Wire Search to get a query working, then switch to Pulse for ongoing monitoring.',
+ input: { q: 'earthquake relief', cursor: '20261014000000' },
+ inputSchema: {
+ type: 'object',
+ required: ['q', 'cursor'],
+ properties: {
+ q: { type: 'string', description: 'Search query, same syntax as News Wire Search.' },
+ cursor: { type: 'string', description: 'GDELT timestamp (YYYYMMDDHHMMSS) or ISO-8601 timestamp to poll since.' },
+ maxRecords: { type: 'integer', minimum: 1, maximum: 75, default: 50 },
+ },
+ },
+ outputExample: {
+ query: 'earthquake relief',
+ cursor: '20261014000000',
+ nextCursor: '20261014001200',
+ newArticleCount: 1,
+ truncated: false,
+ articles: [
+ { title: 'Example wire story', url: 'https://example.com/a', domain: 'example.com', language: 'English', sourceCountry: 'United States', seenDate: '20261014T001100Z', socialImage: null },
+ ],
+ source: 'gdelt-doc-2.0',
+ retrievedAt: '2026-10-14T00:12:00Z',
+ },
+ storefronts: ['x402scan'],
+};
diff --git a/api/_lib/service-catalog/services/news-wire-query.js b/api/_lib/service-catalog/services/news-wire-query.js
new file mode 100644
index 000000000..25cebcb58
--- /dev/null
+++ b/api/_lib/service-catalog/services/news-wire-query.js
@@ -0,0 +1,47 @@
+// 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.
+// Slug is "news-wire-*" (not "news-*") to avoid colliding with the
+// unrelated pre-existing "news-pulse" ticker-sentiment service.
+
+export default {
+ slug: 'news-wire-query',
+ title: 'Global News Wire Search',
+ category: 'live-data',
+ useCase: 'three.ws Global News Wire Search: $0.003 USDC per call searches worldwide news coverage via the GDELT Project (65+ languages, updated every 15 minutes) and returns matching articles plus a coverage-volume timeline.',
+ path: '/api/x402/news-wire-query',
+ method: 'GET',
+ free: true,
+ status: 'live',
+ priceAtomics: '3000',
+ acceptsBuilder: 'standard',
+ serviceName: 'three.ws News Wire',
+ tags: ['news', 'live-data', 'gdelt', 'media-monitoring'],
+ description: 'three.ws Global News Wire Search: live public-data endpoint, no API key anywhere in the chain. Pay $0.003 USDC (or use the free daily per-IP quota) to search the GDELT Project\'s real-time index of worldwide news media in 65+ languages. Returns matching articles (title, URL, domain, language, source country, seen date) plus a coverage-volume timeline over the chosen timespan. GDELT throttles to roughly one upstream request per 5 seconds per IP; this endpoint serializes calls to respect that.',
+ input: { q: 'earthquake relief', timespan: '3d' },
+ inputSchema: {
+ type: 'object',
+ required: ['q'],
+ properties: {
+ q: { type: 'string', description: 'Search query. Free text is quoted automatically; GDELT operators (AND, OR, sourcelang:, etc) pass through as-is.' },
+ timespan: { type: 'string', default: '3d', description: 'GDELT lookback window, e.g. 1d, 3d, 1w, 1m.' },
+ maxRecords: { type: 'integer', minimum: 1, maximum: 75, default: 25 },
+ sourceLang: { type: 'string', description: 'Restrict to a GDELT source language code, e.g. eng.' },
+ sourceCountry: { type: 'string', description: 'Restrict to a GDELT source country code, e.g. us.' },
+ includeTimeline: { type: 'boolean', default: true, description: 'Include the coverage-volume timeline (one extra upstream call).' },
+ },
+ },
+ outputExample: {
+ query: 'earthquake relief',
+ effectiveQuery: '"earthquake relief"',
+ timespan: '3d',
+ count: 2,
+ articles: [
+ { title: 'Example wire story', url: 'https://example.com/a', domain: 'example.com', language: 'English', sourceCountry: 'United States', seenDate: '20261014T120000Z', socialImage: null },
+ ],
+ volumeTimeline: [{ date: '20261013T000000Z', value: 1.2 }],
+ timelineStatus: 'ok',
+ source: 'gdelt-doc-2.0',
+ retrievedAt: '2026-10-14T00:00:00Z',
+ },
+ storefronts: ['x402scan'],
+};
diff --git a/api/_lib/service-catalog/services/places-detail.js b/api/_lib/service-catalog/services/places-detail.js
new file mode 100644
index 000000000..366b2562a
--- /dev/null
+++ b/api/_lib/service-catalog/services/places-detail.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.
+//
+// Upstream x402-places enriches this route with Yelp reviews, falling back
+// to a deterministic fixture when no Yelp key is set. three.ws ships no
+// fake data, so that enrichment is dropped: this returns only the real,
+// live OpenStreetMap record.
+
+export default {
+ slug: 'places-detail',
+ title: 'Place Detail',
+ category: 'live-data',
+ useCase: 'three.ws Place Detail: $0.002 USDC per call returns the full live OpenStreetMap record for one place found via Places Search.',
+ path: '/api/x402/places-detail',
+ method: 'GET',
+ free: false,
+ status: 'live',
+ priceAtomics: '2000',
+ acceptsBuilder: 'standard',
+ serviceName: 'three.ws Places',
+ tags: ['places', 'live-data', 'osm', 'overpass', 'poi'],
+ description: 'three.ws Place Detail: pay $0.002 USDC per call to fetch the full live OpenStreetMap record for one place, by the id returned from Places Search (e.g. "node-1072800838"). Returns every OSM tag alongside the structured fields (name, category, coordinates, opening hours, contact, address, cuisine).',
+ input: { id: 'node-1072800838' },
+ inputSchema: {
+ type: 'object',
+ required: ['id'],
+ properties: {
+ id: { type: 'string', description: 'Place id from Places Search, e.g. "node-1072800838", "way-55", "relation-9".' },
+ },
+ },
+ outputExample: {
+ source: 'overpass',
+ place: { id: 'node-1072800838', osmType: 'node', osmId: 1072800838, name: 'Example Cafe', category: 'cafe', latitude: 42.3519, longitude: -71.0552, openingHours: 'Mo-Fr 07:00-19:00', tags: { amenity: 'cafe', name: 'Example Cafe' } },
+ retrievedAt: '2026-10-14T00:00:00Z',
+ },
+ storefronts: ['x402scan'],
+};
diff --git a/api/_lib/service-catalog/services/places-search.js b/api/_lib/service-catalog/services/places-search.js
new file mode 100644
index 000000000..4a98363fa
--- /dev/null
+++ b/api/_lib/service-catalog/services/places-search.js
@@ -0,0 +1,39 @@
+// 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: 'places-search',
+ title: 'Places Search',
+ category: 'live-data',
+ useCase: 'three.ws Places Search: $0.002 USDC per call returns real points of interest near a coordinate from OpenStreetMap, with opening hours, contact details, address, and cuisine where tagged.',
+ path: '/api/x402/places-search',
+ method: 'GET',
+ free: true,
+ status: 'live',
+ priceAtomics: '2000',
+ acceptsBuilder: 'standard',
+ serviceName: 'three.ws Places',
+ tags: ['places', 'live-data', 'osm', 'overpass', 'poi'],
+ description: 'three.ws Places Search: live public-data endpoint, no API key anywhere in the chain. Pay $0.002 USDC (or use the free daily per-IP quota) to search OpenStreetMap via the Overpass API for points of interest within a radius of a coordinate, optionally filtered to a category (amenity/shop/leisure/tourism value such as cafe, restaurant, pharmacy, museum). Returns each place\'s name, category, coordinates, opening hours, phone, website, address, and cuisine where tagged in OSM.',
+ input: { lat: 42.3519, lon: -71.0552, radius: 500, category: 'cafe', limit: 10 },
+ inputSchema: {
+ type: 'object',
+ required: ['lat', 'lon'],
+ properties: {
+ lat: { type: 'number', minimum: -90, maximum: 90 },
+ lon: { type: 'number', minimum: -180, maximum: 180 },
+ radius: { type: 'integer', minimum: 1, maximum: 5000, default: 500, description: 'Search radius in metres.' },
+ category: { type: 'string', description: 'OSM tag value such as cafe, restaurant, pharmacy, bar, museum.' },
+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 20 },
+ },
+ },
+ outputExample: {
+ source: 'overpass',
+ count: 1,
+ places: [
+ { id: 'node-1072800838', osmType: 'node', osmId: 1072800838, name: 'Example Cafe', category: 'cafe', latitude: 42.3519, longitude: -71.0552, openingHours: 'Mo-Fr 07:00-19:00', phone: null, website: null, address: '1 Example St, Boston, 02110', cuisine: null },
+ ],
+ retrievedAt: '2026-10-14T00:00:00Z',
+ },
+ storefronts: ['x402scan'],
+};
diff --git a/api/_lib/service-catalog/services/transit-delays.js b/api/_lib/service-catalog/services/transit-delays.js
new file mode 100644
index 000000000..8150c0fef
--- /dev/null
+++ b/api/_lib/service-catalog/services/transit-delays.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: 'transit-delays',
+ title: 'Transit Delay Snapshot',
+ category: 'live-data',
+ useCase: 'three.ws Transit Delay Snapshot: $0.001 USDC per call measures live MBTA arrivals against the schedule at a stop, with a running-well/minor-delays/significant-delays verdict.',
+ path: '/api/x402/transit-delays',
+ method: 'GET',
+ free: false,
+ status: 'live',
+ priceAtomics: '1000',
+ acceptsBuilder: 'standard',
+ serviceName: 'three.ws Transit',
+ tags: ['transit', 'live-data', 'gtfs-rt', 'mbta', 'mobility'],
+ description: 'three.ws Transit Delay Snapshot: pay $0.001 USDC per call to see how the MBTA\'s realtime feed compares to the scheduled timetable right now at a stop, optionally filtered to one route. delaySeconds is the realtime prediction minus the scheduled time for the same trip, measured from the feed, never modelled. Returns a per-arrival breakdown plus a summary (on-time / late / early counts, median and worst delay, and a verdict). Find a stop id with Transit Trip Plan or by name first.',
+ input: { stop: 'South Station', route: null, limit: 20 },
+ inputSchema: {
+ type: 'object',
+ required: ['stop'],
+ properties: {
+ stop: { type: 'string', description: 'Stop id, station name, or "lat,lon".' },
+ route: { type: 'string', description: 'Optional feed route id to filter by.' },
+ limit: { type: 'integer', minimum: 1, maximum: 100, default: 20 },
+ },
+ },
+ outputExample: {
+ source: 'gtfs-rt-live',
+ agency: 'MBTA (Massachusetts Bay Transportation Authority)',
+ summary: { predictions: 12, withSchedule: 10, onTime: 8, late: 2, early: 0, medianDelaySeconds: 30, worstDelaySeconds: 240, verdict: 'running-well' },
+ arrivals: [{ routeId: 'Red', routeName: 'Red Line', delaySeconds: 30, status: 'on-time' }],
+ retrievedAt: '2026-10-14T00:00:00Z',
+ },
+ storefronts: ['x402scan'],
+};
diff --git a/api/_lib/service-catalog/services/transit-plan.js b/api/_lib/service-catalog/services/transit-plan.js
new file mode 100644
index 000000000..50ab7fa53
--- /dev/null
+++ b/api/_lib/service-catalog/services/transit-plan.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: 'transit-plan',
+ title: 'Transit Trip Plan',
+ category: 'live-data',
+ useCase: 'three.ws Transit Trip Plan: $0.002 USDC per call returns direct and one-transfer itineraries between two MBTA stops, with realtime predictions overlaid where the feed has them.',
+ path: '/api/x402/transit-plan',
+ method: 'GET',
+ free: true,
+ status: 'live',
+ priceAtomics: '2000',
+ acceptsBuilder: 'standard',
+ serviceName: 'three.ws Transit',
+ tags: ['transit', 'live-data', 'gtfs', 'mbta', 'mobility'],
+ description: 'three.ws Transit Trip Plan: live public-data endpoint, no API key anywhere in the chain. Pay $0.002 USDC (or use the free daily per-IP quota) to plan a trip between two stops on the MBTA\'s public GTFS feed. Each place accepts a feed stop id, a station name, or a "lat,lon" pair. Returns direct and one-transfer itineraries from the static schedule, with realtime arrival/departure predictions overlaid where the GTFS-Realtime feed has them. No fixture mode: an upstream outage is a 502, never an invented departure time.',
+ input: { from: 'South Station', to: 'Alewife', max: 3 },
+ inputSchema: {
+ type: 'object',
+ required: ['from', 'to'],
+ properties: {
+ from: { type: 'string', description: 'Origin: stop id, station name, or "lat,lon".' },
+ to: { type: 'string', description: 'Destination: stop id, station name, or "lat,lon".' },
+ departAfter: { type: 'string', description: 'ISO 8601 timestamp. Defaults to now.' },
+ max: { type: 'integer', minimum: 1, maximum: 10, default: 3, description: 'Max itineraries to return.' },
+ },
+ },
+ outputExample: {
+ source: 'gtfs-live',
+ agency: 'MBTA (Massachusetts Bay Transportation Authority)',
+ itineraries: [
+ {
+ kind: 'direct',
+ departure: '2026-10-14T18:05:00-04:00',
+ arrival: '2026-10-14T18:42:00-04:00',
+ durationMinutes: 37,
+ transfers: 0,
+ legs: [{ routeId: 'Red', routeName: 'Red Line', routeType: 'subway', headsign: 'Alewife', tripId: 'example' }],
+ },
+ ],
+ note: '1 route(s) serve both stops directly.',
+ retrievedAt: '2026-10-14T00:00:00Z',
+ },
+ storefronts: ['x402scan'],
+};
diff --git a/api/_lib/x402-services/news-wire.js b/api/_lib/x402-services/news-wire.js
new file mode 100644
index 000000000..f314663c6
--- /dev/null
+++ b/api/_lib/x402-services/news-wire.js
@@ -0,0 +1,188 @@
+// Live, keyless global news data from the GDELT Project's DOC 2.0 API.
+// GDELT monitors worldwide news media in 65+ languages, updated every 15
+// minutes. It enforces roughly one request per 5 seconds per IP and
+// returns a plain-text throttle notice (HTTP 200) when hit too fast, so
+// every call here goes through a serialized queue that spaces requests
+// >= 5.1s apart, with bounded retries on throttle.
+
+const GDELT = 'https://api.gdeltproject.org/api/v2/doc/doc';
+const THREE_WS_UA = 'three.ws/1.0 (+https://three.ws; [email protected])';
+const MIN_GAP_MS = 5_100;
+const TIMEOUT_MS = 20_000;
+const THROTTLE_RETRIES = 2;
+const RETRY_BACKOFF_MS = 6_000;
+
+export class GdeltThrottledError extends Error {
+ constructor() {
+ super(
+ "GDELT is rate-limiting this server's IP (it allows roughly one request every 5 seconds). " +
+ 'Retry shortly.',
+ );
+ this.name = 'GdeltThrottledError';
+ this.status = 429;
+ this.code = 'upstream_rate_limited';
+ this.retryAfterSeconds = 10;
+ }
+}
+
+let queue = Promise.resolve();
+let lastCallAt = 0;
+
+function throttled(fn) {
+ const run = queue.then(async () => {
+ const wait = lastCallAt + MIN_GAP_MS - Date.now();
+ if (wait > 0) await new Promise((r) => setTimeout(r, wait));
+ try {
+ return await fn();
+ } finally {
+ lastCallAt = Date.now();
+ }
+ });
+ queue = run.catch(() => undefined);
+ return run;
+}
+
+async function gdeltOnce(params) {
+ return throttled(async () => {
+ const url = `${GDELT}?${new URLSearchParams({ format: 'json', ...params })}`;
+ const res = await fetch(url, { headers: { 'user-agent': THREE_WS_UA }, signal: AbortSignal.timeout(TIMEOUT_MS) });
+ if (res.status === 429 || res.status === 503) throw new GdeltThrottledError();
+ const text = await res.text();
+ if (!res.ok) {
+ const err = new Error(`GDELT HTTP ${res.status}`);
+ err.status = 502;
+ err.code = 'upstream_error';
+ throw err;
+ }
+ if (/limit requests|rate limit/i.test(text) && !text.trimStart().startsWith('{')) {
+ throw new GdeltThrottledError();
+ }
+ try {
+ return JSON.parse(text);
+ } catch {
+ const err = new Error(`GDELT: ${text.trim().slice(0, 300) || 'empty response'}`);
+ err.status = 502;
+ err.code = 'upstream_error';
+ throw err;
+ }
+ });
+}
+
+async function gdelt(params) {
+ let lastErr;
+ for (let attempt = 0; attempt <= THROTTLE_RETRIES; attempt++) {
+ try {
+ return await gdeltOnce(params);
+ } catch (err) {
+ lastErr = err;
+ if (!(err instanceof GdeltThrottledError) || attempt === THROTTLE_RETRIES) throw err;
+ await new Promise((r) => setTimeout(r, RETRY_BACKOFF_MS * (attempt + 1)));
+ }
+ }
+ throw lastErr;
+}
+
+function normalizeQuery(q) {
+ const hasOperators = /["():]|(\b(AND|OR|NOT)\b)|(\w+:)/.test(q);
+ if (hasOperators || !q.includes(' ')) return q;
+ return `"${q}"`;
+}
+
+function mapArticles(raw) {
+ return raw.map((a) => ({
+ title: a.title ?? '',
+ url: a.url ?? '',
+ domain: a.domain ?? '',
+ language: a.language ?? '',
+ sourceCountry: a.sourcecountry ?? '',
+ seenDate: a.seendate ?? '',
+ socialImage: a.socialimage || null,
+ }));
+}
+
+function mapTimeline(raw) {
+ const series = raw?.timeline?.[0]?.data;
+ if (!Array.isArray(series)) return null;
+ return series.map((p) => ({ date: p.date ?? '', value: typeof p.value === 'number' ? p.value : Number(p.value ?? 0) }));
+}
+
+export function toGdeltDate(d) {
+ return d.toISOString().replace(/[-:T]/g, '').slice(0, 14);
+}
+
+function parseCursor(cursor) {
+ if (/^\d{14}$/.test(cursor)) return cursor;
+ const d = new Date(cursor);
+ if (Number.isNaN(d.getTime())) {
+ const err = new Error(`Invalid cursor "${cursor}". Use GDELT format YYYYMMDDHHMMSS or an ISO-8601 timestamp.`);
+ err.status = 400;
+ err.code = 'invalid_cursor';
+ throw err;
+ }
+ return toGdeltDate(d);
+}
+
+export async function query(q, opts = {}) {
+ const nq = normalizeQuery(q);
+ const timespan = opts.timespan ?? '3d';
+ const max = Math.min(Math.max(opts.maxRecords ?? 25, 1), 75);
+ let fullQuery = nq;
+ if (opts.sourceLang) fullQuery += ` sourcelang:${opts.sourceLang}`;
+ if (opts.sourceCountry) fullQuery += ` sourcecountry:${opts.sourceCountry}`;
+
+ const artData = await gdelt({ query: fullQuery, mode: 'artlist', maxrecords: String(max), timespan, sort: 'datedesc' });
+ const articles = mapArticles(artData.articles ?? []);
+
+ let timeline = null;
+ let timelineStatus = 'ok';
+ if (opts.includeTimeline !== false) {
+ try {
+ const tlData = await gdelt({ query: fullQuery, mode: 'timelinevolraw', timespan });
+ timeline = mapTimeline(tlData);
+ } catch (err) {
+ timelineStatus = `unavailable: ${err.message}`;
+ }
+ } else {
+ timelineStatus = 'skipped (timeline=false)';
+ }
+
+ return {
+ query: q,
+ effectiveQuery: fullQuery,
+ timespan,
+ count: articles.length,
+ articles,
+ volumeTimeline: timeline,
+ timelineStatus,
+ source: 'gdelt-doc-2.0',
+ retrievedAt: new Date().toISOString(),
+ };
+}
+
+export async function pulse(q, cursor, maxRecords = 50) {
+ const since = parseCursor(cursor);
+ const now = new Date();
+ const nextCursor = toGdeltDate(new Date(now.getTime() - 60_000));
+ const max = Math.min(Math.max(maxRecords, 1), 75);
+
+ const data = await gdelt({
+ query: normalizeQuery(q),
+ mode: 'artlist',
+ maxrecords: String(max),
+ startdatetime: since,
+ enddatetime: toGdeltDate(now),
+ sort: 'datedesc',
+ });
+ const articles = mapArticles(data.articles ?? []);
+
+ return {
+ query: q,
+ cursor: since,
+ nextCursor,
+ newArticleCount: articles.length,
+ truncated: articles.length >= max,
+ articles,
+ source: 'gdelt-doc-2.0',
+ retrievedAt: now.toISOString(),
+ };
+}
diff --git a/api/_lib/x402-services/places.js b/api/_lib/x402-services/places.js
new file mode 100644
index 000000000..f922dce88
--- /dev/null
+++ b/api/_lib/x402-services/places.js
@@ -0,0 +1,99 @@
+// Live, keyless points-of-interest search and detail over the OpenStreetMap
+// Overpass API. Overpass is a free, shared community resource that refuses
+// requests without an identifying User-Agent (HTTP 406), so every call here
+// declares one with a contact address, per Overpass's usage policy.
+//
+// Upstream x402-places also offers Yelp-review enrichment on its detail
+// route, with a deterministic FIXTURE fallback when no Yelp key is set.
+// three.ws ships no fake data, so that enrichment is dropped entirely here:
+// places-detail returns only the real, live OSM record.
+
+const THREE_WS_UA = 'three.ws/1.0 (+https://three.ws; [email protected])';
+const OVERPASS_URL = 'https://overpass-api.de/api/interpreter';
+const TIMEOUT_MS = 25_000;
+
+async function overpass(query) {
+ const res = await fetch(OVERPASS_URL, {
+ method: 'POST',
+ headers: { 'content-type': 'application/x-www-form-urlencoded', 'user-agent': THREE_WS_UA, accept: 'application/json' },
+ body: new URLSearchParams({ data: query }),
+ signal: AbortSignal.timeout(TIMEOUT_MS),
+ });
+ if (!res.ok) {
+ const detail = (await res.text()).slice(0, 300);
+ const err = new Error(`Overpass request failed: HTTP ${res.status} ${detail}`);
+ err.status = 502;
+ err.code = 'upstream_error';
+ throw err;
+ }
+ const body = await res.json();
+ return body.elements ?? [];
+}
+
+function buildAddress(tags) {
+ const parts = [[tags['addr:housenumber'], tags['addr:street']].filter(Boolean).join(' '), tags['addr:city'], tags['addr:postcode']].filter((p) => p && p.length > 0);
+ return parts.length > 0 ? parts.join(', ') : null;
+}
+
+function toPoi(el) {
+ const tags = el.tags ?? {};
+ const lat = el.lat ?? el.center?.lat ?? null;
+ const lon = el.lon ?? el.center?.lon ?? null;
+ const category = tags.amenity ?? tags.shop ?? tags.leisure ?? tags.tourism ?? null;
+ return {
+ id: `${el.type}-${el.id}`,
+ osmType: el.type,
+ osmId: el.id,
+ name: tags.name ?? '(unnamed)',
+ category,
+ latitude: lat,
+ longitude: lon,
+ openingHours: tags.opening_hours ?? null,
+ phone: tags.phone ?? tags['contact:phone'] ?? null,
+ website: tags.website ?? tags['contact:website'] ?? null,
+ address: buildAddress(tags),
+ cuisine: tags.cuisine ?? null,
+ tags,
+ };
+}
+
+function esc(v) {
+ return v.replace(/[\\"]/g, '\\$&');
+}
+
+export async function searchPlaces(latitude, longitude, radiusM, category, limit) {
+ const around = `(around:${radiusM},${latitude},${longitude})`;
+ const filters = category
+ ? ['amenity', 'shop', 'leisure', 'tourism'].map((k) => `nwr["${k}"="${esc(category)}"]["name"]${around};`).join('\n ')
+ : `nwr["amenity"]["name"]${around};`;
+ const query = `[out:json][timeout:25];
+(
+ ${filters}
+);
+out tags center ${Math.min(limit * 3, 200)};`;
+ const elements = await overpass(query);
+ const places = elements.filter((e) => e.tags?.name).slice(0, limit).map(toPoi);
+ return {
+ source: 'overpass',
+ query: { latitude, longitude, radiusM, category, limit },
+ count: places.length,
+ places,
+ retrievedAt: new Date().toISOString(),
+ };
+}
+
+export function parsePoiId(id) {
+ const m = /^(node|way|relation)-(\d+)$/.exec(id);
+ if (!m) return null;
+ return { osmType: m[1], osmId: Number(m[2]) };
+}
+
+export async function placeDetail(osmType, osmId) {
+ const query = `[out:json][timeout:25];
+${osmType}(${osmId});
+out tags center 1;`;
+ const elements = await overpass(query);
+ if (elements.length === 0) return null;
+ const place = toPoi(elements[0]);
+ return { source: 'overpass', place, retrievedAt: new Date().toISOString() };
+}
diff --git a/api/_lib/x402-services/transit.js b/api/_lib/x402-services/transit.js
new file mode 100644
index 000000000..a1ff0b3ea
--- /dev/null
+++ b/api/_lib/x402-services/transit.js
@@ -0,0 +1,472 @@
+// Live, keyless transit trip planning and delay snapshots over the MBTA's
+// public GTFS / GTFS-RT V3 API (a public, keyless JSON projection of its
+// static schedule plus realtime TripUpdates). No fixture mode: an upstream
+// outage surfaces as a 502, never invented departure times.
+
+const THREE_WS_UA = 'three.ws/1.0 (+https://three.ws; [email protected])';
+const API_BASE = 'https://api-v3.mbta.com';
+const AGENCY_NAME = 'MBTA (Massachusetts Bay Transportation Authority)';
+const AGENCY_TIMEZONE = 'America/New_York';
+const TIMEOUT_MS = 12_000;
+const ON_TIME_SECONDS = 60;
+const ROUTE_TYPES = { 0: 'light-rail', 1: 'subway', 2: 'commuter-rail', 3: 'bus', 4: 'ferry' };
+const LATLON = /^(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)$/;
+
+class BadRequestError extends Error {}
+class NotFoundError extends Error {}
+class UpstreamError extends Error {}
+
+async function feedGet(path, params) {
+ const qs = new URLSearchParams(params).toString();
+ const url = `${API_BASE}${path}${qs ? `?${qs}` : ''}`;
+ let res;
+ try {
+ res = await fetch(url, {
+ headers: { accept: 'application/vnd.api+json', 'user-agent': THREE_WS_UA },
+ signal: AbortSignal.timeout(TIMEOUT_MS),
+ });
+ } catch (err) {
+ throw new UpstreamError(`Feed GET ${path} failed: ${err.message}`);
+ }
+ if (!res.ok) {
+ const body = await res.text();
+ throw new UpstreamError(`Feed GET ${path} failed: HTTP ${res.status} ${body.slice(0, 300)}`);
+ }
+ const doc = await res.json();
+ return { data: doc.data ?? [], included: doc.included ?? [] };
+}
+
+function indexIncluded(doc) {
+ const map = new Map();
+ for (const r of doc.included ?? []) map.set(`${r.type}:${r.id}`, r);
+ return map;
+}
+
+function related(resource, name, index) {
+ const ref = resource.relationships?.[name]?.data;
+ if (!ref) return undefined;
+ return index.get(`${ref.type}:${ref.id}`);
+}
+
+function relatedId(resource, name) {
+ return resource?.relationships?.[name]?.data?.id ?? undefined;
+}
+
+function attr(resource, name) {
+ return resource?.attributes?.[name];
+}
+
+let stationCache = null;
+const STATION_TTL_MS = 60 * 60 * 1000;
+
+async function stations() {
+ if (stationCache && Date.now() - stationCache.fetchedAt < STATION_TTL_MS) return stationCache.stations;
+ const doc = await feedGet('/stops', { 'filter[location_type]': '1', 'page[limit]': '500' });
+ const list = doc.data.map((s) => ({
+ id: s.id,
+ name: String(attr(s, 'name') ?? s.id),
+ latitude: Number(attr(s, 'latitude') ?? 0),
+ longitude: Number(attr(s, 'longitude') ?? 0),
+ municipality: String(attr(s, 'municipality') ?? ''),
+ }));
+ stationCache = { stations: list, fetchedAt: Date.now() };
+ return list;
+}
+
+export async function searchStations(rawQuery, limit = 10) {
+ const q = rawQuery.trim().toLowerCase();
+ if (!q) return [];
+ const all = await stations();
+ const exact = all.filter((s) => s.name.toLowerCase() === q);
+ const prefix = all.filter((s) => s.name.toLowerCase().startsWith(q) && !exact.includes(s));
+ const contains = all.filter((s) => s.name.toLowerCase().includes(q) && !exact.includes(s) && !prefix.includes(s));
+ return [...exact, ...prefix, ...contains].slice(0, limit);
+}
+
+async function nearestStation(lat, lon) {
+ const all = await stations();
+ let best;
+ let bestDist = Infinity;
+ for (const s of all) {
+ const d = haversineKm(lat, lon, s.latitude, s.longitude);
+ if (d < bestDist) {
+ bestDist = d;
+ best = s;
+ }
+ }
+ return best;
+}
+
+function haversineKm(lat1, lon1, lat2, lon2) {
+ const R = 6371;
+ const dLat = ((lat2 - lat1) * Math.PI) / 180;
+ const dLon = ((lon2 - lon1) * Math.PI) / 180;
+ const a = Math.sin(dLat / 2) ** 2 + Math.cos((lat1 * Math.PI) / 180) * Math.cos((lat2 * Math.PI) / 180) * Math.sin(dLon / 2) ** 2;
+ return 2 * R * Math.asin(Math.sqrt(a));
+}
+
+function localParts(when) {
+ const fmt = new Intl.DateTimeFormat('en-CA', {
+ timeZone: AGENCY_TIMEZONE,
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ hour: '2-digit',
+ minute: '2-digit',
+ hour12: false,
+ });
+ const parts = Object.fromEntries(fmt.formatToParts(when).map((p) => [p.type, p.value]));
+ return { date: `${parts.year}-${parts.month}-${parts.day}`, hour: Number(parts.hour) % 24, minute: Number(parts.minute) };
+}
+
+function serviceDate(when) {
+ return localParts(when).date;
+}
+
+function serviceTime(when) {
+ const { hour, minute } = localParts(when);
+ return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;
+}
+
+export async function resolvePlace(raw, label) {
+ const value = (raw || '').trim();
+ if (!value) throw new BadRequestError(`${label} is required`);
+
+ const coords = value.match(LATLON);
+ if (coords) {
+ const lat = Number(coords[1]);
+ const lon = Number(coords[2]);
+ if (Math.abs(lat) > 90 || Math.abs(lon) > 180) throw new BadRequestError(`${label} coordinates are out of range`);
+ const near = await nearestStation(lat, lon);
+ if (!near) throw new NotFoundError(`No station found near ${label}=${value}`);
+ return { stopId: near.id, name: near.name, matchedBy: 'coordinates', latitude: near.latitude, longitude: near.longitude };
+ }
+
+ if (/^[A-Za-z0-9_.:-]+$/.test(value)) {
+ try {
+ const doc = await feedGet(`/stops/${encodeURIComponent(value)}`, {});
+ const found = Array.isArray(doc.data) ? doc.data[0] : doc.data;
+ if (found?.id) {
+ return {
+ stopId: found.id,
+ name: String(attr(found, 'name') ?? found.id),
+ matchedBy: 'stop-id',
+ latitude: attr(found, 'latitude'),
+ longitude: attr(found, 'longitude'),
+ };
+ }
+ } catch {
+ // Not a stop id, fall through to a name search.
+ }
+ }
+
+ const matches = await searchStations(value, 1);
+ if (matches.length === 0) {
+ throw new NotFoundError(
+ `Could not resolve ${label}="${value}". Try a station name, a feed stop id, or "lat,lon". GET transit-stops searches names for free.`,
+ );
+ }
+ const s = matches[0];
+ return { stopId: s.id, name: s.name, matchedBy: 'name', latitude: s.latitude, longitude: s.longitude };
+}
+
+function matchesStop(row, wanted) {
+ return row.stopId === wanted || row.parentId === wanted;
+}
+
+function minutesBetween(a, b) {
+ if (!a || !b) return null;
+ return Math.round((new Date(b).getTime() - new Date(a).getTime()) / 60000);
+}
+
+function shiftPreservingOffset(iso, minutes) {
+ const suffix = iso.match(/([+-]\d{2}:\d{2}|Z)$/)?.[1];
+ const shifted = new Date(new Date(iso).getTime() + minutes * 60000);
+ if (!suffix || suffix === 'Z') return shifted.toISOString();
+ const sign = suffix.startsWith('-') ? -1 : 1;
+ const [oh, om] = suffix.slice(1).split(':').map(Number);
+ const offsetMs = sign * (oh * 60 + om) * 60000;
+ return new Date(shifted.getTime() + offsetMs).toISOString().replace(/\.\d{3}Z$/, '') + suffix;
+}
+
+function readSchedules(doc) {
+ const index = indexIncluded(doc);
+ return doc.data.map((s) => {
+ const stop = related(s, 'stop', index);
+ const parent = stop ? relatedId(stop, 'parent_station') : undefined;
+ const stopId = relatedId(s, 'stop') ?? '';
+ return {
+ tripId: relatedId(s, 'trip') ?? '',
+ stopId,
+ parentId: parent ?? stopId,
+ sequence: Number(attr(s, 'stop_sequence') ?? 0),
+ arrival: attr(s, 'arrival_time') ?? null,
+ departure: attr(s, 'departure_time') ?? null,
+ directionId: Number(attr(s, 'direction_id') ?? 0),
+ };
+ });
+}
+
+async function routesAtStop(stopId) {
+ const doc = await feedGet('/routes', { 'filter[stop]': stopId });
+ return doc.data.map((r) => ({
+ id: r.id,
+ name: String(attr(r, 'long_name') || attr(r, 'short_name') || r.id),
+ type: ROUTE_TYPES[String(attr(r, 'type') ?? '')] ?? 'transit',
+ sortOrder: Number(attr(r, 'sort_order') ?? 0),
+ }));
+}
+
+async function directLegsOnRoute(route, from, to, departAfter, limit) {
+ const doc = await feedGet('/schedules', {
+ 'filter[stop]': `${from.stopId},${to.stopId}`,
+ 'filter[route]': route.id,
+ 'filter[date]': serviceDate(departAfter),
+ 'filter[min_time]': serviceTime(departAfter),
+ sort: 'departure_time',
+ include: 'stop,trip',
+ 'page[limit]': '400',
+ });
+ const index = indexIncluded(doc);
+ const rows = readSchedules(doc);
+
+ const headsigns = new Map();
+ for (const s of doc.data) {
+ const trip = related(s, 'trip', index);
+ const tripId = relatedId(s, 'trip');
+ if (trip && tripId) headsigns.set(tripId, String(attr(trip, 'headsign') ?? ''));
+ }
+
+ const byTrip = new Map();
+ for (const r of rows) {
+ if (!r.tripId) continue;
+ const list = byTrip.get(r.tripId) ?? [];
+ list.push(r);
+ byTrip.set(r.tripId, list);
+ }
+
+ const legs = [];
+ for (const [tripId, tripRows] of byTrip) {
+ const origin = tripRows.find((r) => matchesStop(r, from.stopId));
+ const dest = tripRows.find((r) => matchesStop(r, to.stopId));
+ if (!origin || !dest) continue;
+ if (origin.sequence >= dest.sequence) continue;
+
+ const depart = origin.departure ?? origin.arrival;
+ if (!depart) continue;
+ if (new Date(depart).getTime() < departAfter.getTime()) continue;
+
+ const arrive = dest.arrival ?? dest.departure;
+ legs.push({
+ routeId: route.id,
+ routeName: route.name,
+ routeType: route.type,
+ headsign: headsigns.get(tripId) ?? '',
+ tripId,
+ from: { stopId: origin.stopId, name: from.name, scheduledDeparture: depart, predictedDeparture: null },
+ to: { stopId: dest.stopId, name: to.name, scheduledArrival: arrive, predictedArrival: null },
+ durationMinutes: minutesBetween(depart, arrive),
+ realtime: false,
+ });
+ }
+
+ legs.sort((a, b) => new Date(a.from.scheduledDeparture ?? 0).getTime() - new Date(b.from.scheduledDeparture ?? 0).getTime());
+ return legs.slice(0, limit);
+}
+
+async function applyPredictions(legs, from) {
+ if (legs.length === 0) return;
+ try {
+ const doc = await feedGet('/predictions', { 'filter[stop]': from.stopId, 'page[limit]': '150' });
+ const byTrip = new Map();
+ for (const p of doc.data) {
+ const tripId = relatedId(p, 'trip');
+ if (tripId) byTrip.set(tripId, p);
+ }
+ for (const leg of legs) {
+ const p = byTrip.get(leg.tripId);
+ if (!p) continue;
+ const predicted = attr(p, 'departure_time') ?? attr(p, 'arrival_time') ?? null;
+ if (!predicted) continue;
+ leg.from.predictedDeparture = predicted;
+ leg.realtime = true;
+ const drift = minutesBetween(leg.from.scheduledDeparture, predicted);
+ if (drift !== null && leg.to.scheduledArrival) {
+ leg.to.predictedArrival = shiftPreservingOffset(leg.to.scheduledArrival, drift);
+ }
+ }
+ } catch {
+ // Realtime is an enhancement; scheduled itineraries still stand without it.
+ }
+}
+
+function toItinerary(legs) {
+ const first = legs[0];
+ const last = legs[legs.length - 1];
+ const departure = first.from.predictedDeparture ?? first.from.scheduledDeparture;
+ const arrival = last.to.predictedArrival ?? last.to.scheduledArrival;
+ return {
+ kind: legs.length === 1 ? 'direct' : 'one-transfer',
+ departure,
+ arrival,
+ durationMinutes: minutesBetween(departure, arrival),
+ transfers: legs.length - 1,
+ legs,
+ };
+}
+
+async function findTransfer(fromRoutes, toRoutes) {
+ const a = [...fromRoutes].sort((x, y) => x.sortOrder - y.sortOrder).slice(0, 2);
+ const b = [...toRoutes].sort((x, y) => x.sortOrder - y.sortOrder).slice(0, 2);
+ if (a.length === 0 || b.length === 0) return null;
+
+ const stopSets = new Map();
+ const loadStops = async (routeId) => {
+ const cached = stopSets.get(routeId);
+ if (cached) return cached;
+ const doc = await feedGet('/stops', { 'filter[route]': routeId, 'page[limit]': '300' });
+ const map = new Map();
+ for (const s of doc.data) {
+ const parent = relatedId(s, 'parent_station') ?? s.id;
+ map.set(parent, String(attr(s, 'name') ?? parent));
+ }
+ stopSets.set(routeId, map);
+ return map;
+ };
+
+ for (const routeA of a) {
+ const stopsA = await loadStops(routeA.id);
+ for (const routeB of b) {
+ if (routeA.id === routeB.id) continue;
+ const stopsB = await loadStops(routeB.id);
+ for (const [stopId, name] of stopsA) {
+ if (stopsB.has(stopId)) return { routeA, routeB, point: { stopId, name, matchedBy: 'stop-id' } };
+ }
+ }
+ }
+ return null;
+}
+
+export async function planTrip(from, to, departAfter, max) {
+ if (from.stopId === to.stopId) throw new BadRequestError('from and to resolve to the same stop');
+
+ const [fromRoutes, toRoutes] = await Promise.all([routesAtStop(from.stopId), routesAtStop(to.stopId)]);
+ const toIds = new Set(toRoutes.map((r) => r.id));
+ const shared = fromRoutes.filter((r) => toIds.has(r.id)).sort((a, b) => a.sortOrder - b.sortOrder);
+
+ const itineraries = [];
+ let note;
+
+ if (shared.length > 0) {
+ const legSets = await Promise.all(shared.slice(0, 3).map((r) => directLegsOnRoute(r, from, to, departAfter, max)));
+ const legs = legSets.flat();
+ await applyPredictions(legs, from);
+ for (const leg of legs) itineraries.push(toItinerary([leg]));
+ note = `${shared.length} route(s) serve both stops directly. Times are scheduled; predictedDeparture/predictedArrival are filled in where the realtime feed has an update for that trip.`;
+ } else {
+ const transfer = await findTransfer(fromRoutes, toRoutes);
+ if (!transfer) {
+ note = 'No direct route and no single-transfer interchange found between these stops in this feed. They may need two or more transfers, or lie on unconnected networks.';
+ } else {
+ const [firstLegs, secondLegsAll] = await Promise.all([
+ directLegsOnRoute(transfer.routeA, from, transfer.point, departAfter, max),
+ directLegsOnRoute(transfer.routeB, transfer.point, to, departAfter, max * 3),
+ ]);
+ await applyPredictions(firstLegs, from);
+
+ for (const first of firstLegs) {
+ const arrive = first.to.predictedArrival ?? first.to.scheduledArrival;
+ if (!arrive) continue;
+ const readyAt = new Date(new Date(arrive).getTime() + 2 * 60000).getTime();
+ const second = secondLegsAll.find((l) => l.from.scheduledDeparture !== null && new Date(l.from.scheduledDeparture).getTime() >= readyAt);
+ if (!second) continue;
+ itineraries.push(toItinerary([first, second]));
+ if (itineraries.length >= max) break;
+ }
+ note = `No direct route; itineraries transfer at ${transfer.point.name}. A minimum 2-minute connection is enforced.`;
+ }
+ }
+
+ itineraries.sort((a, b) => new Date(a.departure ?? 0).getTime() - new Date(b.departure ?? 0).getTime());
+
+ return {
+ source: 'gtfs-live',
+ agency: AGENCY_NAME,
+ feed: API_BASE,
+ query: { from, to, departAfter: departAfter.toISOString(), max },
+ itineraries: itineraries.slice(0, max),
+ note,
+ retrievedAt: new Date().toISOString(),
+ };
+}
+
+export async function delaySnapshot(stop, routeId, limit) {
+ const params = {
+ 'filter[stop]': stop.stopId,
+ include: 'schedule,route,trip',
+ sort: 'arrival_time',
+ 'page[limit]': String(Math.min(Math.max(limit, 1), 100)),
+ };
+ if (routeId) params['filter[route]'] = routeId;
+
+ const doc = await feedGet('/predictions', params);
+ const index = indexIncluded(doc);
+
+ const arrivals = [];
+ for (const p of doc.data) {
+ const schedule = related(p, 'schedule', index);
+ const route = related(p, 'route', index);
+ const trip = related(p, 'trip', index);
+
+ const predicted = attr(p, 'arrival_time') ?? attr(p, 'departure_time') ?? null;
+ const scheduled = schedule ? attr(schedule, 'arrival_time') ?? attr(schedule, 'departure_time') ?? null : null;
+
+ let delaySeconds = null;
+ if (predicted && scheduled) delaySeconds = Math.round((new Date(predicted).getTime() - new Date(scheduled).getTime()) / 1000);
+
+ arrivals.push({
+ routeId: relatedId(p, 'route') ?? '',
+ routeName: String(attr(route, 'long_name') || attr(route, 'short_name') || relatedId(p, 'route') || ''),
+ tripId: relatedId(p, 'trip') ?? '',
+ headsign: String(attr(p, 'trip_headsign') ?? attr(trip, 'headsign') ?? ''),
+ directionId: Number(attr(p, 'direction_id') ?? 0),
+ stopId: relatedId(p, 'stop') ?? stop.stopId,
+ scheduled,
+ predicted,
+ delaySeconds,
+ delayMinutes: delaySeconds === null ? null : Math.round(delaySeconds / 60),
+ status: delaySeconds === null ? 'unknown' : delaySeconds < -ON_TIME_SECONDS ? 'early' : delaySeconds > ON_TIME_SECONDS ? 'late' : 'on-time',
+ uncertaintySeconds: attr(p, 'arrival_uncertainty') ?? attr(p, 'departure_uncertainty') ?? null,
+ });
+ }
+
+ const measured = arrivals.filter((a) => a.delaySeconds !== null).map((a) => a.delaySeconds);
+ const sorted = [...measured].sort((a, b) => a - b);
+ const median = sorted.length ? sorted[Math.floor(sorted.length / 2)] : null;
+ const worst = sorted.length ? sorted[sorted.length - 1] : null;
+ const late = arrivals.filter((a) => a.status === 'late').length;
+ const early = arrivals.filter((a) => a.status === 'early').length;
+ const onTime = arrivals.filter((a) => a.status === 'on-time').length;
+
+ const verdict = measured.length === 0 ? 'no-data' : (median ?? 0) > 300 ? 'significant-delays' : (median ?? 0) > ON_TIME_SECONDS ? 'minor-delays' : 'running-well';
+
+ return {
+ source: 'gtfs-rt-live',
+ agency: AGENCY_NAME,
+ feed: API_BASE,
+ query: { stop, routeId },
+ summary: { predictions: arrivals.length, withSchedule: measured.length, onTime, late, early, medianDelaySeconds: median, worstDelaySeconds: worst, verdict },
+ arrivals,
+ note: 'delaySeconds is the realtime prediction minus the scheduled time for the same trip at this stop, measured from the feed, not modelled. Predictions without a matching scheduled trip (added or unscheduled service) have delaySeconds: null and status: "unknown".',
+ retrievedAt: new Date().toISOString(),
+ };
+}
+
+export function parseWhen(raw) {
+ if (!raw) return new Date();
+ const t = Date.parse(raw);
+ if (Number.isNaN(t)) throw new BadRequestError('departAfter must be an ISO 8601 timestamp, e.g. 2026-08-07T14:30:00Z');
+ return new Date(t);
+}
+
+export { BadRequestError, NotFoundError, UpstreamError, AGENCY_NAME, API_BASE };
diff --git a/api/x402/news-wire-pulse.js b/api/x402/news-wire-pulse.js
new file mode 100644
index 000000000..a4913ccf9
--- /dev/null
+++ b/api/x402/news-wire-pulse.js
@@ -0,0 +1,69 @@
+// GET /api/x402/news-wire-pulse?q=earthquake+relief&cursor=20261014000000
+//
+// Global News Wire Pulse: $0.002 USDC per call, always paid (the free
+// quota lives on news-wire-query). Delta poll since a cursor, via GDELT.
+
+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 { pulse } from '../_lib/x402-services/news-wire.js';
+import listing from '../_lib/service-catalog/services/news-wire-pulse.js';
+
+const ROUTE = '/api/x402/news-wire-pulse';
+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: ['query', 'cursor', 'nextCursor', 'articles'],
+ properties: {
+ query: { type: 'string' },
+ cursor: { type: 'string' },
+ nextCursor: { type: 'string' },
+ newArticleCount: { type: 'integer' },
+ truncated: { type: 'boolean' },
+ articles: { type: 'array' },
+ },
+};
+
+export const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['media monitoring', 'live news feeds', 'polling 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 }),
+};
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ priceAtomics: priceFor('news-wire-pulse', '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 q = String(params.get('q') || '').trim();
+ const cursor = String(params.get('cursor') || '').trim();
+ const maxRecordsRaw = Number(params.get('maxRecords') || '50');
+ const maxRecords = Number.isFinite(maxRecordsRaw) ? maxRecordsRaw : 50;
+ if (!q) {
+ const err = new Error('query param "q" is required');
+ err.status = 400;
+ err.code = 'missing_query';
+ throw err;
+ }
+ if (!cursor) {
+ const err = new Error('query param "cursor" is required');
+ err.status = 400;
+ err.code = 'missing_cursor';
+ throw err;
+ }
+ return pulse(q, cursor, maxRecords);
+ },
+});
diff --git a/api/x402/news-wire-query.js b/api/x402/news-wire-query.js
new file mode 100644
index 000000000..76ff0e074
--- /dev/null
+++ b/api/x402/news-wire-query.js
@@ -0,0 +1,105 @@
+// GET /api/x402/news-wire-query?q=earthquake+relief&timespan=3d
+//
+// Global News Wire Search: $0.003 USDC per call (free daily per-IP quota
+// runs first). Live worldwide news search via the GDELT Project. No API
+// key. Route name uses "news-wire-*" to avoid colliding with the
+// unrelated pre-existing "news-pulse" ticker-sentiment service.
+
+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 { query } from '../_lib/x402-services/news-wire.js';
+import listing from '../_lib/service-catalog/services/news-wire-query.js';
+
+const ROUTE = '/api/x402/news-wire-query';
+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: ['query', 'count', 'articles'],
+ properties: {
+ query: { type: 'string' },
+ effectiveQuery: { type: 'string' },
+ timespan: { type: 'string' },
+ count: { type: 'integer' },
+ articles: { type: 'array' },
+ volumeTimeline: { type: ['array', 'null'] },
+ timelineStatus: { type: 'string' },
+ tier: { type: 'string', enum: ['free', 'paid'] },
+ free_remaining_today: { type: 'integer' },
+ },
+};
+
+export const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['media monitoring', 'narrative tracking', 'research 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 timespan = params.get('timespan') || '3d';
+ const maxRecordsRaw = Number(params.get('maxRecords') || '25');
+ const maxRecords = Number.isFinite(maxRecordsRaw) ? maxRecordsRaw : 25;
+ const sourceLang = params.get('sourceLang') || null;
+ const sourceCountry = params.get('sourceCountry') || null;
+ const includeTimeline = params.get('includeTimeline') !== 'false';
+ return { q, timespan, maxRecords, sourceLang, sourceCountry, includeTimeline };
+}
+
+let _paid = null;
+function paidHandler() {
+ if (_paid) return _paid;
+ _paid = paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ priceAtomics: priceFor('news-wire-query', '3000'), // $0.003 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, ...opts } = 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 query(q, opts);
+ 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.newsWireFreeIp(clientIp(req));
+ if (!rl.success) return paidHandler()(req, res);
+
+ const { q, ...opts } = parseParams(req);
+ if (!q) return error(res, 400, 'missing_query', 'query param "q" is required');
+
+ try {
+ const data = await query(q, opts);
+ 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);
+ }
+});
diff --git a/api/x402/places-detail.js b/api/x402/places-detail.js
new file mode 100644
index 000000000..94897e7b1
--- /dev/null
+++ b/api/x402/places-detail.js
@@ -0,0 +1,61 @@
+// GET /api/x402/places-detail?id=node-1072800838
+//
+// Place Detail: $0.002 USDC per call, always paid (the free quota lives on
+// places-search). Live OpenStreetMap record, no Yelp fixture enrichment.
+
+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 { parsePoiId, placeDetail } from '../_lib/x402-services/places.js';
+import listing from '../_lib/service-catalog/services/places-detail.js';
+
+const ROUTE = '/api/x402/places-detail';
+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', 'place'],
+ properties: { source: { type: 'string' }, place: { type: 'object' } },
+};
+
+export const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['local discovery', 'mapping agents', 'delivery and 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('places-detail', '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 id = String(params.get('id') || '').trim();
+ const parsed = id ? parsePoiId(id) : null;
+ if (!parsed) {
+ const err = new Error("query param 'id' must look like 'node-123', 'way-123', or 'relation-123' (as returned by Places Search)");
+ err.status = 400;
+ err.code = 'invalid_id';
+ throw err;
+ }
+ const detail = await placeDetail(parsed.osmType, parsed.osmId);
+ if (!detail) {
+ const err = new Error(`no OpenStreetMap ${parsed.osmType} with id ${parsed.osmId}`);
+ err.status = 404;
+ err.code = 'not_found';
+ throw err;
+ }
+ return detail;
+ },
+});
diff --git a/api/x402/places-search.js b/api/x402/places-search.js
new file mode 100644
index 000000000..1f0e8e07f
--- /dev/null
+++ b/api/x402/places-search.js
@@ -0,0 +1,114 @@
+// GET /api/x402/places-search?lat=42.3519&lon=-71.0552&radius=500&category=cafe
+//
+// Places Search: $0.002 USDC per call (free daily per-IP quota runs first).
+// Live OpenStreetMap Overpass POI search. No API key.
+
+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 { searchPlaces } from '../_lib/x402-services/places.js';
+import listing from '../_lib/service-catalog/services/places-search.js';
+
+const ROUTE = '/api/x402/places-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', 'places'],
+ properties: {
+ source: { type: 'string' },
+ count: { type: 'integer' },
+ places: { type: 'array' },
+ tier: { type: 'string', enum: ['free', 'paid'] },
+ free_remaining_today: { type: 'integer' },
+ },
+};
+
+export const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['local discovery', 'mapping agents', 'delivery and 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 }),
+};
+
+function parseParams(req) {
+ const params = new URL(req.url, 'http://x').searchParams;
+ const lat = Number(params.get('lat'));
+ const lon = Number(params.get('lon'));
+ const radiusRaw = Number(params.get('radius') || '500');
+ const limitRaw = Number(params.get('limit') || '20');
+ const category = params.get('category') || null;
+ return {
+ lat,
+ lon,
+ radius: Math.round(Number.isFinite(radiusRaw) ? radiusRaw : 500),
+ limit: Math.round(Number.isFinite(limitRaw) ? limitRaw : 20),
+ category,
+ };
+}
+
+function validate({ lat, lon, radius, limit, category }) {
+ if (!Number.isFinite(lat) || lat < -90 || lat > 90) return { code: 'invalid_lat', message: "query param 'lat' must be a number between -90 and 90" };
+ if (!Number.isFinite(lon) || lon < -180 || lon > 180) return { code: 'invalid_lon', message: "query param 'lon' must be a number between -180 and 180" };
+ if (!Number.isFinite(radius) || radius <= 0 || radius > 5000) return { code: 'invalid_radius', message: "query param 'radius' must be a number of metres between 1 and 5000" };
+ if (!Number.isFinite(limit) || limit < 1 || limit > 50) return { code: 'invalid_limit', message: "query param 'limit' must be an integer between 1 and 50" };
+ if (category !== null && !/^[a-z0-9_]{1,40}$/.test(category)) return { code: 'invalid_category', message: "query param 'category' must be an OSM tag value such as cafe, restaurant, pharmacy, bar, museum" };
+ return null;
+}
+
+let _paid = null;
+function paidHandler() {
+ if (_paid) return _paid;
+ _paid = paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ priceAtomics: priceFor('places-search', '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 = parseParams(req);
+ const invalid = validate(params);
+ if (invalid) {
+ const err = new Error(invalid.message);
+ err.status = 400;
+ err.code = invalid.code;
+ throw err;
+ }
+ const data = await searchPlaces(params.lat, params.lon, params.radius, params.category, params.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.placesFreeIp(clientIp(req));
+ if (!rl.success) return paidHandler()(req, res);
+
+ const params = parseParams(req);
+ const invalid = validate(params);
+ if (invalid) return error(res, 400, invalid.code, invalid.message);
+
+ try {
+ const data = await searchPlaces(params.lat, params.lon, params.radius, params.category, params.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);
+ }
+});
diff --git a/api/x402/transit-delays.js b/api/x402/transit-delays.js
new file mode 100644
index 000000000..490a04e82
--- /dev/null
+++ b/api/x402/transit-delays.js
@@ -0,0 +1,89 @@
+// GET /api/x402/transit-delays?stop=South+Station&limit=20
+//
+// Transit Delay Snapshot: $0.001 USDC per call, always paid (the free
+// quota lives on transit-plan). Live MBTA GTFS-Realtime vs schedule.
+
+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 { resolvePlace, delaySnapshot, BadRequestError, NotFoundError, UpstreamError } from '../_lib/x402-services/transit.js';
+import listing from '../_lib/service-catalog/services/transit-delays.js';
+
+const ROUTE = '/api/x402/transit-delays';
+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', 'summary', 'arrivals'],
+ properties: {
+ source: { type: 'string' },
+ agency: { type: 'string' },
+ summary: { type: 'object' },
+ arrivals: { type: 'array' },
+ },
+};
+
+export const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['service monitoring', 'commute automation', 'mobility 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 clamp(n, lo, hi) {
+ return Math.max(lo, Math.min(hi, Math.round(n)));
+}
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ priceAtomics: priceFor('transit-delays', '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 stopRaw = String(params.get('stop') || '').trim();
+ if (!stopRaw) {
+ const err = new Error('query param "stop" is required');
+ err.status = 400;
+ err.code = 'missing_stop';
+ throw err;
+ }
+ const routeId = params.get('route') || null;
+ const limitRaw = Number(params.get('limit') || '20');
+ const limit = clamp(Number.isFinite(limitRaw) ? limitRaw : 20, 1, 100);
+
+ try {
+ const stop = await resolvePlace(stopRaw, 'stop');
+ return await delaySnapshot(stop, routeId, limit);
+ } catch (err) {
+ if (err instanceof BadRequestError) {
+ const e = new Error(err.message);
+ e.status = 400;
+ e.code = 'bad_request';
+ throw e;
+ }
+ if (err instanceof NotFoundError) {
+ const e = new Error(err.message);
+ e.status = 404;
+ e.code = 'not_found';
+ throw e;
+ }
+ if (err instanceof UpstreamError) {
+ const e = new Error(err.message);
+ e.status = 502;
+ e.code = 'upstream_error';
+ throw e;
+ }
+ throw err;
+ }
+ },
+});
diff --git a/api/x402/transit-plan.js b/api/x402/transit-plan.js
new file mode 100644
index 000000000..0c5cf028c
--- /dev/null
+++ b/api/x402/transit-plan.js
@@ -0,0 +1,117 @@
+// GET /api/x402/transit-plan?from=South+Station&to=Alewife&max=3
+//
+// Transit Trip Plan: $0.002 USDC per call (free daily per-IP quota runs
+// first). Live MBTA GTFS schedule plus GTFS-Realtime predictions. No key.
+
+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 { resolvePlace, planTrip, parseWhen, BadRequestError, NotFoundError, UpstreamError } from '../_lib/x402-services/transit.js';
+import listing from '../_lib/service-catalog/services/transit-plan.js';
+
+const ROUTE = '/api/x402/transit-plan';
+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', 'agency', 'itineraries'],
+ properties: {
+ source: { type: 'string' },
+ agency: { type: 'string' },
+ feed: { type: 'string' },
+ itineraries: { type: 'array' },
+ note: { type: 'string' },
+ tier: { type: 'string', enum: ['free', 'paid'] },
+ free_remaining_today: { type: 'integer' },
+ },
+};
+
+export const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['trip planning', 'mobility agents', 'commute 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 clamp(n, lo, hi) {
+ return Math.max(lo, Math.min(hi, Math.round(n)));
+}
+
+async function resolveAndPlan(req) {
+ const params = new URL(req.url, 'http://x').searchParams;
+ const fromRaw = String(params.get('from') || '').trim();
+ const toRaw = String(params.get('to') || '').trim();
+ if (!fromRaw || !toRaw) {
+ const err = new Error('"from" and "to" are required. Each accepts a stop id, a station name, or "lat,lon".');
+ err.status = 400;
+ err.code = 'missing_place';
+ throw err;
+ }
+ const maxRaw = Number(params.get('max') || '3');
+ const max = clamp(Number.isFinite(maxRaw) ? maxRaw : 3, 1, 10);
+ const departAfter = parseWhen(params.get('departAfter') || undefined);
+
+ const [from, to] = await Promise.all([resolvePlace(fromRaw, 'from'), resolvePlace(toRaw, 'to')]);
+ return planTrip(from, to, departAfter, max);
+}
+
+function toHttpError(err) {
+ if (err instanceof BadRequestError) return { status: 400, code: 'bad_request', message: err.message };
+ if (err instanceof NotFoundError) return { status: 404, code: 'not_found', message: err.message };
+ if (err instanceof UpstreamError) return { status: 502, code: 'upstream_error', message: err.message };
+ return { status: err.status || 500, code: err.code || 'internal_error', message: err.message };
+}
+
+let _paid = null;
+function paidHandler() {
+ if (_paid) return _paid;
+ _paid = paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ priceAtomics: priceFor('transit-plan', '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 }) {
+ try {
+ const data = await resolveAndPlan(req);
+ return { ...data, tier: 'paid' };
+ } catch (err) {
+ const { status, code, message } = toHttpError(err);
+ const e = new Error(message);
+ e.status = status;
+ e.code = code;
+ throw e;
+ }
+ },
+ });
+ 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.transitFreeIp(clientIp(req));
+ if (!rl.success) return paidHandler()(req, res);
+
+ try {
+ const data = await resolveAndPlan(req);
+ return json(res, 200, { ...data, tier: 'free', free_remaining_today: Math.max(0, rl.remaining) }, { 'cache-control': 'no-store' });
+ } catch (err) {
+ const { status, code, message } = toHttpError(err);
+ return error(res, status, code, message);
+ }
+});