@opennodes/registry 0.1.40 → 0.1.41
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/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/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') {
|
package/src/search.js
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
// Offering search + transparent ranking (ONP-3 §5–6).
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
residencyWithin, residencyCodes, servingLocations, basisRank,
|
|
4
|
+
inJurisdiction, localSizes, pullsOf, specialtyOf, isEmbedder,
|
|
5
|
+
} from '@opennodes/core';
|
|
6
|
+
|
|
7
|
+
/** BCP 47 prefix match (ONP-3 §5): `fr` matches `fr` and `fr-CA`; `fr-CA` matches only itself. */
|
|
8
|
+
export const langMatches = (tag, wanted) => {
|
|
9
|
+
const t = String(tag).toLowerCase();
|
|
10
|
+
const w = String(wanted).toLowerCase();
|
|
11
|
+
return t === w || t.startsWith(`${w}-`);
|
|
12
|
+
};
|
|
3
13
|
|
|
4
14
|
export const RANK_COMPONENTS = { price: 0.35, tier: 0.35, probe_success: 0.30 };
|
|
5
15
|
const TIER_SCORE = { unverified: 0, community: 0.4, verified: 0.8, attested: 1.0 };
|
|
@@ -89,15 +99,20 @@ async function buildOfferings(store) {
|
|
|
89
99
|
binding: offering.binding,
|
|
90
100
|
pricing: offering.pricing,
|
|
91
101
|
data_policy: offering.data_policy ?? null,
|
|
102
|
+
node_regions: card.node?.regions ?? [],
|
|
92
103
|
// Where the operator is (ONP-2 node.operator.country, node.regions).
|
|
93
104
|
// Registered nodes declare it in their signed card; imports get it from the importer's list of
|
|
94
|
-
// known providers, labeled inferred.
|
|
105
|
+
// known providers, labeled inferred. `location` is the registry's own server-location check.
|
|
95
106
|
jurisdiction: {
|
|
96
107
|
country: card.node?.operator?.country ?? null,
|
|
97
108
|
regions: card.node?.regions ?? [],
|
|
98
109
|
basis: card.node?.operator?.country ? (node.source === 'import' ? 'inferred' : 'declared') : null,
|
|
99
110
|
location,
|
|
100
111
|
},
|
|
112
|
+
// Where requests are served: live sites with their evidence basis (ONP-2 §3a), and the
|
|
113
|
+
// codes a residency check must cover (pins + sites, else node regions).
|
|
114
|
+
locations: servingLocations(offering, card),
|
|
115
|
+
residency: residencyCodes(offering, card),
|
|
101
116
|
// Allocated hardware for THIS offering (offering-level override wins over the
|
|
102
117
|
// node-level description) — same artifact on different vendors runs on different
|
|
103
118
|
// silicon, and clients deserve to see which. Always basis-labeled, never measured.
|
|
@@ -139,6 +154,20 @@ export async function searchOfferingsPaged(store, query) {
|
|
|
139
154
|
if (q('max_input_price')) items = items.filter((o) => (o.pricing.input_per_mtok ?? Infinity) <= Number(q('max_input_price')));
|
|
140
155
|
if (q('scheme')) items = items.filter((o) => o.pricing.schemes.includes(q('scheme')));
|
|
141
156
|
if (q('jurisdiction')) items = items.filter((o) => inJurisdiction(o, q('jurisdiction')));
|
|
157
|
+
if (q('region')) {
|
|
158
|
+
// Residency: every pinned region and live serving site (else the node's regions) inside.
|
|
159
|
+
items = items.filter((o) => residencyWithin(o.residency, q('region')));
|
|
160
|
+
}
|
|
161
|
+
if (q('location_basis')) {
|
|
162
|
+
// Evidence: the offering has serving sites and every one is at least this well supported.
|
|
163
|
+
const min = basisRank(q('location_basis'));
|
|
164
|
+
items = items.filter((o) => o.locations.length && o.locations.every((l) => basisRank(l.basis) >= min));
|
|
165
|
+
}
|
|
166
|
+
if (q('exclude_lineage')) {
|
|
167
|
+
// Origin policy on declared lineage; offerings that declare none are kept (unknown).
|
|
168
|
+
const banned = q('exclude_lineage').toUpperCase().split(',');
|
|
169
|
+
items = items.filter((o) => !(o.model.lineage_origins ?? []).some((c) => banned.includes(c)));
|
|
170
|
+
}
|
|
142
171
|
if (q('tier')) {
|
|
143
172
|
const order = ['unverified', 'community', 'verified', 'attested'];
|
|
144
173
|
const min = order.indexOf(q('tier'));
|
|
@@ -148,7 +177,7 @@ export async function searchOfferingsPaged(store, query) {
|
|
|
148
177
|
const [lang, minGrade = 'basic'] = q('lang').split(':');
|
|
149
178
|
const grades = ['basic', 'strong', 'native'];
|
|
150
179
|
items = items.filter((o) => (o.serving?.languages ?? []).some(
|
|
151
|
-
(l) => l.lang
|
|
180
|
+
(l) => langMatches(l.lang, lang) && grades.indexOf(l.grade) >= grades.indexOf(minGrade)));
|
|
152
181
|
}
|
|
153
182
|
if (q('q')) {
|
|
154
183
|
const needle = q('q').toLowerCase();
|
package/src/server.js
CHANGED
|
@@ -24,8 +24,17 @@ import { checkNodeLocation } from './location.js';
|
|
|
24
24
|
import {
|
|
25
25
|
importModelsDev, importHuggingFace, importOpenRouter,
|
|
26
26
|
importOllamaLibrary, parseOllamaLibrary,
|
|
27
|
-
|
|
27
|
+
importOpenRouterProviders, fetchOpenRouterEndpoints, importLocationSeed,
|
|
28
|
+
HF_ROUTER_URL, HF_HUB_URL, OPENROUTER_URL, OPENROUTER_PROVIDERS_URL, OLLAMA_LIBRARY_URL,
|
|
28
29
|
} from './importers.js';
|
|
30
|
+
import { locationRoutes, loadLocationSeeds } from './locations.js';
|
|
31
|
+
|
|
32
|
+
/** Default basemap. OSM's tile policy asks for attribution and light use; busy registries set their own. */
|
|
33
|
+
export const OSM_TILES = {
|
|
34
|
+
tiles: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
|
|
35
|
+
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
|
|
36
|
+
max_zoom: 19,
|
|
37
|
+
};
|
|
29
38
|
|
|
30
39
|
export async function startRegistry({
|
|
31
40
|
port = 0, host = '127.0.0.1', dbPath = ':memory:',
|
|
@@ -41,9 +50,16 @@ export async function startRegistry({
|
|
|
41
50
|
admitCooldownMs = 0, // minimum gap between Stage B runs per node (0 = none; set in production)
|
|
42
51
|
trustProxy = false, // read the client address from X-Forwarded-For (behind Caddy / a CDN)
|
|
43
52
|
location = null, // { selfSite, agents, intervalMs, fetchImpl, resolve, rtt } to check server locations
|
|
53
|
+
locationSeeds = false, // import the bundled curated location seeds (src/data/locations-*.json) at start
|
|
54
|
+
mapTiles = OSM_TILES, // basemap for the "Where models run" map: { tiles, attribution, max_zoom }, or null for no map
|
|
44
55
|
} = {}) {
|
|
45
56
|
const store = watchStoreWrites(await createStore(dbPath)); // sqlite path/:memory: or postgres:// URL; writes refresh the cached catalog
|
|
46
57
|
const safeFetch = makeSafeFetch({ allowPrivate: allowPrivateTargets });
|
|
58
|
+
const seeds = locationSeeds ? loadLocationSeeds() : [];
|
|
59
|
+
for (const seed of seeds) {
|
|
60
|
+
const result = await importLocationSeed(store, seed);
|
|
61
|
+
if (result.skipped.length) console.warn(`location seed ${seed.seed}: skipped ${result.skipped.join('; ')}`);
|
|
62
|
+
}
|
|
47
63
|
const webApp = readFileSync(fileURLToPath(new URL('./web/index.html', import.meta.url)), 'utf8');
|
|
48
64
|
let registryKeys;
|
|
49
65
|
if (keyPath && existsSync(keyPath)) {
|
|
@@ -315,6 +331,7 @@ export async function startRegistry({
|
|
|
315
331
|
operator: card?.node?.operator?.name ?? null,
|
|
316
332
|
country: card?.node?.operator?.country ?? null,
|
|
317
333
|
regions: card?.node?.regions ?? [],
|
|
334
|
+
locations: card?.node?.locations ?? [],
|
|
318
335
|
offerings: card?.offerings?.length ?? 0,
|
|
319
336
|
availability,
|
|
320
337
|
});
|
|
@@ -487,6 +504,32 @@ export async function startRegistry({
|
|
|
487
504
|
sendJson(res, 200, await importOpenRouter(store, catalog));
|
|
488
505
|
}],
|
|
489
506
|
|
|
507
|
+
// OpenRouter per-provider importer with declared locations (admin): inline
|
|
508
|
+
// {providers, models, endpoints: {modelId: [...]}}, or fetch the live APIs (one call per model).
|
|
509
|
+
['POST', '/v0/import/openrouter-providers', async (req, res) => {
|
|
510
|
+
if (!adminOk(req, res)) return;
|
|
511
|
+
const body = await readJson(req, 100_000_000);
|
|
512
|
+
const json = async (url) => (await safeFetch(url, {}, 60_000)).json();
|
|
513
|
+
const providers = body.providers ?? (await json(OPENROUTER_PROVIDERS_URL)).data;
|
|
514
|
+
const models = body.models ?? (await json(OPENROUTER_URL)).data;
|
|
515
|
+
const endpoints = body.endpoints ? new Map(Object.entries(body.endpoints)) : await fetchOpenRouterEndpoints(json, models);
|
|
516
|
+
sendJson(res, 200, await importOpenRouterProviders(store, providers, models, endpoints));
|
|
517
|
+
}],
|
|
518
|
+
|
|
519
|
+
// Curated location seed (admin): inline {seed}, or re-import the bundled seeds.
|
|
520
|
+
['POST', '/v0/import/locations', async (req, res) => {
|
|
521
|
+
if (!adminOk(req, res)) return;
|
|
522
|
+
const body = await readJson(req, 10_000_000);
|
|
523
|
+
const list = body.seed ? [body.seed] : loadLocationSeeds();
|
|
524
|
+
const results = {};
|
|
525
|
+
for (const seed of list) {
|
|
526
|
+
results[seed.seed] = await importLocationSeed(store, seed);
|
|
527
|
+
const i = seeds.findIndex((s) => s.seed === seed.seed); // /v0/locations reads site-only entries from here
|
|
528
|
+
if (i < 0) seeds.push(seed); else seeds[i] = seed;
|
|
529
|
+
}
|
|
530
|
+
sendJson(res, 200, results);
|
|
531
|
+
}],
|
|
532
|
+
|
|
490
533
|
['GET', '/v0/health', (req, res) => {
|
|
491
534
|
sendJson(res, 200, {
|
|
492
535
|
service: 'opennodes-registry',
|
|
@@ -497,6 +540,8 @@ export async function startRegistry({
|
|
|
497
540
|
mcp: '/mcp',
|
|
498
541
|
webmcp: true, // the web app at / registers in-page tools via navigator.modelContext where supported
|
|
499
542
|
export: '/v0/export',
|
|
543
|
+
locations: '/v0/locations',
|
|
544
|
+
map: mapTiles,
|
|
500
545
|
signing_key: { ...registryKeys.publicJwk, kid: 'registry-1' },
|
|
501
546
|
stage_c: Boolean(stageC),
|
|
502
547
|
});
|
|
@@ -508,8 +553,9 @@ export async function startRegistry({
|
|
|
508
553
|
res.end(webApp);
|
|
509
554
|
}],
|
|
510
555
|
|
|
511
|
-
...mcpRoutes(store),
|
|
556
|
+
...mcpRoutes(store, seeds),
|
|
512
557
|
...exportRoutes(store, registryKeys),
|
|
558
|
+
...locationRoutes(store, seeds),
|
|
513
559
|
], { cors: true }); // public read API: third-party web clients may call it directly
|
|
514
560
|
|
|
515
561
|
// ---- server-location checks (location.js) ----
|