@routstr/sdk 0.3.6 → 0.3.7

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