@opennodes/registry 0.1.40 → 0.1.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -3
- package/bin.js +5 -0
- package/package.json +2 -2
- package/src/data/locations-ca.json +208 -0
- package/src/data/locations-eu.json +539 -0
- package/src/importers.js +196 -0
- package/src/location.js +4 -8
- package/src/locations.js +242 -0
- package/src/mcp.js +21 -15
- package/src/probes.js +21 -1
- package/src/reimport.js +8 -1
- package/src/search.js +32 -3
- package/src/server.js +48 -2
- package/src/web/index.html +161 -2
package/src/importers.js
CHANGED
|
@@ -406,3 +406,199 @@ export async function importOpenRouter(store, catalog) {
|
|
|
406
406
|
if (err) return { providers: 0, offerings: 0, skipped: [err] };
|
|
407
407
|
return { providers: 1, offerings: offeringList.length, skipped: [] };
|
|
408
408
|
}
|
|
409
|
+
|
|
410
|
+
/* ------------------------------------------------------------------ locations (ONP-2 §3a) */
|
|
411
|
+
|
|
412
|
+
/** Save a listing-only card: like saveImportedCard, but without invocation endpoints. */
|
|
413
|
+
async function saveListingCard(store, nodeId, origin, sourceRef, card) {
|
|
414
|
+
const errors = validateCard(card)
|
|
415
|
+
.filter((e) => !/^\/endpoints must have required property '(openai|health)'$/.test(e));
|
|
416
|
+
if (errors.length) return errors[0];
|
|
417
|
+
await store.upsertNode(nodeId, origin, sourceRef, 'indexed', 'import');
|
|
418
|
+
await store.saveRevision(nodeId, card.revision, card, false);
|
|
419
|
+
return null;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
export const OPENROUTER_PROVIDERS_URL = 'https://openrouter.ai/api/v1/providers';
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* Region segments seen in OpenRouter endpoint tags (`amazon-bedrock/eu-west-1`,
|
|
426
|
+
* `baseten/fp4/us`) -> ONP region codes. `global` means the provider may serve anywhere.
|
|
427
|
+
*/
|
|
428
|
+
export const CLOUD_REGIONS = {
|
|
429
|
+
us: 'US', eu: 'EU', europe: 'EU', global: null,
|
|
430
|
+
'us-east-1': 'US-VA', 'us-east-2': 'US-OH', 'us-west-2': 'US-OR', 'us-east5': 'US-OH', 'us-central1': 'US-IA',
|
|
431
|
+
'eu-west-1': 'IE', 'eu-central-1': 'DE', swedencentral: 'SE',
|
|
432
|
+
'ca-central-1': 'CA-QC', 'ca-west-1': 'CA-AB', canadacentral: 'CA-ON', canadaeast: 'CA-QC',
|
|
433
|
+
'northamerica-northeast1': 'CA-QC', 'northamerica-northeast2': 'CA-ON',
|
|
434
|
+
};
|
|
435
|
+
|
|
436
|
+
/** Fetch every model's endpoint list (`links.details`), a few at a time. Returns Map(model id -> endpoints). */
|
|
437
|
+
export async function fetchOpenRouterEndpoints(getJson, models, concurrency = 4) {
|
|
438
|
+
const out = new Map();
|
|
439
|
+
const queue = [...models];
|
|
440
|
+
const worker = async () => {
|
|
441
|
+
for (let m = queue.shift(); m; m = queue.shift()) {
|
|
442
|
+
const path = m.links?.details ?? `/api/v1/models/${m.id}/endpoints`;
|
|
443
|
+
try { out.set(m.id, (await getJson(new URL(path, 'https://openrouter.ai').href))?.data?.endpoints ?? []); }
|
|
444
|
+
catch { out.set(m.id, []); } // a model can vanish between the two calls
|
|
445
|
+
}
|
|
446
|
+
};
|
|
447
|
+
await Promise.all(Array.from({ length: concurrency }, worker));
|
|
448
|
+
return out;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* Import OpenRouter per provider, with the locations providers declare to OpenRouter:
|
|
453
|
+
* `headquarters` -> operator country, `datacenters` -> node locations, and a region segment
|
|
454
|
+
* in the endpoint tag -> that offering's location. All are `claimed`. Only endpoints with
|
|
455
|
+
* some location become offerings (listing-only, node `import.openrouter.p.{provider}`); the
|
|
456
|
+
* rest are counted as `unlocated`, which is the size of the gap.
|
|
457
|
+
*/
|
|
458
|
+
export async function importOpenRouterProviders(store, providers, models, endpointsById, { checked = today() } = {}) {
|
|
459
|
+
const bySlug = new Map((providers ?? []).map((p) => [p.slug, p]));
|
|
460
|
+
const byName = new Map((providers ?? []).map((p) => [p.name, p]));
|
|
461
|
+
const groups = new Map(); // provider slug -> offerings[]
|
|
462
|
+
let unlocated = 0;
|
|
463
|
+
|
|
464
|
+
for (const model of models ?? []) {
|
|
465
|
+
const author = vendorSlug(model.id.split('/')[0] || 'unknown');
|
|
466
|
+
const inputs = model.architecture?.input_modalities ?? ['text'];
|
|
467
|
+
const outputs = model.architecture?.output_modalities ?? ['text'];
|
|
468
|
+
for (const ep of endpointsById.get(model.id) ?? []) {
|
|
469
|
+
const [tagSlug, ...rest] = String(ep.tag ?? '').split('/');
|
|
470
|
+
const provider = bySlug.get(tagSlug) ?? byName.get(ep.provider_name);
|
|
471
|
+
if (!provider) { unlocated++; continue; }
|
|
472
|
+
const regionSeg = rest.find((s) => s in CLOUD_REGIONS);
|
|
473
|
+
const declared = provider.datacenters ?? [];
|
|
474
|
+
if (regionSeg === 'global' || (!regionSeg && !declared.length)) { unlocated++; continue; }
|
|
475
|
+
|
|
476
|
+
const supports = ['streaming'];
|
|
477
|
+
const params = ep.supported_parameters ?? model.supported_parameters ?? [];
|
|
478
|
+
if (params.includes('tools')) supports.push('tool_calls');
|
|
479
|
+
if (params.includes('response_format') || params.includes('structured_outputs')) supports.push('json_mode');
|
|
480
|
+
if (inputs.includes('image') && outputs.includes('text')) supports.push('vision');
|
|
481
|
+
const offering = {
|
|
482
|
+
offering_id: slug([model.id.replace('/', '-'), ...rest].join('-')),
|
|
483
|
+
modality: mapModalities(inputs, outputs),
|
|
484
|
+
modalities: { input: inputs, output: outputs },
|
|
485
|
+
model: {
|
|
486
|
+
name: model.name ?? model.id,
|
|
487
|
+
family: author,
|
|
488
|
+
artifact: model.hugging_face_id
|
|
489
|
+
? `hf:${model.hugging_face_id}`
|
|
490
|
+
: `urn:proprietary:${author}:${slug(model.id.split('/').slice(1).join('-') || model.id)}`,
|
|
491
|
+
...(ep.quantization && ep.quantization !== 'unknown' ? { quantization: ep.quantization } : {}),
|
|
492
|
+
},
|
|
493
|
+
serving: {
|
|
494
|
+
supports,
|
|
495
|
+
...(ep.context_length ? { context_window: Math.floor(ep.context_length) } : {}),
|
|
496
|
+
...(ep.max_completion_tokens ? { max_output_tokens: Math.floor(ep.max_completion_tokens) } : {}),
|
|
497
|
+
},
|
|
498
|
+
binding: { profile: 'onp.openai.chat/v1', model_id: model.id },
|
|
499
|
+
pricing: {
|
|
500
|
+
currency: 'USD',
|
|
501
|
+
input_per_mtok: perMtok(ep.pricing?.prompt),
|
|
502
|
+
output_per_mtok: perMtok(ep.pricing?.completion),
|
|
503
|
+
schemes: ['prepaid'],
|
|
504
|
+
},
|
|
505
|
+
...(regionSeg ? { locations: [{
|
|
506
|
+
region: CLOUD_REGIONS[regionSeg], basis: 'claimed', note: `OpenRouter endpoint tag ${ep.tag}`,
|
|
507
|
+
}] } : {}),
|
|
508
|
+
};
|
|
509
|
+
if (!groups.has(provider.slug)) groups.set(provider.slug, []);
|
|
510
|
+
const list = groups.get(provider.slug);
|
|
511
|
+
if (list.some((o) => o.offering_id === offering.offering_id)) offering.offering_id = slug(`${offering.offering_id}-${list.length}`);
|
|
512
|
+
list.push(offering);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
let count = 0, offerings = 0;
|
|
517
|
+
const skipped = [];
|
|
518
|
+
for (const [providerSlug, offeringList] of groups) {
|
|
519
|
+
const p = bySlug.get(providerSlug);
|
|
520
|
+
const nodeId = `import.openrouter.p.${vendorSlug(providerSlug)}`;
|
|
521
|
+
const declared = (p.datacenters ?? []).filter((c) => /^[A-Z]{2}$/.test(c));
|
|
522
|
+
const card = {
|
|
523
|
+
onp: '0.1',
|
|
524
|
+
revision: new Date().toISOString(),
|
|
525
|
+
node: {
|
|
526
|
+
id: nodeId,
|
|
527
|
+
name: `${p.name} (via OpenRouter)`,
|
|
528
|
+
description: 'Imported from the OpenRouter provider and endpoint APIs. Locations are what the provider declares to OpenRouter (claimed). Listing only: call it through OpenRouter with provider routing.',
|
|
529
|
+
operator: { name: p.name, ...(/^[A-Z]{2}$/.test(p.headquarters ?? '') ? { country: p.headquarters } : {}) },
|
|
530
|
+
...(declared.length ? {
|
|
531
|
+
regions: declared,
|
|
532
|
+
locations: declared.map((c) => ({ region: c, basis: 'claimed', source: OPENROUTER_PROVIDERS_URL, checked })),
|
|
533
|
+
} : {}),
|
|
534
|
+
},
|
|
535
|
+
endpoints: { docs: `https://openrouter.ai/provider/${encodeURIComponent(providerSlug)}` },
|
|
536
|
+
offerings: offeringList,
|
|
537
|
+
payment: { schemes: [{ scheme: 'prepaid', signup: 'https://openrouter.ai/keys' }] },
|
|
538
|
+
};
|
|
539
|
+
const err = await saveListingCard(store, nodeId, 'https://openrouter.ai', `import:openrouter-provider:${providerSlug}`, card);
|
|
540
|
+
if (err) { skipped.push(`${providerSlug}: ${err}`); continue; }
|
|
541
|
+
count++;
|
|
542
|
+
offerings += offeringList.length;
|
|
543
|
+
}
|
|
544
|
+
return { providers: count, offerings, unlocated, skipped };
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* Import a curated location seed (src/data/locations-*.json): providers, their sites with
|
|
549
|
+
* evidence, and the models each site serves. A provider with listed models becomes a
|
|
550
|
+
* listing-only node `import.seed.{seed}.{id}`; one without (models not published) stays
|
|
551
|
+
* site-only and is served by /v0/locations straight from the seed.
|
|
552
|
+
*/
|
|
553
|
+
export async function importLocationSeed(store, seed) {
|
|
554
|
+
let providers = 0, offerings = 0, siteOnly = 0;
|
|
555
|
+
const skipped = [];
|
|
556
|
+
for (const p of seed?.providers ?? []) {
|
|
557
|
+
if (!p.models?.length) { siteOnly++; continue; }
|
|
558
|
+
const sites = new Map((p.sites ?? []).map((s) => [s.id, siteLocation(s)]));
|
|
559
|
+
const offeringList = p.models.map((m) => {
|
|
560
|
+
const family = vendorSlug(m.family ?? p.id);
|
|
561
|
+
return {
|
|
562
|
+
offering_id: slug(m.id ?? m.name),
|
|
563
|
+
modality: m.modality ?? 'text',
|
|
564
|
+
model: {
|
|
565
|
+
name: m.name,
|
|
566
|
+
family,
|
|
567
|
+
artifact: m.artifact ?? `urn:proprietary:${family}:${slug(m.id ?? m.name).replace(/\//g, '-')}`,
|
|
568
|
+
...(m.lineage_origins ? { lineage_origins: m.lineage_origins } : {}),
|
|
569
|
+
},
|
|
570
|
+
serving: {},
|
|
571
|
+
binding: { profile: m.modality === 'embedding' ? 'onp.openai.embeddings/v1' : 'onp.openai.chat/v1', model_id: m.model_id ?? m.name },
|
|
572
|
+
pricing: { currency: 'USD', schemes: ['contract'] },
|
|
573
|
+
...(m.sites ? { locations: m.sites.map((id) => sites.get(id)).filter(Boolean) } : {}),
|
|
574
|
+
};
|
|
575
|
+
});
|
|
576
|
+
const nodeId = `import.seed.${vendorSlug(seed.seed)}.${vendorSlug(p.id)}`;
|
|
577
|
+
const card = {
|
|
578
|
+
onp: '0.1',
|
|
579
|
+
revision: new Date().toISOString(),
|
|
580
|
+
node: {
|
|
581
|
+
id: nodeId,
|
|
582
|
+
name: p.name,
|
|
583
|
+
description: [p.note, seed.note].filter(Boolean).join(' ').slice(0, 4000),
|
|
584
|
+
operator: { name: p.operator?.name ?? p.name, ...(p.operator?.country ? { country: p.operator.country } : {}), ...(p.operator?.url ? { url: p.operator.url } : {}) },
|
|
585
|
+
locations: [...sites.values()],
|
|
586
|
+
},
|
|
587
|
+
endpoints: { ...(p.operator?.url ? { docs: p.operator.url } : {}) },
|
|
588
|
+
offerings: offeringList,
|
|
589
|
+
payment: { schemes: [{ scheme: 'contract' }] },
|
|
590
|
+
};
|
|
591
|
+
const err = await saveListingCard(store, nodeId, p.operator?.url ? new URL(p.operator.url).origin : 'https://opennodes.io', `import:seed:${seed.seed}:${p.id}`, card);
|
|
592
|
+
if (err) { skipped.push(`${p.id}: ${err}`); continue; }
|
|
593
|
+
providers++;
|
|
594
|
+
offerings += offeringList.length;
|
|
595
|
+
}
|
|
596
|
+
return { providers, offerings, site_only: siteOnly, skipped };
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/** A seed site -> an ONP location (drops the seed-local `id`). */
|
|
600
|
+
export function siteLocation({ id, ...location }) {
|
|
601
|
+
return location;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
const today = () => new Date().toISOString().slice(0, 10);
|
package/src/location.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Server-location checks (ONP-1 §6 threat 5, ONP-3 §6.
|
|
1
|
+
// Server-location checks (ONP-1 §6 threat 5, ONP-3 §6.4): where a node's API host actually is,
|
|
2
2
|
// compared with the operator's declared country. Two signals, both evidence rather than proof:
|
|
3
3
|
// (a) IP geolocation + network owner of the endpoint host (RIPE NCC RIPEstat, no key needed);
|
|
4
4
|
// CDN / anycast networks are reported as such, never as a location.
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
// (an auditor's credential) is the strong guarantee, planned for Draft 0.2.
|
|
11
11
|
import net from 'node:net';
|
|
12
12
|
import dns from 'node:dns/promises';
|
|
13
|
-
import { EEA_COUNTRIES } from '@opennodes/core';
|
|
13
|
+
import { EEA_COUNTRIES, distanceKm } from '@opennodes/core';
|
|
14
14
|
import { isPrivateHost } from './namespace.js';
|
|
15
15
|
|
|
16
16
|
const RIPESTAT = 'https://stat.ripe.net/data';
|
|
@@ -25,12 +25,8 @@ export const CDN_ASNS = new Map([
|
|
|
25
25
|
|
|
26
26
|
const EEA = new Set(EEA_COUNTRIES);
|
|
27
27
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
const dLat = rad(b.lat - a.lat), dLon = rad(b.lon - a.lon);
|
|
31
|
-
const h = Math.sin(dLat / 2) ** 2 + Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(dLon / 2) ** 2;
|
|
32
|
-
return 2 * 6371 * Math.asin(Math.sqrt(h));
|
|
33
|
-
}
|
|
28
|
+
/** Great-circle distance in km; one implementation, shared with /v0/locations (core geo.js). */
|
|
29
|
+
export const haversineKm = distanceKm;
|
|
34
30
|
|
|
35
31
|
/**
|
|
36
32
|
* Judge measured RTTs against a claimed point. vantages: [{site, lat, lon, rtt_ms}].
|
package/src/locations.js
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
// Where models run (ONP-3 §5c): every known serving site, with its evidence basis and the
|
|
2
|
+
// models it serves, built from card locations (registered nodes and imports) plus the
|
|
3
|
+
// site-only entries of the curated seeds (providers that publish sites but not models).
|
|
4
|
+
import { readFileSync, readdirSync } from 'node:fs';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import {
|
|
7
|
+
sendJson, problem, regionWithin, countryOf, basisRank, pointFor, distanceKm, parsePoint, precisionRank,
|
|
8
|
+
} from '@opennodes/core';
|
|
9
|
+
import { siteLocation } from './importers.js';
|
|
10
|
+
|
|
11
|
+
const DATA_DIR = fileURLToPath(new URL('./data/', import.meta.url));
|
|
12
|
+
const HIDDEN = ['delisted', 'suspended', 'submitted', 'challenged', 'disputed', 'claimed'];
|
|
13
|
+
|
|
14
|
+
/** The curated seeds bundled with the registry (src/data/locations-*.json). */
|
|
15
|
+
export function loadLocationSeeds(dir = DATA_DIR) {
|
|
16
|
+
return readdirSync(dir).filter((f) => /^locations-.+\.json$/.test(f)).sort()
|
|
17
|
+
.map((f) => JSON.parse(readFileSync(dir + f, 'utf8')));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** All sites, unfiltered: one entry per (node, region, site), models attached. */
|
|
21
|
+
export async function collectSites(store, seeds = []) {
|
|
22
|
+
const sites = new Map();
|
|
23
|
+
let located = 0, unlocated = 0;
|
|
24
|
+
const siteFor = (base, loc) => {
|
|
25
|
+
const key = `${base.node_id}|${loc.region}|${loc.site ?? ''}`;
|
|
26
|
+
if (!sites.has(key)) {
|
|
27
|
+
sites.set(key, {
|
|
28
|
+
...base,
|
|
29
|
+
country: countryOf(loc.region),
|
|
30
|
+
region: loc.region,
|
|
31
|
+
site: loc.site ?? null,
|
|
32
|
+
status: loc.status ?? 'live',
|
|
33
|
+
basis: loc.basis,
|
|
34
|
+
facility_operator: loc.facility_operator ?? null,
|
|
35
|
+
source_url: loc.source ?? null,
|
|
36
|
+
checked: loc.checked ?? null,
|
|
37
|
+
note: loc.note ?? null,
|
|
38
|
+
geo: pointFor(loc), // declared point, else an approximate one from the region (derived: true)
|
|
39
|
+
models: [],
|
|
40
|
+
models_note: null,
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
return sites.get(key);
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
for (const node of await store.allNodes()) {
|
|
47
|
+
if (HIDDEN.includes(node.state)) continue;
|
|
48
|
+
const card = await store.latestCard(node.id);
|
|
49
|
+
if (!card) continue;
|
|
50
|
+
// The registry's server-location check (location.js, ONP-3 §6.4) covers the node's API host,
|
|
51
|
+
// not each site: shown beside the declared sites, never turning one into `measured` by itself.
|
|
52
|
+
const check = (await store.getObservations(node.id, '_node')).location ?? null;
|
|
53
|
+
const base = {
|
|
54
|
+
node_id: node.id,
|
|
55
|
+
provider: card.node?.name ?? node.id,
|
|
56
|
+
operator: card.node?.operator?.name ?? null,
|
|
57
|
+
operator_country: card.node?.operator?.country ?? null,
|
|
58
|
+
tier: node.state === 'indexed' ? 'unverified' : node.state,
|
|
59
|
+
source: node.source ?? 'registration',
|
|
60
|
+
server_check: check ? {
|
|
61
|
+
verdict: check.verdict, server_country: check.server?.country ?? null,
|
|
62
|
+
latency: check.latency?.verdict ?? 'unknown', checked_at: check.checked_at ?? null,
|
|
63
|
+
} : null,
|
|
64
|
+
};
|
|
65
|
+
for (const loc of card.node?.locations ?? []) siteFor(base, loc);
|
|
66
|
+
for (const o of card.offerings) {
|
|
67
|
+
const locs = Array.isArray(o.locations) ? o.locations : (card.node?.locations ?? []);
|
|
68
|
+
if (!locs.length) { unlocated++; continue; }
|
|
69
|
+
located++;
|
|
70
|
+
for (const loc of locs) {
|
|
71
|
+
siteFor(base, loc).models.push({
|
|
72
|
+
offering_id: o.offering_id,
|
|
73
|
+
name: o.model.name,
|
|
74
|
+
artifact: o.model.artifact,
|
|
75
|
+
family: o.model.family ?? null,
|
|
76
|
+
modality: o.modality,
|
|
77
|
+
lineage_origins: o.model.lineage_origins ?? null,
|
|
78
|
+
invocable: Boolean(card.endpoints?.openai),
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
for (const seed of seeds) {
|
|
85
|
+
for (const p of seed.providers ?? []) {
|
|
86
|
+
if (p.models?.length) continue; // imported as a card; its sites came in above
|
|
87
|
+
const base = {
|
|
88
|
+
node_id: `import.seed.${seed.seed}.${p.id}`,
|
|
89
|
+
provider: p.name,
|
|
90
|
+
operator: p.operator?.name ?? p.name,
|
|
91
|
+
operator_country: p.operator?.country ?? null,
|
|
92
|
+
tier: 'unverified',
|
|
93
|
+
source: 'seed',
|
|
94
|
+
server_check: null,
|
|
95
|
+
};
|
|
96
|
+
for (const s of p.sites ?? []) siteFor(base, siteLocation(s)).models_note = p.models_note ?? 'Models not published';
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return { sites: [...sites.values()], located_offerings: located, unlocated_offerings: unlocated };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Filter and summarise. Query: country | region (containment), basis (minimum evidence),
|
|
104
|
+
* status (live | planned), model (substring of name or artifact), exclude_lineage (CSV of
|
|
105
|
+
* countries; drops those models, keeps undeclared lineage), near=lat,lon (adds distance_km,
|
|
106
|
+
* nearest first) with within_km (radius; country-level points never match), format=csv|geojson.
|
|
107
|
+
*/
|
|
108
|
+
export async function buildLocations(store, seeds, query) {
|
|
109
|
+
const q = (k) => query.get(k);
|
|
110
|
+
const near = q('near') ? parsePoint(q('near')) : null;
|
|
111
|
+
if (q('near') && !near) throw Object.assign(new Error('near must be "lat,lon" in decimal degrees, e.g. 45.50,-73.57'), { status: 400 });
|
|
112
|
+
if (q('within_km') && !(near && Number(q('within_km')) > 0)) throw Object.assign(new Error('within_km needs near and a positive number of km'), { status: 400 });
|
|
113
|
+
const all = await collectSites(store, seeds);
|
|
114
|
+
let sites = all.sites;
|
|
115
|
+
const where = q('region') ?? q('country');
|
|
116
|
+
if (where) sites = sites.filter((s) => regionWithin(s.region, where));
|
|
117
|
+
if (q('basis')) sites = sites.filter((s) => basisRank(s.basis) >= basisRank(q('basis')));
|
|
118
|
+
if (q('status')) sites = sites.filter((s) => s.status === q('status'));
|
|
119
|
+
const banned = q('exclude_lineage')?.toUpperCase().split(',') ?? [];
|
|
120
|
+
const needle = q('model')?.toLowerCase();
|
|
121
|
+
if (banned.length || needle) {
|
|
122
|
+
sites = sites.map((s) => ({
|
|
123
|
+
...s,
|
|
124
|
+
models: s.models.filter((m) => !(m.lineage_origins ?? []).some((c) => banned.includes(c))
|
|
125
|
+
&& (!needle || `${m.name} ${m.artifact}`.toLowerCase().includes(needle))),
|
|
126
|
+
}));
|
|
127
|
+
if (needle) sites = sites.filter((s) => s.models.length);
|
|
128
|
+
}
|
|
129
|
+
sites.sort((a, b) => a.country.localeCompare(b.country) || a.region.localeCompare(b.region)
|
|
130
|
+
|| a.provider.localeCompare(b.provider) || String(a.site).localeCompare(String(b.site)));
|
|
131
|
+
if (near) {
|
|
132
|
+
sites = sites.map((s) => ({ ...s, distance_km: s.geo ? Math.round(distanceKm(near, s.geo)) : null }));
|
|
133
|
+
if (q('within_km')) {
|
|
134
|
+
// A radius is only meaningful for points placed at least to the region.
|
|
135
|
+
const r = Number(q('within_km'));
|
|
136
|
+
sites = sites.filter((s) => s.distance_km != null && s.distance_km <= r && precisionRank(s.geo.precision) <= precisionRank('region'));
|
|
137
|
+
}
|
|
138
|
+
sites.sort((a, b) => (a.distance_km ?? Infinity) - (b.distance_km ?? Infinity)); // stable: ties keep country order
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const countries = new Map();
|
|
142
|
+
for (const s of sites) {
|
|
143
|
+
const c = countries.get(s.country) ?? { country: s.country, providers: new Set(), sites: 0, live_sites: 0, models: new Set() };
|
|
144
|
+
c.providers.add(s.node_id);
|
|
145
|
+
c.sites++;
|
|
146
|
+
if (s.status === 'live') c.live_sites++;
|
|
147
|
+
for (const m of s.models) c.models.add(m.artifact);
|
|
148
|
+
countries.set(s.country, c);
|
|
149
|
+
}
|
|
150
|
+
return {
|
|
151
|
+
generated_at: new Date().toISOString(),
|
|
152
|
+
filters: Object.fromEntries([...query].filter(([k]) => k !== 'format')),
|
|
153
|
+
summary: {
|
|
154
|
+
countries: countries.size,
|
|
155
|
+
sites: sites.length,
|
|
156
|
+
located_offerings: all.located_offerings,
|
|
157
|
+
unlocated_offerings: all.unlocated_offerings,
|
|
158
|
+
},
|
|
159
|
+
countries: [...countries.values()].map((c) => ({
|
|
160
|
+
country: c.country, providers: c.providers.size, sites: c.sites, live_sites: c.live_sites, models: c.models.size,
|
|
161
|
+
})),
|
|
162
|
+
sites,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const CSV_COLUMNS = ['country', 'region', 'site', 'status', 'basis', 'provider', 'operator', 'operator_country',
|
|
167
|
+
'facility_operator', 'node_id', 'tier', 'source', 'model', 'artifact', 'lineage_origins', 'source_url', 'checked', 'note',
|
|
168
|
+
'lat', 'lon', 'precision', 'derived', 'distance_km'];
|
|
169
|
+
const csvCell = (v) => {
|
|
170
|
+
const s = v == null ? '' : String(v);
|
|
171
|
+
return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
/** One row per site and model; a site with no published models gets one row with its note. */
|
|
175
|
+
export function locationsCsv(report) {
|
|
176
|
+
const rows = [CSV_COLUMNS.join(',')];
|
|
177
|
+
for (const s of report.sites) {
|
|
178
|
+
const models = s.models.length ? s.models : [{ name: s.models_note ?? '', artifact: '', lineage_origins: null }];
|
|
179
|
+
for (const m of models) {
|
|
180
|
+
const row = {
|
|
181
|
+
...s, model: m.name, artifact: m.artifact, lineage_origins: (m.lineage_origins ?? []).join(' '),
|
|
182
|
+
lat: s.geo?.lat, lon: s.geo?.lon, precision: s.geo?.precision, derived: s.geo?.derived,
|
|
183
|
+
};
|
|
184
|
+
rows.push(CSV_COLUMNS.map((c) => csvCell(row[c])).join(','));
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return rows.join('\n') + '\n';
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* RFC 7946 GeoJSON: one Point feature per site with a point ([lon, lat]). Properties are flat
|
|
192
|
+
* (lists joined with "; ") so desktop GIS tools (QGIS, ArcGIS) read them as plain columns.
|
|
193
|
+
* Sites with no point at all are counted in the foreign member `unmapped`.
|
|
194
|
+
*/
|
|
195
|
+
export function locationsGeoJson(report) {
|
|
196
|
+
const features = report.sites.filter((s) => s.geo).map((s) => ({
|
|
197
|
+
type: 'Feature',
|
|
198
|
+
id: `${s.node_id}|${s.region}|${s.site ?? ''}`,
|
|
199
|
+
geometry: { type: 'Point', coordinates: [s.geo.lon, s.geo.lat] },
|
|
200
|
+
properties: {
|
|
201
|
+
provider: s.provider, operator: s.operator, operator_country: s.operator_country,
|
|
202
|
+
node_id: s.node_id, tier: s.tier, source: s.source,
|
|
203
|
+
country: s.country, region: s.region, site: s.site, status: s.status, basis: s.basis,
|
|
204
|
+
facility_operator: s.facility_operator, source_url: s.source_url, checked: s.checked, note: s.note,
|
|
205
|
+
precision: s.geo.precision, derived: s.geo.derived,
|
|
206
|
+
models_count: s.models.length,
|
|
207
|
+
models: s.models.map((m) => m.name).join('; '),
|
|
208
|
+
lineage: [...new Set(s.models.flatMap((m) => m.lineage_origins ?? []))].join('; '),
|
|
209
|
+
models_note: s.models_note,
|
|
210
|
+
...(s.distance_km !== undefined ? { distance_km: s.distance_km } : {}),
|
|
211
|
+
},
|
|
212
|
+
}));
|
|
213
|
+
return {
|
|
214
|
+
type: 'FeatureCollection',
|
|
215
|
+
generated_at: report.generated_at,
|
|
216
|
+
filters: report.filters,
|
|
217
|
+
unmapped: report.sites.length - features.length,
|
|
218
|
+
features,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export function locationRoutes(store, seeds) {
|
|
223
|
+
return [
|
|
224
|
+
['GET', '/v0/locations', async (req, res, { query }) => {
|
|
225
|
+
let report;
|
|
226
|
+
try { report = await buildLocations(store, seeds, query); }
|
|
227
|
+
catch (err) { if (err.status === 400) return problem(res, 400, 'bad-query', err.message); throw err; }
|
|
228
|
+
const format = query.get('format');
|
|
229
|
+
if (format === 'csv') {
|
|
230
|
+
res.writeHead(200, { 'content-type': 'text/csv; charset=utf-8', 'content-disposition': 'inline; filename="locations.csv"' });
|
|
231
|
+
res.end(locationsCsv(report));
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
if (format === 'geojson') {
|
|
235
|
+
res.writeHead(200, { 'content-type': 'application/geo+json; charset=utf-8', 'content-disposition': 'inline; filename="locations.geojson"' });
|
|
236
|
+
res.end(JSON.stringify(locationsGeoJson(report)));
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
sendJson(res, 200, report);
|
|
240
|
+
}],
|
|
241
|
+
];
|
|
242
|
+
}
|
package/src/mcp.js
CHANGED
|
@@ -1,9 +1,18 @@
|
|
|
1
1
|
// DS-MCP-01: the registry as an MCP server (streamable HTTP, stateless).
|
|
2
2
|
// Minimal JSON-RPC handler covering initialize / tools/list / tools/call so any
|
|
3
|
-
// MCP host gets ONP discovery (recommend, search_offerings, get_offering, get_node, estimate
|
|
3
|
+
// MCP host gets ONP discovery (recommend, search_offerings, get_offering, get_node, estimate,
|
|
4
|
+
// find_locations) for free.
|
|
4
5
|
import { readFileSync } from 'node:fs';
|
|
5
6
|
import { readJson, sendJson, problem, estimateBounds, round6, extractFeatures, recommend, MCP_TOOLS, MCP_INSTRUCTIONS, summarizeNode } from '@opennodes/core';
|
|
6
7
|
import { searchOfferingsPaged, searchOfferings, collectOfferings, pricePublished } from './search.js';
|
|
8
|
+
import { buildLocations } from './locations.js';
|
|
9
|
+
|
|
10
|
+
/** Tool arguments -> the query string the REST routes take (null/undefined dropped). */
|
|
11
|
+
const toQuery = (args = {}) => {
|
|
12
|
+
const query = new URLSearchParams();
|
|
13
|
+
for (const [k, v] of Object.entries(args)) if (v !== undefined && v !== null) query.set(k, String(v));
|
|
14
|
+
return query;
|
|
15
|
+
};
|
|
7
16
|
|
|
8
17
|
const PROTOCOL_VERSION = '2025-06-18';
|
|
9
18
|
const { version: VERSION } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
@@ -29,7 +38,7 @@ const TOOLS = MCP_TOOLS.map((tool) => {
|
|
|
29
38
|
};
|
|
30
39
|
});
|
|
31
40
|
|
|
32
|
-
async function runTool(store, name, args = {}) {
|
|
41
|
+
async function runTool(store, seeds, name, args = {}) {
|
|
33
42
|
switch (name) {
|
|
34
43
|
case 'recommend': {
|
|
35
44
|
const features = args.features ?? (args.task != null
|
|
@@ -37,11 +46,10 @@ async function runTool(store, name, args = {}) {
|
|
|
37
46
|
if (!features) throw new Error('recommend needs "task" or "features"');
|
|
38
47
|
return recommend((await collectOfferings(store)).filter((o) => o.invocable), features, args.policy ?? {});
|
|
39
48
|
}
|
|
40
|
-
case 'search_offerings':
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
return
|
|
44
|
-
}
|
|
49
|
+
case 'search_offerings':
|
|
50
|
+
return searchOfferingsPaged(store, toQuery(args));
|
|
51
|
+
case 'find_locations':
|
|
52
|
+
return buildLocations(store, seeds, toQuery(args));
|
|
45
53
|
case 'get_offering': {
|
|
46
54
|
const found = (await collectOfferings(store)).find(
|
|
47
55
|
(o) => o.node_id === args.node_id && o.offering_id === args.offering_id);
|
|
@@ -69,9 +77,7 @@ async function runTool(store, name, args = {}) {
|
|
|
69
77
|
offering = all.find((o) => o.node_id === nodeId && o.offering_id === offeringId);
|
|
70
78
|
if (!offering) throw new Error(`unknown offering: ${step.offering}`);
|
|
71
79
|
} else if (step.select) {
|
|
72
|
-
|
|
73
|
-
for (const [k, v] of Object.entries(step.select)) query.set(k, String(v));
|
|
74
|
-
offering = (await searchOfferings(store, query))[0];
|
|
80
|
+
offering = (await searchOfferings(store, toQuery(step.select)))[0];
|
|
75
81
|
if (!offering) throw new Error(`no offering matches select: ${JSON.stringify(step.select)}`);
|
|
76
82
|
} else {
|
|
77
83
|
throw new Error('each step needs "offering" or "select"');
|
|
@@ -94,7 +100,7 @@ async function runTool(store, name, args = {}) {
|
|
|
94
100
|
}
|
|
95
101
|
}
|
|
96
102
|
|
|
97
|
-
async function handleRpc(store, msg) {
|
|
103
|
+
async function handleRpc(store, seeds, msg) {
|
|
98
104
|
const { id, method, params } = msg;
|
|
99
105
|
const reply = (result) => ({ jsonrpc: '2.0', id, result });
|
|
100
106
|
const rpcError = (code, message) => ({ jsonrpc: '2.0', id, error: { code, message } });
|
|
@@ -113,7 +119,7 @@ async function handleRpc(store, msg) {
|
|
|
113
119
|
return reply({ tools: TOOLS });
|
|
114
120
|
case 'tools/call':
|
|
115
121
|
try {
|
|
116
|
-
const result = await runTool(store, params?.name, params?.arguments);
|
|
122
|
+
const result = await runTool(store, seeds, params?.name, params?.arguments);
|
|
117
123
|
return reply({
|
|
118
124
|
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
|
119
125
|
structuredContent: result,
|
|
@@ -132,13 +138,13 @@ async function handleRpc(store, msg) {
|
|
|
132
138
|
}
|
|
133
139
|
}
|
|
134
140
|
|
|
135
|
-
/** Routes to mount into the registry app. */
|
|
136
|
-
export function mcpRoutes(store) {
|
|
141
|
+
/** Routes to mount into the registry app. `seeds` = the curated location seeds (find_locations). */
|
|
142
|
+
export function mcpRoutes(store, seeds = []) {
|
|
137
143
|
return [
|
|
138
144
|
['POST', '/mcp', async (req, res) => {
|
|
139
145
|
const body = await readJson(req, 5_000_000);
|
|
140
146
|
const messages = Array.isArray(body) ? body : [body];
|
|
141
|
-
const replies = (await Promise.all(messages.map((m) => handleRpc(store, m)))).filter(Boolean);
|
|
147
|
+
const replies = (await Promise.all(messages.map((m) => handleRpc(store, seeds, m)))).filter(Boolean);
|
|
142
148
|
if (replies.length === 0) { res.writeHead(202); res.end(); return; }
|
|
143
149
|
sendJson(res, 200, Array.isArray(body) ? replies : replies[0]);
|
|
144
150
|
}],
|
package/src/probes.js
CHANGED
|
@@ -1,7 +1,23 @@
|
|
|
1
|
-
// Stage A admission probes (DS-ADM-01): health, blind invocation, /models agreement.
|
|
1
|
+
// Stage A admission probes (DS-ADM-01): card consistency, health, blind invocation, /models agreement.
|
|
2
2
|
// All outbound traffic goes through the SSRF-guarded fetcher (safefetch.js).
|
|
3
3
|
import { fetchJsonCapped } from './safefetch.js';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* Card rules a schema cannot express (ONP-2 §5): every offering declares a data_policy
|
|
7
|
+
* (required from `community` up), and offers only payment schemes the node declares.
|
|
8
|
+
* Returns a list of problems; empty means consistent.
|
|
9
|
+
*/
|
|
10
|
+
export function cardConsistency(card) {
|
|
11
|
+
const nodeSchemes = new Set((card.payment?.schemes ?? []).map((s) => s.scheme));
|
|
12
|
+
const problems = [];
|
|
13
|
+
for (const o of card.offerings ?? []) {
|
|
14
|
+
if (!o.data_policy) problems.push(`${o.offering_id}: no data_policy`);
|
|
15
|
+
const undeclared = (o.pricing?.schemes ?? []).filter((s) => !nodeSchemes.has(s));
|
|
16
|
+
if (undeclared.length) problems.push(`${o.offering_id}: schemes not in payment.schemes: ${undeclared.join(', ')}`);
|
|
17
|
+
}
|
|
18
|
+
return problems;
|
|
19
|
+
}
|
|
20
|
+
|
|
5
21
|
/** Run Stage A against a card. Records results via store; returns { ok, results }. */
|
|
6
22
|
export async function runStageA(store, nodeId, card, { safeFetch } = {}) {
|
|
7
23
|
if (!safeFetch) safeFetch = (url, opts = {}, t = 10_000) => fetch(url, { ...opts, signal: AbortSignal.timeout(t) });
|
|
@@ -12,6 +28,10 @@ export async function runStageA(store, nodeId, card, { safeFetch } = {}) {
|
|
|
12
28
|
results.push({ offeringId, kind, ok, detail });
|
|
13
29
|
};
|
|
14
30
|
|
|
31
|
+
// 0. Card consistency (no network)
|
|
32
|
+
const problems = cardConsistency(card);
|
|
33
|
+
await record(null, 'card-consistency', problems.length === 0, problems.length ? problems.join('; ') : null);
|
|
34
|
+
|
|
15
35
|
// 1. Health endpoint
|
|
16
36
|
try {
|
|
17
37
|
const t0 = performance.now();
|
package/src/reimport.js
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
import {
|
|
4
4
|
importModelsDev, importHuggingFace, importOpenRouter,
|
|
5
5
|
importOllamaLibrary, parseOllamaLibrary,
|
|
6
|
-
|
|
6
|
+
importOpenRouterProviders, fetchOpenRouterEndpoints,
|
|
7
|
+
HF_ROUTER_URL, HF_HUB_URL, OPENROUTER_URL, OPENROUTER_PROVIDERS_URL, OLLAMA_LIBRARY_URL,
|
|
7
8
|
} from './importers.js';
|
|
8
9
|
|
|
9
10
|
export const MODELS_DEV_URL = 'https://models.dev/api.json';
|
|
@@ -28,6 +29,12 @@ export function startReimport(store, {
|
|
|
28
29
|
let hub = [];
|
|
29
30
|
try { hub = await json(HF_HUB_URL); } catch { /* enrichment optional */ }
|
|
30
31
|
results[source] = await importHuggingFace(store, router, hub);
|
|
32
|
+
} else if (source === 'openrouter-providers') {
|
|
33
|
+
// One call per model for its endpoint list (~450): prefer a long interval for this source.
|
|
34
|
+
const models = (await json(OPENROUTER_URL)).data;
|
|
35
|
+
const providers = (await json(OPENROUTER_PROVIDERS_URL)).data;
|
|
36
|
+
results[source] = await importOpenRouterProviders(store, providers, models,
|
|
37
|
+
await fetchOpenRouterEndpoints((url) => json(url, 30_000), models));
|
|
31
38
|
} else if (source === 'models-dev') {
|
|
32
39
|
results[source] = await importModelsDev(store, await json(MODELS_DEV_URL));
|
|
33
40
|
} else if (source === 'ollama') {
|