@routstr/sdk 0.1.0 → 0.1.2

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.
@@ -0,0 +1,293 @@
1
+ import { M as Model, a as Message, T as TransactionHistory, l as StreamingResult } from '../types-BlHjmWRK.mjs';
2
+ import { P as ProviderRegistry, W as WalletAdapter, S as StorageAdapter, a as StreamingCallbacks } from '../interfaces-B85Wx7ni.mjs';
3
+ import { CashuSpender, BalanceManager } from '../wallet/index.mjs';
4
+
5
+ /**
6
+ * ProviderManager - Handles provider selection and failover logic
7
+ *
8
+ * Handles:
9
+ * - Finding the best provider for a model based on price
10
+ * - Provider failover when errors occur
11
+ * - Tracking failed providers to avoid retry loops
12
+ * - Provider version compatibility
13
+ *
14
+ * Extracted from utils/apiUtils.ts findNextBestProvider and related logic
15
+ */
16
+
17
+ interface ModelProviderPrice {
18
+ baseUrl: string;
19
+ model: Model;
20
+ promptPerMillion: number;
21
+ completionPerMillion: number;
22
+ totalPerMillion: number;
23
+ }
24
+ declare class ProviderManager {
25
+ private providerRegistry;
26
+ private failedProviders;
27
+ constructor(providerRegistry: ProviderRegistry);
28
+ /**
29
+ * Reset the failed providers list
30
+ */
31
+ resetFailedProviders(): void;
32
+ /**
33
+ * Mark a provider as failed
34
+ */
35
+ markFailed(baseUrl: string): void;
36
+ /**
37
+ * Check if a provider has failed
38
+ */
39
+ hasFailed(baseUrl: string): boolean;
40
+ /**
41
+ * Find the next best provider for a model
42
+ * @param modelId The model ID to find a provider for
43
+ * @param currentBaseUrl The current provider to exclude
44
+ * @returns The best provider URL or null if none available
45
+ */
46
+ findNextBestProvider(modelId: string, currentBaseUrl: string): string | null;
47
+ /**
48
+ * Find the best model for a provider
49
+ * Useful when switching providers and need to find equivalent model
50
+ */
51
+ getModelForProvider(baseUrl: string, modelId: string): Promise<Model | null>;
52
+ /**
53
+ * Get all available providers for a model
54
+ * Returns sorted list by price
55
+ */
56
+ getAllProvidersForModel(modelId: string): Array<{
57
+ baseUrl: string;
58
+ model: Model;
59
+ cost: number;
60
+ }>;
61
+ /**
62
+ * Get providers for a model sorted by prompt+completion pricing
63
+ */
64
+ getProviderPriceRankingForModel(modelId: string, options?: {
65
+ torMode?: boolean;
66
+ includeDisabled?: boolean;
67
+ }): ModelProviderPrice[];
68
+ /**
69
+ * Get best-priced provider for a specific model
70
+ */
71
+ getBestProviderForModel(modelId: string, options?: {
72
+ torMode?: boolean;
73
+ includeDisabled?: boolean;
74
+ }): string | null;
75
+ private normalizeModelId;
76
+ /**
77
+ * Check if a provider accepts a specific mint
78
+ */
79
+ providerAcceptsMint(baseUrl: string, mintUrl: string): boolean;
80
+ /**
81
+ * Get required sats for a model based on message history
82
+ * Simple estimation based on typical usage
83
+ */
84
+ getRequiredSatsForModel(model: Model, apiMessages: any[], maxTokens?: number): number;
85
+ }
86
+
87
+ /**
88
+ * RoutstrClient - Main API client for Routstr
89
+ *
90
+ * Orchestrates:
91
+ * - Token spending via CashuSpender
92
+ * - API requests with authentication
93
+ * - Streaming response processing
94
+ * - Provider failover via ProviderManager
95
+ * - Error handling and refunds
96
+ *
97
+ * Extracted from utils/apiUtils.ts
98
+ */
99
+
100
+ /**
101
+ * Options for fetching AI response
102
+ */
103
+ interface FetchOptions {
104
+ messageHistory: Message[];
105
+ selectedModel: Model;
106
+ baseUrl: string;
107
+ mintUrl: string;
108
+ balance: number;
109
+ transactionHistory: TransactionHistory[];
110
+ maxTokens?: number;
111
+ headers?: Record<string, string>;
112
+ }
113
+ /**
114
+ * RoutstrClient is the main SDK entry point
115
+ */
116
+ type AlertLevel = "max" | "min";
117
+ type RoutstrClientMode = "xcashu" | "lazyrefund" | "apikeys";
118
+ type DebugLevel = "DEBUG" | "WARN" | "ERROR";
119
+ interface RouteRequestParams {
120
+ path: string;
121
+ method: string;
122
+ body?: unknown;
123
+ headers?: Record<string, string>;
124
+ baseUrl: string;
125
+ mintUrl: string;
126
+ modelId?: string;
127
+ }
128
+ declare class RoutstrClient {
129
+ private walletAdapter;
130
+ private storageAdapter;
131
+ private providerRegistry;
132
+ private cashuSpender;
133
+ private balanceManager;
134
+ private streamProcessor;
135
+ private providerManager;
136
+ private alertLevel;
137
+ private mode;
138
+ private debugLevel;
139
+ constructor(walletAdapter: WalletAdapter, storageAdapter: StorageAdapter, providerRegistry: ProviderRegistry, alertLevel: AlertLevel, mode?: RoutstrClientMode);
140
+ /**
141
+ * Get the current client mode
142
+ */
143
+ getMode(): RoutstrClientMode;
144
+ getDebugLevel(): DebugLevel;
145
+ setDebugLevel(level: DebugLevel): void;
146
+ private _log;
147
+ /**
148
+ * Get the CashuSpender instance
149
+ */
150
+ getCashuSpender(): CashuSpender;
151
+ /**
152
+ * Get the BalanceManager instance
153
+ */
154
+ getBalanceManager(): BalanceManager;
155
+ /**
156
+ * Get the ProviderManager instance
157
+ */
158
+ getProviderManager(): ProviderManager;
159
+ /**
160
+ * Check if the client is currently busy (in critical section)
161
+ */
162
+ get isBusy(): boolean;
163
+ /**
164
+ * Route an API request to the upstream provider
165
+ *
166
+ * This is a simpler alternative to fetchAIResponse that just proxies
167
+ * the request upstream without the streaming callback machinery.
168
+ * Useful for daemon-style routing where you just need to forward
169
+ * requests and get responses back.
170
+ */
171
+ routeRequest(params: RouteRequestParams): Promise<Response>;
172
+ /**
173
+ * Fetch AI response with streaming
174
+ */
175
+ fetchAIResponse(options: FetchOptions, callbacks: StreamingCallbacks): Promise<void>;
176
+ /**
177
+ * Make the API request with failover support
178
+ */
179
+ private _makeRequest;
180
+ /**
181
+ * Handle error responses with failover
182
+ */
183
+ private _handleErrorResponse;
184
+ /**
185
+ * Handle post-response balance update for all modes
186
+ */
187
+ private _handlePostResponseBalanceUpdate;
188
+ /**
189
+ * Convert messages for API format
190
+ */
191
+ private _convertMessages;
192
+ /**
193
+ * Create assistant message from streaming result
194
+ */
195
+ private _createAssistantMessage;
196
+ /**
197
+ * Create a child key for a parent API key via the provider's API
198
+ * POST /v1/balance/child-key
199
+ */
200
+ private _createChildKey;
201
+ /**
202
+ * Calculate estimated costs from usage
203
+ */
204
+ private _getEstimatedCosts;
205
+ /**
206
+ * Get pending cashu token amount
207
+ */
208
+ private _getPendingCashuTokenAmount;
209
+ /**
210
+ * Check if error message indicates a network error
211
+ */
212
+ private _isNetworkError;
213
+ /**
214
+ * Handle errors and notify callbacks
215
+ */
216
+ private _handleError;
217
+ /**
218
+ * Check wallet balance and throw if insufficient
219
+ */
220
+ private _checkBalance;
221
+ /**
222
+ * Spend a token using CashuSpender with standardized error handling
223
+ */
224
+ private _spendToken;
225
+ /**
226
+ * Build request headers with common defaults and dev mock controls
227
+ */
228
+ private _buildBaseHeaders;
229
+ /**
230
+ * Attach auth headers using the active client mode
231
+ */
232
+ private _withAuthHeader;
233
+ }
234
+
235
+ /**
236
+ * StreamProcessor - Handles SSE streaming response parsing
237
+ *
238
+ * Handles:
239
+ * - Line buffering for large payloads
240
+ * - Content extraction from delta chunks
241
+ * - Thinking/reasoning block extraction
242
+ * - Image data merging and deduplication
243
+ * - Usage statistics extraction
244
+ * - Citations and annotations
245
+ *
246
+ * Extracted from utils/apiUtils.ts processStreamingResponse
247
+ */
248
+
249
+ /**
250
+ * Callbacks for streaming updates
251
+ */
252
+ interface StreamCallbacks {
253
+ /** Called when new content arrives */
254
+ onContent: (content: string) => void;
255
+ /** Called when thinking content arrives */
256
+ onThinking: (thinking: string) => void;
257
+ }
258
+ /**
259
+ * StreamProcessor parses SSE streaming responses
260
+ */
261
+ declare class StreamProcessor {
262
+ private accumulatedContent;
263
+ private accumulatedThinking;
264
+ private accumulatedImages;
265
+ private isInThinking;
266
+ private isInContent;
267
+ /**
268
+ * Process a streaming response
269
+ */
270
+ process(response: Response, callbacks: StreamCallbacks, modelId?: string): Promise<StreamingResult>;
271
+ /**
272
+ * Parse a single SSE line
273
+ */
274
+ private _parseLine;
275
+ /**
276
+ * Handle content delta with thinking support
277
+ */
278
+ private _handleContent;
279
+ /**
280
+ * Handle thinking/reasoning content
281
+ */
282
+ private _handleThinking;
283
+ /**
284
+ * Extract thinking blocks from content (for models with inline thinking)
285
+ */
286
+ private _extractThinkingFromContent;
287
+ /**
288
+ * Merge images into accumulated array, avoiding duplicates
289
+ */
290
+ private _mergeImages;
291
+ }
292
+
293
+ export { type AlertLevel, type DebugLevel, type FetchOptions, type ModelProviderPrice, ProviderManager, type RouteRequestParams, RoutstrClient, type RoutstrClientMode, type StreamCallbacks, StreamProcessor };
@@ -0,0 +1,293 @@
1
+ import { M as Model, a as Message, T as TransactionHistory, l as StreamingResult } from '../types-BlHjmWRK.js';
2
+ import { P as ProviderRegistry, W as WalletAdapter, S as StorageAdapter, a as StreamingCallbacks } from '../interfaces-BVNyAmKu.js';
3
+ import { CashuSpender, BalanceManager } from '../wallet/index.js';
4
+
5
+ /**
6
+ * ProviderManager - Handles provider selection and failover logic
7
+ *
8
+ * Handles:
9
+ * - Finding the best provider for a model based on price
10
+ * - Provider failover when errors occur
11
+ * - Tracking failed providers to avoid retry loops
12
+ * - Provider version compatibility
13
+ *
14
+ * Extracted from utils/apiUtils.ts findNextBestProvider and related logic
15
+ */
16
+
17
+ interface ModelProviderPrice {
18
+ baseUrl: string;
19
+ model: Model;
20
+ promptPerMillion: number;
21
+ completionPerMillion: number;
22
+ totalPerMillion: number;
23
+ }
24
+ declare class ProviderManager {
25
+ private providerRegistry;
26
+ private failedProviders;
27
+ constructor(providerRegistry: ProviderRegistry);
28
+ /**
29
+ * Reset the failed providers list
30
+ */
31
+ resetFailedProviders(): void;
32
+ /**
33
+ * Mark a provider as failed
34
+ */
35
+ markFailed(baseUrl: string): void;
36
+ /**
37
+ * Check if a provider has failed
38
+ */
39
+ hasFailed(baseUrl: string): boolean;
40
+ /**
41
+ * Find the next best provider for a model
42
+ * @param modelId The model ID to find a provider for
43
+ * @param currentBaseUrl The current provider to exclude
44
+ * @returns The best provider URL or null if none available
45
+ */
46
+ findNextBestProvider(modelId: string, currentBaseUrl: string): string | null;
47
+ /**
48
+ * Find the best model for a provider
49
+ * Useful when switching providers and need to find equivalent model
50
+ */
51
+ getModelForProvider(baseUrl: string, modelId: string): Promise<Model | null>;
52
+ /**
53
+ * Get all available providers for a model
54
+ * Returns sorted list by price
55
+ */
56
+ getAllProvidersForModel(modelId: string): Array<{
57
+ baseUrl: string;
58
+ model: Model;
59
+ cost: number;
60
+ }>;
61
+ /**
62
+ * Get providers for a model sorted by prompt+completion pricing
63
+ */
64
+ getProviderPriceRankingForModel(modelId: string, options?: {
65
+ torMode?: boolean;
66
+ includeDisabled?: boolean;
67
+ }): ModelProviderPrice[];
68
+ /**
69
+ * Get best-priced provider for a specific model
70
+ */
71
+ getBestProviderForModel(modelId: string, options?: {
72
+ torMode?: boolean;
73
+ includeDisabled?: boolean;
74
+ }): string | null;
75
+ private normalizeModelId;
76
+ /**
77
+ * Check if a provider accepts a specific mint
78
+ */
79
+ providerAcceptsMint(baseUrl: string, mintUrl: string): boolean;
80
+ /**
81
+ * Get required sats for a model based on message history
82
+ * Simple estimation based on typical usage
83
+ */
84
+ getRequiredSatsForModel(model: Model, apiMessages: any[], maxTokens?: number): number;
85
+ }
86
+
87
+ /**
88
+ * RoutstrClient - Main API client for Routstr
89
+ *
90
+ * Orchestrates:
91
+ * - Token spending via CashuSpender
92
+ * - API requests with authentication
93
+ * - Streaming response processing
94
+ * - Provider failover via ProviderManager
95
+ * - Error handling and refunds
96
+ *
97
+ * Extracted from utils/apiUtils.ts
98
+ */
99
+
100
+ /**
101
+ * Options for fetching AI response
102
+ */
103
+ interface FetchOptions {
104
+ messageHistory: Message[];
105
+ selectedModel: Model;
106
+ baseUrl: string;
107
+ mintUrl: string;
108
+ balance: number;
109
+ transactionHistory: TransactionHistory[];
110
+ maxTokens?: number;
111
+ headers?: Record<string, string>;
112
+ }
113
+ /**
114
+ * RoutstrClient is the main SDK entry point
115
+ */
116
+ type AlertLevel = "max" | "min";
117
+ type RoutstrClientMode = "xcashu" | "lazyrefund" | "apikeys";
118
+ type DebugLevel = "DEBUG" | "WARN" | "ERROR";
119
+ interface RouteRequestParams {
120
+ path: string;
121
+ method: string;
122
+ body?: unknown;
123
+ headers?: Record<string, string>;
124
+ baseUrl: string;
125
+ mintUrl: string;
126
+ modelId?: string;
127
+ }
128
+ declare class RoutstrClient {
129
+ private walletAdapter;
130
+ private storageAdapter;
131
+ private providerRegistry;
132
+ private cashuSpender;
133
+ private balanceManager;
134
+ private streamProcessor;
135
+ private providerManager;
136
+ private alertLevel;
137
+ private mode;
138
+ private debugLevel;
139
+ constructor(walletAdapter: WalletAdapter, storageAdapter: StorageAdapter, providerRegistry: ProviderRegistry, alertLevel: AlertLevel, mode?: RoutstrClientMode);
140
+ /**
141
+ * Get the current client mode
142
+ */
143
+ getMode(): RoutstrClientMode;
144
+ getDebugLevel(): DebugLevel;
145
+ setDebugLevel(level: DebugLevel): void;
146
+ private _log;
147
+ /**
148
+ * Get the CashuSpender instance
149
+ */
150
+ getCashuSpender(): CashuSpender;
151
+ /**
152
+ * Get the BalanceManager instance
153
+ */
154
+ getBalanceManager(): BalanceManager;
155
+ /**
156
+ * Get the ProviderManager instance
157
+ */
158
+ getProviderManager(): ProviderManager;
159
+ /**
160
+ * Check if the client is currently busy (in critical section)
161
+ */
162
+ get isBusy(): boolean;
163
+ /**
164
+ * Route an API request to the upstream provider
165
+ *
166
+ * This is a simpler alternative to fetchAIResponse that just proxies
167
+ * the request upstream without the streaming callback machinery.
168
+ * Useful for daemon-style routing where you just need to forward
169
+ * requests and get responses back.
170
+ */
171
+ routeRequest(params: RouteRequestParams): Promise<Response>;
172
+ /**
173
+ * Fetch AI response with streaming
174
+ */
175
+ fetchAIResponse(options: FetchOptions, callbacks: StreamingCallbacks): Promise<void>;
176
+ /**
177
+ * Make the API request with failover support
178
+ */
179
+ private _makeRequest;
180
+ /**
181
+ * Handle error responses with failover
182
+ */
183
+ private _handleErrorResponse;
184
+ /**
185
+ * Handle post-response balance update for all modes
186
+ */
187
+ private _handlePostResponseBalanceUpdate;
188
+ /**
189
+ * Convert messages for API format
190
+ */
191
+ private _convertMessages;
192
+ /**
193
+ * Create assistant message from streaming result
194
+ */
195
+ private _createAssistantMessage;
196
+ /**
197
+ * Create a child key for a parent API key via the provider's API
198
+ * POST /v1/balance/child-key
199
+ */
200
+ private _createChildKey;
201
+ /**
202
+ * Calculate estimated costs from usage
203
+ */
204
+ private _getEstimatedCosts;
205
+ /**
206
+ * Get pending cashu token amount
207
+ */
208
+ private _getPendingCashuTokenAmount;
209
+ /**
210
+ * Check if error message indicates a network error
211
+ */
212
+ private _isNetworkError;
213
+ /**
214
+ * Handle errors and notify callbacks
215
+ */
216
+ private _handleError;
217
+ /**
218
+ * Check wallet balance and throw if insufficient
219
+ */
220
+ private _checkBalance;
221
+ /**
222
+ * Spend a token using CashuSpender with standardized error handling
223
+ */
224
+ private _spendToken;
225
+ /**
226
+ * Build request headers with common defaults and dev mock controls
227
+ */
228
+ private _buildBaseHeaders;
229
+ /**
230
+ * Attach auth headers using the active client mode
231
+ */
232
+ private _withAuthHeader;
233
+ }
234
+
235
+ /**
236
+ * StreamProcessor - Handles SSE streaming response parsing
237
+ *
238
+ * Handles:
239
+ * - Line buffering for large payloads
240
+ * - Content extraction from delta chunks
241
+ * - Thinking/reasoning block extraction
242
+ * - Image data merging and deduplication
243
+ * - Usage statistics extraction
244
+ * - Citations and annotations
245
+ *
246
+ * Extracted from utils/apiUtils.ts processStreamingResponse
247
+ */
248
+
249
+ /**
250
+ * Callbacks for streaming updates
251
+ */
252
+ interface StreamCallbacks {
253
+ /** Called when new content arrives */
254
+ onContent: (content: string) => void;
255
+ /** Called when thinking content arrives */
256
+ onThinking: (thinking: string) => void;
257
+ }
258
+ /**
259
+ * StreamProcessor parses SSE streaming responses
260
+ */
261
+ declare class StreamProcessor {
262
+ private accumulatedContent;
263
+ private accumulatedThinking;
264
+ private accumulatedImages;
265
+ private isInThinking;
266
+ private isInContent;
267
+ /**
268
+ * Process a streaming response
269
+ */
270
+ process(response: Response, callbacks: StreamCallbacks, modelId?: string): Promise<StreamingResult>;
271
+ /**
272
+ * Parse a single SSE line
273
+ */
274
+ private _parseLine;
275
+ /**
276
+ * Handle content delta with thinking support
277
+ */
278
+ private _handleContent;
279
+ /**
280
+ * Handle thinking/reasoning content
281
+ */
282
+ private _handleThinking;
283
+ /**
284
+ * Extract thinking blocks from content (for models with inline thinking)
285
+ */
286
+ private _extractThinkingFromContent;
287
+ /**
288
+ * Merge images into accumulated array, avoiding duplicates
289
+ */
290
+ private _mergeImages;
291
+ }
292
+
293
+ export { type AlertLevel, type DebugLevel, type FetchOptions, type ModelProviderPrice, ProviderManager, type RouteRequestParams, RoutstrClient, type RoutstrClientMode, type StreamCallbacks, StreamProcessor };