@routstr/sdk 0.3.7 → 0.3.9

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.
Files changed (39) hide show
  1. package/dist/client/index.d.mts +411 -0
  2. package/dist/client/index.d.ts +411 -0
  3. package/dist/client/index.js +4938 -0
  4. package/dist/client/index.js.map +1 -0
  5. package/dist/client/index.mjs +4932 -0
  6. package/dist/client/index.mjs.map +1 -0
  7. package/dist/discovery/index.d.mts +247 -0
  8. package/dist/discovery/index.d.ts +247 -0
  9. package/dist/discovery/index.js +894 -0
  10. package/dist/discovery/index.js.map +1 -0
  11. package/dist/discovery/index.mjs +891 -0
  12. package/dist/discovery/index.mjs.map +1 -0
  13. package/dist/index.d.mts +195 -0
  14. package/dist/index.d.ts +195 -0
  15. package/dist/index.js +6797 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/index.mjs +6746 -0
  18. package/dist/index.mjs.map +1 -0
  19. package/dist/interfaces-C-DYd9Jy.d.ts +176 -0
  20. package/dist/interfaces-Csn8Uq04.d.mts +176 -0
  21. package/dist/interfaces-Cv1k2EUK.d.mts +118 -0
  22. package/dist/interfaces-iL7CWeG5.d.ts +118 -0
  23. package/dist/storage/index.d.mts +113 -0
  24. package/dist/storage/index.d.ts +113 -0
  25. package/dist/storage/index.js +2019 -0
  26. package/dist/storage/index.js.map +1 -0
  27. package/dist/storage/index.mjs +1995 -0
  28. package/dist/storage/index.mjs.map +1 -0
  29. package/dist/store-58VcEUoA.d.ts +172 -0
  30. package/dist/store-C6dfj1cc.d.mts +172 -0
  31. package/dist/types-_21yYFZG.d.mts +234 -0
  32. package/dist/types-_21yYFZG.d.ts +234 -0
  33. package/dist/wallet/index.d.mts +249 -0
  34. package/dist/wallet/index.d.ts +249 -0
  35. package/dist/wallet/index.js +1383 -0
  36. package/dist/wallet/index.js.map +1 -0
  37. package/dist/wallet/index.mjs +1380 -0
  38. package/dist/wallet/index.mjs.map +1 -0
  39. package/package.json +3 -2
@@ -0,0 +1,891 @@
1
+ import { RelayPool, onlyEvents } from 'applesauce-relay';
2
+ import { EventStore } from 'applesauce-core';
3
+ import { tap } from 'rxjs';
4
+
5
+ // core/types.ts
6
+ function makeConsoleLogger(prefix) {
7
+ const fmt = (args) => prefix ? [prefix, ...args] : args;
8
+ return {
9
+ log: (...args) => console.log(...fmt(args)),
10
+ warn: (...args) => console.warn(...fmt(args)),
11
+ error: (...args) => console.error(...fmt(args)),
12
+ debug: (...args) => console.log(...fmt(args)),
13
+ child: (p) => makeConsoleLogger(prefix ? `${prefix}:${p}` : p)
14
+ };
15
+ }
16
+ var consoleLogger = makeConsoleLogger();
17
+
18
+ // core/errors.ts
19
+ var ProviderBootstrapError = class extends Error {
20
+ constructor(failedProviders, message) {
21
+ super(
22
+ message || `Failed to bootstrap providers. Tried: ${failedProviders.join(", ")}`
23
+ );
24
+ this.failedProviders = failedProviders;
25
+ this.name = "ProviderBootstrapError";
26
+ }
27
+ failedProviders;
28
+ };
29
+ var NoProvidersAvailableError = class extends Error {
30
+ constructor() {
31
+ super("No providers are available for model discovery");
32
+ this.name = "NoProvidersAvailableError";
33
+ }
34
+ };
35
+ function isBunRuntime() {
36
+ return typeof Bun !== "undefined";
37
+ }
38
+ var ModelManager = class _ModelManager {
39
+ constructor(adapter, config = {}) {
40
+ this.adapter = adapter;
41
+ this.providerDirectoryUrl = config.providerDirectoryUrl || "https://api.routstr.com/v1/providers/";
42
+ this.cacheTTL = config.cacheTTL || 210 * 60 * 1e3;
43
+ this.includeProviderUrls = config.includeProviderUrls || [];
44
+ this.excludeProviderUrls = config.excludeProviderUrls || [];
45
+ this.routstrPubkey = config.routstrPubkey || "4ad6fa2d16e2a9b576c863b4cf7404a70d4dc320c0c447d10ad6ff58993eacc8";
46
+ this.logger = (config.logger ?? consoleLogger).child("ModelManager");
47
+ this.eventStoreDbPath = config.eventStoreDbPath;
48
+ }
49
+ adapter;
50
+ cacheTTL;
51
+ providerDirectoryUrl;
52
+ includeProviderUrls;
53
+ excludeProviderUrls;
54
+ routstrPubkey;
55
+ logger;
56
+ providerNodePubkeysByUrl = /* @__PURE__ */ new Map();
57
+ /** Persistent event store for relay-fetched events (null if not configured/initialized) */
58
+ eventStore = null;
59
+ eventStoreDb = null;
60
+ eventStoreInitPromise = null;
61
+ eventStoreDbPath;
62
+ /**
63
+ * Get the list of bootstrapped provider base URLs
64
+ * @returns Array of provider base URLs
65
+ */
66
+ getBaseUrls() {
67
+ return this.adapter.getBaseUrlsList();
68
+ }
69
+ /**
70
+ * Lazily initialize the persistent event store.
71
+ * Returns null if no eventStoreDbPath was provided.
72
+ */
73
+ async ensureEventStore() {
74
+ if (!this.eventStoreDbPath) return null;
75
+ if (this.eventStore) return this.eventStore;
76
+ if (!this.eventStoreInitPromise) {
77
+ this.eventStoreInitPromise = (async () => {
78
+ try {
79
+ const db = await this.createPersistentEventDatabase();
80
+ this.eventStoreDb = db;
81
+ this.eventStore = new EventStore({ database: db });
82
+ this.initializeEventStoreMetadata();
83
+ this.logger.log(
84
+ `Persistent event store initialized at ${this.eventStoreDbPath}`
85
+ );
86
+ return this.eventStore;
87
+ } catch (error) {
88
+ this.eventStoreInitPromise = null;
89
+ throw new Error(
90
+ `applesauce-sqlite with a supported SQLite driver is required for persistent Nostr event storage. Bun uses bun:sqlite; Node.js uses better-sqlite3. Install optional dependencies or omit eventStoreDbPath. (${error})`
91
+ );
92
+ }
93
+ })();
94
+ }
95
+ return this.eventStoreInitPromise;
96
+ }
97
+ /**
98
+ * Get the persistent event store, initializing it if configured.
99
+ * Returns null if no eventStoreDbPath was provided.
100
+ */
101
+ async getEventStore() {
102
+ return this.ensureEventStore();
103
+ }
104
+ async createPersistentEventDatabase() {
105
+ if (isBunRuntime()) {
106
+ const { BunSqliteEventDatabase } = await import('applesauce-sqlite/bun');
107
+ return new BunSqliteEventDatabase(
108
+ this.eventStoreDbPath
109
+ );
110
+ }
111
+ const { BetterSqlite3EventDatabase } = await import('applesauce-sqlite/better-sqlite3');
112
+ return new BetterSqlite3EventDatabase(
113
+ this.eventStoreDbPath
114
+ );
115
+ }
116
+ /** Close the persistent event store database handle, if configured. */
117
+ closeEventStore() {
118
+ this.eventStoreDb?.close?.();
119
+ this.eventStore = null;
120
+ this.eventStoreDb = null;
121
+ this.eventStoreInitPromise = null;
122
+ }
123
+ initializeEventStoreMetadata() {
124
+ this.eventStoreDb?.db?.exec(
125
+ `CREATE TABLE IF NOT EXISTS routstr_event_cache_metadata (
126
+ event_id TEXT PRIMARY KEY,
127
+ fetched_at INTEGER NOT NULL
128
+ )`
129
+ );
130
+ }
131
+ markEventFetched(event, fetchedAt = Date.now()) {
132
+ const db = this.eventStoreDb?.db;
133
+ if (!db) return;
134
+ db.prepare(
135
+ `INSERT INTO routstr_event_cache_metadata (event_id, fetched_at)
136
+ VALUES (?, ?)
137
+ ON CONFLICT(event_id) DO UPDATE SET fetched_at = excluded.fetched_at`
138
+ ).run?.(event.id, fetchedAt);
139
+ }
140
+ getEventFetchedAt(event) {
141
+ const db = this.eventStoreDb?.db;
142
+ if (!db) return void 0;
143
+ const row = db.prepare(
144
+ `SELECT fetched_at FROM routstr_event_cache_metadata WHERE event_id = ?`
145
+ ).get?.(event.id);
146
+ return typeof row?.fetched_at === "number" ? row.fetched_at : void 0;
147
+ }
148
+ /**
149
+ * Check the persistent event store for fresh cached events.
150
+ * Returns events from SQLite if they were fetched within `maxAge`, otherwise
151
+ * returns empty array (caller should hit relays). Events without local fetch
152
+ * metadata fall back to Nostr created_at for backwards compatibility.
153
+ */
154
+ async getCachedNostrEvents(filter, maxAge, forceRefresh = false) {
155
+ const eventStore = await this.ensureEventStore();
156
+ if (forceRefresh) return [];
157
+ if (!eventStore) return [];
158
+ const timeline = eventStore.getTimeline(filter);
159
+ if (timeline.length === 0) return [];
160
+ const cutoff = Date.now() - maxAge;
161
+ const freshest = Math.max(
162
+ ...timeline.map((e) => this.getEventFetchedAt(e) ?? e.created_at * 1e3)
163
+ );
164
+ if (freshest < cutoff) return [];
165
+ return timeline;
166
+ }
167
+ static async init(adapter, config = {}, options = {}) {
168
+ const manager = new _ModelManager(adapter, config);
169
+ const torMode = options.torMode ?? false;
170
+ const forceRefresh = options.forceRefresh ?? false;
171
+ const providers = await manager.bootstrapProviders(torMode, forceRefresh);
172
+ await manager.fetchModels(providers, forceRefresh);
173
+ return manager;
174
+ }
175
+ /**
176
+ * Bootstrap provider list from the provider directory
177
+ * First tries to fetch from Nostr (kind 30421), falls back to HTTP
178
+ * @param torMode Whether running in Tor context
179
+ * @param forceRefresh Ignore provider cache and refresh provider sources
180
+ * @returns Array of provider base URLs
181
+ * @throws ProviderBootstrapError if all providers fail to fetch
182
+ */
183
+ async bootstrapProviders(torMode = false, forceRefresh = false) {
184
+ if (!forceRefresh) {
185
+ const cachedUrls = this.adapter.getBaseUrlsList();
186
+ if (cachedUrls.length > 0) {
187
+ const lastUpdate = this.adapter.getBaseUrlsLastUpdate();
188
+ const cacheValid = lastUpdate && Date.now() - lastUpdate <= this.cacheTTL;
189
+ if (cacheValid) {
190
+ const filteredCachedUrls = this.filterBaseUrlsForTor(
191
+ cachedUrls,
192
+ torMode
193
+ );
194
+ await this.fetchRoutstr21Models(forceRefresh);
195
+ await this.syncReviewedProvidersFromNostr(
196
+ filteredCachedUrls,
197
+ this.providerNodePubkeysByUrl,
198
+ forceRefresh
199
+ );
200
+ return filteredCachedUrls;
201
+ }
202
+ }
203
+ }
204
+ try {
205
+ const nostrProviders = await this.bootstrapFromNostr(
206
+ 38421,
207
+ torMode,
208
+ forceRefresh
209
+ );
210
+ if (nostrProviders.length > 0) {
211
+ const filtered = this.filterBaseUrlsForTor(nostrProviders, torMode);
212
+ this.adapter.setBaseUrlsList(filtered);
213
+ this.adapter.setBaseUrlsLastUpdate(Date.now());
214
+ await this.fetchRoutstr21Models(forceRefresh);
215
+ await this.syncReviewedProvidersFromNostr(
216
+ filtered,
217
+ this.providerNodePubkeysByUrl,
218
+ forceRefresh
219
+ );
220
+ return filtered;
221
+ }
222
+ } catch (e) {
223
+ this.logger.warn("Nostr bootstrap failed, falling back to HTTP:", e);
224
+ }
225
+ return this.bootstrapFromHttp(torMode, forceRefresh);
226
+ }
227
+ /**
228
+ * Bootstrap providers from Nostr network (kind 38421)
229
+ * @param kind The Nostr kind to fetch
230
+ * @param torMode Whether running in Tor context
231
+ * @returns Array of provider base URLs
232
+ */
233
+ async bootstrapFromNostr(kind, torMode, forceRefresh = false) {
234
+ const DEFAULT_RELAYS = [
235
+ "wss://relay.primal.net",
236
+ "wss://nos.lol",
237
+ "wss://relay.damus.io"
238
+ ];
239
+ const cached = await this.getCachedNostrEvents(
240
+ { kinds: [kind] },
241
+ this.cacheTTL,
242
+ forceRefresh
243
+ );
244
+ let sessionEvents = cached;
245
+ if (cached.length === 0) {
246
+ const pool = new RelayPool();
247
+ const timeoutMs = 5e3;
248
+ await new Promise((resolve) => {
249
+ pool.req(DEFAULT_RELAYS, {
250
+ kinds: [kind],
251
+ limit: 100
252
+ }).pipe(
253
+ onlyEvents(),
254
+ tap((event) => {
255
+ sessionEvents.push(event);
256
+ this.eventStore?.add(event);
257
+ this.markEventFetched(event);
258
+ })
259
+ ).subscribe({
260
+ complete: () => {
261
+ resolve();
262
+ }
263
+ });
264
+ setTimeout(() => {
265
+ resolve();
266
+ }, timeoutMs);
267
+ });
268
+ } else {
269
+ this.logger.log(`Using ${cached.length} cached kind ${kind} events from persistent store`);
270
+ }
271
+ const bases = /* @__PURE__ */ new Set();
272
+ this.providerNodePubkeysByUrl = /* @__PURE__ */ new Map();
273
+ for (const event of sessionEvents) {
274
+ const eventUrls = [];
275
+ for (const tag of event.tags) {
276
+ if (tag[0] === "u" && typeof tag[1] === "string") {
277
+ eventUrls.push(tag[1]);
278
+ }
279
+ }
280
+ if (eventUrls.length > 0) {
281
+ for (const url of eventUrls) {
282
+ const normalized = this.normalizeUrl(url);
283
+ if (!torMode || normalized.includes(".onion")) {
284
+ bases.add(normalized);
285
+ this.addProviderNode(
286
+ this.providerNodePubkeysByUrl,
287
+ normalized,
288
+ event.pubkey
289
+ );
290
+ }
291
+ }
292
+ continue;
293
+ }
294
+ try {
295
+ const content = JSON.parse(event.content);
296
+ const providers = Array.isArray(content) ? content : content.providers || [];
297
+ for (const p of providers) {
298
+ const endpoints = this.getProviderEndpoints(p, torMode);
299
+ for (const endpoint of endpoints) {
300
+ bases.add(endpoint);
301
+ this.addProviderNode(
302
+ this.providerNodePubkeysByUrl,
303
+ endpoint,
304
+ p?.pubkey || event.pubkey
305
+ );
306
+ }
307
+ }
308
+ } catch {
309
+ try {
310
+ const providers = JSON.parse(event.content);
311
+ if (Array.isArray(providers)) {
312
+ for (const p of providers) {
313
+ const endpoints = this.getProviderEndpoints(p, torMode);
314
+ for (const endpoint of endpoints) {
315
+ bases.add(endpoint);
316
+ this.addProviderNode(
317
+ this.providerNodePubkeysByUrl,
318
+ endpoint,
319
+ p?.pubkey || event.pubkey
320
+ );
321
+ }
322
+ }
323
+ }
324
+ } catch {
325
+ this.logger.warn(
326
+ "NostrBootstrap: failed to parse event content:",
327
+ event.id
328
+ );
329
+ }
330
+ }
331
+ }
332
+ for (const url of this.includeProviderUrls) {
333
+ const normalized = this.normalizeUrl(url);
334
+ if (!torMode || normalized.includes(".onion")) {
335
+ bases.add(normalized);
336
+ }
337
+ }
338
+ const excluded = new Set(
339
+ this.excludeProviderUrls.map((url) => this.normalizeUrl(url))
340
+ );
341
+ const result = Array.from(bases).filter((base) => !excluded.has(base));
342
+ return result;
343
+ }
344
+ /**
345
+ * Bootstrap providers from HTTP endpoint
346
+ * @param torMode Whether running in Tor context
347
+ * @param forceRefresh Ignore routstr21 cache and fetch fresh data
348
+ * @returns Array of provider base URLs
349
+ */
350
+ async bootstrapFromHttp(torMode, forceRefresh = false) {
351
+ try {
352
+ const res = await fetch(this.providerDirectoryUrl);
353
+ if (!res.ok) {
354
+ throw new Error(`Failed to fetch providers: ${res.status}`);
355
+ }
356
+ const data = await res.json();
357
+ const providers = Array.isArray(data?.providers) ? data.providers : [];
358
+ const bases = /* @__PURE__ */ new Set();
359
+ this.providerNodePubkeysByUrl = /* @__PURE__ */ new Map();
360
+ for (const p of providers) {
361
+ const endpoints = this.getProviderEndpoints(p, torMode);
362
+ for (const endpoint of endpoints) {
363
+ bases.add(endpoint);
364
+ this.addProviderNode(this.providerNodePubkeysByUrl, endpoint, p?.pubkey);
365
+ }
366
+ }
367
+ for (const url of this.includeProviderUrls) {
368
+ const normalized = this.normalizeUrl(url);
369
+ if (!torMode || normalized.includes(".onion")) {
370
+ bases.add(normalized);
371
+ }
372
+ }
373
+ const excluded = new Set(
374
+ this.excludeProviderUrls.map((url) => this.normalizeUrl(url))
375
+ );
376
+ const list = Array.from(bases).filter((base) => !excluded.has(base));
377
+ if (list.length > 0) {
378
+ this.adapter.setBaseUrlsList(list);
379
+ this.adapter.setBaseUrlsLastUpdate(Date.now());
380
+ await this.fetchRoutstr21Models(forceRefresh);
381
+ await this.syncReviewedProvidersFromNostr(
382
+ list,
383
+ this.providerNodePubkeysByUrl,
384
+ forceRefresh
385
+ );
386
+ }
387
+ return list;
388
+ } catch (e) {
389
+ this.logger.error("Failed to bootstrap providers", e);
390
+ throw new ProviderBootstrapError([], `Provider bootstrap failed: ${e}`);
391
+ }
392
+ }
393
+ /**
394
+ * Fetch Routstr review events from Nostr (kind 38425) and disable providers
395
+ * whose 38421 node pubkey does not have at least one review tagged `t=lgtm`.
396
+ *
397
+ * Review events are expected to have:
398
+ * - `node`: the reviewed 38421 provider event pubkey
399
+ * - `t`: review label, where `lgtm` means the node looks good
400
+ *
401
+ * @param baseUrls Current provider base URLs to evaluate
402
+ * @returns Array of provider base URLs disabled by the review set
403
+ */
404
+ async syncReviewedProvidersFromNostr(baseUrls = this.adapter.getBaseUrlsList(), providerNodes = this.providerNodePubkeysByUrl, forceRefresh = false) {
405
+ if (baseUrls.length === 0) return [];
406
+ if (!this.adapter.setDisabledProviders) {
407
+ this.logger.warn(
408
+ "NostrReviews: adapter does not support setDisabledProviders; skipping provider disable sync"
409
+ );
410
+ return [];
411
+ }
412
+ const reviewedNodePubkeys = /* @__PURE__ */ new Set();
413
+ {
414
+ const cached = await this.getCachedNostrEvents(
415
+ { kinds: [38425], "#t": ["lgtm"], authors: [this.routstrPubkey] },
416
+ this.cacheTTL,
417
+ forceRefresh
418
+ );
419
+ let sessionEvents = cached;
420
+ if (cached.length === 0) {
421
+ const LGTM_RELAYS = [
422
+ "wss://relay.primal.net",
423
+ "wss://nos.lol",
424
+ "wss://relay.damus.io",
425
+ "wss://relay.routstr.com"
426
+ ];
427
+ const pool = new RelayPool();
428
+ const timeoutMs = 5e3;
429
+ await new Promise((resolve) => {
430
+ pool.req(LGTM_RELAYS, {
431
+ kinds: [38425],
432
+ "#t": ["lgtm"],
433
+ limit: 500,
434
+ authors: [this.routstrPubkey]
435
+ }).pipe(
436
+ onlyEvents(),
437
+ tap((event) => {
438
+ sessionEvents.push(event);
439
+ this.eventStore?.add(event);
440
+ this.markEventFetched(event);
441
+ })
442
+ ).subscribe({ complete: () => resolve() });
443
+ setTimeout(() => resolve(), timeoutMs);
444
+ });
445
+ } else {
446
+ this.logger.log(`Using ${cached.length} cached kind 38425 events from persistent store`);
447
+ }
448
+ for (const event of sessionEvents) {
449
+ const hasLgtmTag = event.tags.some(
450
+ (tag) => tag[0] === "t" && tag[1]?.toLowerCase() === "lgtm"
451
+ );
452
+ if (!hasLgtmTag) continue;
453
+ for (const tag of event.tags) {
454
+ if (tag[0] === "node" && typeof tag[1] === "string" && tag[1]) {
455
+ reviewedNodePubkeys.add(tag[1]);
456
+ }
457
+ }
458
+ }
459
+ }
460
+ if (reviewedNodePubkeys.size === 0) {
461
+ this.logger.warn(
462
+ "NostrReviews: no kind 38425 lgtm reviews found; keeping disabled providers unchanged"
463
+ );
464
+ return [];
465
+ }
466
+ if (providerNodes.size === 0) {
467
+ this.logger.warn(
468
+ "NostrReviews: no kind 38421 provider node metadata found; keeping disabled providers unchanged"
469
+ );
470
+ return [];
471
+ }
472
+ const disabledByReview = [];
473
+ for (const url of baseUrls) {
474
+ const normalized = this.normalizeUrl(url);
475
+ const nodePubkeys = providerNodes.get(normalized) || /* @__PURE__ */ new Set();
476
+ const hasLgtmReview = Array.from(nodePubkeys).some(
477
+ (pubkey) => reviewedNodePubkeys.has(pubkey)
478
+ );
479
+ if (!hasLgtmReview) {
480
+ disabledByReview.push(normalized);
481
+ }
482
+ }
483
+ this.adapter.setDisabledProviders(Array.from(new Set(disabledByReview)));
484
+ return disabledByReview;
485
+ }
486
+ addProviderNode(map, url, pubkey) {
487
+ if (!pubkey) return;
488
+ const normalized = this.normalizeUrl(url);
489
+ const existing = map.get(normalized) || /* @__PURE__ */ new Set();
490
+ existing.add(pubkey);
491
+ map.set(normalized, existing);
492
+ }
493
+ /**
494
+ * Fetch models from all providers and select best-priced options
495
+ * Uses cache if available and not expired
496
+ * @param baseUrls List of provider base URLs to fetch from
497
+ * @param forceRefresh Ignore cache and fetch fresh data
498
+ * @param onProgress Callback fired after each provider completes with current combined models
499
+ * @returns Array of unique models with best prices selected
500
+ */
501
+ async fetchModels(baseUrls, forceRefresh = false, onProgress) {
502
+ if (baseUrls.length === 0) {
503
+ throw new NoProvidersAvailableError();
504
+ }
505
+ const bestById = /* @__PURE__ */ new Map();
506
+ const modelsFromAllProviders = {};
507
+ const disabledProviders = this.adapter.getDisabledProviders();
508
+ const estimateMinCost = (m) => {
509
+ return m?.sats_pricing?.completion ?? 0;
510
+ };
511
+ const emitProgress = () => {
512
+ if (onProgress) {
513
+ const currentModels = Array.from(bestById.values()).map((v) => v.model);
514
+ onProgress(currentModels);
515
+ }
516
+ };
517
+ const fetchPromises = baseUrls.map(async (url) => {
518
+ const base = url.endsWith("/") ? url : `${url}/`;
519
+ try {
520
+ let list;
521
+ if (!forceRefresh) {
522
+ const lastUpdate = this.adapter.getProviderLastUpdate(base);
523
+ const cacheValid = lastUpdate && Date.now() - lastUpdate <= this.cacheTTL;
524
+ if (cacheValid) {
525
+ const cachedModels = this.adapter.getCachedModels();
526
+ const cachedList = cachedModels[base] || [];
527
+ list = cachedList;
528
+ } else {
529
+ list = await this.fetchModelsFromProvider(base);
530
+ }
531
+ } else {
532
+ list = await this.fetchModelsFromProvider(base);
533
+ }
534
+ modelsFromAllProviders[base] = list;
535
+ this.adapter.setProviderLastUpdate(base, Date.now());
536
+ if (!disabledProviders.includes(base)) {
537
+ for (const m of list) {
538
+ const existing = bestById.get(m.id);
539
+ if (!m.sats_pricing) continue;
540
+ if (!existing) {
541
+ bestById.set(m.id, { model: m, base });
542
+ continue;
543
+ }
544
+ const currentCost = estimateMinCost(m);
545
+ const existingCost = estimateMinCost(existing.model);
546
+ if (currentCost < existingCost && m.sats_pricing) {
547
+ bestById.set(m.id, { model: m, base });
548
+ }
549
+ }
550
+ }
551
+ emitProgress();
552
+ return { success: true, base, list };
553
+ } catch (error) {
554
+ if (this.isProviderDownError(error)) {
555
+ this.logger.warn(`Provider ${base} is down right now.`);
556
+ } else {
557
+ this.logger.warn(`Provider ${base} unreachable: ${error.message}`);
558
+ }
559
+ this.adapter.setProviderLastUpdate(base, Date.now());
560
+ return { success: false, base };
561
+ }
562
+ });
563
+ await Promise.allSettled(fetchPromises);
564
+ const existingCache = this.adapter.getCachedModels();
565
+ this.adapter.setCachedModels({
566
+ ...existingCache,
567
+ ...modelsFromAllProviders
568
+ });
569
+ return Array.from(bestById.values()).map((v) => v.model);
570
+ }
571
+ /**
572
+ * Fetch models from a single provider
573
+ * @param baseUrl Provider base URL
574
+ * @returns Array of models from provider
575
+ */
576
+ async fetchModelsFromProvider(baseUrl) {
577
+ const res = await fetch(`${baseUrl}v1/models`);
578
+ if (!res.ok) {
579
+ throw new Error(`Failed to fetch models: ${res.status}`);
580
+ }
581
+ const json = await res.json();
582
+ const list = Array.isArray(json?.data) ? json.data : [];
583
+ return list;
584
+ }
585
+ isProviderDownError(error) {
586
+ if (!(error instanceof Error)) return false;
587
+ const msg = error.message.toLowerCase();
588
+ if (msg.includes("fetch failed")) return true;
589
+ if (msg.includes("429")) return true;
590
+ if (msg.includes("502")) return true;
591
+ if (msg.includes("503")) return true;
592
+ if (msg.includes("504")) return true;
593
+ const cause = error.cause;
594
+ return cause?.code === "ENOTFOUND";
595
+ }
596
+ /**
597
+ * Get all cached models from all providers
598
+ * @returns Record mapping baseUrl -> models
599
+ */
600
+ getAllCachedModels() {
601
+ return this.adapter.getCachedModels();
602
+ }
603
+ /**
604
+ * Clear cache for a specific provider
605
+ * @param baseUrl Provider base URL
606
+ */
607
+ clearProviderCache(baseUrl) {
608
+ const base = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
609
+ const cached = this.adapter.getCachedModels();
610
+ delete cached[base];
611
+ this.adapter.setCachedModels(cached);
612
+ this.adapter.setProviderLastUpdate(base, 0);
613
+ }
614
+ /**
615
+ * Clear all model caches
616
+ */
617
+ clearAllCache() {
618
+ this.adapter.setCachedModels({});
619
+ }
620
+ /**
621
+ * Filter base URLs based on Tor context
622
+ * @param baseUrls Provider URLs to filter
623
+ * @param torMode Whether in Tor context
624
+ * @returns Filtered URLs appropriate for Tor mode
625
+ */
626
+ filterBaseUrlsForTor(baseUrls, torMode) {
627
+ if (!torMode) {
628
+ return baseUrls.filter((url) => !url.includes(".onion"));
629
+ }
630
+ return baseUrls.filter((url) => url.includes(".onion"));
631
+ }
632
+ /**
633
+ * Get provider endpoints from provider info
634
+ * @param provider Provider object from directory
635
+ * @param torMode Whether in Tor context
636
+ * @returns Array of endpoint URLs
637
+ */
638
+ getProviderEndpoints(provider, torMode) {
639
+ const endpoints = [];
640
+ if (torMode && provider.onion_url) {
641
+ endpoints.push(this.normalizeUrl(provider.onion_url));
642
+ } else if (provider.endpoint_url) {
643
+ endpoints.push(this.normalizeUrl(provider.endpoint_url));
644
+ }
645
+ return endpoints;
646
+ }
647
+ /**
648
+ * Normalize provider URL with trailing slash
649
+ * @param url URL to normalize
650
+ * @returns Normalized URL
651
+ */
652
+ normalizeUrl(url) {
653
+ if (!url.startsWith("http")) {
654
+ url = `https://${url}`;
655
+ }
656
+ return url.endsWith("/") ? url : `${url}/`;
657
+ }
658
+ /**
659
+ * Fetch routstr21 models from Nostr network (kind 38423)
660
+ * Uses cache if available and not expired
661
+ * @returns Array of model IDs or empty array if not found
662
+ */
663
+ async fetchRoutstr21Models(forceRefresh = false) {
664
+ const cachedModels = this.adapter.getRoutstr21Models();
665
+ if (!forceRefresh && cachedModels.length > 0) {
666
+ const lastUpdate = this.adapter.getRoutstr21ModelsLastUpdate();
667
+ const cacheValid = lastUpdate && Date.now() - lastUpdate <= this.cacheTTL;
668
+ if (cacheValid) {
669
+ return cachedModels;
670
+ }
671
+ }
672
+ const DEFAULT_RELAYS = [
673
+ "wss://relay.damus.io",
674
+ "wss://nos.lol",
675
+ "wss://relay.routstr.com"
676
+ ];
677
+ const cached = await this.getCachedNostrEvents(
678
+ { kinds: [38423], "#d": ["routstr-21-models"], authors: [this.routstrPubkey] },
679
+ this.cacheTTL,
680
+ forceRefresh
681
+ );
682
+ let sessionEvents = cached;
683
+ if (cached.length === 0) {
684
+ const pool = new RelayPool();
685
+ const timeoutMs = 5e3;
686
+ await new Promise((resolve) => {
687
+ pool.req(DEFAULT_RELAYS, {
688
+ kinds: [38423],
689
+ "#d": ["routstr-21-models"],
690
+ limit: 1,
691
+ authors: [this.routstrPubkey]
692
+ }).pipe(
693
+ onlyEvents(),
694
+ tap((event2) => {
695
+ sessionEvents.push(event2);
696
+ this.eventStore?.add(event2);
697
+ this.markEventFetched(event2);
698
+ })
699
+ ).subscribe({
700
+ complete: () => {
701
+ resolve();
702
+ }
703
+ });
704
+ setTimeout(() => {
705
+ resolve();
706
+ }, timeoutMs);
707
+ });
708
+ } else {
709
+ this.logger.log(`Using ${cached.length} cached kind 38423 events from persistent store`);
710
+ }
711
+ if (sessionEvents.length === 0) {
712
+ return cachedModels.length > 0 ? cachedModels : [];
713
+ }
714
+ const event = sessionEvents[0];
715
+ try {
716
+ const content = JSON.parse(event.content);
717
+ const models = Array.isArray(content?.models) ? content.models : [];
718
+ this.adapter.setRoutstr21Models(models);
719
+ this.adapter.setRoutstr21ModelsLastUpdate(Date.now());
720
+ return models;
721
+ } catch {
722
+ this.logger.warn(
723
+ "Routstr21Models: failed to parse Nostr event content:",
724
+ event.id
725
+ );
726
+ return cachedModels.length > 0 ? cachedModels : [];
727
+ }
728
+ }
729
+ };
730
+
731
+ // discovery/MintDiscovery.ts
732
+ var MintDiscovery = class {
733
+ constructor(adapter, config = {}) {
734
+ this.adapter = adapter;
735
+ this.cacheTTL = config.cacheTTL || 21 * 60 * 1e3;
736
+ this.logger = (config.logger ?? consoleLogger).child("MintDiscovery");
737
+ }
738
+ adapter;
739
+ cacheTTL;
740
+ logger;
741
+ /**
742
+ * Fetch mints from all providers via their /v1/info endpoints
743
+ * Caches mints and full provider info for later access
744
+ * @param baseUrls List of provider base URLs to fetch from
745
+ * @returns Object with mints and provider info from all providers
746
+ */
747
+ async discoverMints(baseUrls, options = {}) {
748
+ if (baseUrls.length === 0) {
749
+ return { mintsFromProviders: {}, infoFromProviders: {} };
750
+ }
751
+ const mintsFromAllProviders = {};
752
+ const infoFromAllProviders = {};
753
+ const forceRefresh = options.forceRefresh ?? false;
754
+ const fetchPromises = baseUrls.map(async (url) => {
755
+ const base = url.endsWith("/") ? url : `${url}/`;
756
+ try {
757
+ if (!forceRefresh) {
758
+ const lastUpdate = this.adapter.getProviderLastUpdate(base);
759
+ const cacheValid = lastUpdate && Date.now() - lastUpdate <= this.cacheTTL;
760
+ if (cacheValid) {
761
+ const cachedMints = this.adapter.getCachedMints()[base] || [];
762
+ const cachedInfo = this.adapter.getCachedProviderInfo()[base];
763
+ mintsFromAllProviders[base] = cachedMints;
764
+ if (cachedInfo) {
765
+ infoFromAllProviders[base] = cachedInfo;
766
+ }
767
+ return {
768
+ success: true,
769
+ base,
770
+ mints: cachedMints,
771
+ info: cachedInfo
772
+ };
773
+ }
774
+ }
775
+ const res = await fetch(`${base}v1/info`);
776
+ if (!res.ok) {
777
+ throw new Error(`Failed to fetch info: ${res.status}`);
778
+ }
779
+ const json = await res.json();
780
+ const mints = Array.isArray(json?.mints) ? json.mints : [];
781
+ const normalizedMints = mints.map(
782
+ (mint) => mint.endsWith("/") ? mint.slice(0, -1) : mint
783
+ );
784
+ mintsFromAllProviders[base] = normalizedMints;
785
+ infoFromAllProviders[base] = json;
786
+ this.adapter.setProviderLastUpdate(base, Date.now());
787
+ return { success: true, base, mints: normalizedMints, info: json };
788
+ } catch (error) {
789
+ this.adapter.setProviderLastUpdate(base, Date.now());
790
+ if (this.isProviderDownError(error)) {
791
+ this.logger.warn(`Provider ${base} is down right now.`);
792
+ } else {
793
+ this.logger.warn(`Failed to fetch mints from ${base}:`, error);
794
+ }
795
+ return { success: false, base, mints: [], info: null };
796
+ }
797
+ });
798
+ const results = await Promise.allSettled(fetchPromises);
799
+ for (const result of results) {
800
+ if (result.status === "fulfilled") {
801
+ const { base, mints, info } = result.value;
802
+ mintsFromAllProviders[base] = mints;
803
+ if (info) {
804
+ infoFromAllProviders[base] = info;
805
+ }
806
+ } else {
807
+ this.logger.error("Mint discovery error:", result.reason);
808
+ }
809
+ }
810
+ try {
811
+ this.adapter.setCachedMints(mintsFromAllProviders);
812
+ this.adapter.setCachedProviderInfo(infoFromAllProviders);
813
+ } catch (error) {
814
+ this.logger.error("Error caching mint discovery results:", error);
815
+ }
816
+ return {
817
+ mintsFromProviders: mintsFromAllProviders,
818
+ infoFromProviders: infoFromAllProviders
819
+ };
820
+ }
821
+ /**
822
+ * Get cached mints from all providers
823
+ * @returns Record mapping baseUrl -> mint URLs
824
+ */
825
+ getCachedMints() {
826
+ return this.adapter.getCachedMints();
827
+ }
828
+ /**
829
+ * Get cached provider info from all providers
830
+ * @returns Record mapping baseUrl -> provider info
831
+ */
832
+ getCachedProviderInfo() {
833
+ return this.adapter.getCachedProviderInfo();
834
+ }
835
+ /**
836
+ * Get mints for a specific provider
837
+ * @param baseUrl Provider base URL
838
+ * @returns Array of mint URLs for the provider
839
+ */
840
+ getProviderMints(baseUrl) {
841
+ const normalized = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
842
+ const allMints = this.getCachedMints();
843
+ return allMints[normalized] || [];
844
+ }
845
+ /**
846
+ * Get info for a specific provider
847
+ * @param baseUrl Provider base URL
848
+ * @returns Provider info object or null if not found
849
+ */
850
+ getProviderInfo(baseUrl) {
851
+ const normalized = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
852
+ const allInfo = this.getCachedProviderInfo();
853
+ return allInfo[normalized] || null;
854
+ }
855
+ /**
856
+ * Clear mint cache for a specific provider
857
+ * @param baseUrl Provider base URL
858
+ */
859
+ clearProviderMintCache(baseUrl) {
860
+ const normalized = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
861
+ const mints = this.getCachedMints();
862
+ delete mints[normalized];
863
+ this.adapter.setCachedMints(mints);
864
+ const info = this.getCachedProviderInfo();
865
+ delete info[normalized];
866
+ this.adapter.setCachedProviderInfo(info);
867
+ }
868
+ /**
869
+ * Clear all mint caches
870
+ */
871
+ clearAllCache() {
872
+ this.adapter.setCachedMints({});
873
+ this.adapter.setCachedProviderInfo({});
874
+ }
875
+ isProviderDownError(error) {
876
+ if (!(error instanceof Error)) return false;
877
+ const msg = error.message.toLowerCase();
878
+ if (msg.includes("fetch failed")) return true;
879
+ if (msg.includes("429")) return true;
880
+ if (msg.includes("502")) return true;
881
+ if (msg.includes("503")) return true;
882
+ if (msg.includes("504")) return true;
883
+ const cause = error.cause;
884
+ if (cause?.code === "ENOTFOUND") return true;
885
+ return false;
886
+ }
887
+ };
888
+
889
+ export { MintDiscovery, ModelManager };
890
+ //# sourceMappingURL=index.mjs.map
891
+ //# sourceMappingURL=index.mjs.map