@routstr/sdk 0.3.7 → 0.3.9

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