@opennodes/registry 0.1.42 → 0.1.44

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/src/locations.js CHANGED
@@ -1,10 +1,13 @@
1
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).
2
+ // models it serves, built from card locations (registered nodes and imports) plus the curated
3
+ // seeds: site-only providers (sites but no models) and entries that describe an existing node.
4
+ // Residency commitments (ONP-2 §3b, ONP-3 §5d) come from cards and seeds and are attached to
5
+ // each site they cover.
4
6
  import { readFileSync, readdirSync } from 'node:fs';
5
7
  import { fileURLToPath } from 'node:url';
6
8
  import {
7
9
  sendJson, problem, regionWithin, countryOf, basisRank, pointFor, distanceKm, parsePoint, precisionRank,
10
+ residencyAt, residencyMeets, commitmentRank, scopeCovers, RESIDENCY_COMMITMENTS,
8
11
  } from '@opennodes/core';
9
12
  import { siteLocation } from './importers.js';
10
13
 
@@ -17,15 +20,33 @@ export function loadLocationSeeds(dir = DATA_DIR) {
17
20
  .map((f) => JSON.parse(readFileSync(dir + f, 'utf8')));
18
21
  }
19
22
 
23
+ /** `{seed}:{id}` -> seed provider, for `residency_of` references between seeds. */
24
+ const seedIndex = (seeds) => new Map(seeds.flatMap((seed) => (seed.providers ?? []).map((p) => [`${seed.seed}:${p.id}`, { seed, p }])));
25
+ /** A seed provider's own commitments, or those of the entry it points to with `residency_of`. */
26
+ const seedResidency = (index, p) => (p.residency_of ? index.get(p.residency_of)?.p.residency : p.residency) ?? null;
27
+
28
+ /** Visible nodes with their latest cards. */
29
+ async function listedCards(store) {
30
+ const cards = [];
31
+ for (const node of await store.allNodes()) {
32
+ if (HIDDEN.includes(node.state)) continue;
33
+ const card = await store.latestCard(node.id);
34
+ if (card) cards.push({ node, card });
35
+ }
36
+ return cards;
37
+ }
38
+
20
39
  /** All sites, unfiltered: one entry per (node, region, site), models attached. */
21
40
  export async function collectSites(store, seeds = []) {
22
41
  const sites = new Map();
23
42
  let located = 0, unlocated = 0;
43
+ const index = seedIndex(seeds);
24
44
  const siteFor = (base, loc) => {
25
45
  const key = `${base.node_id}|${loc.region}|${loc.site ?? ''}`;
26
46
  if (!sites.has(key)) {
47
+ const { commitments, ...rest } = base;
27
48
  sites.set(key, {
28
- ...base,
49
+ ...rest,
29
50
  country: countryOf(loc.region),
30
51
  region: loc.region,
31
52
  site: loc.site ?? null,
@@ -36,6 +57,7 @@ export async function collectSites(store, seeds = []) {
36
57
  checked: loc.checked ?? null,
37
58
  note: loc.note ?? null,
38
59
  geo: pointFor(loc), // declared point, else an approximate one from the region (derived: true)
60
+ residency: commitments ? residencyAt(commitments, loc.region) : null,
39
61
  models: [],
40
62
  models_note: null,
41
63
  });
@@ -43,32 +65,72 @@ export async function collectSites(store, seeds = []) {
43
65
  return sites.get(key);
44
66
  };
45
67
 
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;
68
+ const cards = await listedCards(store);
69
+ const listed = new Set(cards.map((c) => c.node.id));
70
+
71
+ // Seed entries that describe registered nodes (`nodes`): the first listed node holds the
72
+ // sites; with placement "all", the offerings of every listed node are served there.
73
+ const attached = new Map(); // node id -> { p, primary }
74
+ for (const seed of seeds) {
75
+ for (const p of seed.providers ?? []) {
76
+ if (p.models?.length || !p.nodes?.length) continue;
77
+ const primary = p.nodes.find((id) => listed.has(id));
78
+ for (const id of p.nodes) if (listed.has(id)) attached.set(id, { p, primary });
79
+ }
80
+ }
81
+ const residencyOf = new Map(); // node id -> commitments, from seeds
82
+ for (const seed of seeds) {
83
+ for (const p of seed.providers ?? []) {
84
+ const r = seedResidency(index, p);
85
+ if (!r) continue;
86
+ if (p.models?.length) residencyOf.set(`import.seed.${seed.seed}.${p.id}`, r);
87
+ for (const id of p.nodes ?? []) if (!residencyOf.has(id)) residencyOf.set(id, r);
88
+ }
89
+ }
90
+
91
+ const bases = new Map();
92
+ for (const { node, card } of cards) {
50
93
  // The registry's server-location check (location.js, ONP-3 §6.4) covers the node's API host,
51
94
  // not each site: shown beside the declared sites, never turning one into `measured` by itself.
52
95
  const check = (await store.getObservations(node.id, '_node')).location ?? null;
53
- const base = {
96
+ const via = attached.get(node.id);
97
+ const holds = via?.primary === node.id;
98
+ bases.set(node.id, {
54
99
  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,
100
+ provider: holds ? via.p.name : (card.node?.name ?? node.id),
101
+ operator: card.node?.operator?.name ?? via?.p.operator?.name ?? null,
102
+ operator_country: card.node?.operator?.country ?? via?.p.operator?.country ?? null,
58
103
  tier: node.state === 'indexed' ? 'unverified' : node.state,
59
- source: node.source ?? 'registration',
104
+ source: holds ? 'seed' : (node.source ?? 'registration'),
60
105
  server_check: check ? {
61
106
  verdict: check.verdict, server_country: check.server?.country ?? null,
62
107
  latency: check.latency?.verdict ?? 'unknown', checked_at: check.checked_at ?? null,
63
108
  } : null,
64
- };
109
+ commitments: card.node?.residency ?? residencyOf.get(node.id) ?? null,
110
+ });
111
+ }
112
+ for (const { node, card } of cards) {
113
+ const base = bases.get(node.id);
65
114
  for (const loc of card.node?.locations ?? []) siteFor(base, loc);
115
+ const via = attached.get(node.id);
116
+ const seedLocs = via ? (via.p.sites ?? []).map(siteLocation) : [];
117
+ if (via?.primary === node.id) {
118
+ for (const loc of seedLocs) {
119
+ siteFor(base, loc).models_note = via.p.placement === 'all' ? null
120
+ : (via.p.models_note ?? 'The provider does not say which models run at which site.');
121
+ }
122
+ }
66
123
  for (const o of card.offerings) {
67
- const locs = Array.isArray(o.locations) ? o.locations : (card.node?.locations ?? []);
124
+ let locs = Array.isArray(o.locations) ? o.locations : (card.node?.locations ?? []);
125
+ let holder = base;
126
+ if (!locs.length && !Array.isArray(o.locations) && via?.p.placement === 'all' && seedLocs.length) {
127
+ locs = seedLocs;
128
+ holder = bases.get(via.primary);
129
+ }
68
130
  if (!locs.length) { unlocated++; continue; }
69
131
  located++;
70
132
  for (const loc of locs) {
71
- siteFor(base, loc).models.push({
133
+ siteFor(holder, loc).models.push({
72
134
  offering_id: o.offering_id,
73
135
  name: o.model.name,
74
136
  artifact: o.model.artifact,
@@ -83,7 +145,8 @@ export async function collectSites(store, seeds = []) {
83
145
 
84
146
  for (const seed of seeds) {
85
147
  for (const p of seed.providers ?? []) {
86
- if (p.models?.length) continue; // imported as a card; its sites came in above
148
+ if (p.models?.length) continue; // imported as a card; its sites came in above
149
+ if (p.nodes?.some((id) => listed.has(id))) continue; // attached to a registered node above
87
150
  const base = {
88
151
  node_id: `import.seed.${seed.seed}.${p.id}`,
89
152
  provider: p.name,
@@ -92,10 +155,16 @@ export async function collectSites(store, seeds = []) {
92
155
  tier: 'unverified',
93
156
  source: 'seed',
94
157
  server_check: null,
158
+ commitments: seedResidency(index, p),
95
159
  };
96
160
  for (const s of p.sites ?? []) siteFor(base, siteLocation(s)).models_note = p.models_note ?? 'Models not published';
97
161
  }
98
162
  }
163
+ // Several nodes of one provider at one site: each model once.
164
+ for (const s of sites.values()) {
165
+ const seen = new Set();
166
+ s.models = s.models.filter((m) => { const k = `${m.name}|${m.artifact}`; return !seen.has(k) && seen.add(k); });
167
+ }
99
168
  return { sites: [...sites.values()], located_offerings: located, unlocated_offerings: unlocated };
100
169
  }
101
170
 
@@ -116,6 +185,10 @@ export async function buildLocations(store, seeds, query) {
116
185
  if (where) sites = sites.filter((s) => regionWithin(s.region, where));
117
186
  if (q('basis')) sites = sites.filter((s) => basisRank(s.basis) >= basisRank(q('basis')));
118
187
  if (q('status')) sites = sites.filter((s) => s.status === q('status'));
188
+ if (q('residency')) {
189
+ if (!['processing', 'storage'].includes(q('residency'))) throw Object.assign(new Error('residency must be processing or storage'), { status: 400 });
190
+ sites = sites.filter((s) => residencyMeets(s.residency, q('residency'), q('availability') ?? 'enterprise'));
191
+ }
119
192
  const banned = q('exclude_lineage')?.toUpperCase().split(',') ?? [];
120
193
  const needle = q('model')?.toLowerCase();
121
194
  if (banned.length || needle) {
@@ -165,7 +238,10 @@ export async function buildLocations(store, seeds, query) {
165
238
 
166
239
  const CSV_COLUMNS = ['country', 'region', 'site', 'status', 'basis', 'provider', 'operator', 'operator_country',
167
240
  'facility_operator', 'node_id', 'tier', 'source', 'model', 'artifact', 'lineage_origins', 'source_url', 'checked', 'note',
168
- 'lat', 'lon', 'precision', 'derived', 'distance_km'];
241
+ 'lat', 'lon', 'precision', 'derived', 'distance_km', 'residency'];
242
+ /** "processing EU (opt_in); none" — a site's or provider's commitments as one cell. */
243
+ export const residencyText = (list) => (list ?? []).map((r) => [r.commitment, (r.scope ?? []).join(r.per_region ? '|' : '+'),
244
+ r.availability && r.availability !== 'default' ? `(${r.availability})` : ''].filter(Boolean).join(' ')).join('; ');
169
245
  const csvCell = (v) => {
170
246
  const s = v == null ? '' : String(v);
171
247
  return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
@@ -180,6 +256,7 @@ export function locationsCsv(report) {
180
256
  const row = {
181
257
  ...s, model: m.name, artifact: m.artifact, lineage_origins: (m.lineage_origins ?? []).join(' '),
182
258
  lat: s.geo?.lat, lon: s.geo?.lon, precision: s.geo?.precision, derived: s.geo?.derived,
259
+ residency: residencyText(s.residency),
183
260
  };
184
261
  rows.push(CSV_COLUMNS.map((c) => csvCell(row[c])).join(','));
185
262
  }
@@ -207,6 +284,7 @@ export function locationsGeoJson(report) {
207
284
  models: s.models.map((m) => m.name).join('; '),
208
285
  lineage: [...new Set(s.models.flatMap((m) => m.lineage_origins ?? []))].join('; '),
209
286
  models_note: s.models_note,
287
+ residency: residencyText(s.residency),
210
288
  ...(s.distance_km !== undefined ? { distance_km: s.distance_km } : {}),
211
289
  },
212
290
  }));
@@ -219,8 +297,98 @@ export function locationsGeoJson(report) {
219
297
  };
220
298
  }
221
299
 
300
+ /**
301
+ * Residency commitments per provider (ONP-3 §5d): curated seed entries (an entry that points to
302
+ * another with `residency_of` is folded into it), registered cards that declare their own, and
303
+ * every other listed node as unstated. Query: scope (a processing or storage commitment whose
304
+ * scope lies within it), commitment (minimum), availability, kind, node_id.
305
+ */
306
+ export async function buildResidency(store, seeds, query) {
307
+ const q = (k) => query.get(k);
308
+ if (q('commitment') && !['processing', 'storage'].includes(q('commitment'))) throw Object.assign(new Error('commitment must be processing or storage'), { status: 400 });
309
+ const { sites } = await collectSites(store, seeds);
310
+ const siteCount = new Map();
311
+ for (const s of sites) siteCount.set(s.node_id, (siteCount.get(s.node_id) ?? 0) + 1);
312
+ const index = seedIndex(seeds);
313
+ const entries = new Map();
314
+ const covered = new Set();
315
+ for (const seed of seeds) {
316
+ for (const p of seed.providers ?? []) {
317
+ const key = p.residency_of && index.has(p.residency_of) ? p.residency_of : `${seed.seed}:${p.id}`;
318
+ const holder = index.get(key).p;
319
+ if (!entries.has(key)) {
320
+ entries.set(key, {
321
+ id: key, provider: holder.name, kind: holder.kind ?? null,
322
+ operator: holder.operator?.name ?? null, operator_country: holder.operator?.country ?? null,
323
+ node_ids: new Set(), sites: 0, source: 'seed', residency: holder.residency ?? [],
324
+ });
325
+ }
326
+ const e = entries.get(key);
327
+ for (const id of [...(p.nodes ?? []), `import.seed.${seed.seed}.${p.id}`]) { e.node_ids.add(id); covered.add(id); }
328
+ }
329
+ }
330
+ for (const { node, card } of await listedCards(store)) {
331
+ if (covered.has(node.id)) continue;
332
+ entries.set(node.id, {
333
+ id: node.id, provider: card.node?.name ?? node.id, kind: null,
334
+ operator: card.node?.operator?.name ?? null, operator_country: card.node?.operator?.country ?? null,
335
+ node_ids: new Set([node.id]), sites: 0,
336
+ source: card.node?.residency ? 'card' : 'none', residency: card.node?.residency ?? [],
337
+ });
338
+ }
339
+ let list = [...entries.values()].map((e) => {
340
+ const ids = [...e.node_ids];
341
+ const strongest = e.residency.reduce((best, r) => (commitmentRank(r.commitment) > commitmentRank(best) ? r.commitment : best), 'unstated');
342
+ return { ...e, node_ids: ids, sites: ids.reduce((n, id) => n + (siteCount.get(id) ?? 0), 0),
343
+ strongest: RESIDENCY_COMMITMENTS.includes(strongest) ? strongest : 'unstated' };
344
+ });
345
+ const availability = q('availability') ?? 'enterprise';
346
+ const min = q('commitment') ?? (q('scope') ? 'storage' : null);
347
+ if (min || q('scope')) {
348
+ list = list.filter((e) => e.residency.some((r) => residencyMeets([r], min ?? 'unstated', availability)
349
+ && (!q('scope') || (commitmentRank(r.commitment) >= 2 && (r.scope ?? []).length
350
+ // One area: all of it inside the requested scope. Separate choices: one of them is.
351
+ && (r.per_region ? r.scope.some : r.scope.every).call(r.scope, (s) => scopeCovers(q('scope'), s))))));
352
+ }
353
+ if (q('kind')) list = list.filter((e) => e.kind === q('kind'));
354
+ if (q('node_id')) list = list.filter((e) => e.node_ids.includes(q('node_id')));
355
+ list.sort((a, b) => a.provider.localeCompare(b.provider));
356
+ const by = Object.fromEntries(RESIDENCY_COMMITMENTS.map((c) => [c, list.filter((e) => e.strongest === c).length]));
357
+ return {
358
+ generated_at: new Date().toISOString(),
359
+ filters: Object.fromEntries([...query].filter(([k]) => k !== 'format')),
360
+ summary: { providers: list.length, by_strongest_commitment: by },
361
+ providers: list,
362
+ };
363
+ }
364
+
365
+ const RESIDENCY_CSV = ['provider', 'kind', 'operator', 'operator_country', 'node_ids', 'sites', 'commitment', 'scope',
366
+ 'availability', 'programme', 'statement', 'source', 'checked'];
367
+ /** One row per provider and commitment; a provider with none gets one "unstated" row. */
368
+ export function residencyCsv(report) {
369
+ const rows = [RESIDENCY_CSV.join(',')];
370
+ for (const e of report.providers) {
371
+ for (const r of e.residency.length ? e.residency : [{ commitment: 'unstated' }]) {
372
+ const row = { ...e, ...r, node_ids: e.node_ids.join(' '), scope: (r.scope ?? []).join(' '), availability: r.availability ?? 'default' };
373
+ rows.push(RESIDENCY_CSV.map((c) => csvCell(row[c])).join(','));
374
+ }
375
+ }
376
+ return rows.join('\n') + '\n';
377
+ }
378
+
222
379
  export function locationRoutes(store, seeds) {
223
380
  return [
381
+ ['GET', '/v0/residency', async (req, res, { query }) => {
382
+ let report;
383
+ try { report = await buildResidency(store, seeds, query); }
384
+ catch (err) { if (err.status === 400) return problem(res, 400, 'bad-query', err.message); throw err; }
385
+ if (query.get('format') === 'csv') {
386
+ res.writeHead(200, { 'content-type': 'text/csv; charset=utf-8', 'content-disposition': 'inline; filename="residency.csv"' });
387
+ res.end(residencyCsv(report));
388
+ return;
389
+ }
390
+ sendJson(res, 200, report);
391
+ }],
224
392
  ['GET', '/v0/locations', async (req, res, { query }) => {
225
393
  let report;
226
394
  try { report = await buildLocations(store, seeds, query); }
package/src/mcp.js CHANGED
@@ -1,11 +1,11 @@
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
3
  // MCP host gets ONP discovery (recommend, search_offerings, get_offering, get_node, estimate,
4
- // find_locations) for free.
4
+ // find_locations, find_residency) for free.
5
5
  import { readFileSync } from 'node:fs';
6
6
  import { readJson, sendJson, problem, estimateBounds, round6, extractFeatures, recommend, MCP_TOOLS, MCP_INSTRUCTIONS, summarizeNode } from '@opennodes/core';
7
7
  import { searchOfferingsPaged, searchOfferings, collectOfferings, pricePublished } from './search.js';
8
- import { buildLocations } from './locations.js';
8
+ import { buildLocations, buildResidency } from './locations.js';
9
9
 
10
10
  /** Tool arguments -> the query string the REST routes take (null/undefined dropped). */
11
11
  const toQuery = (args = {}) => {
@@ -50,6 +50,8 @@ async function runTool(store, seeds, name, args = {}) {
50
50
  return searchOfferingsPaged(store, toQuery(args));
51
51
  case 'find_locations':
52
52
  return buildLocations(store, seeds, toQuery(args));
53
+ case 'find_residency':
54
+ return buildResidency(store, seeds, toQuery(args));
53
55
  case 'get_offering': {
54
56
  const found = (await collectOfferings(store)).find(
55
57
  (o) => o.node_id === args.node_id && o.offering_id === args.offering_id);