@routstr/sdk 0.3.7 → 0.3.8

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 +4883 -0
  4. package/dist/client/index.js.map +1 -0
  5. package/dist/client/index.mjs +4877 -0
  6. package/dist/client/index.mjs.map +1 -0
  7. package/dist/discovery/index.d.mts +213 -0
  8. package/dist/discovery/index.d.ts +213 -0
  9. package/dist/discovery/index.js +738 -0
  10. package/dist/discovery/index.js.map +1 -0
  11. package/dist/discovery/index.mjs +735 -0
  12. package/dist/discovery/index.mjs.map +1 -0
  13. package/dist/index.d.mts +194 -0
  14. package/dist/index.d.ts +194 -0
  15. package/dist/index.js +6307 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/index.mjs +6258 -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 +87 -0
  24. package/dist/storage/index.d.ts +87 -0
  25. package/dist/storage/index.js +1740 -0
  26. package/dist/storage/index.js.map +1 -0
  27. package/dist/storage/index.mjs +1718 -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 +245 -0
  34. package/dist/wallet/index.d.ts +245 -0
  35. package/dist/wallet/index.js +1376 -0
  36. package/dist/wallet/index.js.map +1 -0
  37. package/dist/wallet/index.mjs +1373 -0
  38. package/dist/wallet/index.mjs.map +1 -0
  39. package/package.json +1 -1
@@ -0,0 +1,4883 @@
1
+ 'use strict';
2
+
3
+ var cashuTs = require('@cashu/cashu-ts');
4
+ var vanilla = require('zustand/vanilla');
5
+ var stream = require('stream');
6
+ var string_decoder = require('string_decoder');
7
+
8
+ // core/types.ts
9
+ function makeConsoleLogger(prefix) {
10
+ const fmt = (args) => prefix ? [prefix, ...args] : args;
11
+ return {
12
+ log: (...args) => console.log(...fmt(args)),
13
+ warn: (...args) => console.warn(...fmt(args)),
14
+ error: (...args) => console.error(...fmt(args)),
15
+ debug: (...args) => console.log(...fmt(args)),
16
+ child: (p) => makeConsoleLogger(prefix ? `${prefix}:${p}` : p)
17
+ };
18
+ }
19
+ var consoleLogger = makeConsoleLogger();
20
+
21
+ // core/errors.ts
22
+ var InsufficientBalanceError = class extends Error {
23
+ constructor(required, available, maxMintBalance = 0, maxMintUrl = "", customMessage) {
24
+ super(
25
+ customMessage ?? `Insufficient balance: need ${required} sats, have ${available} sats available. ` + (maxMintBalance > 0 ? `Largest mint balance: ${maxMintBalance} sats from ${maxMintUrl}` : "")
26
+ );
27
+ this.required = required;
28
+ this.available = available;
29
+ this.maxMintBalance = maxMintBalance;
30
+ this.maxMintUrl = maxMintUrl;
31
+ this.name = "InsufficientBalanceError";
32
+ }
33
+ required;
34
+ available;
35
+ maxMintBalance;
36
+ maxMintUrl;
37
+ };
38
+ var ProviderError = class extends Error {
39
+ constructor(baseUrl, statusCode, message, requestId) {
40
+ super(
41
+ `Provider ${baseUrl} returned ${statusCode}: ${message}` + (requestId ? ` (Request ID: ${requestId})` : "")
42
+ );
43
+ this.baseUrl = baseUrl;
44
+ this.statusCode = statusCode;
45
+ this.requestId = requestId;
46
+ this.name = "ProviderError";
47
+ }
48
+ baseUrl;
49
+ statusCode;
50
+ requestId;
51
+ };
52
+ var FailoverError = class extends Error {
53
+ constructor(originalProvider, failedProviders, message) {
54
+ super(
55
+ message || `All providers failed. Original: ${originalProvider}, Failed: ${failedProviders.join(", ")}`
56
+ );
57
+ this.originalProvider = originalProvider;
58
+ this.failedProviders = failedProviders;
59
+ this.name = "FailoverError";
60
+ }
61
+ originalProvider;
62
+ failedProviders;
63
+ };
64
+
65
+ // wallet/AuditLogger.ts
66
+ var AuditLogger = class _AuditLogger {
67
+ static instance = null;
68
+ static getInstance() {
69
+ if (!_AuditLogger.instance) {
70
+ _AuditLogger.instance = new _AuditLogger();
71
+ }
72
+ return _AuditLogger.instance;
73
+ }
74
+ async log(entry) {
75
+ const fullEntry = {
76
+ ...entry,
77
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
78
+ };
79
+ const logLine = JSON.stringify(fullEntry) + "\n";
80
+ if (typeof window === "undefined") {
81
+ try {
82
+ const fs = await import('fs');
83
+ const path = await import('path');
84
+ const logPath = path.join(process.cwd(), "audit.log");
85
+ fs.appendFileSync(logPath, logLine);
86
+ } catch (error) {
87
+ console.error("[AuditLogger] Failed to write to file:", error);
88
+ }
89
+ } else {
90
+ console.log("[AUDIT]", logLine.trim());
91
+ }
92
+ }
93
+ async logBalanceSnapshot(action, amounts, options) {
94
+ await this.log({
95
+ action,
96
+ totalBalance: amounts.totalBalance,
97
+ providerBalances: amounts.providerBalances,
98
+ mintBalances: amounts.mintBalances,
99
+ amount: options?.amount,
100
+ mintUrl: options?.mintUrl,
101
+ baseUrl: options?.baseUrl,
102
+ status: options?.status ?? "success",
103
+ details: options?.details
104
+ });
105
+ }
106
+ };
107
+ var auditLogger = AuditLogger.getInstance();
108
+
109
+ // wallet/tokenUtils.ts
110
+ function isNetworkErrorMessage(message) {
111
+ return message.includes("NetworkError when attempting to fetch resource") || message.includes("Failed to fetch") || message.includes("Load failed") || message.includes("ERR_TLS_CERT_ALTNAME_INVALID") || message.includes("ERR_TLS_CERT_NOT_YET_VALID") || message.includes("ERR_TLS_CERT_EXPIRED") || message.includes("UNABLE_TO_VERIFY_LEAF_SIGNATURE") || message.includes("SELF_SIGNED_CERT_IN_CHAIN");
112
+ }
113
+ function getBalanceInSats(balance, unit) {
114
+ return unit === "msat" ? balance / 1e3 : balance;
115
+ }
116
+ function selectMintWithBalance(balances, units, amount, excludeMints = []) {
117
+ for (const mintUrl in balances) {
118
+ if (excludeMints.includes(mintUrl)) {
119
+ continue;
120
+ }
121
+ const balanceInSats = getBalanceInSats(balances[mintUrl], units[mintUrl]);
122
+ if (balanceInSats >= amount) {
123
+ return { selectedMintUrl: mintUrl, selectedMintBalance: balanceInSats };
124
+ }
125
+ }
126
+ return { selectedMintUrl: null, selectedMintBalance: 0 };
127
+ }
128
+ var CashuSpender = class {
129
+ constructor(walletAdapter, storageAdapter, _providerRegistry, balanceManager, logger) {
130
+ this.walletAdapter = walletAdapter;
131
+ this.storageAdapter = storageAdapter;
132
+ this._providerRegistry = _providerRegistry;
133
+ this.balanceManager = balanceManager;
134
+ this.logger = (logger ?? consoleLogger).child("CashuSpender");
135
+ }
136
+ walletAdapter;
137
+ storageAdapter;
138
+ _providerRegistry;
139
+ balanceManager;
140
+ _isBusy = false;
141
+ debugLevel = "WARN";
142
+ logger;
143
+ async receiveToken(token) {
144
+ try {
145
+ const result = await this.walletAdapter.receiveToken(token);
146
+ return result;
147
+ } catch (error) {
148
+ const errorMessage = error instanceof Error ? error.message : String(error);
149
+ if (errorMessage.includes("Failed to fetch mint")) {
150
+ const cachedTokens = this.storageAdapter.getCachedReceiveTokens();
151
+ const existingIndex = cachedTokens.findIndex((t) => t.token === token);
152
+ if (existingIndex === -1) {
153
+ const { amount: amount2, unit: unit2 } = this._decodeTokenAmount(token);
154
+ this.storageAdapter.setCachedReceiveTokens([
155
+ ...cachedTokens,
156
+ {
157
+ token,
158
+ amount: amount2,
159
+ unit: unit2,
160
+ createdAt: Date.now()
161
+ }
162
+ ]);
163
+ }
164
+ }
165
+ const { amount, unit } = this._decodeTokenAmount(token);
166
+ return { success: false, amount, unit, message: errorMessage };
167
+ }
168
+ }
169
+ _decodeTokenAmount(token) {
170
+ try {
171
+ const decoded = cashuTs.getDecodedToken(token);
172
+ const amount = decoded.proofs.reduce(
173
+ (acc, proof) => acc + proof.amount,
174
+ 0
175
+ );
176
+ const unit = decoded.unit || "sat";
177
+ return { amount, unit };
178
+ } catch {
179
+ return { amount: 0, unit: "sat" };
180
+ }
181
+ }
182
+ async _getBalanceState() {
183
+ if (this.balanceManager) {
184
+ return this.balanceManager.getBalanceState();
185
+ }
186
+ const mintBalances = await this.walletAdapter.getBalances();
187
+ const units = this.walletAdapter.getMintUnits();
188
+ let totalMintBalance = 0;
189
+ const normalizedMintBalances = {};
190
+ for (const url in mintBalances) {
191
+ const balance = mintBalances[url];
192
+ const unit = units[url];
193
+ const balanceInSats = getBalanceInSats(balance, unit);
194
+ normalizedMintBalances[url] = balanceInSats;
195
+ totalMintBalance += balanceInSats;
196
+ }
197
+ const providerBalances = {};
198
+ let totalProviderBalance = 0;
199
+ const apiKeys = this.storageAdapter.getAllApiKeys();
200
+ for (const apiKey of apiKeys) {
201
+ if (!providerBalances[apiKey.baseUrl]) {
202
+ providerBalances[apiKey.baseUrl] = 0;
203
+ }
204
+ providerBalances[apiKey.baseUrl] += apiKey.balance;
205
+ totalProviderBalance += apiKey.balance;
206
+ }
207
+ return {
208
+ totalBalance: totalMintBalance + totalProviderBalance,
209
+ providerBalances,
210
+ mintBalances: normalizedMintBalances
211
+ };
212
+ }
213
+ async _logTransaction(action, options) {
214
+ const balanceState = await this._getBalanceState();
215
+ await auditLogger.logBalanceSnapshot(action, balanceState, options);
216
+ }
217
+ /**
218
+ * Check if the spender is currently in a critical operation
219
+ */
220
+ get isBusy() {
221
+ return this._isBusy;
222
+ }
223
+ getDebugLevel() {
224
+ return this.debugLevel;
225
+ }
226
+ setDebugLevel(level) {
227
+ this.debugLevel = level;
228
+ }
229
+ _log(level, ...args) {
230
+ const levelPriority = {
231
+ DEBUG: 0,
232
+ WARN: 1,
233
+ ERROR: 2
234
+ };
235
+ if (levelPriority[level] >= levelPriority[this.debugLevel]) {
236
+ switch (level) {
237
+ case "DEBUG":
238
+ this.logger.log(...args);
239
+ break;
240
+ case "WARN":
241
+ this.logger.warn(...args);
242
+ break;
243
+ case "ERROR":
244
+ this.logger.error(...args);
245
+ break;
246
+ }
247
+ }
248
+ }
249
+ /**
250
+ * Spend Cashu tokens with automatic mint selection and retry logic
251
+ * Throws errors on failure instead of returning failed SpendResult
252
+ */
253
+ async spend(options) {
254
+ const {
255
+ mintUrl,
256
+ amount,
257
+ baseUrl,
258
+ reuseToken = false,
259
+ p2pkPubkey,
260
+ excludeMints = [],
261
+ retryCount = 0
262
+ } = options;
263
+ this._isBusy = true;
264
+ try {
265
+ const result = await this._spendInternal({
266
+ mintUrl,
267
+ amount,
268
+ baseUrl,
269
+ reuseToken,
270
+ p2pkPubkey,
271
+ excludeMints,
272
+ retryCount
273
+ });
274
+ if (result.status === "failed" || !result.token) {
275
+ const errorMsg = result.error || `Insufficient balance. Need ${amount} sats.`;
276
+ if (this._isNetworkError(errorMsg)) {
277
+ throw new Error(
278
+ `Your mint ${mintUrl} is unreachable or is blocking your IP. Please try again later or switch mints.`
279
+ );
280
+ }
281
+ if (result.errorDetails) {
282
+ throw new InsufficientBalanceError(
283
+ result.errorDetails.required,
284
+ result.errorDetails.available,
285
+ result.errorDetails.maxMintBalance,
286
+ result.errorDetails.maxMintUrl
287
+ );
288
+ }
289
+ throw new Error(errorMsg);
290
+ }
291
+ return result;
292
+ } finally {
293
+ this._isBusy = false;
294
+ }
295
+ }
296
+ /**
297
+ * Check if error message indicates a network error
298
+ */
299
+ _isNetworkError(message) {
300
+ return isNetworkErrorMessage(message) || message.includes("Your mint") && message.includes("unreachable");
301
+ }
302
+ /**
303
+ * Internal spending logic
304
+ */
305
+ async _spendInternal(options) {
306
+ let {
307
+ mintUrl,
308
+ amount,
309
+ baseUrl,
310
+ reuseToken,
311
+ p2pkPubkey,
312
+ excludeMints,
313
+ retryCount
314
+ } = options;
315
+ this._log(
316
+ "DEBUG",
317
+ `[CashuSpender] _spendInternal: amount=${amount}, mintUrl=${mintUrl}, baseUrl=${baseUrl}, reuseToken=${reuseToken}`
318
+ );
319
+ let adjustedAmount = Math.ceil(amount);
320
+ if (!adjustedAmount || isNaN(adjustedAmount)) {
321
+ this._log(
322
+ "ERROR",
323
+ `[CashuSpender] _spendInternal: Invalid amount: ${amount}`
324
+ );
325
+ return {
326
+ token: null,
327
+ status: "failed",
328
+ balance: 0,
329
+ error: "Please enter a valid amount"
330
+ };
331
+ }
332
+ if (reuseToken && baseUrl) {
333
+ this._log(
334
+ "DEBUG",
335
+ `[CashuSpender] _spendInternal: Attempting to reuse token for ${baseUrl}`
336
+ );
337
+ const existingResult = await this._tryReuseToken(
338
+ baseUrl,
339
+ adjustedAmount,
340
+ mintUrl
341
+ );
342
+ if (existingResult) {
343
+ this._log(
344
+ "DEBUG",
345
+ `[CashuSpender] _spendInternal: Successfully reused token, balance: ${existingResult.balance}`
346
+ );
347
+ return existingResult;
348
+ }
349
+ this._log(
350
+ "DEBUG",
351
+ `[CashuSpender] _spendInternal: Could not reuse token, will create new token`
352
+ );
353
+ }
354
+ const balanceState = await this._getBalanceState();
355
+ const totalAvailableBalance = balanceState.totalBalance;
356
+ this._log(
357
+ "DEBUG",
358
+ `[CashuSpender] _spendInternal: totalAvailableBalance=${totalAvailableBalance}, adjustedAmount=${adjustedAmount}`
359
+ );
360
+ if (totalAvailableBalance < adjustedAmount) {
361
+ this._log(
362
+ "ERROR",
363
+ `[CashuSpender] _spendInternal: Insufficient balance, have=${totalAvailableBalance}, need=${adjustedAmount}`
364
+ );
365
+ return this._createInsufficientBalanceError(
366
+ adjustedAmount,
367
+ balanceState.mintBalances,
368
+ totalAvailableBalance
369
+ );
370
+ }
371
+ let token = null;
372
+ let selectedMintUrl;
373
+ let spentAmount = adjustedAmount;
374
+ if (this.balanceManager) {
375
+ const tokenResult = await this.balanceManager.createProviderToken({
376
+ mintUrl,
377
+ baseUrl,
378
+ amount: adjustedAmount,
379
+ p2pkPubkey,
380
+ excludeMints,
381
+ retryCount
382
+ });
383
+ if (!tokenResult.success || !tokenResult.token) {
384
+ if ((tokenResult.error || "").includes("Insufficient balance")) {
385
+ return this._createInsufficientBalanceError(
386
+ adjustedAmount,
387
+ balanceState.mintBalances,
388
+ totalAvailableBalance
389
+ );
390
+ }
391
+ return {
392
+ token: null,
393
+ status: "failed",
394
+ balance: 0,
395
+ error: tokenResult.error || "Failed to create token"
396
+ };
397
+ }
398
+ token = tokenResult.token;
399
+ selectedMintUrl = tokenResult.selectedMintUrl;
400
+ spentAmount = tokenResult.amountSpent || adjustedAmount;
401
+ } else {
402
+ try {
403
+ token = await this.walletAdapter.sendToken(
404
+ mintUrl,
405
+ adjustedAmount,
406
+ p2pkPubkey
407
+ );
408
+ selectedMintUrl = mintUrl;
409
+ } catch (error) {
410
+ const errorMsg = error instanceof Error ? error.message : String(error);
411
+ return {
412
+ token: null,
413
+ status: "failed",
414
+ balance: 0,
415
+ error: `Error generating token: ${errorMsg}`
416
+ };
417
+ }
418
+ }
419
+ if (token) {
420
+ this._log(
421
+ "DEBUG",
422
+ `[CashuSpender] _spendInternal: Successfully spent ${spentAmount}, returning token with balance=${spentAmount}`
423
+ );
424
+ }
425
+ this._logTransaction("spend", {
426
+ amount: spentAmount,
427
+ mintUrl: selectedMintUrl || mintUrl,
428
+ baseUrl,
429
+ status: "success"
430
+ });
431
+ this._log(
432
+ "DEBUG",
433
+ `[CashuSpender] _spendInternal: Successfully spent ${spentAmount}, returning token with balance=${spentAmount}`
434
+ );
435
+ const units = this.walletAdapter.getMintUnits();
436
+ return {
437
+ token,
438
+ status: "success",
439
+ balance: spentAmount,
440
+ unit: (selectedMintUrl ? units[selectedMintUrl] : units[mintUrl]) || "sat"
441
+ };
442
+ }
443
+ /**
444
+ * Try to reuse an existing API key
445
+ */
446
+ async _tryReuseToken(baseUrl, amount, mintUrl) {
447
+ const apiKeyEntry = this.storageAdapter.getApiKey(baseUrl);
448
+ if (!apiKeyEntry) return null;
449
+ const apiKeyDistribution = this.storageAdapter.getApiKeyDistribution();
450
+ const balanceForBaseUrl = apiKeyDistribution.find((b) => b.baseUrl === baseUrl)?.amount || 0;
451
+ this._log("DEBUG", "Reusing API key", balanceForBaseUrl, amount);
452
+ if (balanceForBaseUrl > amount) {
453
+ const units = this.walletAdapter.getMintUnits();
454
+ const unit = units[mintUrl] || "sat";
455
+ return {
456
+ token: apiKeyEntry.key,
457
+ status: "success",
458
+ balance: balanceForBaseUrl,
459
+ unit
460
+ };
461
+ }
462
+ if (this.balanceManager) {
463
+ const topUpAmount = Math.ceil(amount * 1.2 - balanceForBaseUrl);
464
+ const topUpResult = await this.balanceManager.topUp({
465
+ mintUrl,
466
+ baseUrl,
467
+ amount: topUpAmount,
468
+ token: apiKeyEntry.key
469
+ });
470
+ this._log("DEBUG", "TOPUP ", topUpResult);
471
+ if (topUpResult.success && topUpResult.toppedUpAmount) {
472
+ const newBalance = balanceForBaseUrl + topUpResult.toppedUpAmount;
473
+ const units = this.walletAdapter.getMintUnits();
474
+ const unit = units[mintUrl] || "sat";
475
+ this._logTransaction("topup", {
476
+ amount: topUpResult.toppedUpAmount,
477
+ mintUrl,
478
+ baseUrl,
479
+ status: "success"
480
+ });
481
+ return {
482
+ token: apiKeyEntry.key,
483
+ status: "success",
484
+ balance: newBalance,
485
+ unit
486
+ };
487
+ }
488
+ const providerBalance = await this._getProviderTokenBalance(
489
+ baseUrl,
490
+ apiKeyEntry.key
491
+ );
492
+ this._log("DEBUG", providerBalance);
493
+ if (providerBalance <= 0) {
494
+ this.storageAdapter.removeApiKey(baseUrl);
495
+ }
496
+ }
497
+ return null;
498
+ }
499
+ /**
500
+ * Refund all xcashu tokens from storage by calling the provider's refund endpoint.
501
+ * The xcashu token acts as an API key to claim the refund, and the response contains
502
+ * the actual refunded Cashu token which is then received into the wallet.
503
+ * @param mintUrl - The mint URL for receiving tokens
504
+ * @param excludeBaseUrls - Base URLs to exclude from refund (optional)
505
+ * @returns Results for each xcashu token refund attempt
506
+ */
507
+ async refundXcashuTokens(mintUrl, excludeBaseUrls) {
508
+ const results = [];
509
+ const xcashuTokens = this.storageAdapter.getXcashuTokens();
510
+ const excludedUrls = new Set(excludeBaseUrls || []);
511
+ for (const [baseUrl, tokens] of Object.entries(xcashuTokens)) {
512
+ if (excludedUrls.has(baseUrl)) continue;
513
+ for (const xcashuToken of tokens) {
514
+ try {
515
+ if (!this.balanceManager) {
516
+ throw new Error("BalanceManager not available for xcashu refund");
517
+ }
518
+ const fetchResult = await this.balanceManager.fetchRefundToken(
519
+ baseUrl,
520
+ xcashuToken.token,
521
+ true
522
+ );
523
+ if (!fetchResult.success || !fetchResult.token) {
524
+ throw new Error(
525
+ fetchResult.error || "Failed to fetch refund token from provider"
526
+ );
527
+ }
528
+ const receiveResult = await this.receiveToken(fetchResult.token);
529
+ if (receiveResult.success) {
530
+ this.storageAdapter.removeXcashuToken(baseUrl, xcashuToken.token);
531
+ results.push({
532
+ baseUrl,
533
+ token: xcashuToken.token,
534
+ success: true
535
+ });
536
+ this._log(
537
+ "DEBUG",
538
+ `[CashuSpender] refundXcashuTokens: Successfully refunded xcashu token for ${baseUrl}, amount=${receiveResult.amount}`
539
+ );
540
+ } else {
541
+ const currentTryCount = xcashuToken.tryCount ?? 0;
542
+ const newTryCount = currentTryCount + 1;
543
+ this.storageAdapter.updateXcashuTokenTryCount(
544
+ xcashuToken.token,
545
+ newTryCount
546
+ );
547
+ results.push({
548
+ baseUrl,
549
+ token: xcashuToken.token,
550
+ success: false,
551
+ error: receiveResult.message ?? "Refund failed"
552
+ });
553
+ this._log(
554
+ "DEBUG",
555
+ `[CashuSpender] refundXcashuTokens: Failed to receive refund token for ${baseUrl}, incremented tryCount to ${newTryCount}: ${receiveResult.message}`
556
+ );
557
+ }
558
+ } catch (error) {
559
+ const currentTryCount = xcashuToken.tryCount ?? 0;
560
+ const newTryCount = currentTryCount + 1;
561
+ this.storageAdapter.updateXcashuTokenTryCount(
562
+ xcashuToken.token,
563
+ newTryCount
564
+ );
565
+ const errorMessage = error instanceof Error ? error.message : String(error);
566
+ results.push({
567
+ baseUrl,
568
+ token: xcashuToken.token,
569
+ success: false,
570
+ error: errorMessage
571
+ });
572
+ this._log(
573
+ "ERROR",
574
+ `[CashuSpender] refundXcashuTokens: Exception during refund for ${baseUrl}: ${errorMessage}, incremented tryCount to ${newTryCount}`
575
+ );
576
+ }
577
+ }
578
+ }
579
+ return results;
580
+ }
581
+ /**
582
+ * Refund specific providers without retrying spend
583
+ */
584
+ async refundProviders(mintUrl, forceRefund) {
585
+ const results = [];
586
+ const apiKeyDistribution = this.storageAdapter.getApiKeyDistribution();
587
+ for (const apiKeyEntry of apiKeyDistribution) {
588
+ const apiKeyEntryFull = this.storageAdapter.getApiKey(
589
+ apiKeyEntry.baseUrl
590
+ );
591
+ if (apiKeyEntryFull && this.balanceManager) {
592
+ try {
593
+ const balanceResult = await this.balanceManager.getTokenBalance(
594
+ apiKeyEntryFull.key,
595
+ apiKeyEntry.baseUrl
596
+ );
597
+ if (balanceResult.isInvalidApiKey) {
598
+ this.logger.warn(
599
+ `refundProviders: ${apiKeyEntry.baseUrl} returned invalid API key; removing local key and treating as success`
600
+ );
601
+ this.storageAdapter.removeApiKey(apiKeyEntry.baseUrl);
602
+ results.push({
603
+ baseUrl: apiKeyEntry.baseUrl,
604
+ success: true
605
+ });
606
+ continue;
607
+ }
608
+ if (balanceResult.amount >= 0) {
609
+ const balanceSat = balanceResult.unit === "msat" ? Math.floor(balanceResult.amount / 1e3) : balanceResult.amount;
610
+ this.storageAdapter.updateApiKeyBalance(
611
+ apiKeyEntry.baseUrl,
612
+ balanceSat
613
+ );
614
+ } else {
615
+ this.logger.warn(
616
+ `refundProviders: balance refresh for ${apiKeyEntry.baseUrl} returned negative amount; keeping stale local balance=${apiKeyEntryFull.balance}`
617
+ );
618
+ }
619
+ } catch (error) {
620
+ this.logger.warn(
621
+ `refundProviders: balance refresh threw for ${apiKeyEntry.baseUrl}; proceeding with stale local balance`,
622
+ error
623
+ );
624
+ }
625
+ const refreshedEntry = this.storageAdapter.getApiKey(
626
+ apiKeyEntry.baseUrl
627
+ );
628
+ if (!refreshedEntry) {
629
+ continue;
630
+ }
631
+ const refundResult = await this.balanceManager.refundApiKey({
632
+ mintUrl,
633
+ baseUrl: apiKeyEntry.baseUrl,
634
+ apiKey: refreshedEntry.key,
635
+ forceRefund
636
+ });
637
+ if (refundResult.success) {
638
+ this.storageAdapter.removeApiKey(apiKeyEntry.baseUrl);
639
+ } else {
640
+ const currentEntry = this.storageAdapter.getApiKey(
641
+ apiKeyEntry.baseUrl
642
+ );
643
+ this.logger.warn(
644
+ `refundProviders: refund failed for ${apiKeyEntry.baseUrl}; currentEntry=${Boolean(currentEntry)} balance=${currentEntry?.balance ?? "none"}. Touching lastUsed to rate-limit retries.`
645
+ );
646
+ if (currentEntry) {
647
+ this.storageAdapter.updateApiKeyBalance(
648
+ apiKeyEntry.baseUrl,
649
+ currentEntry.balance
650
+ );
651
+ }
652
+ }
653
+ results.push({
654
+ baseUrl: apiKeyEntry.baseUrl,
655
+ success: refundResult.success
656
+ });
657
+ } else {
658
+ this.logger.warn(
659
+ `refundProviders: cannot refund ${apiKeyEntry.baseUrl}; apiKeyEntryFull=${Boolean(apiKeyEntryFull)} balanceManager=${Boolean(this.balanceManager)}`
660
+ );
661
+ results.push({
662
+ baseUrl: apiKeyEntry.baseUrl,
663
+ success: false
664
+ });
665
+ }
666
+ }
667
+ return results;
668
+ }
669
+ /**
670
+ * Create an insufficient balance error result
671
+ */
672
+ _createInsufficientBalanceError(required, normalizedBalances, availableBalance) {
673
+ let maxBalance = 0;
674
+ let maxMintUrl = "";
675
+ for (const mintUrl in normalizedBalances) {
676
+ const balanceInSats = normalizedBalances[mintUrl];
677
+ if (balanceInSats > maxBalance) {
678
+ maxBalance = balanceInSats;
679
+ maxMintUrl = mintUrl;
680
+ }
681
+ }
682
+ const error = new InsufficientBalanceError(
683
+ required,
684
+ availableBalance ?? maxBalance,
685
+ maxBalance,
686
+ maxMintUrl
687
+ );
688
+ return {
689
+ token: null,
690
+ status: "failed",
691
+ balance: 0,
692
+ error: error.message,
693
+ errorDetails: {
694
+ required,
695
+ available: availableBalance ?? maxBalance,
696
+ maxMintBalance: maxBalance,
697
+ maxMintUrl
698
+ }
699
+ };
700
+ }
701
+ async _getProviderTokenBalance(baseUrl, token) {
702
+ try {
703
+ const response = await fetch(`${baseUrl}v1/wallet/info`, {
704
+ headers: {
705
+ Authorization: `Bearer ${token}`
706
+ }
707
+ });
708
+ if (response.ok) {
709
+ const data = await response.json();
710
+ return data.balance / 1e3;
711
+ }
712
+ } catch {
713
+ return 0;
714
+ }
715
+ return 0;
716
+ }
717
+ };
718
+
719
+ // wallet/BalanceManager.ts
720
+ var BalanceManager = class _BalanceManager {
721
+ constructor(walletAdapter, storageAdapter, providerRegistry, cashuSpender, logger) {
722
+ this.walletAdapter = walletAdapter;
723
+ this.storageAdapter = storageAdapter;
724
+ this.providerRegistry = providerRegistry;
725
+ this.logger = (logger ?? consoleLogger).child("BalanceManager");
726
+ if (cashuSpender) {
727
+ this.cashuSpender = cashuSpender;
728
+ } else {
729
+ this.cashuSpender = new CashuSpender(
730
+ walletAdapter,
731
+ storageAdapter,
732
+ providerRegistry,
733
+ this,
734
+ this.logger
735
+ );
736
+ }
737
+ }
738
+ walletAdapter;
739
+ storageAdapter;
740
+ providerRegistry;
741
+ cashuSpender;
742
+ /** In-memory guard for per-provider wallet mutations (topup / refund) */
743
+ providerWalletOps = /* @__PURE__ */ new Map();
744
+ /** Cooldown (ms) between opposite operations on the same provider */
745
+ static PROVIDER_WALLET_COOLDOWN_MS = 1e4;
746
+ logger;
747
+ /**
748
+ * Check whether a wallet operation (topup/refund) may run for a provider.
749
+ * Returns the reason when blocked.
750
+ */
751
+ _canRunProviderWalletOperation(baseUrl, type) {
752
+ const existing = this.providerWalletOps.get(baseUrl);
753
+ if (!existing) {
754
+ return { allowed: true };
755
+ }
756
+ if (existing.type === type) {
757
+ return { allowed: true };
758
+ }
759
+ if (!existing.endTime) {
760
+ return {
761
+ allowed: false,
762
+ reason: `Provider wallet operation locked; ${existing.type} in progress`
763
+ };
764
+ }
765
+ const elapsed = Date.now() - existing.endTime;
766
+ if (elapsed < _BalanceManager.PROVIDER_WALLET_COOLDOWN_MS) {
767
+ return {
768
+ allowed: false,
769
+ reason: `Provider wallet operation locked; recent ${existing.type} completed ${Math.round(elapsed / 1e3)}s ago`
770
+ };
771
+ }
772
+ this.providerWalletOps.delete(baseUrl);
773
+ return { allowed: true };
774
+ }
775
+ _beginProviderWalletOperation(baseUrl, type) {
776
+ this.providerWalletOps.set(baseUrl, { type, startTime: Date.now() });
777
+ }
778
+ _endProviderWalletOperation(baseUrl, type) {
779
+ const existing = this.providerWalletOps.get(baseUrl);
780
+ if (existing && existing.type === type) {
781
+ existing.endTime = Date.now();
782
+ }
783
+ }
784
+ async getBalanceState() {
785
+ const mintBalances = await this.walletAdapter.getBalances();
786
+ const units = this.walletAdapter.getMintUnits();
787
+ let totalMintBalance = 0;
788
+ const normalizedMintBalances = {};
789
+ for (const url in mintBalances) {
790
+ const balance = mintBalances[url];
791
+ const unit = units[url];
792
+ const balanceInSats = getBalanceInSats(balance, unit);
793
+ normalizedMintBalances[url] = balanceInSats;
794
+ totalMintBalance += balanceInSats;
795
+ }
796
+ const providerBalances = {};
797
+ let totalProviderBalance = 0;
798
+ const apiKeys = this.storageAdapter.getAllApiKeys();
799
+ for (const apiKey of apiKeys) {
800
+ if (!providerBalances[apiKey.baseUrl]) {
801
+ providerBalances[apiKey.baseUrl] = 0;
802
+ }
803
+ providerBalances[apiKey.baseUrl] += apiKey.balance;
804
+ totalProviderBalance += apiKey.balance;
805
+ }
806
+ return {
807
+ totalBalance: totalMintBalance + totalProviderBalance,
808
+ providerBalances,
809
+ mintBalances: normalizedMintBalances
810
+ };
811
+ }
812
+ /**
813
+ * Refund API key balance - convert remaining API key balance to cashu token
814
+ * @param options - Refund options including forceRefund flag
815
+ * @returns Refund result
816
+ */
817
+ async refundApiKey(options) {
818
+ const { mintUrl, baseUrl, apiKey, forceRefund } = options;
819
+ const guard = this._canRunProviderWalletOperation(baseUrl, "refund");
820
+ if (!guard.allowed) {
821
+ this.logger.log(`Skipping refund for ${baseUrl} - ${guard.reason}`);
822
+ return { success: false, message: guard.reason };
823
+ }
824
+ this._beginProviderWalletOperation(baseUrl, "refund");
825
+ try {
826
+ return await this._refundApiKeyImpl({ mintUrl, baseUrl, apiKey, forceRefund });
827
+ } finally {
828
+ this._endProviderWalletOperation(baseUrl, "refund");
829
+ }
830
+ }
831
+ async _refundApiKeyImpl(options) {
832
+ const { mintUrl, baseUrl, apiKey, forceRefund } = options;
833
+ if (!apiKey) {
834
+ this.logger.warn(`refundApiKey: aborting for ${baseUrl} - no API key`);
835
+ return { success: false, message: "No API key to refund" };
836
+ }
837
+ if (!forceRefund) {
838
+ const apiKeyEntry = this.storageAdapter.getApiKey(baseUrl);
839
+ if (apiKeyEntry?.lastUsed) {
840
+ const fiveMinutesAgo = Date.now() - 5 * 60 * 1e3;
841
+ if (apiKeyEntry.lastUsed > fiveMinutesAgo) {
842
+ this.logger.log(
843
+ `refundApiKey: skipping ${baseUrl} - used ${Math.round((Date.now() - apiKeyEntry.lastUsed) / 1e3)}s ago`
844
+ );
845
+ return {
846
+ success: false,
847
+ message: "API key was used recently, skipping refund"
848
+ };
849
+ }
850
+ }
851
+ }
852
+ let fetchResult;
853
+ try {
854
+ fetchResult = await this.fetchRefundToken(baseUrl, apiKey);
855
+ if (fetchResult.error === "No balance to refund") {
856
+ this.logger.log(`refundApiKey: provider says no balance for ${baseUrl}; removing API key`);
857
+ this.storageAdapter.removeApiKey(baseUrl);
858
+ return { success: true, message: "No balance to refund, key cleaned up" };
859
+ }
860
+ if (!fetchResult.success) {
861
+ this.logger.warn(
862
+ `refundApiKey: fetch failed for ${baseUrl}: ${fetchResult.error || "API key refund failed"}`
863
+ );
864
+ return {
865
+ success: false,
866
+ message: fetchResult.error || "API key refund failed",
867
+ requestId: fetchResult.requestId
868
+ };
869
+ }
870
+ if (!fetchResult.token) {
871
+ this.logger.warn(`refundApiKey: no token received for ${baseUrl}`);
872
+ return {
873
+ success: false,
874
+ message: "No token received from API key refund",
875
+ requestId: fetchResult.requestId
876
+ };
877
+ }
878
+ const receiveResult = await this.cashuSpender.receiveToken(
879
+ fetchResult.token
880
+ );
881
+ const totalAmountMsat = receiveResult.unit === "msat" ? receiveResult.amount : receiveResult.amount * 1e3;
882
+ if (receiveResult.success) {
883
+ this.storageAdapter.removeApiKey(baseUrl);
884
+ } else {
885
+ this.logger.warn(
886
+ `refundApiKey: receive failed for ${baseUrl}; keeping API key. message=${receiveResult.message ?? "none"}`
887
+ );
888
+ }
889
+ return {
890
+ success: receiveResult.success,
891
+ refundedAmount: totalAmountMsat,
892
+ message: receiveResult.message,
893
+ requestId: fetchResult.requestId
894
+ };
895
+ } catch (error) {
896
+ this.logger.error("API key refund error", error);
897
+ return this._handleRefundError(error, mintUrl, fetchResult?.requestId);
898
+ }
899
+ }
900
+ /**
901
+ * Fetch refund token from provider API using API key (or xcashu token) authentication
902
+ */
903
+ async fetchRefundToken(baseUrl, apiKeyOrToken, xCashu = false) {
904
+ if (!baseUrl) {
905
+ return {
906
+ success: false,
907
+ error: "No base URL configured"
908
+ };
909
+ }
910
+ const normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
911
+ const url = `${normalizedBaseUrl}v1/wallet/refund`;
912
+ const controller = new AbortController();
913
+ const timeoutId = setTimeout(() => {
914
+ controller.abort();
915
+ }, 6e4);
916
+ try {
917
+ const headers = {
918
+ "Content-Type": "application/json"
919
+ };
920
+ if (xCashu) {
921
+ headers["X-Cashu"] = apiKeyOrToken;
922
+ } else {
923
+ headers["Authorization"] = `Bearer ${apiKeyOrToken}`;
924
+ }
925
+ const response = await fetch(url, {
926
+ method: "POST",
927
+ headers,
928
+ signal: controller.signal
929
+ });
930
+ clearTimeout(timeoutId);
931
+ const requestId = response.headers.get("x-routstr-request-id") || void 0;
932
+ if (!response.ok) {
933
+ const errorData = await response.json().catch(() => ({}));
934
+ this.logger.warn(
935
+ `fetchRefundToken: non-ok response for ${url} status=${response.status} statusText=${response.statusText}`,
936
+ errorData
937
+ );
938
+ return {
939
+ success: false,
940
+ requestId,
941
+ error: `API key refund failed: ${errorData?.detail || response.statusText}`
942
+ };
943
+ }
944
+ const data = await response.json();
945
+ return {
946
+ success: true,
947
+ token: data.token,
948
+ requestId
949
+ };
950
+ } catch (error) {
951
+ clearTimeout(timeoutId);
952
+ this.logger.error("fetchRefundToken fetch error", error);
953
+ if (error instanceof Error) {
954
+ if (error.name === "AbortError") {
955
+ return {
956
+ success: false,
957
+ error: "Request timed out after 1 minute"
958
+ };
959
+ }
960
+ return {
961
+ success: false,
962
+ error: error.message
963
+ };
964
+ }
965
+ return {
966
+ success: false,
967
+ error: "Unknown error occurred during API key refund request"
968
+ };
969
+ }
970
+ }
971
+ /**
972
+ * Top up API key balance with a cashu token
973
+ */
974
+ async topUp(options) {
975
+ const { mintUrl, baseUrl, amount, token: providedToken } = options;
976
+ const guard = this._canRunProviderWalletOperation(baseUrl, "topup");
977
+ if (!guard.allowed) {
978
+ this.logger.log(`Skipping topup for ${baseUrl} - ${guard.reason}`);
979
+ return { success: false, message: guard.reason };
980
+ }
981
+ this._beginProviderWalletOperation(baseUrl, "topup");
982
+ try {
983
+ return await this._topUpImpl({ mintUrl, baseUrl, amount, token: providedToken });
984
+ } finally {
985
+ this._endProviderWalletOperation(baseUrl, "topup");
986
+ }
987
+ }
988
+ async _topUpImpl(options) {
989
+ const { mintUrl, baseUrl, amount, token: providedToken } = options;
990
+ if (!amount || amount <= 0) {
991
+ return { success: false, message: "Invalid top up amount" };
992
+ }
993
+ const apiKeyEntry = providedToken ? null : this.storageAdapter.getApiKey(baseUrl);
994
+ const apiKey = providedToken || apiKeyEntry?.key;
995
+ if (!apiKey) {
996
+ return { success: false, message: "No API key available for top up" };
997
+ }
998
+ let cashuToken = null;
999
+ let requestId;
1000
+ try {
1001
+ const tokenResult = await this.createProviderToken({
1002
+ mintUrl,
1003
+ baseUrl,
1004
+ amount
1005
+ });
1006
+ if (!tokenResult.success || !tokenResult.token) {
1007
+ return {
1008
+ success: false,
1009
+ message: tokenResult.error || "Unable to create top up token"
1010
+ };
1011
+ }
1012
+ cashuToken = tokenResult.token;
1013
+ const topUpResult = await this._postTopUp(baseUrl, apiKey, cashuToken);
1014
+ requestId = topUpResult.requestId;
1015
+ this.logger.log("topUpResult:", topUpResult);
1016
+ if (!topUpResult.success) {
1017
+ await this._recoverFailedTopUp(cashuToken);
1018
+ return {
1019
+ success: false,
1020
+ message: topUpResult.error || "Top up failed",
1021
+ requestId,
1022
+ recoveredToken: true
1023
+ };
1024
+ }
1025
+ return {
1026
+ success: true,
1027
+ toppedUpAmount: amount,
1028
+ requestId
1029
+ };
1030
+ } catch (error) {
1031
+ this.logger.log(`topup error for ${baseUrl}: ${error}`);
1032
+ if (cashuToken) {
1033
+ await this._recoverFailedTopUp(cashuToken);
1034
+ }
1035
+ return this._handleTopUpError(error, mintUrl, requestId);
1036
+ }
1037
+ }
1038
+ async createProviderToken(options) {
1039
+ const {
1040
+ mintUrl,
1041
+ baseUrl,
1042
+ amount,
1043
+ retryCount = 0,
1044
+ excludeMints = [],
1045
+ p2pkPubkey
1046
+ } = options;
1047
+ const adjustedAmount = Math.ceil(amount);
1048
+ this.logger.log(`createProviderToken: baseUrl=${baseUrl} mintUrl=${mintUrl} amount=${amount} adjustedAmount=${adjustedAmount} retryCount=${retryCount}`);
1049
+ if (!adjustedAmount || isNaN(adjustedAmount)) {
1050
+ this.logger.error(`createProviderToken: invalid amount=${amount}`);
1051
+ return { success: false, error: "Invalid top up amount" };
1052
+ }
1053
+ const balanceState = await this.getBalanceState();
1054
+ const balances = await this.walletAdapter.getBalances();
1055
+ const units = this.walletAdapter.getMintUnits();
1056
+ const totalMintBalance = Object.values(balanceState.mintBalances).reduce(
1057
+ (sum, value) => sum + value,
1058
+ 0
1059
+ );
1060
+ const targetProviderBalance = balanceState.providerBalances[baseUrl] || 0;
1061
+ const refundableProviderBalance = Object.entries(
1062
+ balanceState.providerBalances
1063
+ ).filter(([providerBaseUrl]) => providerBaseUrl !== baseUrl).reduce((sum, [, value]) => sum + value, 0);
1064
+ if (totalMintBalance + targetProviderBalance < adjustedAmount && totalMintBalance + targetProviderBalance + refundableProviderBalance >= adjustedAmount && retryCount < 2) {
1065
+ await this._refundOtherProvidersForTopUp(baseUrl, mintUrl, retryCount);
1066
+ return this.createProviderToken({
1067
+ ...options,
1068
+ retryCount: retryCount + 1
1069
+ });
1070
+ }
1071
+ if (totalMintBalance + targetProviderBalance < adjustedAmount) {
1072
+ const error = new InsufficientBalanceError(
1073
+ adjustedAmount,
1074
+ totalMintBalance + targetProviderBalance,
1075
+ totalMintBalance,
1076
+ Object.entries(balanceState.mintBalances).reduce(
1077
+ (max, [url, balance]) => balance > max.balance ? { url, balance } : max,
1078
+ { url: "", balance: 0 }
1079
+ ).url
1080
+ );
1081
+ this.logger.error(`createProviderToken: insufficient balance required=${adjustedAmount} available=${totalMintBalance + targetProviderBalance} totalMint=${totalMintBalance} targetProvider=${targetProviderBalance}`);
1082
+ return { success: false, error: error.message };
1083
+ }
1084
+ const providerMints = baseUrl && this.providerRegistry ? this.providerRegistry.getProviderMints(baseUrl) : [];
1085
+ let requiredAmount = adjustedAmount;
1086
+ const supportedMintsOnly = providerMints.length > 0;
1087
+ let candidates = this._selectCandidateMints({
1088
+ balances,
1089
+ units,
1090
+ amount: requiredAmount,
1091
+ preferredMintUrl: mintUrl,
1092
+ excludeMints,
1093
+ allowedMints: supportedMintsOnly ? providerMints : void 0
1094
+ });
1095
+ if (candidates.length === 0 && supportedMintsOnly) {
1096
+ requiredAmount += 2;
1097
+ candidates = this._selectCandidateMints({
1098
+ balances,
1099
+ units,
1100
+ amount: requiredAmount,
1101
+ preferredMintUrl: mintUrl,
1102
+ excludeMints
1103
+ });
1104
+ }
1105
+ if (candidates.length === 0) {
1106
+ let maxBalance = 0;
1107
+ let maxMintUrl = "";
1108
+ for (const mintUrl2 in balances) {
1109
+ const balance = balances[mintUrl2];
1110
+ const unit = units[mintUrl2];
1111
+ const balanceInSats = getBalanceInSats(balance, unit);
1112
+ if (balanceInSats > maxBalance) {
1113
+ maxBalance = balanceInSats;
1114
+ maxMintUrl = mintUrl2;
1115
+ }
1116
+ }
1117
+ this.logger.error(`createProviderToken: no candidate mints required=${requiredAmount} totalMint=${totalMintBalance} maxBalance=${maxBalance} maxMint=${maxMintUrl}`);
1118
+ const error = new InsufficientBalanceError(
1119
+ adjustedAmount,
1120
+ totalMintBalance,
1121
+ maxBalance,
1122
+ maxMintUrl
1123
+ );
1124
+ return { success: false, error: error.message };
1125
+ }
1126
+ let lastError;
1127
+ for (const candidateMint of candidates) {
1128
+ try {
1129
+ this.logger.log(`createProviderToken: attempting mint=${candidateMint} amount=${requiredAmount}`);
1130
+ const token = await this.walletAdapter.sendToken(
1131
+ candidateMint,
1132
+ requiredAmount,
1133
+ p2pkPubkey
1134
+ );
1135
+ this.logger.log(`createProviderToken: success from mint=${candidateMint}`);
1136
+ return {
1137
+ success: true,
1138
+ token,
1139
+ selectedMintUrl: candidateMint,
1140
+ amountSpent: requiredAmount
1141
+ };
1142
+ } catch (error) {
1143
+ const errorMsg = error instanceof Error ? error.message : String(error);
1144
+ this.logger.error(`createProviderToken: mint=${candidateMint} failed: ${errorMsg}`);
1145
+ if (error instanceof Error) {
1146
+ lastError = errorMsg;
1147
+ if (isNetworkErrorMessage(error.message)) {
1148
+ this.logger.warn(`createProviderToken: network error from ${candidateMint}, trying next mint...`);
1149
+ continue;
1150
+ }
1151
+ }
1152
+ return {
1153
+ success: false,
1154
+ error: lastError || "Failed to create top up token"
1155
+ };
1156
+ }
1157
+ }
1158
+ this.logger.error(`createProviderToken: all candidate mints exhausted lastError=${lastError}`);
1159
+ return {
1160
+ success: false,
1161
+ error: lastError || "All candidate mints failed while creating top up token"
1162
+ };
1163
+ }
1164
+ _selectCandidateMints(options) {
1165
+ const {
1166
+ balances,
1167
+ units,
1168
+ amount,
1169
+ preferredMintUrl,
1170
+ excludeMints,
1171
+ allowedMints
1172
+ } = options;
1173
+ const candidates = [];
1174
+ const { selectedMintUrl: firstMint } = selectMintWithBalance(
1175
+ balances,
1176
+ units,
1177
+ amount,
1178
+ excludeMints
1179
+ );
1180
+ if (firstMint && (!allowedMints || allowedMints.length === 0 || allowedMints.includes(firstMint))) {
1181
+ candidates.push(firstMint);
1182
+ }
1183
+ const canUseMint = (mint) => {
1184
+ if (excludeMints.includes(mint)) return false;
1185
+ if (allowedMints && allowedMints.length > 0 && !allowedMints.includes(mint)) {
1186
+ return false;
1187
+ }
1188
+ const rawBalance = balances[mint] || 0;
1189
+ const unit = units[mint];
1190
+ const balanceInSats = getBalanceInSats(rawBalance, unit);
1191
+ return balanceInSats >= amount;
1192
+ };
1193
+ if (preferredMintUrl && canUseMint(preferredMintUrl) && !candidates.includes(preferredMintUrl)) {
1194
+ candidates.push(preferredMintUrl);
1195
+ }
1196
+ for (const mint in balances) {
1197
+ if (mint === preferredMintUrl || candidates.includes(mint)) continue;
1198
+ if (canUseMint(mint)) {
1199
+ candidates.push(mint);
1200
+ }
1201
+ }
1202
+ return candidates;
1203
+ }
1204
+ async _refundOtherProvidersForTopUp(baseUrl, mintUrl, retryCount) {
1205
+ const apiKeyDistribution = this.storageAdapter.getApiKeyDistribution();
1206
+ const forceRefund = retryCount >= 2;
1207
+ const apiKeysToRefund = apiKeyDistribution.filter(
1208
+ (apiKey) => apiKey.baseUrl !== baseUrl && apiKey.amount > 0
1209
+ );
1210
+ const apiKeyRefundResults = await Promise.allSettled(
1211
+ apiKeysToRefund.map(async (apiKeyEntry) => {
1212
+ const fullApiKeyEntry = this.storageAdapter.getApiKey(
1213
+ apiKeyEntry.baseUrl
1214
+ );
1215
+ if (!fullApiKeyEntry) {
1216
+ return { baseUrl: apiKeyEntry.baseUrl, success: false };
1217
+ }
1218
+ const result = await this.refundApiKey({
1219
+ mintUrl,
1220
+ baseUrl: apiKeyEntry.baseUrl,
1221
+ apiKey: fullApiKeyEntry.key,
1222
+ forceRefund
1223
+ });
1224
+ return { baseUrl: apiKeyEntry.baseUrl, success: result.success };
1225
+ })
1226
+ );
1227
+ for (const result of apiKeyRefundResults) {
1228
+ if (result.status === "fulfilled" && result.value.success) {
1229
+ this.storageAdapter.updateApiKeyBalance(result.value.baseUrl, 0);
1230
+ }
1231
+ }
1232
+ }
1233
+ /**
1234
+ * Post topup request to provider API
1235
+ */
1236
+ async _postTopUp(baseUrl, storedToken, cashuToken) {
1237
+ if (!baseUrl) {
1238
+ return {
1239
+ success: false,
1240
+ error: "No base URL configured"
1241
+ };
1242
+ }
1243
+ const normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
1244
+ const url = `${normalizedBaseUrl}v1/wallet/topup?cashu_token=${encodeURIComponent(
1245
+ cashuToken
1246
+ )}`;
1247
+ const controller = new AbortController();
1248
+ const timeoutId = setTimeout(() => {
1249
+ controller.abort();
1250
+ }, 6e4);
1251
+ try {
1252
+ const response = await fetch(url, {
1253
+ method: "POST",
1254
+ headers: {
1255
+ Authorization: `Bearer ${storedToken}`,
1256
+ "Content-Type": "application/json"
1257
+ },
1258
+ signal: controller.signal
1259
+ });
1260
+ clearTimeout(timeoutId);
1261
+ const requestId = response.headers.get("x-routstr-request-id") || void 0;
1262
+ if (!response.ok) {
1263
+ const errorData = await response.json().catch(() => ({}));
1264
+ return {
1265
+ success: false,
1266
+ requestId,
1267
+ error: errorData?.detail || `Top up failed with status ${response.status}`
1268
+ };
1269
+ }
1270
+ return { success: true, requestId };
1271
+ } catch (error) {
1272
+ clearTimeout(timeoutId);
1273
+ this.logger.error("_postTopUp fetch error", error);
1274
+ if (error instanceof Error) {
1275
+ if (error.name === "AbortError") {
1276
+ return {
1277
+ success: false,
1278
+ error: "Request timed out after 1 minute"
1279
+ };
1280
+ }
1281
+ return {
1282
+ success: false,
1283
+ error: error.message
1284
+ };
1285
+ }
1286
+ return {
1287
+ success: false,
1288
+ error: "Unknown error occurred during top up request"
1289
+ };
1290
+ }
1291
+ }
1292
+ /**
1293
+ * Attempt to receive token back after failed top up
1294
+ */
1295
+ async _recoverFailedTopUp(cashuToken) {
1296
+ try {
1297
+ await this.cashuSpender.receiveToken(cashuToken);
1298
+ } catch (error) {
1299
+ this.logger.error("_recoverFailedTopUp: failed to recover token", error);
1300
+ }
1301
+ }
1302
+ /**
1303
+ * Handle refund errors with specific error types
1304
+ */
1305
+ _handleRefundError(error, mintUrl, requestId) {
1306
+ if (error instanceof Error) {
1307
+ if (isNetworkErrorMessage(error.message)) {
1308
+ return {
1309
+ success: false,
1310
+ message: `Failed to connect to the mint: ${mintUrl}`,
1311
+ requestId
1312
+ };
1313
+ }
1314
+ if (error.message.includes("Wallet not found")) {
1315
+ return {
1316
+ success: false,
1317
+ message: `Wallet couldn't be loaded. Please save this refunded cashu token manually.`,
1318
+ requestId
1319
+ };
1320
+ }
1321
+ return {
1322
+ success: false,
1323
+ message: error.message,
1324
+ requestId
1325
+ };
1326
+ }
1327
+ return {
1328
+ success: false,
1329
+ message: "Refund failed",
1330
+ requestId
1331
+ };
1332
+ }
1333
+ /**
1334
+ * Get token balance from provider
1335
+ */
1336
+ async getTokenBalance(token, baseUrl) {
1337
+ try {
1338
+ const response = await fetch(`${baseUrl}v1/wallet/info`, {
1339
+ headers: {
1340
+ Authorization: `Bearer ${token}`
1341
+ }
1342
+ });
1343
+ if (response.ok) {
1344
+ const data = await response.json();
1345
+ return {
1346
+ amount: data.balance,
1347
+ reserved: data.reserved ?? 0,
1348
+ unit: "msat",
1349
+ apiKey: data.api_key
1350
+ };
1351
+ } else {
1352
+ this.logger.warn(`getTokenBalance: status=${response.status}`);
1353
+ const data = await response.json();
1354
+ this.logger.warn("getTokenBalance: FAILED", data);
1355
+ const isInvalidApiKey = response.status === 401 && data?.detail?.error?.code === "invalid_api_key" && data?.detail?.error?.message?.includes("proofs already spent");
1356
+ return {
1357
+ amount: -1,
1358
+ reserved: data.reserved ?? 0,
1359
+ unit: "msat",
1360
+ apiKey: data.api_key,
1361
+ isInvalidApiKey
1362
+ };
1363
+ }
1364
+ } catch (error) {
1365
+ this.logger.error("getTokenBalance error", error);
1366
+ }
1367
+ return { amount: -1, reserved: 0, unit: "sat", apiKey: "" };
1368
+ }
1369
+ /**
1370
+ * Handle topup errors with specific error types
1371
+ */
1372
+ _handleTopUpError(error, mintUrl, requestId) {
1373
+ if (error instanceof Error) {
1374
+ if (isNetworkErrorMessage(error.message)) {
1375
+ return {
1376
+ success: false,
1377
+ message: `Failed to connect to the mint: ${mintUrl}`,
1378
+ requestId
1379
+ };
1380
+ }
1381
+ if (error.message.includes("Wallet not found")) {
1382
+ return {
1383
+ success: false,
1384
+ message: "Wallet couldn't be loaded. The cashu token was recovered locally.",
1385
+ requestId
1386
+ };
1387
+ }
1388
+ return {
1389
+ success: false,
1390
+ message: error.message,
1391
+ requestId
1392
+ };
1393
+ }
1394
+ return {
1395
+ success: false,
1396
+ message: "Top up failed",
1397
+ requestId
1398
+ };
1399
+ }
1400
+ };
1401
+
1402
+ // client/usage.ts
1403
+ function extractUsageFromResponseBody(body, fallbackSatsCost = 0) {
1404
+ if (!body || typeof body !== "object") return null;
1405
+ const usage = body.usage;
1406
+ if (!usage || typeof usage !== "object") return null;
1407
+ const promptTokens = Number(usage.prompt_tokens ?? 0);
1408
+ const completionTokens = Number(usage.completion_tokens ?? 0);
1409
+ const totalTokens = Number(usage.total_tokens ?? 0);
1410
+ const costValue = usage.cost;
1411
+ let cost = 0;
1412
+ let satsCost = fallbackSatsCost;
1413
+ if (typeof costValue === "number") {
1414
+ cost = costValue;
1415
+ } else if (costValue && typeof costValue === "object") {
1416
+ const costObj = costValue;
1417
+ const totalUsd = costObj.total_usd;
1418
+ const totalMsats = costObj.total_msats;
1419
+ cost = typeof totalUsd === "number" ? totalUsd : 0;
1420
+ if (typeof totalMsats === "number") {
1421
+ satsCost = totalMsats / 1e3;
1422
+ }
1423
+ }
1424
+ if (promptTokens === 0 && completionTokens === 0 && totalTokens === 0 && cost === 0 && satsCost === 0) {
1425
+ return null;
1426
+ }
1427
+ return {
1428
+ promptTokens,
1429
+ completionTokens,
1430
+ totalTokens,
1431
+ cost,
1432
+ satsCost
1433
+ };
1434
+ }
1435
+ function extractResponseId(body) {
1436
+ if (!body || typeof body !== "object") return void 0;
1437
+ const id = body.id;
1438
+ if (typeof id !== "string") return void 0;
1439
+ const trimmed = id.trim();
1440
+ return trimmed.length > 0 ? trimmed : void 0;
1441
+ }
1442
+ function extractUsageFromSSEJson(parsed, fallbackSatsCost = 0) {
1443
+ if (!parsed || typeof parsed !== "object") {
1444
+ return null;
1445
+ }
1446
+ if (!parsed.usage && parsed.cost && typeof parsed.cost === "object") {
1447
+ const costObj = parsed.cost;
1448
+ const msats2 = costObj.total_msats ?? 0;
1449
+ const cost2 = costObj.total_usd ?? 0;
1450
+ if (msats2 === 0 && cost2 === 0) return null;
1451
+ return {
1452
+ promptTokens: Number(costObj.input_tokens ?? 0),
1453
+ completionTokens: Number(costObj.output_tokens ?? 0),
1454
+ totalTokens: Number((costObj.input_tokens ?? 0) + (costObj.output_tokens ?? 0)),
1455
+ cost: Number(cost2),
1456
+ satsCost: msats2 > 0 ? msats2 / 1e3 : fallbackSatsCost
1457
+ };
1458
+ }
1459
+ if (!parsed.usage) {
1460
+ return null;
1461
+ }
1462
+ const usage = parsed.usage;
1463
+ const usageCost = usage.cost;
1464
+ let cost = 0;
1465
+ let msats = 0;
1466
+ if (typeof usageCost === "number") {
1467
+ cost = usageCost;
1468
+ } else if (usageCost && typeof usageCost === "object") {
1469
+ cost = usageCost.total_usd ?? 0;
1470
+ msats = usageCost.total_msats ?? 0;
1471
+ }
1472
+ if (cost === 0) {
1473
+ cost = parsed.metadata?.routstr?.cost?.total_usd ?? 0;
1474
+ }
1475
+ if (msats === 0) {
1476
+ msats = parsed.metadata?.routstr?.cost?.total_msats ?? (typeof usage.cost_sats === "number" ? usage.cost_sats * 1e3 : 0);
1477
+ }
1478
+ const promptTokens = Number(usage.prompt_tokens ?? usage.input_tokens ?? 0);
1479
+ const completionTokens = Number(usage.completion_tokens ?? usage.output_tokens ?? 0);
1480
+ const totalTokens = Number(usage.total_tokens ?? promptTokens + completionTokens);
1481
+ const result = {
1482
+ promptTokens,
1483
+ completionTokens,
1484
+ totalTokens,
1485
+ cost: Number(cost ?? 0),
1486
+ satsCost: msats > 0 ? msats / 1e3 : fallbackSatsCost
1487
+ };
1488
+ if (result.promptTokens === 0 && result.completionTokens === 0 && result.totalTokens === 0 && result.cost === 0 && result.satsCost === 0) {
1489
+ return null;
1490
+ }
1491
+ return result;
1492
+ }
1493
+ function toUsageStats(usage) {
1494
+ if (!usage) return void 0;
1495
+ return {
1496
+ total_tokens: usage.totalTokens,
1497
+ prompt_tokens: usage.promptTokens,
1498
+ completion_tokens: usage.completionTokens,
1499
+ cost: usage.cost,
1500
+ sats_cost: usage.satsCost
1501
+ };
1502
+ }
1503
+
1504
+ // client/StreamProcessor.ts
1505
+ var StreamProcessor = class {
1506
+ accumulatedContent = "";
1507
+ accumulatedThinking = "";
1508
+ accumulatedImages = [];
1509
+ isInThinking = false;
1510
+ isInContent = false;
1511
+ /**
1512
+ * Process a streaming response
1513
+ */
1514
+ async process(response, callbacks, modelId) {
1515
+ if (!response.body) {
1516
+ throw new Error("Response body is not available");
1517
+ }
1518
+ const reader = response.body.getReader();
1519
+ const decoder = new TextDecoder("utf-8");
1520
+ let buffer = "";
1521
+ this.accumulatedContent = "";
1522
+ this.accumulatedThinking = "";
1523
+ this.accumulatedImages = [];
1524
+ this.isInThinking = false;
1525
+ this.isInContent = false;
1526
+ let usage;
1527
+ let model;
1528
+ let finish_reason;
1529
+ let citations;
1530
+ let annotations;
1531
+ let responseId;
1532
+ try {
1533
+ while (true) {
1534
+ const { done, value } = await reader.read();
1535
+ if (done) {
1536
+ break;
1537
+ }
1538
+ const chunk = decoder.decode(value, { stream: true });
1539
+ buffer += chunk;
1540
+ const lines = buffer.split("\n");
1541
+ buffer = lines.pop() || "";
1542
+ for (const line of lines) {
1543
+ const parsed = this._parseLine(line);
1544
+ if (!parsed) continue;
1545
+ if (parsed.content) {
1546
+ this._handleContent(parsed.content, callbacks, modelId);
1547
+ }
1548
+ if (parsed.reasoning) {
1549
+ this._handleThinking(parsed.reasoning, callbacks);
1550
+ }
1551
+ if (parsed.usage) {
1552
+ usage = parsed.usage;
1553
+ }
1554
+ if (parsed.model) {
1555
+ model = parsed.model;
1556
+ }
1557
+ if (parsed.finish_reason) {
1558
+ finish_reason = parsed.finish_reason;
1559
+ }
1560
+ if (parsed.responseId) {
1561
+ responseId = parsed.responseId;
1562
+ }
1563
+ if (parsed.citations) {
1564
+ citations = parsed.citations;
1565
+ }
1566
+ if (parsed.annotations) {
1567
+ annotations = parsed.annotations;
1568
+ }
1569
+ if (parsed.images) {
1570
+ this._mergeImages(parsed.images);
1571
+ }
1572
+ }
1573
+ }
1574
+ } finally {
1575
+ reader.releaseLock();
1576
+ }
1577
+ return {
1578
+ content: this.accumulatedContent,
1579
+ thinking: this.accumulatedThinking || void 0,
1580
+ images: this.accumulatedImages.length > 0 ? this.accumulatedImages : void 0,
1581
+ usage,
1582
+ model,
1583
+ responseId,
1584
+ finish_reason,
1585
+ citations,
1586
+ annotations
1587
+ };
1588
+ }
1589
+ /**
1590
+ * Parse a single SSE line
1591
+ */
1592
+ _parseLine(line) {
1593
+ if (!line.trim()) return null;
1594
+ if (!line.startsWith("data: ")) {
1595
+ return null;
1596
+ }
1597
+ const jsonData = line.slice(6);
1598
+ if (jsonData === "[DONE]") {
1599
+ return null;
1600
+ }
1601
+ try {
1602
+ const parsed = JSON.parse(jsonData);
1603
+ const result = {};
1604
+ if (parsed.choices?.[0]?.delta?.content) {
1605
+ result.content = parsed.choices[0].delta.content;
1606
+ }
1607
+ if (parsed.choices?.[0]?.delta?.reasoning) {
1608
+ result.reasoning = parsed.choices[0].delta.reasoning;
1609
+ }
1610
+ const extractedUsage = extractUsageFromSSEJson(parsed);
1611
+ if (extractedUsage) {
1612
+ result.usage = toUsageStats(extractedUsage);
1613
+ } else if (parsed.usage) {
1614
+ result.usage = {
1615
+ total_tokens: parsed.usage.total_tokens ?? parsed.usage.input_tokens + parsed.usage.output_tokens,
1616
+ prompt_tokens: parsed.usage.prompt_tokens ?? parsed.usage.input_tokens,
1617
+ completion_tokens: parsed.usage.completion_tokens ?? parsed.usage.output_tokens
1618
+ };
1619
+ }
1620
+ if (parsed.id) {
1621
+ result.responseId = parsed.id;
1622
+ }
1623
+ if (parsed.model) {
1624
+ result.model = parsed.model;
1625
+ }
1626
+ if (parsed.citations) {
1627
+ result.citations = parsed.citations;
1628
+ }
1629
+ if (parsed.annotations) {
1630
+ result.annotations = parsed.annotations;
1631
+ }
1632
+ if (parsed.choices?.[0]?.finish_reason) {
1633
+ result.finish_reason = parsed.choices[0].finish_reason;
1634
+ }
1635
+ const images = parsed.choices?.[0]?.message?.images || parsed.choices?.[0]?.delta?.images;
1636
+ if (images && Array.isArray(images)) {
1637
+ result.images = images;
1638
+ }
1639
+ return result;
1640
+ } catch {
1641
+ return null;
1642
+ }
1643
+ }
1644
+ /**
1645
+ * Handle content delta with thinking support
1646
+ */
1647
+ _handleContent(content, callbacks, modelId) {
1648
+ if (this.isInThinking && !this.isInContent) {
1649
+ this.accumulatedThinking += "</thinking>";
1650
+ callbacks.onThinking(this.accumulatedThinking);
1651
+ this.isInThinking = false;
1652
+ this.isInContent = true;
1653
+ }
1654
+ if (modelId) {
1655
+ this._extractThinkingFromContent(content, callbacks);
1656
+ } else {
1657
+ this.accumulatedContent += content;
1658
+ }
1659
+ callbacks.onContent(this.accumulatedContent);
1660
+ }
1661
+ /**
1662
+ * Handle thinking/reasoning content
1663
+ */
1664
+ _handleThinking(reasoning, callbacks) {
1665
+ if (!this.isInThinking) {
1666
+ this.accumulatedThinking += "<thinking> ";
1667
+ this.isInThinking = true;
1668
+ }
1669
+ this.accumulatedThinking += reasoning;
1670
+ callbacks.onThinking(this.accumulatedThinking);
1671
+ }
1672
+ /**
1673
+ * Extract thinking blocks from content (for models with inline thinking)
1674
+ */
1675
+ _extractThinkingFromContent(content, callbacks) {
1676
+ const parts = content.split(/(<thinking>|<\/thinking>)/);
1677
+ for (const part of parts) {
1678
+ if (part === "<thinking>") {
1679
+ this.isInThinking = true;
1680
+ if (!this.accumulatedThinking.includes("<thinking>")) {
1681
+ this.accumulatedThinking += "<thinking> ";
1682
+ }
1683
+ } else if (part === "</thinking>") {
1684
+ this.isInThinking = false;
1685
+ this.accumulatedThinking += "</thinking>";
1686
+ } else if (this.isInThinking) {
1687
+ this.accumulatedThinking += part;
1688
+ } else {
1689
+ this.accumulatedContent += part;
1690
+ }
1691
+ }
1692
+ }
1693
+ /**
1694
+ * Merge images into accumulated array, avoiding duplicates
1695
+ */
1696
+ _mergeImages(newImages) {
1697
+ for (const img of newImages) {
1698
+ const newUrl = img.image_url?.url;
1699
+ const existingIndex = this.accumulatedImages.findIndex((existing) => {
1700
+ const existingUrl = existing.image_url?.url;
1701
+ if (newUrl && existingUrl) {
1702
+ return existingUrl === newUrl;
1703
+ }
1704
+ if (img.index !== void 0 && existing.index !== void 0) {
1705
+ return existing.index === img.index;
1706
+ }
1707
+ return false;
1708
+ });
1709
+ if (existingIndex === -1) {
1710
+ this.accumulatedImages.push(img);
1711
+ } else {
1712
+ this.accumulatedImages[existingIndex] = img;
1713
+ }
1714
+ }
1715
+ }
1716
+ };
1717
+
1718
+ // utils/torUtils.ts
1719
+ var TOR_ONION_SUFFIX = ".onion";
1720
+ var isTorContext = () => {
1721
+ if (typeof window === "undefined") return false;
1722
+ const hostname = window.location.hostname.toLowerCase();
1723
+ return hostname.endsWith(TOR_ONION_SUFFIX);
1724
+ };
1725
+ var isOnionUrl = (url) => {
1726
+ if (!url) return false;
1727
+ const trimmed = url.trim().toLowerCase();
1728
+ if (!trimmed) return false;
1729
+ try {
1730
+ const candidate = trimmed.startsWith("http") ? trimmed : `http://${trimmed}`;
1731
+ return new URL(candidate).hostname.endsWith(TOR_ONION_SUFFIX);
1732
+ } catch {
1733
+ return trimmed.includes(TOR_ONION_SUFFIX);
1734
+ }
1735
+ };
1736
+
1737
+ // client/ProviderManager.ts
1738
+ function getImageResolutionFromDataUrl(dataUrl) {
1739
+ try {
1740
+ if (typeof dataUrl !== "string" || !dataUrl.startsWith("data:"))
1741
+ return null;
1742
+ const commaIdx = dataUrl.indexOf(",");
1743
+ if (commaIdx === -1) return null;
1744
+ const meta = dataUrl.slice(5, commaIdx);
1745
+ const base64 = dataUrl.slice(commaIdx + 1);
1746
+ const binary = typeof atob === "function" ? atob(base64) : Buffer.from(base64, "base64").toString("binary");
1747
+ const len = binary.length;
1748
+ const bytes = new Uint8Array(len);
1749
+ for (let i = 0; i < len; i++) bytes[i] = binary.charCodeAt(i);
1750
+ const isPNG = meta.includes("image/png");
1751
+ const isJPEG = meta.includes("image/jpeg") || meta.includes("image/jpg");
1752
+ if (isPNG) {
1753
+ const sig = [137, 80, 78, 71, 13, 10, 26, 10];
1754
+ for (let i = 0; i < sig.length; i++) {
1755
+ if (bytes[i] !== sig[i]) return null;
1756
+ }
1757
+ const view = new DataView(
1758
+ bytes.buffer,
1759
+ bytes.byteOffset,
1760
+ bytes.byteLength
1761
+ );
1762
+ const width = view.getUint32(16, false);
1763
+ const height = view.getUint32(20, false);
1764
+ if (width > 0 && height > 0) return { width, height };
1765
+ return null;
1766
+ }
1767
+ if (isJPEG) {
1768
+ let offset = 0;
1769
+ if (bytes[offset++] !== 255 || bytes[offset++] !== 216) return null;
1770
+ while (offset < bytes.length) {
1771
+ while (offset < bytes.length && bytes[offset] !== 255) offset++;
1772
+ if (offset + 1 >= bytes.length) break;
1773
+ while (bytes[offset] === 255) offset++;
1774
+ const marker = bytes[offset++];
1775
+ if (marker === 216 || marker === 217) continue;
1776
+ if (offset + 1 >= bytes.length) break;
1777
+ const length = bytes[offset] << 8 | bytes[offset + 1];
1778
+ offset += 2;
1779
+ if (marker === 192 || marker === 194) {
1780
+ if (length < 7 || offset + length - 2 > bytes.length) return null;
1781
+ const precision = bytes[offset];
1782
+ const height = bytes[offset + 1] << 8 | bytes[offset + 2];
1783
+ const width = bytes[offset + 3] << 8 | bytes[offset + 4];
1784
+ if (precision > 0 && width > 0 && height > 0)
1785
+ return { width, height };
1786
+ return null;
1787
+ } else {
1788
+ offset += length - 2;
1789
+ }
1790
+ }
1791
+ return null;
1792
+ }
1793
+ return null;
1794
+ } catch {
1795
+ return null;
1796
+ }
1797
+ }
1798
+ function calculateImageTokens(width, height, detail = "auto") {
1799
+ if (detail === "low") return 85;
1800
+ let w = width;
1801
+ let h = height;
1802
+ if (w > 2048 || h > 2048) {
1803
+ const aspectRatio = w / h;
1804
+ if (w > h) {
1805
+ w = 2048;
1806
+ h = Math.floor(w / aspectRatio);
1807
+ } else {
1808
+ h = 2048;
1809
+ w = Math.floor(h * aspectRatio);
1810
+ }
1811
+ }
1812
+ if (w > 768 || h > 768) {
1813
+ const aspectRatio = w / h;
1814
+ if (w > h) {
1815
+ w = 768;
1816
+ h = Math.floor(w / aspectRatio);
1817
+ } else {
1818
+ h = 768;
1819
+ w = Math.floor(h * aspectRatio);
1820
+ }
1821
+ }
1822
+ const tilesWidth = Math.floor((w + 511) / 512);
1823
+ const tilesHeight = Math.floor((h + 511) / 512);
1824
+ const numTiles = tilesWidth * tilesHeight;
1825
+ return 85 + 170 * numTiles;
1826
+ }
1827
+ function isInsecureHttpUrl(url) {
1828
+ return url.startsWith("http://");
1829
+ }
1830
+ var ProviderManager = class _ProviderManager {
1831
+ constructor(providerRegistry, store, logger) {
1832
+ this.providerRegistry = providerRegistry;
1833
+ this.instanceId = `pm_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
1834
+ this.logger = (logger ?? consoleLogger).child(`ProviderManager:${this.instanceId}`);
1835
+ if (store) {
1836
+ this.store = store;
1837
+ this.hydrateFromStore();
1838
+ }
1839
+ }
1840
+ providerRegistry;
1841
+ failedProviders = /* @__PURE__ */ new Set();
1842
+ /** Track when each provider last failed (provider URL -> timestamp) */
1843
+ lastFailed = /* @__PURE__ */ new Map();
1844
+ /** Providers on cooldown: [provider_url, cooldown_started_timestamp][] */
1845
+ providersOnCoolDown = [];
1846
+ /** Cooldown duration in milliseconds (42 seconds) */
1847
+ static COOLDOWN_DURATION_MS = 42 * 1e3;
1848
+ /** Optional persistent store for failure tracking */
1849
+ store = null;
1850
+ /** Instance ID for debugging */
1851
+ instanceId;
1852
+ logger;
1853
+ /**
1854
+ * Hydrate in-memory state from persistent store
1855
+ */
1856
+ hydrateFromStore() {
1857
+ if (!this.store) return;
1858
+ const state = this.store.getState();
1859
+ this.failedProviders = new Set(state.failedProviders);
1860
+ this.lastFailed = new Map(Object.entries(state.lastFailed));
1861
+ const now = Date.now();
1862
+ this.providersOnCoolDown = state.providersOnCooldown.filter(
1863
+ (entry) => now - entry.timestamp < _ProviderManager.COOLDOWN_DURATION_MS
1864
+ ).map((entry) => [entry.baseUrl, entry.timestamp]);
1865
+ this.logger.log(`Hydrated from store: failedProviders=${this.failedProviders.size} lastFailed=${this.lastFailed.size} providersOnCooldown=${this.providersOnCoolDown.length}`);
1866
+ }
1867
+ /**
1868
+ * Get instance ID for debugging
1869
+ */
1870
+ getInstanceId() {
1871
+ return this.instanceId;
1872
+ }
1873
+ /**
1874
+ * Clean up expired cooldown entries
1875
+ * Also removes the provider from failedProviders so it can be retried
1876
+ */
1877
+ cleanupExpiredCooldowns() {
1878
+ const now = Date.now();
1879
+ const before = this.providersOnCoolDown.length;
1880
+ this.providersOnCoolDown = this.providersOnCoolDown.filter(
1881
+ ([url, timestamp]) => {
1882
+ const age = now - timestamp;
1883
+ const isExpired = age >= _ProviderManager.COOLDOWN_DURATION_MS;
1884
+ if (isExpired) {
1885
+ this.logger.log(`Removing expired cooldown for ${url} (age: ${age}ms)`);
1886
+ this.failedProviders.delete(url);
1887
+ if (this.store) {
1888
+ this.store.getState().removeFailedProvider(url);
1889
+ }
1890
+ }
1891
+ return !isExpired;
1892
+ }
1893
+ );
1894
+ const after = this.providersOnCoolDown.length;
1895
+ if (before !== after) {
1896
+ this.logger.log(`Cleaned up ${before - after} expired cooldown(s), ${after} remaining`);
1897
+ }
1898
+ }
1899
+ /**
1900
+ * Get the cooldown duration in milliseconds
1901
+ */
1902
+ getCooldownDurationMs() {
1903
+ return _ProviderManager.COOLDOWN_DURATION_MS;
1904
+ }
1905
+ /**
1906
+ * Check if a provider is currently on cooldown
1907
+ */
1908
+ isOnCooldown(baseUrl) {
1909
+ this.cleanupExpiredCooldowns();
1910
+ const result = this.providersOnCoolDown.some(([url]) => url === baseUrl);
1911
+ return result;
1912
+ }
1913
+ /**
1914
+ * Get all providers currently on cooldown
1915
+ */
1916
+ getProvidersOnCooldown() {
1917
+ this.cleanupExpiredCooldowns();
1918
+ return [...this.providersOnCoolDown];
1919
+ }
1920
+ /**
1921
+ * Reset the failed providers list
1922
+ */
1923
+ resetFailedProviders() {
1924
+ this.failedProviders.clear();
1925
+ if (this.store) {
1926
+ this.store.getState().setFailedProviders([]);
1927
+ }
1928
+ }
1929
+ /**
1930
+ * Get the last failed timestamp for a provider
1931
+ */
1932
+ getLastFailed(baseUrl) {
1933
+ return this.lastFailed.get(baseUrl);
1934
+ }
1935
+ /**
1936
+ * Get all providers with their last failed timestamps
1937
+ */
1938
+ getAllLastFailed() {
1939
+ return new Map(this.lastFailed);
1940
+ }
1941
+ /**
1942
+ * Mark a provider as failed
1943
+ * If a provider fails twice within 5 minutes, it's added to cooldown
1944
+ */
1945
+ markFailed(baseUrl) {
1946
+ const now = Date.now();
1947
+ const lastFailure = this.lastFailed.get(baseUrl);
1948
+ this.logger.log(`markFailed: ${baseUrl} lastFailure=${lastFailure} now=${now}`);
1949
+ if (lastFailure !== void 0) {
1950
+ const timeSinceLastFailure = now - lastFailure;
1951
+ this.logger.log(`markFailed: timeSinceLastFailure=${timeSinceLastFailure}ms withinCooldown=${timeSinceLastFailure < _ProviderManager.COOLDOWN_DURATION_MS}`);
1952
+ }
1953
+ this.lastFailed.set(baseUrl, now);
1954
+ this.failedProviders.add(baseUrl);
1955
+ if (this.store) {
1956
+ this.store.getState().setLastFailedTimestamp(baseUrl, now);
1957
+ this.store.getState().addFailedProvider(baseUrl);
1958
+ }
1959
+ this.logger.log(`markFailed: updated ${baseUrl} to ${now}, failedProviders=${this.failedProviders.size}`);
1960
+ if (lastFailure !== void 0 && now - lastFailure < _ProviderManager.COOLDOWN_DURATION_MS) {
1961
+ this.logger.log(`markFailed: second failure within cooldown window for ${baseUrl}`);
1962
+ if (!this.isOnCooldown(baseUrl)) {
1963
+ this.providersOnCoolDown.push([baseUrl, now]);
1964
+ if (this.store) {
1965
+ this.store.getState().addProviderOnCooldown(baseUrl, now);
1966
+ }
1967
+ this.logger.log(`markFailed: ${baseUrl} added to cooldown`);
1968
+ } else {
1969
+ this.logger.log(`markFailed: ${baseUrl} already on cooldown`);
1970
+ }
1971
+ } else {
1972
+ if (lastFailure === void 0) {
1973
+ this.logger.log(`markFailed: first failure for ${baseUrl}`);
1974
+ } else {
1975
+ this.logger.log(`markFailed: failure outside cooldown window for ${baseUrl} (${now - lastFailure}ms ago)`);
1976
+ }
1977
+ }
1978
+ }
1979
+ /**
1980
+ * Remove a provider from cooldown (e.g., after successful request)
1981
+ */
1982
+ removeFromCooldown(baseUrl) {
1983
+ this.providersOnCoolDown = this.providersOnCoolDown.filter(
1984
+ ([url]) => url !== baseUrl
1985
+ );
1986
+ if (this.store) {
1987
+ this.store.getState().removeProviderFromCooldown(baseUrl);
1988
+ }
1989
+ }
1990
+ /**
1991
+ * Clear all cooldown tracking
1992
+ */
1993
+ clearCooldowns() {
1994
+ this.providersOnCoolDown = [];
1995
+ if (this.store) {
1996
+ this.store.getState().clearProvidersOnCooldown();
1997
+ }
1998
+ }
1999
+ /**
2000
+ * Clear all failure tracking (lastFailed timestamps)
2001
+ */
2002
+ clearFailureHistory() {
2003
+ this.lastFailed.clear();
2004
+ if (this.store) {
2005
+ this.store.getState().setLastFailed({});
2006
+ }
2007
+ }
2008
+ /**
2009
+ * Check if a provider has failed
2010
+ */
2011
+ hasFailed(baseUrl) {
2012
+ return this.failedProviders.has(baseUrl);
2013
+ }
2014
+ /**
2015
+ * Get a copy of the failed providers set
2016
+ */
2017
+ getFailedProviders() {
2018
+ return new Set(this.failedProviders);
2019
+ }
2020
+ /**
2021
+ * Find the next best provider for a model
2022
+ * @param modelId The model ID to find a provider for
2023
+ * @param currentBaseUrl The current provider to exclude
2024
+ * @returns The best provider URL or null if none available
2025
+ */
2026
+ findNextBestProvider(modelId, currentBaseUrl) {
2027
+ try {
2028
+ const torMode = isTorContext();
2029
+ const disabledProviders = new Set(
2030
+ this.providerRegistry.getDisabledProviders()
2031
+ );
2032
+ this.logger.log(`findNextBestProvider: model=${modelId} disabled=${[...disabledProviders].length} onCooldown=${this.providersOnCoolDown.length}`);
2033
+ const allProviders = this.providerRegistry.getAllProvidersModels();
2034
+ this.logger.log(`findNextBestProvider: total providers=${Object.keys(allProviders).length}`);
2035
+ const candidates = [];
2036
+ for (const [baseUrl, models] of Object.entries(allProviders)) {
2037
+ if (baseUrl === currentBaseUrl) {
2038
+ continue;
2039
+ }
2040
+ if (disabledProviders.has(baseUrl)) {
2041
+ continue;
2042
+ }
2043
+ if (this.isOnCooldown(baseUrl)) {
2044
+ continue;
2045
+ }
2046
+ if (!torMode && (isOnionUrl(baseUrl) || isInsecureHttpUrl(baseUrl))) {
2047
+ continue;
2048
+ }
2049
+ const model = models.find((m) => m.id === modelId);
2050
+ if (!model) {
2051
+ continue;
2052
+ }
2053
+ const cost = model.sats_pricing?.completion ?? 0;
2054
+ candidates.push({ baseUrl, model, cost });
2055
+ }
2056
+ candidates.sort((a, b) => a.cost - b.cost);
2057
+ if (candidates.length > 0) {
2058
+ return candidates[0].baseUrl;
2059
+ } else {
2060
+ return null;
2061
+ }
2062
+ } catch (error) {
2063
+ this.logger.error("findNextBestProvider error:", error);
2064
+ return null;
2065
+ }
2066
+ }
2067
+ /**
2068
+ * Find the best model for a provider
2069
+ * Useful when switching providers and need to find equivalent model
2070
+ */
2071
+ async getModelForProvider(baseUrl, modelId) {
2072
+ const models = this.providerRegistry.getModelsForProvider(baseUrl);
2073
+ const exactMatch = models.find((m) => m.id === modelId);
2074
+ if (exactMatch) return exactMatch;
2075
+ const providerInfo = await this.providerRegistry.getProviderInfo(baseUrl);
2076
+ if (providerInfo?.version && /^0\.1\./.test(providerInfo.version)) {
2077
+ const suffix = modelId.split("/").pop();
2078
+ const suffixMatch = models.find((m) => m.id === suffix);
2079
+ if (suffixMatch) return suffixMatch;
2080
+ }
2081
+ return null;
2082
+ }
2083
+ /**
2084
+ * Get all available providers for a model
2085
+ * Returns sorted list by price
2086
+ */
2087
+ getAllProvidersForModel(modelId) {
2088
+ const candidates = [];
2089
+ const allProviders = this.providerRegistry.getAllProvidersModels();
2090
+ const disabledProviders = new Set(
2091
+ this.providerRegistry.getDisabledProviders()
2092
+ );
2093
+ const torMode = isTorContext();
2094
+ for (const [baseUrl, models] of Object.entries(allProviders)) {
2095
+ if (disabledProviders.has(baseUrl)) continue;
2096
+ if (this.isOnCooldown(baseUrl)) continue;
2097
+ if (!torMode && (isOnionUrl(baseUrl) || isInsecureHttpUrl(baseUrl)))
2098
+ continue;
2099
+ const model = models.find((m) => m.id === modelId);
2100
+ if (!model) continue;
2101
+ const cost = model.sats_pricing?.completion ?? 0;
2102
+ candidates.push({ baseUrl, model, cost });
2103
+ }
2104
+ return candidates.sort((a, b) => a.cost - b.cost);
2105
+ }
2106
+ /**
2107
+ * Get providers for a model sorted by prompt+completion pricing
2108
+ */
2109
+ getProviderPriceRankingForModel(modelId, options = {}) {
2110
+ const includeDisabled = options.includeDisabled ?? false;
2111
+ const torMode = options.torMode ?? false;
2112
+ const disabledProviders = new Set(
2113
+ this.providerRegistry.getDisabledProviders()
2114
+ );
2115
+ const allModels = this.providerRegistry.getAllProvidersModels();
2116
+ const results = [];
2117
+ for (const [baseUrl, models] of Object.entries(allModels)) {
2118
+ if (!includeDisabled && disabledProviders.has(baseUrl)) continue;
2119
+ if (this.isOnCooldown(baseUrl)) continue;
2120
+ if (torMode && !baseUrl.includes(".onion")) continue;
2121
+ if (!torMode && (baseUrl.includes(".onion") || isInsecureHttpUrl(baseUrl)))
2122
+ continue;
2123
+ const match = models.find((model) => model.id === modelId);
2124
+ if (!match?.sats_pricing) continue;
2125
+ const prompt = match.sats_pricing.prompt;
2126
+ const completion = match.sats_pricing.completion;
2127
+ if (typeof prompt !== "number" || typeof completion !== "number") {
2128
+ continue;
2129
+ }
2130
+ const promptPerMillion = prompt * 1e6;
2131
+ const completionPerMillion = completion * 1e6;
2132
+ const totalPerMillion = promptPerMillion + completionPerMillion;
2133
+ results.push({
2134
+ baseUrl,
2135
+ model: match,
2136
+ promptPerMillion,
2137
+ completionPerMillion,
2138
+ totalPerMillion
2139
+ });
2140
+ }
2141
+ return results.sort((a, b) => {
2142
+ if (a.totalPerMillion !== b.totalPerMillion) {
2143
+ return a.totalPerMillion - b.totalPerMillion;
2144
+ }
2145
+ return a.baseUrl.localeCompare(b.baseUrl);
2146
+ });
2147
+ }
2148
+ /**
2149
+ * Get best-priced provider for a specific model
2150
+ */
2151
+ getBestProviderForModel(modelId, options = {}) {
2152
+ const ranking = this.getProviderPriceRankingForModel(modelId, options);
2153
+ return ranking[0]?.baseUrl ?? null;
2154
+ }
2155
+ normalizeModelId(modelId) {
2156
+ return modelId.includes("/") ? modelId.split("/").pop() || modelId : modelId;
2157
+ }
2158
+ /**
2159
+ * Check if a provider accepts a specific mint
2160
+ */
2161
+ providerAcceptsMint(baseUrl, mintUrl) {
2162
+ const providerMints = this.providerRegistry.getProviderMints(baseUrl);
2163
+ if (providerMints.length === 0) {
2164
+ return true;
2165
+ }
2166
+ return providerMints.includes(mintUrl);
2167
+ }
2168
+ /**
2169
+ * Get required sats for a model based on message history
2170
+ * Simple estimation based on typical usage
2171
+ */
2172
+ getRequiredSatsForModel(model, apiMessages, maxTokens) {
2173
+ try {
2174
+ let imageTokens = 0;
2175
+ if (apiMessages) {
2176
+ for (const msg of apiMessages) {
2177
+ const content = msg?.content;
2178
+ if (Array.isArray(content)) {
2179
+ for (const part of content) {
2180
+ const isImage = part && typeof part === "object" && part.type === "image_url";
2181
+ const url = isImage ? typeof part.image_url === "string" ? part.image_url : part.image_url?.url : void 0;
2182
+ if (url && typeof url === "string" && url.startsWith("data:")) {
2183
+ const res = getImageResolutionFromDataUrl(url);
2184
+ if (res) {
2185
+ const tokensFromImage = calculateImageTokens(
2186
+ res.width,
2187
+ res.height
2188
+ );
2189
+ imageTokens += tokensFromImage;
2190
+ this.logger.log(`IMAGE INPUT RESOLUTION width=${res.width} height=${res.height} tokens=${tokensFromImage}`);
2191
+ } else {
2192
+ this.logger.log("IMAGE INPUT RESOLUTION: unknown format");
2193
+ }
2194
+ }
2195
+ }
2196
+ }
2197
+ }
2198
+ }
2199
+ const apiMessagesNoImages = apiMessages ? apiMessages.map((m) => {
2200
+ if (Array.isArray(m?.content)) {
2201
+ const filtered = m.content.filter(
2202
+ (p) => !(p && typeof p === "object" && p.type === "image_url")
2203
+ );
2204
+ return { ...m, content: filtered };
2205
+ }
2206
+ return m;
2207
+ }) : void 0;
2208
+ const approximateTokens = apiMessagesNoImages ? Math.ceil(JSON.stringify(apiMessagesNoImages, null, 2).length / 2.84) : 1e4;
2209
+ const totalInputTokens = approximateTokens + imageTokens;
2210
+ const sp = model?.sats_pricing;
2211
+ if (!sp) {
2212
+ return 0;
2213
+ }
2214
+ if (!sp.max_completion_cost) {
2215
+ return sp.max_cost ?? 50;
2216
+ }
2217
+ const promptCosts = (sp.prompt || 0) * totalInputTokens;
2218
+ let completionCost = sp.max_completion_cost;
2219
+ if (maxTokens !== void 0 && sp.completion) {
2220
+ completionCost = sp.completion * maxTokens;
2221
+ }
2222
+ const totalEstimatedCosts = (promptCosts + completionCost) * 1.05;
2223
+ return totalEstimatedCosts;
2224
+ } catch (e) {
2225
+ this.logger.error("getRequiredSatsForModel error:", e);
2226
+ return 0;
2227
+ }
2228
+ }
2229
+ };
2230
+
2231
+ // storage/drivers/localStorage.ts
2232
+ var canUseLocalStorage = () => {
2233
+ return typeof window !== "undefined" && typeof window.localStorage !== "undefined";
2234
+ };
2235
+ var isQuotaExceeded = (error) => {
2236
+ const e = error;
2237
+ return !!e && (e?.name === "QuotaExceededError" || e?.code === 22 || e?.code === 1014);
2238
+ };
2239
+ var NON_CRITICAL_KEYS = /* @__PURE__ */ new Set(["modelsFromAllProviders"]);
2240
+ var localStorageDriver = {
2241
+ async getItem(key, defaultValue) {
2242
+ if (!canUseLocalStorage()) return defaultValue;
2243
+ try {
2244
+ const item = window.localStorage.getItem(key);
2245
+ if (item === null) return defaultValue;
2246
+ try {
2247
+ return JSON.parse(item);
2248
+ } catch (parseError) {
2249
+ if (typeof defaultValue === "string") {
2250
+ return item;
2251
+ }
2252
+ throw parseError;
2253
+ }
2254
+ } catch (error) {
2255
+ console.error(`Error retrieving item with key "${key}":`, error);
2256
+ if (canUseLocalStorage()) {
2257
+ try {
2258
+ window.localStorage.removeItem(key);
2259
+ } catch (removeError) {
2260
+ console.error(
2261
+ `Error removing corrupted item with key "${key}":`,
2262
+ removeError
2263
+ );
2264
+ }
2265
+ }
2266
+ return defaultValue;
2267
+ }
2268
+ },
2269
+ async setItem(key, value) {
2270
+ if (!canUseLocalStorage()) return;
2271
+ try {
2272
+ window.localStorage.setItem(key, JSON.stringify(value));
2273
+ } catch (error) {
2274
+ if (isQuotaExceeded(error)) {
2275
+ if (NON_CRITICAL_KEYS.has(key)) {
2276
+ console.warn(
2277
+ `Storage quota exceeded; skipping non-critical key "${key}".`
2278
+ );
2279
+ return;
2280
+ }
2281
+ try {
2282
+ window.localStorage.removeItem("modelsFromAllProviders");
2283
+ } catch {
2284
+ }
2285
+ try {
2286
+ window.localStorage.setItem(key, JSON.stringify(value));
2287
+ return;
2288
+ } catch (retryError) {
2289
+ console.warn(
2290
+ `Storage quota exceeded; unable to persist key "${key}" after cleanup attempt.`,
2291
+ retryError
2292
+ );
2293
+ return;
2294
+ }
2295
+ }
2296
+ console.error(`Error storing item with key "${key}":`, error);
2297
+ }
2298
+ },
2299
+ async removeItem(key) {
2300
+ if (!canUseLocalStorage()) return;
2301
+ try {
2302
+ window.localStorage.removeItem(key);
2303
+ } catch (error) {
2304
+ console.error(`Error removing item with key "${key}":`, error);
2305
+ }
2306
+ }
2307
+ };
2308
+
2309
+ // storage/drivers/memory.ts
2310
+ var createMemoryDriver = (seed) => {
2311
+ const store = /* @__PURE__ */ new Map();
2312
+ return {
2313
+ async getItem(key, defaultValue) {
2314
+ const item = store.get(key);
2315
+ if (item === void 0) return defaultValue;
2316
+ try {
2317
+ return JSON.parse(item);
2318
+ } catch (parseError) {
2319
+ if (typeof defaultValue === "string") {
2320
+ return item;
2321
+ }
2322
+ throw parseError;
2323
+ }
2324
+ },
2325
+ async setItem(key, value) {
2326
+ store.set(key, JSON.stringify(value));
2327
+ },
2328
+ async removeItem(key) {
2329
+ store.delete(key);
2330
+ }
2331
+ };
2332
+ };
2333
+
2334
+ // storage/drivers/sqlite.ts
2335
+ var isBun = () => {
2336
+ return typeof process.versions.bun !== "undefined";
2337
+ };
2338
+ var cachedDbModule = null;
2339
+ var loadDatabase = async (dbPath) => {
2340
+ if (isBun()) {
2341
+ throw new Error(
2342
+ "SQLite driver not supported in Bun. Use createBunSqliteDriver() instead."
2343
+ );
2344
+ }
2345
+ try {
2346
+ if (!cachedDbModule) {
2347
+ cachedDbModule = (await import('better-sqlite3')).default;
2348
+ }
2349
+ return new cachedDbModule(dbPath);
2350
+ } catch (error) {
2351
+ throw new Error(
2352
+ `better-sqlite3 is required for sqlite storage. Install it to use sqlite storage. (${error})`
2353
+ );
2354
+ }
2355
+ };
2356
+ var createSqliteDriver = (options = {}) => {
2357
+ const dbPath = options.dbPath || "routstr.sqlite";
2358
+ const tableName = options.tableName || "sdk_storage";
2359
+ let db;
2360
+ let selectStmt;
2361
+ let upsertStmt;
2362
+ let deleteStmt;
2363
+ const initDb = async () => {
2364
+ if (!db) {
2365
+ db = await loadDatabase(dbPath);
2366
+ db.exec(
2367
+ `CREATE TABLE IF NOT EXISTS ${tableName} (key TEXT PRIMARY KEY, value TEXT NOT NULL)`
2368
+ );
2369
+ selectStmt = db.prepare(`SELECT value FROM ${tableName} WHERE key = ?`);
2370
+ upsertStmt = db.prepare(
2371
+ `INSERT INTO ${tableName} (key, value) VALUES (?, ?)
2372
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value`
2373
+ );
2374
+ deleteStmt = db.prepare(`DELETE FROM ${tableName} WHERE key = ?`);
2375
+ }
2376
+ };
2377
+ const ensureInit = async () => {
2378
+ if (!db) {
2379
+ await initDb();
2380
+ }
2381
+ };
2382
+ return {
2383
+ async getItem(key, defaultValue) {
2384
+ try {
2385
+ await ensureInit();
2386
+ const row = selectStmt.get(key);
2387
+ if (!row || typeof row.value !== "string") return defaultValue;
2388
+ try {
2389
+ return JSON.parse(row.value);
2390
+ } catch (parseError) {
2391
+ if (typeof defaultValue === "string") {
2392
+ return row.value;
2393
+ }
2394
+ throw parseError;
2395
+ }
2396
+ } catch (error) {
2397
+ console.error(`SQLite getItem failed for key "${key}":`, error);
2398
+ return defaultValue;
2399
+ }
2400
+ },
2401
+ async setItem(key, value) {
2402
+ try {
2403
+ await ensureInit();
2404
+ upsertStmt.run(key, JSON.stringify(value));
2405
+ } catch (error) {
2406
+ console.error(`SQLite setItem failed for key "${key}":`, error);
2407
+ }
2408
+ },
2409
+ async removeItem(key) {
2410
+ try {
2411
+ await ensureInit();
2412
+ deleteStmt.run(key);
2413
+ } catch (error) {
2414
+ console.error(`SQLite removeItem failed for key "${key}":`, error);
2415
+ }
2416
+ }
2417
+ };
2418
+ };
2419
+
2420
+ // storage/keys.ts
2421
+ var SDK_STORAGE_KEYS = {
2422
+ MODELS_FROM_ALL_PROVIDERS: "modelsFromAllProviders",
2423
+ LAST_USED_MODEL: "lastUsedModel",
2424
+ BASE_URLS_LIST: "base_urls_list",
2425
+ DISABLED_PROVIDERS: "disabled_providers",
2426
+ MINTS_FROM_ALL_PROVIDERS: "mints_from_all_providers",
2427
+ INFO_FROM_ALL_PROVIDERS: "info_from_all_providers",
2428
+ LAST_MODELS_UPDATE: "lastModelsUpdate",
2429
+ LAST_BASE_URLS_UPDATE: "lastBaseUrlsUpdate",
2430
+ API_KEYS: "api_keys",
2431
+ CHILD_KEYS: "child_keys",
2432
+ XCASHU_TOKENS: "xcashu_tokens",
2433
+ ROUTSTR21_MODELS: "routstr21Models",
2434
+ LAST_ROUTSTR21_MODELS_UPDATE: "lastRoutstr21ModelsUpdate",
2435
+ CACHED_RECEIVE_TOKENS: "cached_receive_tokens",
2436
+ USAGE_TRACKING: "usage_tracking",
2437
+ CLIENT_IDS: "client_ids",
2438
+ FAILED_PROVIDERS: "failed_providers",
2439
+ LAST_FAILED: "last_failed",
2440
+ PROVIDERS_ON_COOLDOWN: "providers_on_cooldown"
2441
+ };
2442
+
2443
+ // storage/usageTracking/indexedDB.ts
2444
+ var DEFAULT_DB_NAME = "routstr-sdk";
2445
+ var DEFAULT_STORE_NAME = "usage_tracking";
2446
+ var MIGRATION_MARKER_KEY = "usage_tracking_migration_v1";
2447
+ var isBrowser = typeof indexedDB !== "undefined";
2448
+ var normalizeBaseUrl = (baseUrl) => baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
2449
+ var openDatabase = (dbName, storeName) => {
2450
+ if (!isBrowser) {
2451
+ return Promise.reject(new Error("IndexedDB is not available"));
2452
+ }
2453
+ return new Promise((resolve, reject) => {
2454
+ const request = indexedDB.open(dbName, 1);
2455
+ request.onupgradeneeded = () => {
2456
+ const db = request.result;
2457
+ if (!db.objectStoreNames.contains(storeName)) {
2458
+ const store = db.createObjectStore(storeName, { keyPath: "id" });
2459
+ store.createIndex("timestamp", "timestamp", { unique: false });
2460
+ store.createIndex("modelId", "modelId", { unique: false });
2461
+ store.createIndex("baseUrl", "baseUrl", { unique: false });
2462
+ store.createIndex("sessionId", "sessionId", { unique: false });
2463
+ store.createIndex("client", "client", { unique: false });
2464
+ }
2465
+ };
2466
+ request.onsuccess = () => resolve(request.result);
2467
+ request.onerror = () => reject(request.error);
2468
+ });
2469
+ };
2470
+ var matchesFilters = (entry, options = {}) => {
2471
+ if (typeof options.before === "number" && entry.timestamp >= options.before) {
2472
+ return false;
2473
+ }
2474
+ if (typeof options.after === "number" && entry.timestamp <= options.after) {
2475
+ return false;
2476
+ }
2477
+ if (options.modelId && entry.modelId !== options.modelId) {
2478
+ return false;
2479
+ }
2480
+ if (options.baseUrl && normalizeBaseUrl(entry.baseUrl) !== normalizeBaseUrl(options.baseUrl)) {
2481
+ return false;
2482
+ }
2483
+ if (options.sessionId && entry.sessionId !== options.sessionId) {
2484
+ return false;
2485
+ }
2486
+ if (options.client && entry.client !== options.client) {
2487
+ return false;
2488
+ }
2489
+ return true;
2490
+ };
2491
+ var createIndexedDBUsageTrackingDriver = (options = {}) => {
2492
+ const dbName = options.dbName || DEFAULT_DB_NAME;
2493
+ const storeName = options.storeName || DEFAULT_STORE_NAME;
2494
+ const legacyStorageDriver = options.legacyStorageDriver;
2495
+ let dbPromise = null;
2496
+ let migrationPromise = null;
2497
+ const getDb = () => {
2498
+ if (!dbPromise) {
2499
+ dbPromise = openDatabase(dbName, storeName);
2500
+ }
2501
+ return dbPromise;
2502
+ };
2503
+ const putMany = async (entries) => {
2504
+ if (entries.length === 0) return;
2505
+ const db = await getDb();
2506
+ await new Promise((resolve, reject) => {
2507
+ const tx = db.transaction(storeName, "readwrite");
2508
+ const store = tx.objectStore(storeName);
2509
+ for (const entry of entries) {
2510
+ store.put({ ...entry, baseUrl: normalizeBaseUrl(entry.baseUrl) });
2511
+ }
2512
+ tx.oncomplete = () => resolve();
2513
+ tx.onerror = () => reject(tx.error);
2514
+ });
2515
+ };
2516
+ const ensureMigrated = async () => {
2517
+ if (!legacyStorageDriver) return;
2518
+ if (!migrationPromise) {
2519
+ migrationPromise = (async () => {
2520
+ const migrated = await legacyStorageDriver.getItem(
2521
+ MIGRATION_MARKER_KEY,
2522
+ false
2523
+ );
2524
+ if (migrated) return;
2525
+ const legacyEntries = await legacyStorageDriver.getItem(
2526
+ SDK_STORAGE_KEYS.USAGE_TRACKING,
2527
+ []
2528
+ );
2529
+ if (legacyEntries.length > 0) {
2530
+ await putMany(legacyEntries);
2531
+ await legacyStorageDriver.removeItem(SDK_STORAGE_KEYS.USAGE_TRACKING);
2532
+ }
2533
+ await legacyStorageDriver.setItem(MIGRATION_MARKER_KEY, true);
2534
+ })();
2535
+ }
2536
+ await migrationPromise;
2537
+ };
2538
+ return {
2539
+ async migrate() {
2540
+ await ensureMigrated();
2541
+ },
2542
+ async append(entry) {
2543
+ await ensureMigrated();
2544
+ await putMany([entry]);
2545
+ },
2546
+ async appendMany(entries) {
2547
+ await ensureMigrated();
2548
+ await putMany(entries);
2549
+ },
2550
+ async list(options2 = {}) {
2551
+ await ensureMigrated();
2552
+ const db = await getDb();
2553
+ return new Promise((resolve, reject) => {
2554
+ const tx = db.transaction(storeName, "readonly");
2555
+ const store = tx.objectStore(storeName);
2556
+ const index = store.index("timestamp");
2557
+ const direction = "prev";
2558
+ const request = index.openCursor(null, direction);
2559
+ const results = [];
2560
+ const limit = options2.limit;
2561
+ request.onsuccess = () => {
2562
+ const cursor = request.result;
2563
+ if (!cursor) {
2564
+ resolve(results);
2565
+ return;
2566
+ }
2567
+ const value = cursor.value;
2568
+ if (matchesFilters(value, options2)) {
2569
+ results.push(value);
2570
+ if (typeof limit === "number" && results.length >= limit) {
2571
+ resolve(results);
2572
+ return;
2573
+ }
2574
+ }
2575
+ cursor.continue();
2576
+ };
2577
+ request.onerror = () => reject(request.error);
2578
+ });
2579
+ },
2580
+ async count(options2 = {}) {
2581
+ const results = await this.list(options2);
2582
+ return results.length;
2583
+ },
2584
+ async deleteOlderThan(timestamp) {
2585
+ await ensureMigrated();
2586
+ const db = await getDb();
2587
+ return new Promise((resolve, reject) => {
2588
+ const tx = db.transaction(storeName, "readwrite");
2589
+ const store = tx.objectStore(storeName);
2590
+ const index = store.index("timestamp");
2591
+ const range = IDBKeyRange.upperBound(timestamp, true);
2592
+ const request = index.openCursor(range);
2593
+ let deleted = 0;
2594
+ request.onsuccess = () => {
2595
+ const cursor = request.result;
2596
+ if (!cursor) {
2597
+ resolve(deleted);
2598
+ return;
2599
+ }
2600
+ deleted += 1;
2601
+ cursor.delete();
2602
+ cursor.continue();
2603
+ };
2604
+ request.onerror = () => reject(request.error);
2605
+ });
2606
+ },
2607
+ async clear() {
2608
+ await ensureMigrated();
2609
+ const db = await getDb();
2610
+ await new Promise((resolve, reject) => {
2611
+ const tx = db.transaction(storeName, "readwrite");
2612
+ tx.objectStore(storeName).clear();
2613
+ tx.oncomplete = () => resolve();
2614
+ tx.onerror = () => reject(tx.error);
2615
+ });
2616
+ }
2617
+ };
2618
+ };
2619
+
2620
+ // storage/usageTracking/sqlite.ts
2621
+ var MIGRATION_MARKER_KEY2 = "usage_tracking_migration_v1";
2622
+ var normalizeBaseUrl2 = (baseUrl) => baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
2623
+ var isBun2 = () => {
2624
+ return typeof process.versions.bun !== "undefined";
2625
+ };
2626
+ var cachedDbModule2 = null;
2627
+ var loadDatabase2 = async (dbPath) => {
2628
+ if (isBun2()) {
2629
+ throw new Error(
2630
+ "SQLite driver not supported in Bun. Use createMemoryDriver() instead."
2631
+ );
2632
+ }
2633
+ try {
2634
+ if (!cachedDbModule2) {
2635
+ cachedDbModule2 = (await import('better-sqlite3')).default;
2636
+ }
2637
+ return new cachedDbModule2(dbPath);
2638
+ } catch (error) {
2639
+ throw new Error(
2640
+ `better-sqlite3 is required for sqlite usage tracking. Install it to use sqlite storage. (${error})`
2641
+ );
2642
+ }
2643
+ };
2644
+ var buildWhereClause = (options = {}) => {
2645
+ const clauses = [];
2646
+ const params = [];
2647
+ if (typeof options.before === "number") {
2648
+ clauses.push("timestamp < ?");
2649
+ params.push(options.before);
2650
+ }
2651
+ if (typeof options.after === "number") {
2652
+ clauses.push("timestamp > ?");
2653
+ params.push(options.after);
2654
+ }
2655
+ if (options.modelId) {
2656
+ clauses.push("model_id = ?");
2657
+ params.push(options.modelId);
2658
+ }
2659
+ if (options.baseUrl) {
2660
+ clauses.push("base_url = ?");
2661
+ params.push(normalizeBaseUrl2(options.baseUrl));
2662
+ }
2663
+ if (options.sessionId) {
2664
+ clauses.push("session_id = ?");
2665
+ params.push(options.sessionId);
2666
+ }
2667
+ if (options.client) {
2668
+ clauses.push("client = ?");
2669
+ params.push(options.client);
2670
+ }
2671
+ return {
2672
+ sql: clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "",
2673
+ params
2674
+ };
2675
+ };
2676
+ var createSqliteUsageTrackingDriver = (options = {}) => {
2677
+ const dbPath = options.dbPath || "routstr.sqlite";
2678
+ const tableName = options.tableName || "usage_tracking";
2679
+ const legacyStorageDriver = options.legacyStorageDriver;
2680
+ let db;
2681
+ let insertStmt;
2682
+ let migrationComplete = false;
2683
+ const initDb = async () => {
2684
+ if (!db) {
2685
+ db = await loadDatabase2(dbPath);
2686
+ db.exec(`
2687
+ CREATE TABLE IF NOT EXISTS ${tableName} (
2688
+ id TEXT PRIMARY KEY,
2689
+ timestamp INTEGER NOT NULL,
2690
+ model_id TEXT NOT NULL,
2691
+ base_url TEXT NOT NULL,
2692
+ request_id TEXT NOT NULL,
2693
+ cost REAL NOT NULL,
2694
+ sats_cost REAL NOT NULL,
2695
+ prompt_tokens INTEGER NOT NULL,
2696
+ completion_tokens INTEGER NOT NULL,
2697
+ total_tokens INTEGER NOT NULL,
2698
+ client TEXT,
2699
+ session_id TEXT,
2700
+ tags TEXT
2701
+ );
2702
+ CREATE INDEX IF NOT EXISTS idx_${tableName}_timestamp ON ${tableName}(timestamp);
2703
+ CREATE INDEX IF NOT EXISTS idx_${tableName}_model_id ON ${tableName}(model_id);
2704
+ CREATE INDEX IF NOT EXISTS idx_${tableName}_base_url ON ${tableName}(base_url);
2705
+ CREATE INDEX IF NOT EXISTS idx_${tableName}_session_id ON ${tableName}(session_id);
2706
+ CREATE INDEX IF NOT EXISTS idx_${tableName}_client ON ${tableName}(client);
2707
+ `);
2708
+ insertStmt = db.prepare(`
2709
+ INSERT OR REPLACE INTO ${tableName} (
2710
+ id, timestamp, model_id, base_url, request_id,
2711
+ cost, sats_cost, prompt_tokens, completion_tokens, total_tokens,
2712
+ client, session_id, tags
2713
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2714
+ `);
2715
+ }
2716
+ };
2717
+ const ensureInit = async () => {
2718
+ if (!db) {
2719
+ await initDb();
2720
+ }
2721
+ };
2722
+ const appendOne = (entry) => {
2723
+ insertStmt.run(
2724
+ entry.id,
2725
+ entry.timestamp,
2726
+ entry.modelId,
2727
+ normalizeBaseUrl2(entry.baseUrl),
2728
+ entry.requestId,
2729
+ entry.cost,
2730
+ entry.satsCost,
2731
+ entry.promptTokens,
2732
+ entry.completionTokens,
2733
+ entry.totalTokens,
2734
+ entry.client ?? null,
2735
+ entry.sessionId ?? null,
2736
+ JSON.stringify(entry.tags ?? [])
2737
+ );
2738
+ };
2739
+ const ensureMigrated = async () => {
2740
+ if (!legacyStorageDriver || migrationComplete) return;
2741
+ const migrated = await legacyStorageDriver.getItem(
2742
+ MIGRATION_MARKER_KEY2,
2743
+ false
2744
+ );
2745
+ if (migrated) {
2746
+ migrationComplete = true;
2747
+ return;
2748
+ }
2749
+ const legacyEntries = await legacyStorageDriver.getItem(
2750
+ SDK_STORAGE_KEYS.USAGE_TRACKING,
2751
+ []
2752
+ );
2753
+ for (const entry of legacyEntries) {
2754
+ appendOne(entry);
2755
+ }
2756
+ if (legacyEntries.length > 0) {
2757
+ await legacyStorageDriver.removeItem(SDK_STORAGE_KEYS.USAGE_TRACKING);
2758
+ }
2759
+ await legacyStorageDriver.setItem(MIGRATION_MARKER_KEY2, true);
2760
+ migrationComplete = true;
2761
+ };
2762
+ const mapRow = (row) => ({
2763
+ id: row.id,
2764
+ timestamp: row.timestamp,
2765
+ modelId: row.model_id,
2766
+ baseUrl: row.base_url,
2767
+ requestId: row.request_id,
2768
+ cost: row.cost,
2769
+ satsCost: row.sats_cost,
2770
+ promptTokens: row.prompt_tokens,
2771
+ completionTokens: row.completion_tokens,
2772
+ totalTokens: row.total_tokens,
2773
+ client: row.client ?? void 0,
2774
+ sessionId: row.session_id ?? void 0,
2775
+ tags: typeof row.tags === "string" ? JSON.parse(row.tags) : void 0
2776
+ });
2777
+ return {
2778
+ async migrate() {
2779
+ await ensureInit();
2780
+ await ensureMigrated();
2781
+ },
2782
+ async append(entry) {
2783
+ await ensureInit();
2784
+ await ensureMigrated();
2785
+ appendOne(entry);
2786
+ },
2787
+ async appendMany(entries) {
2788
+ await ensureInit();
2789
+ await ensureMigrated();
2790
+ for (const entry of entries) {
2791
+ appendOne(entry);
2792
+ }
2793
+ },
2794
+ async list(options2 = {}) {
2795
+ await ensureInit();
2796
+ await ensureMigrated();
2797
+ const { sql, params } = buildWhereClause(options2);
2798
+ const limitSql = typeof options2.limit === "number" ? " LIMIT ?" : "";
2799
+ const stmt = db.prepare(
2800
+ `SELECT * FROM ${tableName} ${sql} ORDER BY timestamp DESC${limitSql}`
2801
+ );
2802
+ const rows = stmt.all(
2803
+ ...typeof options2.limit === "number" ? [...params, options2.limit] : params
2804
+ );
2805
+ return rows.map(mapRow);
2806
+ },
2807
+ async count(options2 = {}) {
2808
+ await ensureInit();
2809
+ await ensureMigrated();
2810
+ const { sql, params } = buildWhereClause(options2);
2811
+ const stmt = db.prepare(`SELECT COUNT(*) as count FROM ${tableName} ${sql}`);
2812
+ const row = stmt.get(...params);
2813
+ return Number(row?.count ?? 0);
2814
+ },
2815
+ async deleteOlderThan(timestamp) {
2816
+ await ensureInit();
2817
+ await ensureMigrated();
2818
+ const stmt = db.prepare(`DELETE FROM ${tableName} WHERE timestamp < ?`);
2819
+ const result = stmt.run(timestamp);
2820
+ return result.changes;
2821
+ },
2822
+ async clear() {
2823
+ await ensureInit();
2824
+ await ensureMigrated();
2825
+ db.prepare(`DELETE FROM ${tableName}`).run();
2826
+ }
2827
+ };
2828
+ };
2829
+
2830
+ // storage/usageTracking/bunSqlite.ts
2831
+ var MIGRATION_MARKER_KEY3 = "usage_tracking_migration_v1";
2832
+ var normalizeBaseUrl3 = (baseUrl) => baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
2833
+ var buildWhereClause2 = (options = {}) => {
2834
+ const clauses = [];
2835
+ const params = [];
2836
+ if (typeof options.before === "number") {
2837
+ clauses.push("timestamp < ?");
2838
+ params.push(options.before);
2839
+ }
2840
+ if (typeof options.after === "number") {
2841
+ clauses.push("timestamp > ?");
2842
+ params.push(options.after);
2843
+ }
2844
+ if (options.modelId) {
2845
+ clauses.push("model_id = ?");
2846
+ params.push(options.modelId);
2847
+ }
2848
+ if (options.baseUrl) {
2849
+ clauses.push("base_url = ?");
2850
+ params.push(normalizeBaseUrl3(options.baseUrl));
2851
+ }
2852
+ if (options.sessionId) {
2853
+ clauses.push("session_id = ?");
2854
+ params.push(options.sessionId);
2855
+ }
2856
+ if (options.client) {
2857
+ clauses.push("client = ?");
2858
+ params.push(options.client);
2859
+ }
2860
+ return {
2861
+ sql: clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "",
2862
+ params
2863
+ };
2864
+ };
2865
+ var createBunSqliteUsageTrackingDriver = (options = {}) => {
2866
+ const dbPath = options.dbPath || "routstr.sqlite";
2867
+ const tableName = options.tableName || "usage_tracking";
2868
+ const legacyStorageDriver = options.legacyStorageDriver;
2869
+ const SQLiteDatabase = options.sqlite?.Database;
2870
+ let migrationPromise = null;
2871
+ if (!SQLiteDatabase) {
2872
+ throw new Error(
2873
+ "Bun SQLite Database constructor is required. Pass { sqlite: { Database } } when creating the driver."
2874
+ );
2875
+ }
2876
+ const db = new SQLiteDatabase(dbPath);
2877
+ db.run(`
2878
+ CREATE TABLE IF NOT EXISTS ${tableName} (
2879
+ id TEXT PRIMARY KEY,
2880
+ timestamp INTEGER NOT NULL,
2881
+ model_id TEXT NOT NULL,
2882
+ base_url TEXT NOT NULL,
2883
+ request_id TEXT NOT NULL,
2884
+ cost REAL NOT NULL,
2885
+ sats_cost REAL NOT NULL,
2886
+ prompt_tokens INTEGER NOT NULL,
2887
+ completion_tokens INTEGER NOT NULL,
2888
+ total_tokens INTEGER NOT NULL,
2889
+ client TEXT,
2890
+ session_id TEXT,
2891
+ tags TEXT
2892
+ )
2893
+ `);
2894
+ db.run(`CREATE INDEX IF NOT EXISTS idx_${tableName}_timestamp ON ${tableName}(timestamp)`);
2895
+ db.run(`CREATE INDEX IF NOT EXISTS idx_${tableName}_model_id ON ${tableName}(model_id)`);
2896
+ db.run(`CREATE INDEX IF NOT EXISTS idx_${tableName}_base_url ON ${tableName}(base_url)`);
2897
+ const appendOne = (entry) => {
2898
+ db.query(`
2899
+ INSERT OR REPLACE INTO ${tableName} (
2900
+ id, timestamp, model_id, base_url, request_id,
2901
+ cost, sats_cost, prompt_tokens, completion_tokens, total_tokens,
2902
+ client, session_id, tags
2903
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2904
+ `).run(
2905
+ entry.id,
2906
+ entry.timestamp,
2907
+ entry.modelId,
2908
+ normalizeBaseUrl3(entry.baseUrl),
2909
+ entry.requestId,
2910
+ entry.cost,
2911
+ entry.satsCost,
2912
+ entry.promptTokens,
2913
+ entry.completionTokens,
2914
+ entry.totalTokens,
2915
+ entry.client ?? null,
2916
+ entry.sessionId ?? null,
2917
+ JSON.stringify(entry.tags ?? [])
2918
+ );
2919
+ };
2920
+ const mapRow = (row) => ({
2921
+ id: row.id,
2922
+ timestamp: row.timestamp,
2923
+ modelId: row.model_id,
2924
+ baseUrl: row.base_url,
2925
+ requestId: row.request_id,
2926
+ cost: row.cost,
2927
+ satsCost: row.sats_cost,
2928
+ promptTokens: row.prompt_tokens,
2929
+ completionTokens: row.completion_tokens,
2930
+ totalTokens: row.total_tokens,
2931
+ client: row.client ?? void 0,
2932
+ sessionId: row.session_id ?? void 0,
2933
+ tags: typeof row.tags === "string" ? JSON.parse(row.tags) : void 0
2934
+ });
2935
+ const ensureMigrated = async () => {
2936
+ if (!legacyStorageDriver) return;
2937
+ if (!migrationPromise) {
2938
+ migrationPromise = (async () => {
2939
+ const migrated = await legacyStorageDriver.getItem(
2940
+ MIGRATION_MARKER_KEY3,
2941
+ false
2942
+ );
2943
+ if (migrated) return;
2944
+ const legacyEntries = await legacyStorageDriver.getItem(
2945
+ SDK_STORAGE_KEYS.USAGE_TRACKING,
2946
+ []
2947
+ );
2948
+ if (legacyEntries.length > 0) {
2949
+ for (const entry of legacyEntries) {
2950
+ appendOne(entry);
2951
+ }
2952
+ await legacyStorageDriver.removeItem(SDK_STORAGE_KEYS.USAGE_TRACKING);
2953
+ }
2954
+ await legacyStorageDriver.setItem(MIGRATION_MARKER_KEY3, true);
2955
+ })();
2956
+ }
2957
+ await migrationPromise;
2958
+ };
2959
+ return {
2960
+ async migrate() {
2961
+ await ensureMigrated();
2962
+ },
2963
+ async append(entry) {
2964
+ await ensureMigrated();
2965
+ appendOne(entry);
2966
+ },
2967
+ async appendMany(entries) {
2968
+ await ensureMigrated();
2969
+ for (const entry of entries) {
2970
+ appendOne(entry);
2971
+ }
2972
+ },
2973
+ async list(options2 = {}) {
2974
+ await ensureMigrated();
2975
+ const { sql, params } = buildWhereClause2(options2);
2976
+ const limitSql = typeof options2.limit === "number" ? " LIMIT ?" : "";
2977
+ const query = `SELECT * FROM ${tableName} ${sql} ORDER BY timestamp DESC${limitSql}`;
2978
+ let rows;
2979
+ if (typeof options2.limit === "number") {
2980
+ rows = db.query(query).all(...params, options2.limit);
2981
+ } else {
2982
+ rows = db.query(query).all(...params);
2983
+ }
2984
+ return rows.map(mapRow);
2985
+ },
2986
+ async count(options2 = {}) {
2987
+ const { sql, params } = buildWhereClause2(options2);
2988
+ const query = `SELECT COUNT(*) as count FROM ${tableName} ${sql}`;
2989
+ const row = db.query(query).get(...params);
2990
+ return Number(row?.count ?? 0);
2991
+ },
2992
+ async deleteOlderThan(timestamp) {
2993
+ await ensureMigrated();
2994
+ const before = timestamp;
2995
+ const result = db.query(`DELETE FROM ${tableName} WHERE timestamp < ?`).run(before);
2996
+ return result.changes ?? 0;
2997
+ },
2998
+ async clear() {
2999
+ await ensureMigrated();
3000
+ db.query(`DELETE FROM ${tableName}`).run();
3001
+ }
3002
+ };
3003
+ };
3004
+
3005
+ // storage/usageTracking/memory.ts
3006
+ var normalizeBaseUrl4 = (baseUrl) => baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
3007
+ var matchesFilters2 = (entry, options = {}) => {
3008
+ if (typeof options.before === "number" && entry.timestamp >= options.before) {
3009
+ return false;
3010
+ }
3011
+ if (typeof options.after === "number" && entry.timestamp <= options.after) {
3012
+ return false;
3013
+ }
3014
+ if (options.modelId && entry.modelId !== options.modelId) {
3015
+ return false;
3016
+ }
3017
+ if (options.baseUrl && normalizeBaseUrl4(entry.baseUrl) !== normalizeBaseUrl4(options.baseUrl)) {
3018
+ return false;
3019
+ }
3020
+ if (options.sessionId && entry.sessionId !== options.sessionId) {
3021
+ return false;
3022
+ }
3023
+ if (options.client && entry.client !== options.client) {
3024
+ return false;
3025
+ }
3026
+ return true;
3027
+ };
3028
+ var createMemoryUsageTrackingDriver = (seed = []) => {
3029
+ const store = /* @__PURE__ */ new Map();
3030
+ for (const entry of seed) {
3031
+ store.set(entry.id, { ...entry, baseUrl: normalizeBaseUrl4(entry.baseUrl) });
3032
+ }
3033
+ return {
3034
+ async migrate() {
3035
+ return;
3036
+ },
3037
+ async append(entry) {
3038
+ store.set(entry.id, { ...entry, baseUrl: normalizeBaseUrl4(entry.baseUrl) });
3039
+ },
3040
+ async appendMany(entries) {
3041
+ for (const entry of entries) {
3042
+ store.set(entry.id, { ...entry, baseUrl: normalizeBaseUrl4(entry.baseUrl) });
3043
+ }
3044
+ },
3045
+ async list(options = {}) {
3046
+ const entries = [...store.values()].filter((entry) => matchesFilters2(entry, options)).sort((a, b) => b.timestamp - a.timestamp);
3047
+ if (typeof options.limit === "number") {
3048
+ return entries.slice(0, options.limit);
3049
+ }
3050
+ return entries;
3051
+ },
3052
+ async count(options = {}) {
3053
+ return (await this.list(options)).length;
3054
+ },
3055
+ async deleteOlderThan(timestamp) {
3056
+ let deleted = 0;
3057
+ for (const [id, entry] of store.entries()) {
3058
+ if (entry.timestamp < timestamp) {
3059
+ store.delete(id);
3060
+ deleted += 1;
3061
+ }
3062
+ }
3063
+ return deleted;
3064
+ },
3065
+ async clear() {
3066
+ store.clear();
3067
+ }
3068
+ };
3069
+ };
3070
+ var normalizeBaseUrl5 = (baseUrl) => baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
3071
+ var createEmptyStore = (driver) => vanilla.createStore((set, get) => ({
3072
+ modelsFromAllProviders: {},
3073
+ lastUsedModel: null,
3074
+ baseUrlsList: [],
3075
+ lastBaseUrlsUpdate: null,
3076
+ disabledProviders: [],
3077
+ mintsFromAllProviders: {},
3078
+ infoFromAllProviders: {},
3079
+ lastModelsUpdate: {},
3080
+ apiKeys: [],
3081
+ childKeys: [],
3082
+ xcashuTokens: {},
3083
+ routstr21Models: [],
3084
+ lastRoutstr21ModelsUpdate: null,
3085
+ cachedReceiveTokens: [],
3086
+ clientIds: [],
3087
+ failedProviders: [],
3088
+ lastFailed: {},
3089
+ providersOnCooldown: [],
3090
+ setModelsFromAllProviders: (value) => {
3091
+ const normalized = {};
3092
+ for (const [baseUrl, models] of Object.entries(value)) {
3093
+ normalized[normalizeBaseUrl5(baseUrl)] = models;
3094
+ }
3095
+ void driver.setItem(
3096
+ SDK_STORAGE_KEYS.MODELS_FROM_ALL_PROVIDERS,
3097
+ normalized
3098
+ );
3099
+ set({ modelsFromAllProviders: normalized });
3100
+ },
3101
+ setLastUsedModel: (value) => {
3102
+ void driver.setItem(SDK_STORAGE_KEYS.LAST_USED_MODEL, value);
3103
+ set({ lastUsedModel: value });
3104
+ },
3105
+ setBaseUrlsList: (value) => {
3106
+ const normalized = value.map((url) => normalizeBaseUrl5(url));
3107
+ void driver.setItem(SDK_STORAGE_KEYS.BASE_URLS_LIST, normalized);
3108
+ set({ baseUrlsList: normalized });
3109
+ },
3110
+ setBaseUrlsLastUpdate: (value) => {
3111
+ void driver.setItem(SDK_STORAGE_KEYS.LAST_BASE_URLS_UPDATE, value);
3112
+ set({ lastBaseUrlsUpdate: value });
3113
+ },
3114
+ setDisabledProviders: (value) => {
3115
+ const normalized = value.map((url) => normalizeBaseUrl5(url));
3116
+ void driver.setItem(SDK_STORAGE_KEYS.DISABLED_PROVIDERS, normalized);
3117
+ set({ disabledProviders: normalized });
3118
+ },
3119
+ setMintsFromAllProviders: (value) => {
3120
+ const normalized = {};
3121
+ for (const [baseUrl, mints] of Object.entries(value)) {
3122
+ normalized[normalizeBaseUrl5(baseUrl)] = mints.map(
3123
+ (mint) => mint.endsWith("/") ? mint.slice(0, -1) : mint
3124
+ );
3125
+ }
3126
+ void driver.setItem(
3127
+ SDK_STORAGE_KEYS.MINTS_FROM_ALL_PROVIDERS,
3128
+ normalized
3129
+ );
3130
+ set({ mintsFromAllProviders: normalized });
3131
+ },
3132
+ setInfoFromAllProviders: (value) => {
3133
+ const normalized = {};
3134
+ for (const [baseUrl, info] of Object.entries(value)) {
3135
+ normalized[normalizeBaseUrl5(baseUrl)] = info;
3136
+ }
3137
+ void driver.setItem(SDK_STORAGE_KEYS.INFO_FROM_ALL_PROVIDERS, normalized);
3138
+ set({ infoFromAllProviders: normalized });
3139
+ },
3140
+ setLastModelsUpdate: (value) => {
3141
+ const normalized = {};
3142
+ for (const [baseUrl, timestamp] of Object.entries(value)) {
3143
+ normalized[normalizeBaseUrl5(baseUrl)] = timestamp;
3144
+ }
3145
+ void driver.setItem(SDK_STORAGE_KEYS.LAST_MODELS_UPDATE, normalized);
3146
+ set({ lastModelsUpdate: normalized });
3147
+ },
3148
+ setApiKeys: (value) => {
3149
+ set((state) => {
3150
+ const updates = typeof value === "function" ? value(state.apiKeys) : value;
3151
+ const normalized = updates.map((entry) => ({
3152
+ ...entry,
3153
+ baseUrl: normalizeBaseUrl5(entry.baseUrl),
3154
+ balance: entry.balance ?? 0,
3155
+ lastUsed: entry.lastUsed ?? null
3156
+ }));
3157
+ void driver.setItem(SDK_STORAGE_KEYS.API_KEYS, normalized);
3158
+ return { apiKeys: normalized };
3159
+ });
3160
+ },
3161
+ setChildKeys: (value) => {
3162
+ set((state) => {
3163
+ const updates = typeof value === "function" ? value(state.childKeys) : value;
3164
+ const normalized = updates.map((entry) => ({
3165
+ parentBaseUrl: normalizeBaseUrl5(entry.parentBaseUrl),
3166
+ childKey: entry.childKey,
3167
+ balance: entry.balance ?? 0,
3168
+ balanceLimit: entry.balanceLimit,
3169
+ validityDate: entry.validityDate,
3170
+ createdAt: entry.createdAt ?? Date.now()
3171
+ }));
3172
+ void driver.setItem(SDK_STORAGE_KEYS.CHILD_KEYS, normalized);
3173
+ return { childKeys: normalized };
3174
+ });
3175
+ },
3176
+ setXcashuTokens: (value) => {
3177
+ const normalized = {};
3178
+ for (const [baseUrl, tokens] of Object.entries(value)) {
3179
+ normalized[normalizeBaseUrl5(baseUrl)] = tokens.map((entry) => ({
3180
+ ...entry,
3181
+ baseUrl: normalizeBaseUrl5(entry.baseUrl),
3182
+ createdAt: entry.createdAt ?? Date.now(),
3183
+ tryCount: entry.tryCount ?? 0
3184
+ }));
3185
+ }
3186
+ void driver.setItem(SDK_STORAGE_KEYS.XCASHU_TOKENS, normalized);
3187
+ set({ xcashuTokens: normalized });
3188
+ },
3189
+ updateXcashuTokenTryCount: (token, tryCount) => {
3190
+ const currentTokens = get().xcashuTokens;
3191
+ const updatedTokens = {};
3192
+ for (const [baseUrl, tokens] of Object.entries(currentTokens)) {
3193
+ updatedTokens[baseUrl] = tokens.map(
3194
+ (entry) => entry.token === token ? { ...entry, tryCount } : entry
3195
+ );
3196
+ }
3197
+ void driver.setItem(SDK_STORAGE_KEYS.XCASHU_TOKENS, updatedTokens);
3198
+ set({ xcashuTokens: updatedTokens });
3199
+ },
3200
+ setRoutstr21Models: (value) => {
3201
+ void driver.setItem(SDK_STORAGE_KEYS.ROUTSTR21_MODELS, value);
3202
+ set({ routstr21Models: value });
3203
+ },
3204
+ setRoutstr21ModelsLastUpdate: (value) => {
3205
+ void driver.setItem(SDK_STORAGE_KEYS.LAST_ROUTSTR21_MODELS_UPDATE, value);
3206
+ set({ lastRoutstr21ModelsUpdate: value });
3207
+ },
3208
+ setCachedReceiveTokens: (value) => {
3209
+ const normalized = value.map((entry) => ({
3210
+ token: entry.token,
3211
+ amount: entry.amount,
3212
+ unit: entry.unit || "sat",
3213
+ createdAt: entry.createdAt ?? Date.now()
3214
+ }));
3215
+ void driver.setItem(SDK_STORAGE_KEYS.CACHED_RECEIVE_TOKENS, normalized);
3216
+ set({ cachedReceiveTokens: normalized });
3217
+ },
3218
+ setClientIds: (value) => {
3219
+ set((state) => {
3220
+ const updates = typeof value === "function" ? value(state.clientIds) : value;
3221
+ const normalized = updates.map((entry) => ({
3222
+ ...entry,
3223
+ createdAt: entry.createdAt ?? Date.now(),
3224
+ lastUsed: entry.lastUsed ?? null
3225
+ }));
3226
+ void driver.setItem(SDK_STORAGE_KEYS.CLIENT_IDS, normalized);
3227
+ return { clientIds: normalized };
3228
+ });
3229
+ },
3230
+ // ========== Failure Tracking ==========
3231
+ setFailedProviders: (value) => {
3232
+ const normalized = value.map((url) => normalizeBaseUrl5(url));
3233
+ void driver.setItem(SDK_STORAGE_KEYS.FAILED_PROVIDERS, normalized);
3234
+ set({ failedProviders: normalized });
3235
+ },
3236
+ addFailedProvider: (baseUrl) => {
3237
+ const normalized = normalizeBaseUrl5(baseUrl);
3238
+ const current = get().failedProviders;
3239
+ if (!current.includes(normalized)) {
3240
+ const updated = [...current, normalized];
3241
+ void driver.setItem(SDK_STORAGE_KEYS.FAILED_PROVIDERS, updated);
3242
+ set({ failedProviders: updated });
3243
+ }
3244
+ },
3245
+ removeFailedProvider: (baseUrl) => {
3246
+ const normalized = normalizeBaseUrl5(baseUrl);
3247
+ const current = get().failedProviders;
3248
+ const updated = current.filter((url) => url !== normalized);
3249
+ void driver.setItem(SDK_STORAGE_KEYS.FAILED_PROVIDERS, updated);
3250
+ set({ failedProviders: updated });
3251
+ },
3252
+ setLastFailed: (value) => {
3253
+ const normalized = {};
3254
+ for (const [baseUrl, timestamp] of Object.entries(value)) {
3255
+ normalized[normalizeBaseUrl5(baseUrl)] = timestamp;
3256
+ }
3257
+ void driver.setItem(SDK_STORAGE_KEYS.LAST_FAILED, normalized);
3258
+ set({ lastFailed: normalized });
3259
+ },
3260
+ setLastFailedTimestamp: (baseUrl, timestamp) => {
3261
+ const normalized = normalizeBaseUrl5(baseUrl);
3262
+ const current = get().lastFailed;
3263
+ const updated = { ...current, [normalized]: timestamp };
3264
+ void driver.setItem(SDK_STORAGE_KEYS.LAST_FAILED, updated);
3265
+ set({ lastFailed: updated });
3266
+ },
3267
+ setProvidersOnCooldown: (value) => {
3268
+ const normalized = value.map((entry) => ({
3269
+ baseUrl: normalizeBaseUrl5(entry.baseUrl),
3270
+ timestamp: entry.timestamp
3271
+ }));
3272
+ void driver.setItem(SDK_STORAGE_KEYS.PROVIDERS_ON_COOLDOWN, normalized);
3273
+ set({ providersOnCooldown: normalized });
3274
+ },
3275
+ addProviderOnCooldown: (baseUrl, timestamp) => {
3276
+ const normalized = normalizeBaseUrl5(baseUrl);
3277
+ const current = get().providersOnCooldown;
3278
+ if (!current.some((entry) => entry.baseUrl === normalized)) {
3279
+ const updated = [...current, { baseUrl: normalized, timestamp }];
3280
+ void driver.setItem(SDK_STORAGE_KEYS.PROVIDERS_ON_COOLDOWN, updated);
3281
+ set({ providersOnCooldown: updated });
3282
+ }
3283
+ },
3284
+ removeProviderFromCooldown: (baseUrl) => {
3285
+ const normalized = normalizeBaseUrl5(baseUrl);
3286
+ const current = get().providersOnCooldown;
3287
+ const updated = current.filter((entry) => entry.baseUrl !== normalized);
3288
+ void driver.setItem(SDK_STORAGE_KEYS.PROVIDERS_ON_COOLDOWN, updated);
3289
+ set({ providersOnCooldown: updated });
3290
+ },
3291
+ clearProvidersOnCooldown: () => {
3292
+ void driver.setItem(SDK_STORAGE_KEYS.PROVIDERS_ON_COOLDOWN, []);
3293
+ set({ providersOnCooldown: [] });
3294
+ }
3295
+ }));
3296
+ var hydrateStoreFromDriver = async (store, driver) => {
3297
+ const [
3298
+ rawModels,
3299
+ lastUsedModel,
3300
+ rawBaseUrls,
3301
+ lastBaseUrlsUpdate,
3302
+ rawDisabledProviders,
3303
+ rawMints,
3304
+ rawInfo,
3305
+ rawLastModelsUpdate,
3306
+ rawApiKeys,
3307
+ rawChildKeys,
3308
+ rawXcashuTokens,
3309
+ rawRoutstr21Models,
3310
+ rawLastRoutstr21ModelsUpdate,
3311
+ rawCachedReceiveTokens,
3312
+ rawClientIds,
3313
+ rawFailedProviders,
3314
+ rawLastFailed,
3315
+ rawProvidersOnCooldown
3316
+ ] = await Promise.all([
3317
+ driver.getItem(
3318
+ SDK_STORAGE_KEYS.MODELS_FROM_ALL_PROVIDERS,
3319
+ {}
3320
+ ),
3321
+ driver.getItem(SDK_STORAGE_KEYS.LAST_USED_MODEL, null),
3322
+ driver.getItem(SDK_STORAGE_KEYS.BASE_URLS_LIST, []),
3323
+ driver.getItem(SDK_STORAGE_KEYS.LAST_BASE_URLS_UPDATE, null),
3324
+ driver.getItem(SDK_STORAGE_KEYS.DISABLED_PROVIDERS, []),
3325
+ driver.getItem(
3326
+ SDK_STORAGE_KEYS.MINTS_FROM_ALL_PROVIDERS,
3327
+ {}
3328
+ ),
3329
+ driver.getItem(
3330
+ SDK_STORAGE_KEYS.INFO_FROM_ALL_PROVIDERS,
3331
+ {}
3332
+ ),
3333
+ driver.getItem(
3334
+ SDK_STORAGE_KEYS.LAST_MODELS_UPDATE,
3335
+ {}
3336
+ ),
3337
+ driver.getItem(SDK_STORAGE_KEYS.API_KEYS, []),
3338
+ driver.getItem(SDK_STORAGE_KEYS.CHILD_KEYS, []),
3339
+ driver.getItem(SDK_STORAGE_KEYS.XCASHU_TOKENS, {}),
3340
+ driver.getItem(SDK_STORAGE_KEYS.ROUTSTR21_MODELS, []),
3341
+ driver.getItem(
3342
+ SDK_STORAGE_KEYS.LAST_ROUTSTR21_MODELS_UPDATE,
3343
+ null
3344
+ ),
3345
+ driver.getItem(SDK_STORAGE_KEYS.CACHED_RECEIVE_TOKENS, []),
3346
+ driver.getItem(SDK_STORAGE_KEYS.CLIENT_IDS, []),
3347
+ driver.getItem(SDK_STORAGE_KEYS.FAILED_PROVIDERS, []),
3348
+ driver.getItem(SDK_STORAGE_KEYS.LAST_FAILED, {}),
3349
+ driver.getItem(
3350
+ SDK_STORAGE_KEYS.PROVIDERS_ON_COOLDOWN,
3351
+ []
3352
+ )
3353
+ ]);
3354
+ const modelsFromAllProviders = Object.fromEntries(
3355
+ Object.entries(rawModels).map(([baseUrl, models]) => [
3356
+ normalizeBaseUrl5(baseUrl),
3357
+ models
3358
+ ])
3359
+ );
3360
+ const baseUrlsList = rawBaseUrls.map((url) => normalizeBaseUrl5(url));
3361
+ const disabledProviders = rawDisabledProviders.map(
3362
+ (url) => normalizeBaseUrl5(url)
3363
+ );
3364
+ const mintsFromAllProviders = Object.fromEntries(
3365
+ Object.entries(rawMints).map(([baseUrl, mints]) => [
3366
+ normalizeBaseUrl5(baseUrl),
3367
+ mints.map((mint) => mint.endsWith("/") ? mint.slice(0, -1) : mint)
3368
+ ])
3369
+ );
3370
+ const infoFromAllProviders = Object.fromEntries(
3371
+ Object.entries(rawInfo).map(([baseUrl, info]) => [
3372
+ normalizeBaseUrl5(baseUrl),
3373
+ info
3374
+ ])
3375
+ );
3376
+ const lastModelsUpdate = Object.fromEntries(
3377
+ Object.entries(rawLastModelsUpdate).map(([baseUrl, timestamp]) => [
3378
+ normalizeBaseUrl5(baseUrl),
3379
+ timestamp
3380
+ ])
3381
+ );
3382
+ const apiKeys = rawApiKeys.map((entry) => ({
3383
+ ...entry,
3384
+ baseUrl: normalizeBaseUrl5(entry.baseUrl),
3385
+ balance: entry.balance ?? 0,
3386
+ lastUsed: entry.lastUsed ?? null
3387
+ }));
3388
+ const childKeys = rawChildKeys.map((entry) => ({
3389
+ parentBaseUrl: normalizeBaseUrl5(entry.parentBaseUrl),
3390
+ childKey: entry.childKey,
3391
+ balance: entry.balance ?? 0,
3392
+ balanceLimit: entry.balanceLimit,
3393
+ validityDate: entry.validityDate,
3394
+ createdAt: entry.createdAt ?? Date.now()
3395
+ }));
3396
+ const xcashuTokens = Object.fromEntries(
3397
+ Object.entries(rawXcashuTokens).map(([baseUrl, tokens]) => [
3398
+ normalizeBaseUrl5(baseUrl),
3399
+ tokens.map((entry) => ({
3400
+ baseUrl: normalizeBaseUrl5(entry.baseUrl),
3401
+ token: entry.token,
3402
+ createdAt: entry.createdAt ?? Date.now(),
3403
+ tryCount: entry.tryCount ?? 0
3404
+ }))
3405
+ ])
3406
+ );
3407
+ const routstr21Models = rawRoutstr21Models;
3408
+ const lastRoutstr21ModelsUpdate = rawLastRoutstr21ModelsUpdate;
3409
+ const cachedReceiveTokens = rawCachedReceiveTokens?.map((entry) => ({
3410
+ token: entry.token,
3411
+ amount: entry.amount,
3412
+ unit: entry.unit || "sat",
3413
+ createdAt: entry.createdAt ?? Date.now()
3414
+ }));
3415
+ const clientIds = rawClientIds.map((entry) => ({
3416
+ ...entry,
3417
+ createdAt: entry.createdAt ?? Date.now(),
3418
+ lastUsed: entry.lastUsed ?? null
3419
+ }));
3420
+ const failedProviders = rawFailedProviders.map(
3421
+ (url) => normalizeBaseUrl5(url)
3422
+ );
3423
+ const lastFailed = Object.fromEntries(
3424
+ Object.entries(rawLastFailed).map(([baseUrl, timestamp]) => [
3425
+ normalizeBaseUrl5(baseUrl),
3426
+ timestamp
3427
+ ])
3428
+ );
3429
+ const providersOnCooldown = rawProvidersOnCooldown.map((entry) => ({
3430
+ baseUrl: normalizeBaseUrl5(entry.baseUrl),
3431
+ timestamp: entry.timestamp
3432
+ }));
3433
+ store.setState({
3434
+ modelsFromAllProviders,
3435
+ lastUsedModel,
3436
+ baseUrlsList,
3437
+ lastBaseUrlsUpdate,
3438
+ disabledProviders,
3439
+ mintsFromAllProviders,
3440
+ infoFromAllProviders,
3441
+ lastModelsUpdate,
3442
+ apiKeys,
3443
+ childKeys,
3444
+ xcashuTokens,
3445
+ routstr21Models,
3446
+ lastRoutstr21ModelsUpdate,
3447
+ cachedReceiveTokens,
3448
+ clientIds,
3449
+ failedProviders,
3450
+ lastFailed,
3451
+ providersOnCooldown
3452
+ });
3453
+ };
3454
+ var createSdkStore = ({
3455
+ driver
3456
+ }) => {
3457
+ const store = createEmptyStore(driver);
3458
+ return {
3459
+ store,
3460
+ hydrate: hydrateStoreFromDriver(store, driver)
3461
+ };
3462
+ };
3463
+
3464
+ // storage/index.ts
3465
+ var isBrowser2 = () => {
3466
+ try {
3467
+ return typeof window !== "undefined" && typeof window.localStorage !== "undefined";
3468
+ } catch {
3469
+ return false;
3470
+ }
3471
+ };
3472
+ var isNode = () => {
3473
+ try {
3474
+ return typeof process !== "undefined" && process.versions != null && process.versions.node != null;
3475
+ } catch {
3476
+ return false;
3477
+ }
3478
+ };
3479
+ var defaultDriver = null;
3480
+ var isBun3 = () => {
3481
+ return typeof process.versions.bun !== "undefined";
3482
+ };
3483
+ var getDefaultSdkDriver = () => {
3484
+ if (defaultDriver) return defaultDriver;
3485
+ if (isBrowser2()) {
3486
+ defaultDriver = localStorageDriver;
3487
+ return defaultDriver;
3488
+ }
3489
+ if (isBun3()) {
3490
+ defaultDriver = createMemoryDriver();
3491
+ return defaultDriver;
3492
+ }
3493
+ if (isNode()) {
3494
+ defaultDriver = createSqliteDriver();
3495
+ return defaultDriver;
3496
+ }
3497
+ defaultDriver = createMemoryDriver();
3498
+ return defaultDriver;
3499
+ };
3500
+ var defaultStore = null;
3501
+ var defaultUsageTrackingDriver = null;
3502
+ var getDefaultSdkStore = () => {
3503
+ if (!defaultStore) {
3504
+ defaultStore = createSdkStore({ driver: getDefaultSdkDriver() });
3505
+ }
3506
+ return defaultStore.hydrate.then(() => defaultStore.store);
3507
+ };
3508
+ var getDefaultUsageTrackingDriver = () => {
3509
+ if (defaultUsageTrackingDriver) return defaultUsageTrackingDriver;
3510
+ const storageDriver = getDefaultSdkDriver();
3511
+ if (isBrowser2()) {
3512
+ defaultUsageTrackingDriver = createIndexedDBUsageTrackingDriver({
3513
+ legacyStorageDriver: storageDriver
3514
+ });
3515
+ return defaultUsageTrackingDriver;
3516
+ }
3517
+ if (isBun3()) {
3518
+ defaultUsageTrackingDriver = createBunSqliteUsageTrackingDriver();
3519
+ return defaultUsageTrackingDriver;
3520
+ }
3521
+ if (isNode()) {
3522
+ defaultUsageTrackingDriver = createSqliteUsageTrackingDriver({
3523
+ legacyStorageDriver: storageDriver
3524
+ });
3525
+ return defaultUsageTrackingDriver;
3526
+ }
3527
+ defaultUsageTrackingDriver = createMemoryUsageTrackingDriver();
3528
+ return defaultUsageTrackingDriver;
3529
+ };
3530
+ function mergeUsage(previous, next) {
3531
+ if (!previous) return next;
3532
+ return {
3533
+ promptTokens: next.promptTokens > 0 ? next.promptTokens : previous.promptTokens,
3534
+ completionTokens: next.completionTokens > 0 ? next.completionTokens : previous.completionTokens,
3535
+ totalTokens: next.totalTokens > 0 ? next.totalTokens : previous.totalTokens,
3536
+ cost: next.cost > 0 ? next.cost : previous.cost,
3537
+ satsCost: next.satsCost > 0 ? next.satsCost : previous.satsCost
3538
+ };
3539
+ }
3540
+ function hasUsageChanged(previous, next) {
3541
+ if (!previous) return true;
3542
+ return previous.promptTokens !== next.promptTokens || previous.completionTokens !== next.completionTokens || previous.totalTokens !== next.totalTokens || previous.cost !== next.cost || previous.satsCost !== next.satsCost;
3543
+ }
3544
+ async function inspectSSEWebStream(stream, onUsage, onResponseId) {
3545
+ const reader = stream.getReader();
3546
+ const decoder = new TextDecoder("utf-8");
3547
+ let buffer = "";
3548
+ let capturedUsage = null;
3549
+ let capturedResponseId;
3550
+ let responseIdCaptured = false;
3551
+ const inspectDataPayload = (jsonText) => {
3552
+ if (responseIdCaptured && capturedUsage && capturedUsage.totalTokens > 0) {
3553
+ return;
3554
+ }
3555
+ const trimmed = jsonText.trim();
3556
+ if (!trimmed || trimmed === "[DONE]") return;
3557
+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return;
3558
+ try {
3559
+ const data = JSON.parse(trimmed);
3560
+ if (!responseIdCaptured) {
3561
+ const responseId = data?.id;
3562
+ if (typeof responseId === "string" && responseId.trim().length > 0) {
3563
+ capturedResponseId = responseId.trim();
3564
+ onResponseId?.(capturedResponseId);
3565
+ responseIdCaptured = true;
3566
+ }
3567
+ }
3568
+ const usage = extractUsageFromSSEJson(data);
3569
+ if (usage) {
3570
+ const merged = mergeUsage(capturedUsage, usage);
3571
+ if (hasUsageChanged(capturedUsage, merged)) {
3572
+ capturedUsage = merged;
3573
+ onUsage(merged);
3574
+ }
3575
+ }
3576
+ } catch {
3577
+ }
3578
+ };
3579
+ const inspectEventBlock = (eventBlock) => {
3580
+ if (responseIdCaptured && capturedUsage && capturedUsage.totalTokens > 0) {
3581
+ return;
3582
+ }
3583
+ const lines = eventBlock.split(/\r?\n/);
3584
+ const dataParts = [];
3585
+ for (const line of lines) {
3586
+ if (!line || line.startsWith(":")) continue;
3587
+ if (line.startsWith("data:")) {
3588
+ const value = line.startsWith("data: ") ? line.slice(6) : line.slice(5);
3589
+ dataParts.push(value);
3590
+ }
3591
+ }
3592
+ if (dataParts.length === 0) return;
3593
+ inspectDataPayload(dataParts.join("\n"));
3594
+ };
3595
+ const drainBufferedEvents = () => {
3596
+ const terminator = /\r?\n\r?\n/g;
3597
+ let lastIndex = 0;
3598
+ let match;
3599
+ while ((match = terminator.exec(buffer)) !== null) {
3600
+ const block = buffer.slice(lastIndex, match.index);
3601
+ lastIndex = match.index + match[0].length;
3602
+ if (block.length > 0) inspectEventBlock(block);
3603
+ }
3604
+ if (lastIndex > 0) buffer = buffer.slice(lastIndex);
3605
+ };
3606
+ try {
3607
+ while (true) {
3608
+ const { value, done } = await reader.read();
3609
+ if (done) break;
3610
+ if (value && value.byteLength > 0) {
3611
+ buffer += decoder.decode(value, { stream: true });
3612
+ drainBufferedEvents();
3613
+ }
3614
+ }
3615
+ buffer += decoder.decode();
3616
+ drainBufferedEvents();
3617
+ if (buffer.length > 0) {
3618
+ const tail = buffer.replace(/\r?\n+$/, "");
3619
+ if (tail.length > 0) inspectEventBlock(tail);
3620
+ buffer = "";
3621
+ }
3622
+ } catch {
3623
+ } finally {
3624
+ try {
3625
+ reader.releaseLock();
3626
+ } catch {
3627
+ }
3628
+ }
3629
+ return {
3630
+ capturedUsage: capturedUsage ?? void 0,
3631
+ capturedResponseId
3632
+ };
3633
+ }
3634
+ function createSSEParserTransform(onUsage, onResponseId) {
3635
+ let buffer = "";
3636
+ const decoder = new string_decoder.StringDecoder("utf8");
3637
+ let capturedUsage = null;
3638
+ let responseIdCaptured = false;
3639
+ const inspectDataPayload = (jsonText) => {
3640
+ if (responseIdCaptured && capturedUsage && capturedUsage.totalTokens > 0) {
3641
+ return;
3642
+ }
3643
+ const trimmed = jsonText.trim();
3644
+ if (!trimmed || trimmed === "[DONE]") return;
3645
+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return;
3646
+ try {
3647
+ const data = JSON.parse(trimmed);
3648
+ if (!responseIdCaptured) {
3649
+ const responseId = data?.id;
3650
+ if (typeof responseId === "string" && responseId.trim().length > 0) {
3651
+ onResponseId?.(responseId.trim());
3652
+ responseIdCaptured = true;
3653
+ }
3654
+ }
3655
+ const usage = extractUsageFromSSEJson(data);
3656
+ if (usage) {
3657
+ const mergedUsage = mergeUsage(capturedUsage, usage);
3658
+ if (hasUsageChanged(capturedUsage, mergedUsage)) {
3659
+ capturedUsage = mergedUsage;
3660
+ onUsage(mergedUsage);
3661
+ }
3662
+ }
3663
+ } catch {
3664
+ }
3665
+ };
3666
+ const inspectEventBlock = (eventBlock) => {
3667
+ if (responseIdCaptured && capturedUsage && capturedUsage.totalTokens > 0) {
3668
+ return;
3669
+ }
3670
+ const lines = eventBlock.split(/\r?\n/);
3671
+ const dataParts = [];
3672
+ for (const line of lines) {
3673
+ if (!line || line.startsWith(":")) continue;
3674
+ if (line.startsWith("data:")) {
3675
+ const value = line.startsWith("data: ") ? line.slice(6) : line.slice(5);
3676
+ dataParts.push(value);
3677
+ }
3678
+ }
3679
+ if (dataParts.length === 0) return;
3680
+ const payload = dataParts.join("\n");
3681
+ inspectDataPayload(payload);
3682
+ };
3683
+ const processBufferedEvents = () => {
3684
+ const terminator = /\r?\n\r?\n/g;
3685
+ let lastIndex = 0;
3686
+ let match;
3687
+ while ((match = terminator.exec(buffer)) !== null) {
3688
+ const block = buffer.slice(lastIndex, match.index);
3689
+ lastIndex = match.index + match[0].length;
3690
+ if (block.length > 0) {
3691
+ inspectEventBlock(block);
3692
+ }
3693
+ }
3694
+ if (lastIndex > 0) {
3695
+ buffer = buffer.slice(lastIndex);
3696
+ }
3697
+ };
3698
+ return new stream.Transform({
3699
+ transform(chunk, _encoding, callback) {
3700
+ this.push(chunk);
3701
+ buffer += decoder.write(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
3702
+ processBufferedEvents();
3703
+ callback();
3704
+ },
3705
+ flush(callback) {
3706
+ buffer += decoder.end();
3707
+ processBufferedEvents();
3708
+ if (buffer.length > 0) {
3709
+ const tail = buffer.replace(/\r?\n+$/, "");
3710
+ if (tail.length > 0) {
3711
+ inspectEventBlock(tail);
3712
+ }
3713
+ buffer = "";
3714
+ }
3715
+ callback();
3716
+ }
3717
+ });
3718
+ }
3719
+
3720
+ // client/RoutstrClient.ts
3721
+ var TOPUP_MARGIN = 1.2;
3722
+ var RoutstrClient = class {
3723
+ constructor(walletAdapter, storageAdapter, providerRegistry, alertLevel, mode = "xcashu", options = {}) {
3724
+ this.walletAdapter = walletAdapter;
3725
+ this.storageAdapter = storageAdapter;
3726
+ this.providerRegistry = providerRegistry;
3727
+ this.logger = (options.logger ?? consoleLogger).child("RoutstrClient");
3728
+ this.balanceManager = new BalanceManager(
3729
+ walletAdapter,
3730
+ storageAdapter,
3731
+ providerRegistry,
3732
+ void 0,
3733
+ this.logger
3734
+ );
3735
+ this.cashuSpender = new CashuSpender(
3736
+ walletAdapter,
3737
+ storageAdapter,
3738
+ providerRegistry,
3739
+ this.balanceManager,
3740
+ this.logger
3741
+ );
3742
+ this.streamProcessor = new StreamProcessor();
3743
+ this.alertLevel = alertLevel;
3744
+ this.mode = mode;
3745
+ this.usageTrackingDriver = options.usageTrackingDriver;
3746
+ this.sdkStore = options.sdkStore;
3747
+ this.providerManager = options.providerManager ?? new ProviderManager(providerRegistry, this.sdkStore, this.logger);
3748
+ }
3749
+ walletAdapter;
3750
+ storageAdapter;
3751
+ providerRegistry;
3752
+ cashuSpender;
3753
+ balanceManager;
3754
+ streamProcessor;
3755
+ providerManager;
3756
+ alertLevel;
3757
+ mode;
3758
+ debugLevel = "WARN";
3759
+ usageTrackingDriver;
3760
+ sdkStore;
3761
+ logger;
3762
+ /**
3763
+ * Get the current client mode
3764
+ */
3765
+ getMode() {
3766
+ return this.mode;
3767
+ }
3768
+ getDebugLevel() {
3769
+ return this.debugLevel;
3770
+ }
3771
+ setDebugLevel(level) {
3772
+ this.debugLevel = level;
3773
+ }
3774
+ _log(level, ...args) {
3775
+ const levelPriority = {
3776
+ DEBUG: 0,
3777
+ WARN: 1,
3778
+ ERROR: 2
3779
+ };
3780
+ if (levelPriority[level] >= levelPriority[this.debugLevel]) {
3781
+ switch (level) {
3782
+ case "DEBUG":
3783
+ this.logger.log(...args);
3784
+ break;
3785
+ case "WARN":
3786
+ this.logger.warn(...args);
3787
+ break;
3788
+ case "ERROR":
3789
+ this.logger.error(...args);
3790
+ break;
3791
+ }
3792
+ }
3793
+ }
3794
+ /**
3795
+ * Get the CashuSpender instance
3796
+ */
3797
+ getCashuSpender() {
3798
+ return this.cashuSpender;
3799
+ }
3800
+ /**
3801
+ * Get the BalanceManager instance
3802
+ */
3803
+ getBalanceManager() {
3804
+ return this.balanceManager;
3805
+ }
3806
+ /**
3807
+ * Get the ProviderManager instance
3808
+ */
3809
+ getProviderManager() {
3810
+ return this.providerManager;
3811
+ }
3812
+ /**
3813
+ * Check if the client is currently busy (in critical section)
3814
+ */
3815
+ get isBusy() {
3816
+ return this.cashuSpender.isBusy;
3817
+ }
3818
+ /**
3819
+ * Route an API request to the upstream provider
3820
+ *
3821
+ * This is a simpler alternative to fetchAIResponse that just proxies
3822
+ * the request upstream without the streaming callback machinery.
3823
+ * Useful for daemon-style routing where you just need to forward
3824
+ * requests and get responses back.
3825
+ */
3826
+ async routeRequest(params) {
3827
+ const prepared = await this._prepareRoutedRequest(params);
3828
+ const contentType = prepared.response.headers.get("content-type") || "";
3829
+ const isSSE = contentType.includes("text/event-stream");
3830
+ const runFinalize = async () => {
3831
+ const { capturedUsage, capturedResponseId } = await prepared.usagePromise;
3832
+ const usage = capturedUsage ?? prepared.capturedUsage;
3833
+ const requestId = capturedResponseId ?? prepared.capturedResponseId;
3834
+ const satsSpent = await this._handlePostResponseBalanceUpdate({
3835
+ token: prepared.tokenUsed,
3836
+ baseUrl: prepared.baseUrlUsed,
3837
+ mintUrl: params.mintUrl,
3838
+ initialTokenBalance: prepared.tokenBalanceInSats,
3839
+ response: prepared.response,
3840
+ modelId: prepared.modelId,
3841
+ usage,
3842
+ requestId,
3843
+ clientApiKey: prepared.clientApiKey
3844
+ });
3845
+ prepared.response.satsSpent = satsSpent;
3846
+ prepared.response.usage = usage;
3847
+ prepared.response.requestId = requestId;
3848
+ return satsSpent;
3849
+ };
3850
+ if (isSSE) {
3851
+ const finalizePromise = runFinalize().catch((error) => {
3852
+ this._log("ERROR", "[RoutstrClient] SSE finalize failed:", error);
3853
+ return 0;
3854
+ });
3855
+ prepared.response.finalize = () => finalizePromise;
3856
+ return prepared.response;
3857
+ }
3858
+ await runFinalize();
3859
+ return prepared.response;
3860
+ }
3861
+ async _prepareRoutedRequest(params) {
3862
+ const {
3863
+ path: requestPath,
3864
+ method,
3865
+ body,
3866
+ headers = {},
3867
+ baseUrl,
3868
+ mintUrl,
3869
+ modelId,
3870
+ clientApiKey: providedClientApiKey
3871
+ } = params;
3872
+ const clientApiKey = providedClientApiKey ?? this._extractClientApiKey(headers);
3873
+ await this._checkBalance();
3874
+ let requiredSats = 1;
3875
+ let selectedModel;
3876
+ if (modelId) {
3877
+ const providerModel = await this.providerManager.getModelForProvider(
3878
+ baseUrl,
3879
+ modelId
3880
+ );
3881
+ selectedModel = providerModel ?? void 0;
3882
+ if (selectedModel) {
3883
+ const requestMessages = Array.isArray(
3884
+ body?.messages
3885
+ ) ? body.messages : [];
3886
+ const requestMaxTokens = typeof body?.max_tokens === "number" ? body.max_tokens : void 0;
3887
+ this._log(
3888
+ "DEBUG",
3889
+ "[RoutstrClient] generic request pricing input",
3890
+ {
3891
+ modelId: selectedModel.id,
3892
+ messageCount: requestMessages.length,
3893
+ maxTokens: requestMaxTokens
3894
+ }
3895
+ );
3896
+ requiredSats = this.providerManager.getRequiredSatsForModel(
3897
+ selectedModel,
3898
+ requestMessages,
3899
+ requestMaxTokens
3900
+ );
3901
+ }
3902
+ }
3903
+ const { token, tokenBalance, tokenBalanceUnit } = await this._spendToken({
3904
+ mintUrl,
3905
+ amount: requiredSats,
3906
+ baseUrl
3907
+ });
3908
+ let requestBody = body;
3909
+ if (body && typeof body === "object") {
3910
+ const bodyObj = body;
3911
+ if (!bodyObj.stream) {
3912
+ requestBody = { ...bodyObj, stream: false };
3913
+ }
3914
+ }
3915
+ const baseHeaders = this._buildBaseHeaders();
3916
+ const requestHeaders = this._withAuthHeader(baseHeaders, token);
3917
+ const response = await this._makeRequest({
3918
+ path: requestPath,
3919
+ method,
3920
+ body: method === "GET" ? void 0 : requestBody,
3921
+ baseUrl,
3922
+ mintUrl,
3923
+ token,
3924
+ requiredSats,
3925
+ headers: requestHeaders,
3926
+ baseHeaders,
3927
+ selectedModel
3928
+ });
3929
+ const tokenBalanceInSats = tokenBalanceUnit === "msat" ? tokenBalance / 1e3 : tokenBalance;
3930
+ const baseUrlUsed = response.baseUrl || baseUrl;
3931
+ const tokenUsed = response.token || token;
3932
+ const contentType = response.headers.get("content-type") || "";
3933
+ let processedResponse = response;
3934
+ let capturedUsage;
3935
+ let capturedResponseId;
3936
+ let usagePromise = Promise.resolve({});
3937
+ if (contentType.includes("text/event-stream") && response.body) {
3938
+ const [clientStream, inspectStream] = response.body.tee();
3939
+ processedResponse = new Response(clientStream, {
3940
+ status: response.status,
3941
+ statusText: response.statusText,
3942
+ headers: response.headers
3943
+ });
3944
+ processedResponse.baseUrl = response.baseUrl;
3945
+ processedResponse.token = response.token;
3946
+ usagePromise = inspectSSEWebStream(
3947
+ inspectStream,
3948
+ (usage) => {
3949
+ capturedUsage = usage;
3950
+ processedResponse.usage = usage;
3951
+ },
3952
+ (responseId) => {
3953
+ capturedResponseId = responseId;
3954
+ processedResponse.requestId = responseId;
3955
+ }
3956
+ );
3957
+ processedResponse.usagePromise = usagePromise;
3958
+ }
3959
+ return {
3960
+ response: processedResponse,
3961
+ tokenUsed,
3962
+ baseUrlUsed,
3963
+ tokenBalanceInSats,
3964
+ modelId,
3965
+ capturedUsage,
3966
+ capturedResponseId,
3967
+ clientApiKey,
3968
+ usagePromise
3969
+ };
3970
+ }
3971
+ /**
3972
+ * Extract clientApiKey from Authorization Bearer token if present
3973
+ */
3974
+ _extractClientApiKey(headers) {
3975
+ const authHeader = headers["Authorization"] || headers["authorization"];
3976
+ if (authHeader?.startsWith("Bearer ")) {
3977
+ const extractedKey = authHeader.slice(7);
3978
+ return extractedKey;
3979
+ }
3980
+ return void 0;
3981
+ }
3982
+ /**
3983
+ * Fetch AI response with streaming
3984
+ */
3985
+ async fetchAIResponse(options, callbacks) {
3986
+ const {
3987
+ messageHistory,
3988
+ selectedModel,
3989
+ baseUrl,
3990
+ mintUrl,
3991
+ balance,
3992
+ transactionHistory,
3993
+ maxTokens,
3994
+ headers
3995
+ } = options;
3996
+ const apiMessages = await this._convertMessages(messageHistory);
3997
+ const requiredSats = this.providerManager.getRequiredSatsForModel(
3998
+ selectedModel,
3999
+ apiMessages,
4000
+ maxTokens
4001
+ );
4002
+ try {
4003
+ await this._checkBalance();
4004
+ callbacks.onPaymentProcessing?.(true);
4005
+ const spendResult = await this._spendToken({
4006
+ mintUrl,
4007
+ amount: requiredSats,
4008
+ baseUrl
4009
+ });
4010
+ let token = spendResult.token;
4011
+ let tokenBalance = spendResult.tokenBalance;
4012
+ let tokenBalanceUnit = spendResult.tokenBalanceUnit;
4013
+ const tokenBalanceInSats = tokenBalanceUnit === "msat" ? tokenBalance / 1e3 : tokenBalance;
4014
+ callbacks.onTokenCreated?.(this._getPendingCashuTokenAmount());
4015
+ const baseHeaders = this._buildBaseHeaders(headers);
4016
+ const requestHeaders = this._withAuthHeader(baseHeaders, token);
4017
+ const providerInfo = await this.providerRegistry.getProviderInfo(baseUrl);
4018
+ const providerVersion = providerInfo?.version ?? "";
4019
+ let modelIdForRequest = selectedModel.id;
4020
+ if (/^0\.1\./.test(providerVersion)) {
4021
+ const newModel = await this.providerManager.getModelForProvider(
4022
+ baseUrl,
4023
+ selectedModel.id
4024
+ );
4025
+ modelIdForRequest = newModel?.id ?? selectedModel.id;
4026
+ }
4027
+ const body = {
4028
+ model: modelIdForRequest,
4029
+ messages: apiMessages,
4030
+ stream: true
4031
+ };
4032
+ if (maxTokens !== void 0) {
4033
+ body.max_tokens = maxTokens;
4034
+ }
4035
+ if (selectedModel?.name?.startsWith("OpenAI:")) {
4036
+ body.tools = [{ type: "web_search" }];
4037
+ }
4038
+ const response = await this._makeRequest({
4039
+ path: "/v1/chat/completions",
4040
+ method: "POST",
4041
+ body,
4042
+ selectedModel,
4043
+ baseUrl,
4044
+ mintUrl,
4045
+ token,
4046
+ requiredSats,
4047
+ maxTokens,
4048
+ headers: requestHeaders,
4049
+ baseHeaders
4050
+ });
4051
+ if (!response.body) {
4052
+ throw new Error("Response body is not available");
4053
+ }
4054
+ if (response.status === 200) {
4055
+ const baseUrlUsed = response.baseUrl || baseUrl;
4056
+ const streamingResult = await this.streamProcessor.process(
4057
+ response,
4058
+ {
4059
+ onContent: callbacks.onStreamingUpdate,
4060
+ onThinking: callbacks.onThinkingUpdate
4061
+ },
4062
+ selectedModel.id
4063
+ );
4064
+ if (streamingResult.finish_reason === "content_filter") {
4065
+ callbacks.onMessageAppend({
4066
+ role: "assistant",
4067
+ content: "Your request was denied due to content filtering."
4068
+ });
4069
+ } else if (streamingResult.content || streamingResult.images && streamingResult.images.length > 0) {
4070
+ const message = await this._createAssistantMessage(streamingResult);
4071
+ callbacks.onMessageAppend(message);
4072
+ } else {
4073
+ callbacks.onMessageAppend({
4074
+ role: "system",
4075
+ content: "The provider did not respond to this request."
4076
+ });
4077
+ }
4078
+ callbacks.onStreamingUpdate("");
4079
+ callbacks.onThinkingUpdate("");
4080
+ const isApikeysEstimate = this.mode === "apikeys";
4081
+ let satsSpent = await this._handlePostResponseBalanceUpdate({
4082
+ token,
4083
+ baseUrl: baseUrlUsed,
4084
+ mintUrl,
4085
+ initialTokenBalance: tokenBalanceInSats,
4086
+ fallbackSatsSpent: isApikeysEstimate ? this._getEstimatedCosts(selectedModel, streamingResult) : void 0,
4087
+ response,
4088
+ modelId: selectedModel.id,
4089
+ usage: streamingResult.usage ? {
4090
+ promptTokens: Number(streamingResult.usage.prompt_tokens ?? 0),
4091
+ completionTokens: Number(
4092
+ streamingResult.usage.completion_tokens ?? 0
4093
+ ),
4094
+ totalTokens: Number(streamingResult.usage.total_tokens ?? 0),
4095
+ cost: Number(streamingResult.usage.cost ?? 0),
4096
+ satsCost: Number(streamingResult.usage.sats_cost ?? 0)
4097
+ } : void 0,
4098
+ requestId: streamingResult.responseId
4099
+ });
4100
+ const estimatedCosts = this._getEstimatedCosts(
4101
+ selectedModel,
4102
+ streamingResult
4103
+ );
4104
+ const onLastMessageSatsUpdate = callbacks.onLastMessageSatsUpdate;
4105
+ onLastMessageSatsUpdate?.(satsSpent, estimatedCosts);
4106
+ } else {
4107
+ throw new Error(`${response.status} ${response.statusText}`);
4108
+ }
4109
+ } catch (error) {
4110
+ this._handleError(error, callbacks);
4111
+ } finally {
4112
+ callbacks.onPaymentProcessing?.(false);
4113
+ }
4114
+ }
4115
+ /**
4116
+ * Make the API request with failover support
4117
+ */
4118
+ async _makeRequest(params) {
4119
+ const { path, method, body, baseUrl, token, headers } = params;
4120
+ try {
4121
+ const url = `${baseUrl.replace(/\/$/, "")}${path}`;
4122
+ if (this.mode === "xcashu") this._log("DEBUG", "HEADERS,", headers);
4123
+ const response = await fetch(url, {
4124
+ method,
4125
+ headers,
4126
+ body: body === void 0 || method === "GET" ? void 0 : JSON.stringify(body)
4127
+ });
4128
+ if (this.mode === "xcashu") this._log("DEBUG", "response,", response);
4129
+ response.baseUrl = baseUrl;
4130
+ response.token = token;
4131
+ if (!response.ok) {
4132
+ const requestId = response.headers.get("x-routstr-request-id") || void 0;
4133
+ let bodyText;
4134
+ try {
4135
+ bodyText = await response.text();
4136
+ } catch (e) {
4137
+ bodyText = void 0;
4138
+ }
4139
+ return await this._handleErrorResponse(
4140
+ params,
4141
+ token,
4142
+ response.status,
4143
+ requestId,
4144
+ this.mode === "xcashu" ? response.headers.get("x-cashu") ?? void 0 : void 0,
4145
+ bodyText,
4146
+ params.retryCount ?? 0
4147
+ );
4148
+ }
4149
+ return response;
4150
+ } catch (error) {
4151
+ if (isNetworkErrorMessage(error?.message || "")) {
4152
+ return await this._handleErrorResponse(
4153
+ params,
4154
+ token,
4155
+ -1,
4156
+ // just for Network Error to skip all statuses
4157
+ void 0,
4158
+ void 0,
4159
+ void 0,
4160
+ params.retryCount ?? 0
4161
+ );
4162
+ }
4163
+ throw error;
4164
+ }
4165
+ }
4166
+ /**
4167
+ * Handle error responses with failover
4168
+ */
4169
+ async _handleErrorResponse(params, token, status, requestId, xCashuRefundToken, responseBody, retryCount = 0) {
4170
+ const MAX_RETRIES_PER_PROVIDER = 2;
4171
+ const { path, method, body, selectedModel, baseUrl, mintUrl } = params;
4172
+ let tryNextProvider = false;
4173
+ const errorMessage = responseBody;
4174
+ this._log(
4175
+ "DEBUG",
4176
+ `[RoutstrClient] _handleErrorResponse: status=${status}, baseUrl=${baseUrl}, mode=${this.mode}, token preview=${token}, requestId=${requestId}, errorMessage=${errorMessage}`
4177
+ );
4178
+ this._log(
4179
+ "DEBUG",
4180
+ `[RoutstrClient] _handleErrorResponse: Attempting to receive/restore token for ${baseUrl}`
4181
+ );
4182
+ if (params.token.startsWith("cashu")) {
4183
+ const receiveResult = await this.cashuSpender.receiveToken(
4184
+ params.token
4185
+ );
4186
+ if (receiveResult.success) {
4187
+ this._log(
4188
+ "DEBUG",
4189
+ `[RoutstrClient] _handleErrorResponse: Token restored successfully, amount=${receiveResult.amount}`
4190
+ );
4191
+ tryNextProvider = true;
4192
+ } else {
4193
+ this._log(
4194
+ "DEBUG",
4195
+ `[RoutstrClient] _handleErrorResponse: Failed to receive token: ${receiveResult.message}`
4196
+ );
4197
+ }
4198
+ }
4199
+ if (this.mode === "xcashu") {
4200
+ if (xCashuRefundToken) {
4201
+ this._log(
4202
+ "DEBUG",
4203
+ `[RoutstrClient] _handleErrorResponse: Attempting to receive xcashu refund token, preview=${xCashuRefundToken.substring(0, 20)}...`
4204
+ );
4205
+ const receiveResult = await this.cashuSpender.receiveToken(xCashuRefundToken);
4206
+ if (receiveResult.success) {
4207
+ this._log(
4208
+ "DEBUG",
4209
+ `[RoutstrClient] _handleErrorResponse: xcashu refund received, amount=${receiveResult.amount}`
4210
+ );
4211
+ tryNextProvider = true;
4212
+ } else {
4213
+ this._log(
4214
+ "ERROR",
4215
+ `[xcashu] Failed to receive refund token: ${receiveResult.message}`
4216
+ );
4217
+ throw new ProviderError(
4218
+ baseUrl,
4219
+ status,
4220
+ "[xcashu] Failed to receive refund token",
4221
+ requestId
4222
+ );
4223
+ }
4224
+ } else {
4225
+ if (!tryNextProvider)
4226
+ throw new ProviderError(
4227
+ baseUrl,
4228
+ status,
4229
+ "[xcashu] Failed to receive refund token",
4230
+ requestId
4231
+ );
4232
+ }
4233
+ }
4234
+ if (status === 402 && !tryNextProvider && this.mode === "apikeys") {
4235
+ this.storageAdapter.getApiKey(baseUrl);
4236
+ let topupAmount = params.requiredSats;
4237
+ try {
4238
+ const currentBalanceInfo = await this.balanceManager.getTokenBalance(
4239
+ params.token,
4240
+ baseUrl
4241
+ );
4242
+ const currentBalance = currentBalanceInfo.unit === "msat" ? currentBalanceInfo.amount / 1e3 : currentBalanceInfo.amount;
4243
+ const reservedBalance = currentBalanceInfo.unit === "msat" ? (currentBalanceInfo.reserved ?? 0) / 1e3 : currentBalanceInfo.reserved ?? 0;
4244
+ const shortfall = Math.max(0, params.requiredSats - currentBalance + reservedBalance);
4245
+ topupAmount = shortfall > 0.21 * params.requiredSats ? shortfall : 0.21 * params.requiredSats;
4246
+ this._log(
4247
+ "DEBUG",
4248
+ `The shortfall is: ${shortfall}. requiredSats: ${params.requiredSats}. Current Balance: ${currentBalance}. Reserved Balance: ${reservedBalance}. Available Balance: ${currentBalance - reservedBalance}`
4249
+ );
4250
+ } catch (e) {
4251
+ this._log(
4252
+ "WARN",
4253
+ "Could not get current token balance for topup calculation:",
4254
+ e
4255
+ );
4256
+ }
4257
+ const topupResult = await this.balanceManager.topUp({
4258
+ mintUrl,
4259
+ baseUrl,
4260
+ amount: topupAmount * TOPUP_MARGIN,
4261
+ token: params.token
4262
+ });
4263
+ this._log(
4264
+ "DEBUG",
4265
+ `[RoutstrClient] _handleErrorResponse: Topup result for ${baseUrl}: success=${topupResult.success}, message=${topupResult.message}`
4266
+ );
4267
+ if (!topupResult.success) {
4268
+ const message = topupResult.message || "";
4269
+ if (message.includes("Insufficient balance")) {
4270
+ const needMatch = message.match(/need (\d+)/);
4271
+ const haveMatch = message.match(/have (\d+)/);
4272
+ const required = needMatch ? parseInt(needMatch[1], 10) : params.requiredSats;
4273
+ const available = haveMatch ? parseInt(haveMatch[1], 10) : 0;
4274
+ this._log(
4275
+ "DEBUG",
4276
+ `[RoutstrClient] _handleErrorResponse: Insufficient balance, need=${required}, have=${available}`
4277
+ );
4278
+ throw new InsufficientBalanceError(
4279
+ required,
4280
+ available,
4281
+ 0,
4282
+ "",
4283
+ message
4284
+ );
4285
+ } else {
4286
+ this._log(
4287
+ "DEBUG",
4288
+ `[RoutstrClient] _handleErrorResponse: Topup failed with non-insufficient-balance error, will try next provider`
4289
+ );
4290
+ tryNextProvider = true;
4291
+ }
4292
+ } else {
4293
+ this._log(
4294
+ "DEBUG",
4295
+ `[RoutstrClient] _handleErrorResponse: Topup successful, will retry with new token`
4296
+ );
4297
+ }
4298
+ if (!tryNextProvider) {
4299
+ if (retryCount < MAX_RETRIES_PER_PROVIDER) {
4300
+ this._log(
4301
+ "DEBUG",
4302
+ `[RoutstrClient] _handleErrorResponse: Retrying 402 (attempt ${retryCount + 1}/${MAX_RETRIES_PER_PROVIDER})`
4303
+ );
4304
+ return this._makeRequest({
4305
+ ...params,
4306
+ token: params.token,
4307
+ headers: this._withAuthHeader(params.baseHeaders, params.token),
4308
+ retryCount: retryCount + 1
4309
+ });
4310
+ } else {
4311
+ this._log(
4312
+ "DEBUG",
4313
+ `[RoutstrClient] _handleErrorResponse: 402 retry limit reached (${retryCount}/${MAX_RETRIES_PER_PROVIDER}), failing over to next provider`
4314
+ );
4315
+ tryNextProvider = true;
4316
+ }
4317
+ }
4318
+ }
4319
+ const isInsufficientBalance413 = status === 413 && responseBody?.includes("Insufficient balance");
4320
+ if (isInsufficientBalance413 && !tryNextProvider && this.mode === "apikeys") {
4321
+ let retryToken = params.token;
4322
+ try {
4323
+ const latestBalanceInfo = await this.balanceManager.getTokenBalance(
4324
+ params.token,
4325
+ baseUrl
4326
+ );
4327
+ if (latestBalanceInfo.isInvalidApiKey) {
4328
+ this._log(
4329
+ "DEBUG",
4330
+ `[RoutstrClient] _handleErrorResponse: Invalid API key (proofs already spent), removing for ${baseUrl}`
4331
+ );
4332
+ this.storageAdapter.removeApiKey(baseUrl);
4333
+ tryNextProvider = true;
4334
+ } else {
4335
+ const latestTokenBalance = latestBalanceInfo.unit === "msat" ? latestBalanceInfo.amount / 1e3 : latestBalanceInfo.amount;
4336
+ if (latestBalanceInfo.apiKey) {
4337
+ const storedApiKeyEntry = this.storageAdapter.getApiKey(baseUrl);
4338
+ if (storedApiKeyEntry?.key !== latestBalanceInfo.apiKey) {
4339
+ if (storedApiKeyEntry) {
4340
+ this.storageAdapter.removeApiKey(baseUrl);
4341
+ }
4342
+ this.storageAdapter.setApiKey(baseUrl, latestBalanceInfo.apiKey);
4343
+ }
4344
+ retryToken = latestBalanceInfo.apiKey;
4345
+ }
4346
+ if (latestTokenBalance >= 0) {
4347
+ this.storageAdapter.updateApiKeyBalance(
4348
+ baseUrl,
4349
+ latestTokenBalance
4350
+ );
4351
+ }
4352
+ }
4353
+ } catch (error) {
4354
+ this._log(
4355
+ "WARN",
4356
+ `[RoutstrClient] _handleErrorResponse: Failed to refresh API key after 413 insufficient balance for ${baseUrl}`,
4357
+ error
4358
+ );
4359
+ }
4360
+ if (retryCount < MAX_RETRIES_PER_PROVIDER) {
4361
+ this._log(
4362
+ "DEBUG",
4363
+ `[RoutstrClient] _handleErrorResponse: Retrying 413 (attempt ${retryCount + 1}/${MAX_RETRIES_PER_PROVIDER})`
4364
+ );
4365
+ return this._makeRequest({
4366
+ ...params,
4367
+ token: retryToken,
4368
+ headers: this._withAuthHeader(params.baseHeaders, retryToken),
4369
+ retryCount: retryCount + 1
4370
+ });
4371
+ } else {
4372
+ this._log(
4373
+ "DEBUG",
4374
+ `[RoutstrClient] _handleErrorResponse: 413 retry limit reached (${retryCount}/${MAX_RETRIES_PER_PROVIDER}), failing over to next provider`
4375
+ );
4376
+ tryNextProvider = true;
4377
+ }
4378
+ }
4379
+ if (status === 401 && this.mode === "apikeys") {
4380
+ this._log(
4381
+ "DEBUG",
4382
+ `[RoutstrClient] _handleErrorResponse: Checking balance for ${baseUrl}, key preview=${token}`
4383
+ );
4384
+ const latestBalanceInfo = await this.balanceManager.getTokenBalance(
4385
+ token,
4386
+ baseUrl
4387
+ );
4388
+ if (latestBalanceInfo.isInvalidApiKey) {
4389
+ this.storageAdapter.removeApiKey(baseUrl);
4390
+ tryNextProvider = true;
4391
+ }
4392
+ }
4393
+ if ((status === 401 || status === 403 || status === 404 || status === 413 || status === 400 || status === 429 || status === 500 || status === 502 || status === 503 || status === 504 || status === 521) && !tryNextProvider) {
4394
+ this._log(
4395
+ "DEBUG",
4396
+ `[RoutstrClient] _handleErrorResponse: Status ${status} (${status === 429 ? "rate limited" : "auth/server error"}), attempting refund for ${baseUrl}, mode=${this.mode}`
4397
+ );
4398
+ if (this.mode === "apikeys") {
4399
+ this._log(
4400
+ "DEBUG",
4401
+ `[RoutstrClient] _handleErrorResponse: Attempting API key refund for ${baseUrl}, key preview=${token}`
4402
+ );
4403
+ const latestBalanceInfo = await this.balanceManager.getTokenBalance(
4404
+ token,
4405
+ baseUrl
4406
+ );
4407
+ this._log(
4408
+ "DEBUG",
4409
+ `[RoutstrClient] _handleErrorResponse: Initial API key balance: ${latestBalanceInfo.amount}`
4410
+ );
4411
+ const refundResult = await this.balanceManager.refundApiKey({
4412
+ mintUrl,
4413
+ baseUrl,
4414
+ apiKey: token,
4415
+ forceRefund: true
4416
+ });
4417
+ this._log(
4418
+ "DEBUG",
4419
+ `[RoutstrClient] _handleErrorResponse: API key refund result: success=${refundResult.success}, message=${refundResult.message}`
4420
+ );
4421
+ if (!refundResult.success && latestBalanceInfo.amount > 0) {
4422
+ throw new ProviderError(
4423
+ baseUrl,
4424
+ status,
4425
+ refundResult.message ?? "Unknown error"
4426
+ );
4427
+ }
4428
+ }
4429
+ }
4430
+ this.providerManager.markFailed(baseUrl);
4431
+ this._log(
4432
+ "DEBUG",
4433
+ `[RoutstrClient] _handleErrorResponse: Marked provider ${baseUrl} as failed`
4434
+ );
4435
+ if (!selectedModel) {
4436
+ throw new ProviderError(
4437
+ baseUrl,
4438
+ status,
4439
+ "Funny, no selected model. HMM. "
4440
+ );
4441
+ }
4442
+ const nextProvider = this.providerManager.findNextBestProvider(
4443
+ selectedModel.id,
4444
+ baseUrl
4445
+ );
4446
+ if (nextProvider) {
4447
+ this._log(
4448
+ "DEBUG",
4449
+ `[RoutstrClient] _handleErrorResponse: Failing over to next provider: ${nextProvider}, model: ${selectedModel.id}`
4450
+ );
4451
+ const newModel = await this.providerManager.getModelForProvider(
4452
+ nextProvider,
4453
+ selectedModel.id
4454
+ ) ?? selectedModel;
4455
+ const messagesForPricing = Array.isArray(
4456
+ body?.messages
4457
+ ) ? body.messages : [];
4458
+ const newRequiredSats = this.providerManager.getRequiredSatsForModel(
4459
+ newModel,
4460
+ messagesForPricing,
4461
+ params.maxTokens
4462
+ );
4463
+ this._log(
4464
+ "DEBUG",
4465
+ `[RoutstrClient] _handleErrorResponse: Creating new token for failover provider ${nextProvider}, required sats: ${newRequiredSats}`
4466
+ );
4467
+ const spendResult = await this._spendToken({
4468
+ mintUrl,
4469
+ amount: newRequiredSats,
4470
+ baseUrl: nextProvider
4471
+ });
4472
+ return this._makeRequest({
4473
+ ...params,
4474
+ path,
4475
+ method,
4476
+ body,
4477
+ baseUrl: nextProvider,
4478
+ selectedModel: newModel,
4479
+ token: spendResult.token,
4480
+ requiredSats: newRequiredSats,
4481
+ headers: this._withAuthHeader(params.baseHeaders, spendResult.token),
4482
+ retryCount: 0
4483
+ });
4484
+ }
4485
+ throw new FailoverError(
4486
+ baseUrl,
4487
+ Array.from(this.providerManager.getFailedProviders())
4488
+ );
4489
+ }
4490
+ /**
4491
+ * Handle post-response balance update for all modes
4492
+ */
4493
+ async _handlePostResponseBalanceUpdate(params) {
4494
+ const {
4495
+ token,
4496
+ baseUrl,
4497
+ mintUrl,
4498
+ initialTokenBalance,
4499
+ fallbackSatsSpent,
4500
+ response,
4501
+ modelId,
4502
+ usage,
4503
+ requestId,
4504
+ clientApiKey
4505
+ } = params;
4506
+ let satsSpent = initialTokenBalance;
4507
+ if (this.mode === "xcashu" && response) {
4508
+ const refundToken = response.headers.get("x-cashu") ?? void 0;
4509
+ if (refundToken) {
4510
+ const receiveResult = await this.cashuSpender.receiveToken(refundToken);
4511
+ if (receiveResult.success) {
4512
+ this.storageAdapter.removeXcashuToken(baseUrl, token);
4513
+ satsSpent = initialTokenBalance - receiveResult.amount * (receiveResult.unit == "sat" ? 1 : 1e3);
4514
+ } else {
4515
+ this._log(
4516
+ "ERROR",
4517
+ `[xcashu] Failed to receive refund token: ${receiveResult.message}`
4518
+ );
4519
+ }
4520
+ }
4521
+ } else if (this.mode === "apikeys") {
4522
+ try {
4523
+ const latestBalanceInfo = await this.balanceManager.getTokenBalance(
4524
+ token,
4525
+ baseUrl
4526
+ );
4527
+ this._log(
4528
+ "DEBUG",
4529
+ "LATEST Balance",
4530
+ latestBalanceInfo.amount,
4531
+ latestBalanceInfo.reserved,
4532
+ latestBalanceInfo.apiKey,
4533
+ baseUrl
4534
+ );
4535
+ const latestTokenBalance = latestBalanceInfo.unit === "msat" ? latestBalanceInfo.amount / 1e3 : latestBalanceInfo.amount;
4536
+ const storedApiKeyEntry = this.storageAdapter.getApiKey(baseUrl);
4537
+ if (storedApiKeyEntry?.key.startsWith("cashu") && latestBalanceInfo.apiKey) {
4538
+ this.storageAdapter.removeApiKey(baseUrl);
4539
+ this.storageAdapter.setApiKey(baseUrl, latestBalanceInfo.apiKey);
4540
+ }
4541
+ this.storageAdapter.updateApiKeyBalance(baseUrl, latestTokenBalance);
4542
+ satsSpent = initialTokenBalance - latestTokenBalance;
4543
+ } catch (e) {
4544
+ this._log("WARN", "Could not get updated API key balance:", e);
4545
+ satsSpent = fallbackSatsSpent ?? initialTokenBalance;
4546
+ }
4547
+ }
4548
+ await this._trackResponseUsage({
4549
+ token,
4550
+ baseUrl,
4551
+ response,
4552
+ modelId,
4553
+ satsSpent,
4554
+ usage,
4555
+ requestId,
4556
+ clientApiKey
4557
+ });
4558
+ (async () => {
4559
+ })();
4560
+ return satsSpent;
4561
+ }
4562
+ async _trackResponseUsage(params) {
4563
+ const {
4564
+ token,
4565
+ baseUrl,
4566
+ response,
4567
+ modelId,
4568
+ satsSpent,
4569
+ usage: providedUsage,
4570
+ requestId: providedRequestId,
4571
+ clientApiKey
4572
+ } = params;
4573
+ if (!response || !modelId) {
4574
+ return;
4575
+ }
4576
+ try {
4577
+ let usage = providedUsage;
4578
+ let requestId = providedRequestId;
4579
+ if (!usage || !requestId) {
4580
+ const contentType = response.headers.get("content-type") || "";
4581
+ if (contentType.includes("text/event-stream")) {
4582
+ usage = usage ?? response.usage;
4583
+ requestId = requestId ?? response.requestId ?? response.headers.get("x-routstr-request-id") ?? void 0;
4584
+ if (!usage) {
4585
+ return;
4586
+ }
4587
+ } else {
4588
+ const cloned = response.clone();
4589
+ const responseBody = await cloned.json();
4590
+ usage = usage ?? extractUsageFromResponseBody(responseBody, satsSpent) ?? void 0;
4591
+ requestId = requestId ?? extractResponseId(responseBody) ?? response.headers.get("x-routstr-request-id") ?? void 0;
4592
+ }
4593
+ }
4594
+ if (!usage) {
4595
+ return;
4596
+ }
4597
+ const finalRequestId = requestId || "unknown";
4598
+ const store = this.sdkStore ?? await getDefaultSdkStore();
4599
+ const state = store.getState();
4600
+ const matchKey = clientApiKey ?? token;
4601
+ const matchingClient = state.clientIds.find(
4602
+ (client) => client.apiKey === matchKey
4603
+ );
4604
+ const entryId = finalRequestId === "unknown" ? `req-${Date.now()}-${modelId}` : finalRequestId;
4605
+ const usageTracking = this.usageTrackingDriver ?? getDefaultUsageTrackingDriver();
4606
+ const entry = {
4607
+ id: entryId,
4608
+ timestamp: Date.now(),
4609
+ modelId,
4610
+ baseUrl,
4611
+ requestId: finalRequestId,
4612
+ client: matchingClient?.clientId,
4613
+ ...usage
4614
+ };
4615
+ if (this.mode === "xcashu") {
4616
+ entry.satsCost = satsSpent;
4617
+ }
4618
+ await usageTracking.append(entry);
4619
+ } catch (error) {
4620
+ }
4621
+ }
4622
+ /**
4623
+ * Convert messages for API format
4624
+ */
4625
+ async _convertMessages(messages) {
4626
+ return Promise.all(
4627
+ messages.filter((m) => m.role !== "system").map(async (m) => ({
4628
+ role: m.role,
4629
+ content: typeof m.content === "string" ? m.content : m.content
4630
+ }))
4631
+ );
4632
+ }
4633
+ /**
4634
+ * Create assistant message from streaming result
4635
+ */
4636
+ async _createAssistantMessage(result) {
4637
+ if (result.images && result.images.length > 0) {
4638
+ const content = [];
4639
+ if (result.content) {
4640
+ content.push({
4641
+ type: "text",
4642
+ text: result.content,
4643
+ thinking: result.thinking,
4644
+ citations: result.citations,
4645
+ annotations: result.annotations
4646
+ });
4647
+ }
4648
+ for (const img of result.images) {
4649
+ content.push({
4650
+ type: "image_url",
4651
+ image_url: {
4652
+ url: img.image_url.url
4653
+ }
4654
+ });
4655
+ }
4656
+ return {
4657
+ role: "assistant",
4658
+ content
4659
+ };
4660
+ }
4661
+ return {
4662
+ role: "assistant",
4663
+ content: result.content || ""
4664
+ };
4665
+ }
4666
+ /**
4667
+ * Calculate estimated costs from usage
4668
+ */
4669
+ _getEstimatedCosts(selectedModel, streamingResult) {
4670
+ let estimatedCosts = 0;
4671
+ if (streamingResult.usage) {
4672
+ const { completion_tokens, prompt_tokens } = streamingResult.usage;
4673
+ if (completion_tokens !== void 0 && prompt_tokens !== void 0) {
4674
+ estimatedCosts = (selectedModel.sats_pricing?.completion ?? 0) * completion_tokens + (selectedModel.sats_pricing?.prompt ?? 0) * prompt_tokens;
4675
+ }
4676
+ }
4677
+ return estimatedCosts;
4678
+ }
4679
+ /**
4680
+ * Get pending API key amount
4681
+ */
4682
+ _getPendingCashuTokenAmount() {
4683
+ const apiKeyDistribution = this.storageAdapter.getApiKeyDistribution();
4684
+ return apiKeyDistribution.reduce((total, item) => total + item.amount, 0);
4685
+ }
4686
+ /**
4687
+ * Handle errors and notify callbacks
4688
+ */
4689
+ _handleError(error, callbacks) {
4690
+ this._log("ERROR", "[RoutstrClient] _handleError: Error occurred", error);
4691
+ if (error instanceof Error) {
4692
+ const isStreamError = error.message.includes("Error in input stream") || error.message.includes("Load failed");
4693
+ const modifiedErrorMsg = isStreamError ? "AI stream was cut off, turn on Keep Active or please try again" : error.message;
4694
+ this._log(
4695
+ "ERROR",
4696
+ `[RoutstrClient] _handleError: Error type=${error.constructor.name}, message=${modifiedErrorMsg}, isStreamError=${isStreamError}`
4697
+ );
4698
+ callbacks.onMessageAppend({
4699
+ role: "system",
4700
+ content: "Uncaught Error: " + modifiedErrorMsg + (this.alertLevel === "max" ? " | " + error.stack : "")
4701
+ });
4702
+ } else {
4703
+ callbacks.onMessageAppend({
4704
+ role: "system",
4705
+ content: "Unknown Error: Please tag Routstr on Nostr and/or retry."
4706
+ });
4707
+ }
4708
+ }
4709
+ /**
4710
+ * Check wallet balance and throw if insufficient
4711
+ */
4712
+ async _checkBalance() {
4713
+ const balances = await this.walletAdapter.getBalances();
4714
+ const totalBalance = Object.values(balances).reduce((sum, v) => sum + v, 0);
4715
+ if (totalBalance <= 0) {
4716
+ throw new InsufficientBalanceError(1, 0);
4717
+ }
4718
+ }
4719
+ /**
4720
+ * Spend a token using CashuSpender with standardized error handling
4721
+ */
4722
+ async _spendToken(params) {
4723
+ const { mintUrl, amount, baseUrl } = params;
4724
+ this._log(
4725
+ "DEBUG",
4726
+ `[RoutstrClient] _spendToken: mode=${this.mode}, amount=${amount}, baseUrl=${baseUrl}, mintUrl=${mintUrl}`
4727
+ );
4728
+ if (this.mode === "apikeys") {
4729
+ let parentApiKey = this.storageAdapter.getApiKey(baseUrl);
4730
+ if (!parentApiKey) {
4731
+ this._log(
4732
+ "DEBUG",
4733
+ `[RoutstrClient] _spendToken: No existing API key for ${baseUrl}, creating new one via Cashu`
4734
+ );
4735
+ const spendResult2 = await this.cashuSpender.spend({
4736
+ mintUrl,
4737
+ amount: amount * TOPUP_MARGIN,
4738
+ baseUrl: "",
4739
+ reuseToken: false
4740
+ });
4741
+ if (!spendResult2.token) {
4742
+ this._log(
4743
+ "ERROR",
4744
+ `[RoutstrClient] _spendToken: Failed to create Cashu token for API key creation, error:`,
4745
+ spendResult2.error
4746
+ );
4747
+ throw new Error(
4748
+ `[RoutstrClient] _spendToken: Failed to create Cashu token for API key creation, error: ${spendResult2.error}`
4749
+ );
4750
+ } else {
4751
+ this._log(
4752
+ "DEBUG",
4753
+ `[RoutstrClient] _spendToken: Cashu token created, token preview: ${spendResult2.token}`
4754
+ );
4755
+ }
4756
+ this._log(
4757
+ "DEBUG",
4758
+ `[RoutstrClient] _spendToken: Created API key for ${baseUrl}, key preview: ${spendResult2.token}, balance: ${spendResult2.balance}`
4759
+ );
4760
+ try {
4761
+ this.storageAdapter.setApiKey(baseUrl, spendResult2.token);
4762
+ } catch (error) {
4763
+ if (error instanceof Error && error.message.includes("ApiKey already exists")) {
4764
+ const receiveResult = await this.cashuSpender.receiveToken(
4765
+ spendResult2.token
4766
+ );
4767
+ if (receiveResult.success) {
4768
+ this._log(
4769
+ "DEBUG",
4770
+ `[RoutstrClient] _handleErrorResponse: Token restored successfully, amount=${receiveResult.amount}`
4771
+ );
4772
+ } else {
4773
+ this._log(
4774
+ "DEBUG",
4775
+ `[RoutstrClient] _handleErrorResponse: Token restore failed: ${receiveResult.message}`
4776
+ );
4777
+ }
4778
+ this._log(
4779
+ "DEBUG",
4780
+ `[RoutstrClient] _spendToken: API key already exists for ${baseUrl}, using existing key`
4781
+ );
4782
+ } else {
4783
+ throw error;
4784
+ }
4785
+ }
4786
+ parentApiKey = this.storageAdapter.getApiKey(baseUrl);
4787
+ } else {
4788
+ this._log(
4789
+ "DEBUG",
4790
+ `[RoutstrClient] _spendToken: Using existing API key for ${baseUrl}, key preview: ${parentApiKey.key}`
4791
+ );
4792
+ }
4793
+ let tokenBalance = 0;
4794
+ let tokenBalanceUnit = "sat";
4795
+ const apiKeyDistribution = this.storageAdapter.getApiKeyDistribution();
4796
+ const distributionForBaseUrl = apiKeyDistribution.find(
4797
+ (d) => d.baseUrl === baseUrl
4798
+ );
4799
+ if (distributionForBaseUrl) {
4800
+ tokenBalance = distributionForBaseUrl.amount;
4801
+ }
4802
+ if (tokenBalance === 0 && parentApiKey) {
4803
+ try {
4804
+ const balanceInfo = await this.balanceManager.getTokenBalance(
4805
+ parentApiKey.key,
4806
+ baseUrl
4807
+ );
4808
+ tokenBalance = balanceInfo.amount;
4809
+ tokenBalanceUnit = balanceInfo.unit;
4810
+ } catch (e) {
4811
+ this._log("WARN", "Could not get initial API key balance:", e);
4812
+ }
4813
+ }
4814
+ this._log(
4815
+ "DEBUG",
4816
+ `[RoutstrClient] _spendToken: Returning token with balance=${tokenBalance} ${tokenBalanceUnit}`
4817
+ );
4818
+ return {
4819
+ token: parentApiKey?.key ?? "",
4820
+ tokenBalance,
4821
+ tokenBalanceUnit
4822
+ };
4823
+ }
4824
+ this._log(
4825
+ "DEBUG",
4826
+ `[RoutstrClient] _spendToken: Calling CashuSpender.spend for amount=${amount}, mintUrl=${mintUrl}, mode=${this.mode}`
4827
+ );
4828
+ const spendResult = await this.cashuSpender.spend({
4829
+ mintUrl,
4830
+ amount,
4831
+ baseUrl: "",
4832
+ reuseToken: false
4833
+ });
4834
+ if (!spendResult.token) {
4835
+ this._log(
4836
+ "ERROR",
4837
+ `[RoutstrClient] _spendToken: CashuSpender.spend failed, error:`,
4838
+ spendResult.error
4839
+ );
4840
+ } else {
4841
+ this._log(
4842
+ "DEBUG",
4843
+ `[RoutstrClient] _spendToken: Cashu token created, token preview: ${spendResult.token}, balance: ${spendResult.balance} ${spendResult.unit ?? "sat"}`
4844
+ );
4845
+ this.storageAdapter.addXcashuToken(baseUrl, spendResult.token);
4846
+ }
4847
+ return {
4848
+ token: spendResult.token,
4849
+ tokenBalance: spendResult.balance,
4850
+ tokenBalanceUnit: spendResult.unit ?? "sat"
4851
+ };
4852
+ }
4853
+ /**
4854
+ * Build request headers with common defaults and dev mock controls
4855
+ */
4856
+ _buildBaseHeaders(additionalHeaders = {}, token) {
4857
+ const headers = {
4858
+ ...additionalHeaders,
4859
+ "Content-Type": "application/json"
4860
+ };
4861
+ return headers;
4862
+ }
4863
+ /**
4864
+ * Attach auth headers using the active client mode
4865
+ */
4866
+ _withAuthHeader(headers, token) {
4867
+ const nextHeaders = { ...headers };
4868
+ if (this.mode === "xcashu") {
4869
+ nextHeaders["X-Cashu"] = token;
4870
+ } else {
4871
+ nextHeaders["Authorization"] = `Bearer ${token}`;
4872
+ }
4873
+ return nextHeaders;
4874
+ }
4875
+ };
4876
+
4877
+ exports.ProviderManager = ProviderManager;
4878
+ exports.RoutstrClient = RoutstrClient;
4879
+ exports.StreamProcessor = StreamProcessor;
4880
+ exports.createSSEParserTransform = createSSEParserTransform;
4881
+ exports.inspectSSEWebStream = inspectSSEWebStream;
4882
+ //# sourceMappingURL=index.js.map
4883
+ //# sourceMappingURL=index.js.map