@mixrpay/agent-sdk 0.8.8 → 0.9.5

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.
package/dist/index.d.cts CHANGED
@@ -1,356 +1,131 @@
1
1
  /**
2
- * MixrPay Agent SDK - Type definitions
3
- *
4
- * This file contains all TypeScript types and interfaces used throughout the SDK.
5
- */
6
- /**
7
- * Configuration options for AgentWallet.
8
- *
9
- * @example Minimal configuration
10
- * ```typescript
11
- * const config: AgentWalletConfig = {
12
- * sessionKey: 'sk_live_abc123...'
13
- * };
14
- * ```
15
- *
16
- * @example Full configuration
17
- * ```typescript
18
- * const config: AgentWalletConfig = {
19
- * sessionKey: 'sk_live_abc123...',
20
- * maxPaymentUsd: 5.0,
21
- * onPayment: (p) => console.log(`Paid $${p.amountUsd}`),
22
- * logLevel: 'info',
23
- * timeout: 60000,
24
- * };
25
- * ```
2
+ * @packageDocumentation
26
3
  */
27
4
  interface AgentWalletConfig {
28
- /**
29
- * Session key granted by the wallet owner.
30
- *
31
- * Format: `sk_live_` (mainnet) or `sk_test_` (testnet) followed by 64 hex characters.
32
- *
33
- * Get session keys from:
34
- * - The wallet owner at https://mixrpay.com/manage/invites
35
- * - Programmatically via the MixrPay API
36
- *
37
- * @example 'sk_live_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'
38
- */
5
+ /** Session key (sk_live_ or sk_test_ prefix). */
39
6
  sessionKey: string;
40
- /**
41
- * Optional smart wallet address.
42
- *
43
- * If not provided, will be derived from the session key.
44
- * Only needed in advanced scenarios where the session key address
45
- * differs from the wallet address.
46
- */
7
+ /** Override wallet address. */
47
8
  walletAddress?: string;
48
- /**
49
- * Optional client-side maximum payment per request in USD.
50
- *
51
- * This is an additional safety limit on the client side, independent
52
- * of the session key's limits. Useful for preventing accidental
53
- * large payments due to bugs or misconfiguration.
54
- *
55
- * @example 5.0 - Maximum $5 per request
56
- */
9
+ /** Client-side max payment per request in USD. */
57
10
  maxPaymentUsd?: number;
58
- /**
59
- * Optional callback when a payment is successfully made.
60
- *
61
- * Use this to track payments in your application, update UI,
62
- * or log payment events.
63
- *
64
- * @example
65
- * ```typescript
66
- * onPayment: (payment) => {
67
- * console.log(`Paid $${payment.amountUsd} for ${payment.description}`);
68
- * analytics.track('payment', payment);
69
- * }
70
- * ```
71
- */
11
+ /** Payment event callback. */
72
12
  onPayment?: (payment: PaymentEvent) => void;
73
- /**
74
- * x402 facilitator endpoint.
75
- *
76
- * The facilitator processes the payment and forwards the request.
77
- * Default: 'https://x402.org/facilitator'
78
- */
13
+ /** Override facilitator URL. */
79
14
  facilitatorUrl?: string;
80
- /**
81
- * MixrPay API base URL.
82
- *
83
- * Default: 'http://localhost:3000' (or MIXRPAY_BASE_URL env var)
84
- */
15
+ /** Override API base URL. */
85
16
  baseUrl?: string;
86
- /**
87
- * Request timeout in milliseconds.
88
- *
89
- * Default: 30000 (30 seconds)
90
- */
17
+ /** Request timeout in ms (default: 30000). */
91
18
  timeout?: number;
92
- /**
93
- * Log level for SDK operations.
94
- *
95
- * - 'debug': Verbose logging for development
96
- * - 'info': Important events (payments, etc.)
97
- * - 'warn': Warnings only
98
- * - 'error': Errors only
99
- * - 'none': No logging (default)
100
- *
101
- * @example 'info' - Log payments and important events
102
- */
19
+ /** Log level (default: 'none'). */
103
20
  logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'none';
21
+ /** Agent API key (agt_live_ prefix). Set automatically by connect(). */
22
+ apiKey?: string;
104
23
  }
105
- /**
106
- * Record of a payment made by the SDK.
107
- *
108
- * This is emitted via the `onPayment` callback and stored in the payment history.
109
- */
110
24
  interface PaymentEvent {
111
- /** Payment amount in USD */
112
25
  amountUsd: number;
113
- /** Recipient wallet address */
114
26
  recipient: string;
115
- /** Transaction hash on the blockchain (if available) */
116
27
  txHash: string | null;
117
- /** Timestamp when the payment was made */
118
28
  timestamp: Date;
119
- /** Description of what was paid for (from the server) */
120
29
  description?: string;
121
- /** URL that triggered the payment */
122
30
  url?: string;
123
- /** Auto-generated unique ID for this request */
124
31
  requestId: string;
125
- /** User-provided correlation ID (from X-Correlation-Id header if provided) */
126
32
  correlationId?: string;
127
33
  }
128
- /**
129
- * Information about a session key.
130
- */
131
34
  interface SessionKeyInfo {
132
- /** The session key's derived address (used for signing requests) */
133
35
  address: string;
134
- /**
135
- * The wallet address this session key is authorized to spend from.
136
- * This is the human's funded wallet, NOT your agent's external wallet.
137
- * All charges are deducted from this wallet.
138
- */
139
36
  walletAddress: string | null;
140
- /** Whether the session key is currently valid */
141
37
  isValid: boolean;
142
- /** Spending limits configured for this session key */
143
38
  limits: {
144
- /** Maximum amount per transaction in USD (null = no limit) */
145
39
  perTxUsd: number | null;
146
- /** Maximum amount per day in USD (null = no limit) */
147
40
  dailyUsd: number | null;
148
- /** Maximum total amount in USD (null = no limit) */
149
41
  totalUsd: number | null;
150
42
  };
151
- /** Current usage statistics */
152
43
  usage: {
153
- /** Amount spent today in USD */
154
44
  todayUsd: number;
155
- /** Total amount spent in USD */
156
45
  totalUsd: number;
157
- /** Number of transactions made */
158
46
  txCount: number;
159
47
  };
160
- /** When the session key expires (null = never) */
161
48
  expiresAt: Date | null;
162
- /** When the session key was created */
163
49
  createdAt: Date | null;
164
- /** Optional name given to this session key */
165
50
  name?: string;
166
- /** Allowed merchants/tools (empty = allow all) */
167
51
  allowedMerchants?: string[];
168
52
  }
169
- /**
170
- * Spending statistics for the current session.
171
- */
172
53
  interface SpendingStats {
173
- /** Total amount spent in USD during this session */
174
54
  totalSpentUsd: number;
175
- /** Number of payment transactions made */
176
55
  txCount: number;
177
- /** Remaining daily limit in USD (null if no limit or unknown) */
178
56
  remainingDailyUsd: number | null;
179
- /** Remaining total limit in USD (null if no limit or unknown) */
180
57
  remainingTotalUsd: number | null;
181
- /** When the session key expires (null if never or unknown) */
182
58
  expiresAt: Date | null;
183
59
  }
184
- /**
185
- * Result of running diagnostics on the wallet.
186
- */
187
60
  interface DiagnosticsResult {
188
- /** Whether all checks passed */
189
61
  healthy: boolean;
190
- /** List of issues found (empty if healthy) */
191
62
  issues: string[];
192
- /** Individual check results */
193
63
  checks: {
194
- /** Session key format is valid */
195
64
  sessionKeyFormat?: boolean;
196
- /** Can connect to MixrPay API */
197
65
  apiConnectivity?: boolean;
198
- /** Session key is valid and not expired */
199
66
  sessionKeyValid?: boolean;
200
- /** Wallet has USDC balance */
201
67
  hasBalance?: boolean;
202
68
  };
203
- /** SDK version */
204
69
  sdkVersion: string;
205
- /** Network name (Base or Base Sepolia) */
206
70
  network: string;
207
- /** Wallet address */
208
71
  walletAddress: string;
209
- /** Session key limit info (if available) */
210
72
  sessionLimits?: {
211
- /** Remaining daily limit in USD (null if no limit) */
212
73
  remainingDailyUsd: number | null;
213
- /** Remaining total limit in USD (null if no limit) */
214
74
  remainingTotalUsd: number | null;
215
- /** When the session key expires (null if never) */
216
75
  expiresAt: Date | null;
217
- /** Hours until expiration (null if never) */
218
76
  expiresInHours: number | null;
219
77
  };
220
- /** Network latency to API in milliseconds */
221
78
  latencyMs?: number;
222
- /** Actionable recommendations based on issues found */
223
79
  recommendations: string[];
224
80
  }
225
- /**
226
- * Options for creating a session authorization with a MixrPay merchant.
227
- */
81
+ /** @internal */
228
82
  interface CreateSessionOptions {
229
- /**
230
- * The merchant's MixrPay public key.
231
- * Format: `pk_live_...` or `pk_test_...`
232
- */
233
83
  merchantPublicKey: string;
234
- /**
235
- * Maximum spending limit for this session in USD.
236
- * @default 25.00
237
- */
238
84
  spendingLimitUsd?: number;
239
- /**
240
- * Number of days this session should be valid.
241
- * @default 7
242
- */
243
85
  durationDays?: number;
244
86
  }
245
- /**
246
- * Status of a session authorization.
247
- */
87
+ /** @internal */
248
88
  type SessionAuthStatus = 'pending' | 'active' | 'expired' | 'revoked';
249
- /**
250
- * A session authorization with a MixrPay merchant.
251
- *
252
- * This represents a user-approved spending permission for a specific merchant.
253
- */
254
89
  interface SessionAuthorization {
255
- /** Unique session ID */
256
90
  id: string;
257
- /** Merchant ID */
258
91
  merchantId: string;
259
- /** Merchant name */
260
92
  merchantName: string;
261
- /** Current session status */
262
93
  status: SessionAuthStatus;
263
- /** Maximum spending limit in USD */
264
94
  spendingLimitUsd: number;
265
- /** Amount already spent in USD */
266
95
  amountUsedUsd: number;
267
- /** Remaining spending limit in USD */
268
96
  remainingLimitUsd: number;
269
- /** When the session expires */
270
97
  expiresAt: Date;
271
- /** When the session was created */
272
98
  createdAt: Date;
273
99
  }
274
- /**
275
- * Options for calling a MixrPay merchant's API.
276
- */
277
100
  interface CallMerchantApiOptions {
278
- /**
279
- * The merchant API URL to call.
280
- */
281
101
  url: string;
282
- /**
283
- * HTTP method (default: 'POST').
284
- */
285
102
  method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
286
- /**
287
- * Request body (will be JSON-serialized if object).
288
- */
289
103
  body?: unknown;
290
- /**
291
- * Additional headers to include.
292
- */
293
104
  headers?: Record<string, string>;
294
- /**
295
- * The merchant's MixrPay public key.
296
- * Required to identify which session to use.
297
- */
298
105
  merchantPublicKey: string;
299
- /**
300
- * Expected price in USD for this request.
301
- * Used for client-side validation.
302
- */
303
106
  priceUsd?: number;
304
- /**
305
- * Feature slug for tracking/analytics.
306
- */
307
107
  feature?: string;
308
108
  }
309
- /**
310
- * Options for charging against a session.
311
- */
109
+ /** @internal */
312
110
  interface ChargeSessionOptions {
313
- /** Feature slug for tracking */
314
111
  feature?: string;
315
- /** Idempotency key to prevent double-charges */
316
112
  idempotencyKey?: string;
317
- /** Additional metadata */
318
113
  metadata?: Record<string, unknown>;
319
114
  }
320
- /**
321
- * Result of a session charge.
322
- */
323
115
  interface ChargeResult {
324
- /** Whether the charge succeeded */
325
116
  success: boolean;
326
- /** Charge ID */
327
117
  chargeId: string;
328
- /** Amount charged in USD */
329
118
  amountUsd: number;
330
- /** Transaction hash (if on-chain) */
331
119
  txHash?: string;
332
- /** Remaining session balance in USD */
333
120
  remainingSessionBalanceUsd: number;
334
121
  }
335
- /**
336
- * Statistics about session authorizations.
337
- *
338
- * This provides an overview of all sessions managed by the wallet.
339
- */
340
122
  interface SessionStats {
341
- /** Number of active sessions */
342
123
  activeCount: number;
343
- /** Number of expired sessions */
344
124
  expiredCount: number;
345
- /** Number of revoked sessions */
346
125
  revokedCount: number;
347
- /** Total amount authorized across all active sessions in USD */
348
126
  totalAuthorizedUsd: number;
349
- /** Total amount spent across all sessions in USD */
350
127
  totalSpentUsd: number;
351
- /** Total remaining across all active sessions in USD */
352
128
  totalRemainingUsd: number;
353
- /** List of active sessions (summary) */
354
129
  activeSessions: Array<{
355
130
  id: string;
356
131
  merchantName: string;
@@ -360,32 +135,87 @@ interface SessionStats {
360
135
  expiresAt: Date;
361
136
  }>;
362
137
  }
363
-
364
- /**
365
- * MixrPay Agent SDK - AgentWallet
366
- *
367
- * Main class for AI agents to make x402 payments. Provides a simple interface
368
- * for making HTTP requests that automatically handle payments using session keys.
369
- *
370
- * @example Quick Start
371
- * ```typescript
372
- * import { AgentWallet } from '@mixrpay/agent-sdk';
373
- *
374
- * // Initialize with your session key
375
- * const wallet = new AgentWallet({ sessionKey: 'sk_live_...' });
376
- *
377
- * // Make requests - payments handled automatically!
378
- * const response = await wallet.fetch('https://api.example.com/ai/query', {
379
- * method: 'POST',
380
- * body: JSON.stringify({ prompt: 'Hello world' })
381
- * });
382
- *
383
- * console.log(await response.json());
384
- * ```
385
- */
138
+ interface TokenBalance {
139
+ balance: string;
140
+ raw: string;
141
+ decimals?: number;
142
+ }
143
+ interface DelegationBudget {
144
+ budget_total_usd: string;
145
+ budget_spent_usd: string;
146
+ budget_remaining_usd: string;
147
+ per_tx_limit_usd: string;
148
+ daily_limit_usd: string;
149
+ }
150
+ interface BalancesResponse {
151
+ wallet_address: string;
152
+ chain: string;
153
+ chain_id: number;
154
+ balances: Record<string, TokenBalance>;
155
+ delegation?: DelegationBudget;
156
+ request_id: string;
157
+ }
158
+ interface TransferResponse {
159
+ success: boolean;
160
+ tx_hash: string;
161
+ amount_usd: string;
162
+ remaining_budget_usd: string | null;
163
+ charge_id: string;
164
+ }
165
+ interface SwapResponse {
166
+ success: boolean;
167
+ tx_hash: string;
168
+ sell_amount: string;
169
+ sell_token: string;
170
+ buy_amount: string;
171
+ min_buy_amount: string;
172
+ buy_token: string;
173
+ price: string;
174
+ gas_estimate: string;
175
+ remaining_budget_usd: string | null;
176
+ charge_id: string;
177
+ }
178
+ interface BridgeResponse {
179
+ success: boolean;
180
+ tx_hash: string;
181
+ order_id: string;
182
+ amount: string;
183
+ source_chain: string;
184
+ dest_chain: string;
185
+ estimated_receive: string;
186
+ remaining_budget_usd: string | null;
187
+ charge_id: string;
188
+ }
189
+ interface BridgeStatusResponse {
190
+ order_id: string;
191
+ status: 'pending' | 'fulfilled' | 'failed' | 'cancelled';
192
+ source_chain: string;
193
+ source_tx_hash: string;
194
+ dest_chain: string;
195
+ dest_tx_hash?: string;
196
+ estimated_time_remaining?: string;
197
+ }
198
+ interface FetchPaymentInfo {
199
+ paid: boolean;
200
+ amount_usd: string;
201
+ tx_hash?: string;
202
+ remaining_budget_usd: string | null;
203
+ }
204
+ interface FetchPaidResponse {
205
+ status: number;
206
+ headers: Record<string, string>;
207
+ body: unknown;
208
+ payment?: FetchPaymentInfo;
209
+ }
210
+ interface FetchPaidOptions {
211
+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
212
+ headers?: Record<string, string>;
213
+ body?: unknown;
214
+ maxPaymentUsd?: number;
215
+ }
386
216
 
387
217
  /** Current SDK version */
388
- declare const SDK_VERSION = "0.8.7";
218
+ declare const SDK_VERSION = "0.9.4";
389
219
  /** Supported networks */
390
220
  declare const NETWORKS: {
391
221
  readonly BASE_MAINNET: {
@@ -553,11 +383,122 @@ interface AgentClaimInviteResult {
553
383
  /** Name of the person who created the invite */
554
384
  inviterName: string;
555
385
  }
386
+ /**
387
+ * Options for activating an agent
388
+ */
389
+ interface AgentActivateOptions {
390
+ /** MixrPay API base URL (default: https://www.mixrpay.com) */
391
+ baseUrl?: string;
392
+ }
393
+ /**
394
+ * Agent runtime returned from activation
395
+ * Contains the wallet instance and all capabilities/tools available to the agent
396
+ */
397
+ interface AgentRuntime {
398
+ /** Pre-configured AgentWallet instance */
399
+ wallet: AgentWallet;
400
+ /** Budget limits and current spending */
401
+ budget: {
402
+ maxTotalUsd: number | null;
403
+ maxDailyUsd: number | null;
404
+ maxPerTxUsd: number | null;
405
+ spentUsd: number;
406
+ remainingUsd: number | null;
407
+ };
408
+ /** Feature capabilities */
409
+ capabilities: {
410
+ executeTransactions: boolean;
411
+ gasSponsored: boolean;
412
+ batchedTx: boolean;
413
+ };
414
+ /** Installed business skills */
415
+ skills: Array<{
416
+ id: string;
417
+ name: string;
418
+ version: number;
419
+ }>;
420
+ /** Available tools */
421
+ tools: Array<{
422
+ name: string;
423
+ type: string;
424
+ }>;
425
+ /** Configured gateway providers and their tools */
426
+ gatewayProviders: Array<{
427
+ name: string;
428
+ tools: string[];
429
+ }>;
430
+ }
431
+ /**
432
+ * Options for AgentWallet.connect() auth cascade
433
+ */
434
+ interface ConnectOptions {
435
+ /** Explicit session key (highest priority) */
436
+ sessionKey?: string;
437
+ /** Access code from MixrPay dashboard (mixr-xxx) - one-time use, auto-cached */
438
+ accessCode?: string;
439
+ /** Master key for multi-agent deployments */
440
+ masterKey?: string;
441
+ /** Agent name when using master key */
442
+ agentName?: string;
443
+ /** Enable interactive device flow login if no credentials found */
444
+ interactive?: boolean;
445
+ /** MixrPay API base URL (default: https://www.mixrpay.com) */
446
+ baseUrl?: string;
447
+ /** Log level for debugging */
448
+ logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'none';
449
+ /** Client-side maximum payment amount in USD */
450
+ maxPaymentUsd?: number;
451
+ /** Callback for payment events */
452
+ onPayment?: (payment: PaymentEvent) => void;
453
+ }
454
+ /**
455
+ * Options for generating a SIWE (Sign-In with Ethereum) message
456
+ * Per EIP-4361: https://eips.ethereum.org/EIPS/eip-4361
457
+ */
458
+ interface SiweOptions {
459
+ /** The domain making the request (e.g., "example.com") */
460
+ domain: string;
461
+ /** The URI of the resource being accessed */
462
+ uri: string;
463
+ /** Human-readable statement for the user */
464
+ statement?: string;
465
+ /** Server-provided nonce for replay protection (default: random UUID) */
466
+ nonce?: string;
467
+ /** When the message was issued (default: now) */
468
+ issuedAt?: Date;
469
+ /** When the signed message expires */
470
+ expirationTime?: Date;
471
+ /** When the signed message becomes valid */
472
+ notBefore?: Date;
473
+ /** System-specific request identifier */
474
+ requestId?: string;
475
+ /** List of resources the user is authorizing */
476
+ resources?: string[];
477
+ }
478
+ /**
479
+ * Result from generating a SIWE message
480
+ */
481
+ interface SiweResult {
482
+ /** The formatted SIWE message */
483
+ message: string;
484
+ /** The signature (hex string with 0x prefix) */
485
+ signature: string;
486
+ /** The signing address */
487
+ address: string;
488
+ /** The chain ID */
489
+ chainId: number;
490
+ /** The nonce used */
491
+ nonce: string;
492
+ /** When the message was issued */
493
+ issuedAt: Date;
494
+ /** When the message expires (if set) */
495
+ expirationTime?: Date;
496
+ }
556
497
  /**
557
498
  * Options for spawning a child invite
558
499
  */
559
500
  interface SpawnChildOptions {
560
- /** Budget in USD for the child (max 20% of available) */
501
+ /** Budget in USD for the child (subject to platform limits) */
561
502
  budgetUsd: number;
562
503
  /** Name for the child invite */
563
504
  name: string;
@@ -574,13 +515,13 @@ interface SpawnChildResult {
574
515
  inviteCode: string;
575
516
  /** Database ID of the invite */
576
517
  inviteId: string;
577
- /** Actual budget (may be less than requested due to 20% cap) */
518
+ /** Actual budget (may be less than requested due to platform limits) */
578
519
  budgetUsd: number;
579
520
  /** When the invite expires */
580
521
  expiresAt: Date;
581
522
  /** Depth in hierarchy (1 = child, 2 = grandchild, etc.) */
582
523
  depth: number;
583
- /** How much this child can spawn (20% of their budget) */
524
+ /** How much this child can spawn */
584
525
  maxSpawnBudget: number;
585
526
  /** Allowed merchants for this child */
586
527
  allowedMerchants: string[];
@@ -597,9 +538,9 @@ interface AvailableBudget {
597
538
  allocatedToChildren: number;
598
539
  /** Available for spending or spawning */
599
540
  available: number;
600
- /** Maximum budget for next spawn (20% of available) */
541
+ /** Maximum budget for next spawn */
601
542
  maxSpawnBudget: number;
602
- /** Whether spawning is allowed (depth < 10, can_spawn, available > 0) */
543
+ /** Whether spawning is allowed */
603
544
  canSpawn: boolean;
604
545
  }
605
546
  /**
@@ -673,6 +614,16 @@ type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'none';
673
614
  * @see {@link AgentWalletConfig} for configuration options
674
615
  * @see {@link PaymentEvent} for payment tracking
675
616
  */
617
+ /**
618
+ * Configuration returned by {@link AgentWallet.mcp} for use with the
619
+ * Claude Agent SDK's `mcpServers` option or any MCP client that accepts
620
+ * stdio server configs.
621
+ */
622
+ interface McpServerConfig {
623
+ command: string;
624
+ args: string[];
625
+ env: Record<string, string>;
626
+ }
676
627
  declare class AgentWallet {
677
628
  private readonly sessionKey;
678
629
  private readonly walletAddress;
@@ -687,6 +638,10 @@ declare class AgentWallet {
687
638
  private sessionKeyInfoFetchedAt?;
688
639
  private allowlist?;
689
640
  private allowlistFetchedAt?;
641
+ private selfCustodyAddress?;
642
+ private selfCustodyKey?;
643
+ private agentInstanceId?;
644
+ private apiKey?;
690
645
  /**
691
646
  * Create a new AgentWallet instance.
692
647
  *
@@ -748,7 +703,7 @@ declare class AgentWallet {
748
703
  /**
749
704
  * Register a new agent with MixrPay.
750
705
  *
751
- * This creates a Privy-managed embedded wallet for the agent's payments.
706
+ * This creates a platform-managed embedded wallet for the agent's payments.
752
707
  * The agent proves ownership of their external wallet by signing a challenge.
753
708
  *
754
709
  * @param options - Registration options including the private key
@@ -786,7 +741,7 @@ declare class AgentWallet {
786
741
  healthy: boolean;
787
742
  database: string;
788
743
  agentRegistrationAvailable: boolean;
789
- privyConfigured: boolean;
744
+ walletServiceConfigured: boolean;
790
745
  error?: string;
791
746
  }>;
792
747
  /**
@@ -885,9 +840,11 @@ declare class AgentWallet {
885
840
  /**
886
841
  * Claim an agent invite code to receive a session key for the inviter's wallet.
887
842
  *
888
- * This allows an agent to get a pre-configured session key from a human wallet owner
889
- * without needing to register their own wallet or fund it. The human sets the budget
890
- * limits and merchant whitelist when creating the invite.
843
+ * @deprecated Use `AgentWallet.fromAccessCode()` instead for a simpler flow that requires
844
+ * no wallet or signature. The new method:
845
+ * - Accepts a simple access code (mixr-xxx) instead of requiring a private key
846
+ * - Auto-caches credentials for subsequent calls
847
+ * - Works with `connect({ accessCode: 'mixr-xxx' })` or `MIXRPAY_ACCESS_CODE` env var
891
848
  *
892
849
  * @param options - Claim invite options including the invite code and agent's private key
893
850
  * @returns Claim result with the new session key
@@ -895,28 +852,211 @@ declare class AgentWallet {
895
852
  *
896
853
  * @example
897
854
  * ```typescript
898
- * // Human creates invite at https://mixrpay.com/manage/invites, shares code "mixr-abc123"
899
- *
855
+ * // DEPRECATED: Old way requiring private key
900
856
  * const result = await AgentWallet.claimInvite({
901
857
  * inviteCode: 'mixr-abc123',
902
858
  * privateKey: process.env.AGENT_WALLET_KEY as `0x${string}`,
903
859
  * });
904
860
  *
905
- * console.log(`Got session key: ${result.sessionKey}`);
906
- * console.log(`Budget: $${result.limits.budgetUsd}/${result.limits.budgetPeriod}`);
907
- * console.log(`Invited by: ${result.inviterName}`);
908
- *
909
- * // Use the session key to make payments
910
- * const wallet = new AgentWallet({ sessionKey: result.sessionKey });
911
- * const response = await wallet.fetch('https://api.example.com/endpoint');
861
+ * // NEW: Use fromAccessCode() instead - no private key needed
862
+ * const wallet = await AgentWallet.fromAccessCode('mixr-abc123');
863
+ * // or: const wallet = await AgentWallet.connect({ accessCode: 'mixr-abc123' });
912
864
  * ```
913
865
  */
914
866
  static claimInvite(options: AgentClaimInviteOptions): Promise<AgentClaimInviteResult>;
867
+ /**
868
+ * Activate an agent using a session key.
869
+ *
870
+ * This is the recommended way to initialize an agent at startup. It creates
871
+ * an AgentWallet instance and fetches all capabilities, budget info, skills,
872
+ * tools, and gateway providers in a single call.
873
+ *
874
+ * @param sessionKey - The session key in sk_live_ or sk_test_ format
875
+ * @param options - Optional configuration
876
+ * @returns AgentRuntime with wallet and all capabilities
877
+ * @throws {MixrPayError} If activation fails
878
+ *
879
+ * @example
880
+ * ```typescript
881
+ * // Activate at agent startup
882
+ * const runtime = await AgentWallet.activate(process.env.MIXRPAY_SESSION_KEY!);
883
+ *
884
+ * // Use the wallet for payments
885
+ * const response = await runtime.wallet.fetch('https://api.example.com/endpoint');
886
+ *
887
+ * // Check capabilities
888
+ * if (runtime.capabilities.gasSponsored) {
889
+ * console.log('Gas is sponsored - no ETH needed!');
890
+ * }
891
+ *
892
+ * // List available gateway providers
893
+ * for (const provider of runtime.gatewayProviders) {
894
+ * console.log(`${provider.name}: ${provider.tools.join(', ')}`);
895
+ * }
896
+ *
897
+ * // Check budget
898
+ * console.log(`Budget remaining: $${runtime.budget.remainingUsd}`);
899
+ * ```
900
+ */
901
+ static activate(sessionKey: string, options?: AgentActivateOptions): Promise<AgentRuntime>;
902
+ /**
903
+ * Connect to MixrPay with automatic credential resolution.
904
+ *
905
+ * This is the recommended zero-config entry point for agents. It implements
906
+ * an auth cascade that tries multiple credential sources in order:
907
+ *
908
+ * 1. **Explicit key**: If `sessionKey` is provided in options
909
+ * 2. **Environment variables**: `MIXRPAY_SESSION_KEY` (session key)
910
+ * 3. **Environment variables**: `MIXRPAY_API_KEY` or `MIXRPAY_AGENT_TOKEN` (agent token)
911
+ * 4. **Access code**: `options.accessCode` or `MIXRPAY_ACCESS_CODE` env var (one-time use)
912
+ * 5. **Master key + name**: `MIXRPAY_MASTER_KEY` + `options.agentName` (for multi-agent setups)
913
+ * 6. **Cached credentials**: Previously saved via `saveCredentials()` or CLI login
914
+ * 7. **Device flow**: Interactive browser-based login (if `interactive: true`)
915
+ *
916
+ * @param options - Optional connection options
917
+ * @returns Connected AgentWallet instance
918
+ * @throws {MixrPayError} If no credentials found and interactive mode disabled
919
+ *
920
+ * @example Zero-config (uses env vars or cached creds)
921
+ * ```typescript
922
+ * const wallet = await AgentWallet.connect();
923
+ * await wallet.fetch('https://api.example.com/endpoint');
924
+ * ```
925
+ *
926
+ * @example With explicit session key
927
+ * ```typescript
928
+ * const wallet = await AgentWallet.connect({
929
+ * sessionKey: 'sk_live_...',
930
+ * });
931
+ * ```
932
+ *
933
+ * @example With master key for specific agent
934
+ * ```typescript
935
+ * const wallet = await AgentWallet.connect({
936
+ * masterKey: process.env.MIXRPAY_MASTER_KEY,
937
+ * agentName: 'research-agent',
938
+ * });
939
+ * ```
940
+ *
941
+ * @example Interactive mode (prompts for login if no creds)
942
+ * ```typescript
943
+ * const wallet = await AgentWallet.connect({
944
+ * interactive: true,
945
+ * });
946
+ * ```
947
+ */
948
+ static connect(options?: ConnectOptions): Promise<AgentWallet>;
949
+ /**
950
+ * Create an AgentWallet from an API key (agt_live_xxx format).
951
+ *
952
+ * API keys are long-lived tokens that can be exchanged for session keys.
953
+ * This is useful for server-side deployments where you don't want to
954
+ * manage session key rotation manually.
955
+ *
956
+ * @param apiKey - API key in agt_live_xxx or agt_test_xxx format
957
+ * @param options - Optional configuration
958
+ * @returns Connected AgentWallet instance
959
+ * @throws {MixrPayError} If API key is invalid or exchange fails
960
+ *
961
+ * @example
962
+ * ```typescript
963
+ * const wallet = await AgentWallet.fromApiKey('agt_live_xxx');
964
+ * await wallet.fetch('https://api.example.com/endpoint');
965
+ * ```
966
+ */
967
+ static fromApiKey(apiKey: string, options?: {
968
+ baseUrl?: string;
969
+ logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'none';
970
+ }): Promise<AgentWallet>;
971
+ /**
972
+ * Create an AgentWallet from an access code (mixr-xxx format).
973
+ *
974
+ * Access codes are one-time use codes generated in the MixrPay dashboard.
975
+ * After activation, the code is consumed and credentials are cached
976
+ * for subsequent use. This is the recommended method for external agents
977
+ * (Cursor, Claude, GPT, etc.) to connect to MixrPay.
978
+ *
979
+ * The access code is exchanged for:
980
+ * - `session_key` (sk_live_xxx) - used for signing delegation payments
981
+ * - `token` (agt_live_xxx) - bearer token for API calls
982
+ * - `agent_id` - AgentInstance ID for reference
983
+ * - `budget` - spending limits
984
+ * - `tools` - available MCP tools
985
+ *
986
+ * @param code - Access code in mixr-xxx format
987
+ * @param options - Optional configuration
988
+ * @returns Connected AgentWallet instance
989
+ * @throws {MixrPayError} If access code is invalid, expired, or already used
990
+ *
991
+ * @example
992
+ * ```typescript
993
+ * // First-time setup with access code
994
+ * const wallet = await AgentWallet.fromAccessCode('mixr-abc123def456');
995
+ *
996
+ * // Session key is auto-cached, subsequent calls use cached credentials
997
+ * const wallet2 = await AgentWallet.connect();
998
+ * ```
999
+ */
1000
+ static fromAccessCode(code: string, options?: {
1001
+ baseUrl?: string;
1002
+ logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'none';
1003
+ }): Promise<AgentWallet>;
1004
+ /**
1005
+ * Create an AgentWallet using a master key for a specific agent.
1006
+ *
1007
+ * Master keys (mk_live_xxx) are organization-level credentials that can
1008
+ * create sessions for any agent in the organization. This is useful for
1009
+ * multi-agent deployments managed by a single entity.
1010
+ *
1011
+ * Note: Master key flow provides delegation access only. Self-custody
1012
+ * wallet operations (createSelfCustodyWallet, transferUSDC, executeFromOwnWallet)
1013
+ * require an agt_live_ token -- use fromApiKey() or fromAccessCode() instead.
1014
+ *
1015
+ * @param masterKey - Master key in mk_live_xxx format
1016
+ * @param agentName - Name of the agent to connect as
1017
+ * @param options - Optional configuration
1018
+ * @returns Connected AgentWallet instance
1019
+ * @throws {MixrPayError} If master key is invalid or agent not found
1020
+ *
1021
+ * @example
1022
+ * ```typescript
1023
+ * const wallet = await AgentWallet.fromMasterKey(
1024
+ * process.env.MIXRPAY_MASTER_KEY!,
1025
+ * 'research-agent'
1026
+ * );
1027
+ * ```
1028
+ */
1029
+ static fromMasterKey(masterKey: string, agentName: string, options?: {
1030
+ baseUrl?: string;
1031
+ logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'none';
1032
+ }): Promise<AgentWallet>;
1033
+ /**
1034
+ * Interactive device flow login.
1035
+ *
1036
+ * Opens a browser for the user to authenticate, then polls for completion.
1037
+ * This is the OAuth 2.0 Device Authorization Grant flow.
1038
+ *
1039
+ * @param options - Optional configuration
1040
+ * @returns Connected AgentWallet instance
1041
+ * @throws {MixrPayError} If device flow fails or times out
1042
+ *
1043
+ * @example
1044
+ * ```typescript
1045
+ * // In a CLI or terminal application
1046
+ * const wallet = await AgentWallet.deviceFlowLogin();
1047
+ * // User sees: "Visit https://mixrpay.com/device and enter code: ABCD-1234"
1048
+ * // After user authenticates, wallet is ready to use
1049
+ * ```
1050
+ */
1051
+ static deviceFlowLogin(options?: {
1052
+ baseUrl?: string;
1053
+ logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'none';
1054
+ }): Promise<AgentWallet>;
915
1055
  /**
916
1056
  * Spawn a child invite for sub-agents.
917
1057
  *
918
1058
  * Allows an agent to create an invite code for a sub-agent with a portion
919
- * of their remaining budget (max 20%). The child inherits merchant restrictions
1059
+ * of their remaining budget. The child inherits merchant restrictions
920
1060
  * and cannot outlive the parent session.
921
1061
  *
922
1062
  * @param options - Spawn options
@@ -930,7 +1070,7 @@ declare class AgentWallet {
930
1070
  *
931
1071
  * // Spawn a child invite for a sub-agent
932
1072
  * const childInvite = await wallet.spawnChildInvite({
933
- * budgetUsd: 10.00, // Max 20% of available budget
1073
+ * budgetUsd: 10.00,
934
1074
  * name: 'Research Sub-Agent',
935
1075
  * allowedMerchants: ['firecrawl.dev'], // Must be subset of parent
936
1076
  * expiresInDays: 7, // Will be capped to parent's expiry
@@ -944,8 +1084,7 @@ declare class AgentWallet {
944
1084
  /**
945
1085
  * Get available budget information for spawning.
946
1086
  *
947
- * Returns the current budget status including how much can be spawned
948
- * to child agents (20% of available).
1087
+ * Returns the current budget status including spawn availability.
949
1088
  *
950
1089
  * @returns Budget information
951
1090
  *
@@ -1141,6 +1280,184 @@ declare class AgentWallet {
1141
1280
  * @returns Total spent in USD
1142
1281
  */
1143
1282
  getTotalSpent(): number;
1283
+ /**
1284
+ * Create a self-custody wallet for this agent.
1285
+ *
1286
+ * Generates a new private key, signs a proof of ownership, registers the
1287
+ * address with MixrPay, and persists the key locally.
1288
+ *
1289
+ * The private key is stored locally and NEVER transmitted to MixrPay.
1290
+ * MixrPay only stores the public address for transaction verification.
1291
+ *
1292
+ * @returns The wallet address and private key
1293
+ * @throws {MixrPayError} If agent instance ID is not set or registration fails
1294
+ *
1295
+ * @example
1296
+ * ```typescript
1297
+ * const wallet = await AgentWallet.connect();
1298
+ *
1299
+ * // Create self-custody wallet (only needed once)
1300
+ * const { address, privateKey } = await wallet.createSelfCustodyWallet();
1301
+ * console.log(`Deposit address: ${address}`);
1302
+ *
1303
+ * // The private key is stored locally and loaded automatically
1304
+ * ```
1305
+ */
1306
+ createSelfCustodyWallet(): Promise<{
1307
+ address: `0x${string}`;
1308
+ privateKey: `0x${string}`;
1309
+ }>;
1310
+ /**
1311
+ * Register a wallet address with MixrPay.
1312
+ *
1313
+ * This is called automatically by createSelfCustodyWallet().
1314
+ * Only use directly if you have an existing private key.
1315
+ *
1316
+ * @param address - The wallet address to register
1317
+ * @param signature - Signature proving ownership
1318
+ * @param timestamp - Timestamp used in signature message
1319
+ * @throws {MixrPayError} If registration fails
1320
+ */
1321
+ private registerWalletAddress;
1322
+ /**
1323
+ * Load an existing self-custody wallet from local storage.
1324
+ *
1325
+ * @returns True if wallet was loaded, false if no wallet exists
1326
+ */
1327
+ loadSelfCustodyWallet(): Promise<boolean>;
1328
+ /**
1329
+ * Check if this agent has a self-custody wallet.
1330
+ *
1331
+ * @returns True if a self-custody wallet exists
1332
+ */
1333
+ hasSelfCustodyWallet(): Promise<boolean>;
1334
+ /**
1335
+ * Get the self-custody wallet address if one exists.
1336
+ *
1337
+ * @returns The wallet address or null if no self-custody wallet
1338
+ */
1339
+ getSelfCustodyAddress(): `0x${string}` | null;
1340
+ /**
1341
+ * Execute a transaction from the agent's self-custody wallet.
1342
+ *
1343
+ * Signs the transaction locally using viem and submits directly to Base RPC.
1344
+ * Reports the transaction to MixrPay for audit logging.
1345
+ *
1346
+ * @param params - Transaction parameters
1347
+ * @returns Transaction result with hash
1348
+ * @throws {MixrPayError} If wallet not loaded or transaction fails
1349
+ *
1350
+ * @example
1351
+ * ```typescript
1352
+ * const result = await wallet.executeFromOwnWallet({
1353
+ * to: '0x...',
1354
+ * value: parseEther('0.01'),
1355
+ * data: '0x...',
1356
+ * });
1357
+ * console.log(`TX: ${result.txHash}`);
1358
+ * ```
1359
+ */
1360
+ executeFromOwnWallet(params: {
1361
+ to: `0x${string}`;
1362
+ value?: bigint;
1363
+ data?: `0x${string}`;
1364
+ gasLimit?: bigint;
1365
+ }): Promise<{
1366
+ txHash: `0x${string}`;
1367
+ reportedToMixrPay: boolean;
1368
+ }>;
1369
+ /**
1370
+ * Transfer USDC from the agent's self-custody wallet.
1371
+ *
1372
+ * This is a convenience method for ERC-20 USDC transfers on Base.
1373
+ * Returns the transaction hash. The transaction is automatically
1374
+ * reported to MixrPay for audit logging.
1375
+ *
1376
+ * @param params - Transfer parameters
1377
+ * @returns Transaction hash
1378
+ * @throws {MixrPayError} If wallet not loaded or transfer fails
1379
+ *
1380
+ * @example
1381
+ * ```typescript
1382
+ * // Pay $5 USDC to a recipient
1383
+ * const txHash = await wallet.transferUSDC({
1384
+ * to: '0xRecipientAddress...',
1385
+ * amountUsdc: 5.00,
1386
+ * });
1387
+ *
1388
+ * console.log(`Transfer complete: ${txHash}`);
1389
+ * ```
1390
+ */
1391
+ transferUSDC(params: {
1392
+ to: `0x${string}`;
1393
+ amountUsdc: number;
1394
+ }): Promise<`0x${string}`>;
1395
+ /**
1396
+ * Report a transaction to MixrPay for audit logging.
1397
+ *
1398
+ * This is called automatically by executeFromOwnWallet().
1399
+ *
1400
+ * @param txHash - The transaction hash
1401
+ * @param to - The recipient address
1402
+ * @param value - The value transferred (in wei)
1403
+ */
1404
+ private reportTransaction;
1405
+ /**
1406
+ * Get the agent instance ID.
1407
+ *
1408
+ * @returns The agent instance ID or undefined if not set
1409
+ */
1410
+ getAgentInstanceId(): string | undefined;
1411
+ /**
1412
+ * Set the agent instance ID.
1413
+ *
1414
+ * This is typically set automatically when using fromApiKey() or connect().
1415
+ *
1416
+ * @param id - The agent instance ID
1417
+ */
1418
+ setAgentInstanceId(id: string): void;
1419
+ /**
1420
+ * Set the API key for self-custody operations.
1421
+ *
1422
+ * This is set automatically when using fromApiKey(). The API key is used
1423
+ * for bearer token authentication on self-custody API calls (wallet registration,
1424
+ * transaction reporting, etc.).
1425
+ *
1426
+ * @param key - The API key (agt_live_xxx or agt_test_xxx)
1427
+ */
1428
+ setApiKey(key: string): void;
1429
+ /**
1430
+ * Return an MCP server config for use with the Claude Agent SDK.
1431
+ *
1432
+ * Spawns a child stdio MCP server process that exposes wallet tools
1433
+ * (balance, marketplace, skills, transfers, budget delegation, tasks).
1434
+ *
1435
+ * @example With the Claude Agent SDK
1436
+ * ```typescript
1437
+ * import { query } from "@anthropic-ai/claude-agent-sdk";
1438
+ * import { AgentWallet } from "@mixrpay/agent-sdk";
1439
+ *
1440
+ * const wallet = new AgentWallet({ sessionKey: process.env.MIXRPAY_SESSION_KEY! });
1441
+ *
1442
+ * for await (const msg of query({
1443
+ * prompt: "Use firecrawl to scrape example.com",
1444
+ * options: {
1445
+ * mcpServers: { mixrpay: wallet.mcp() },
1446
+ * allowedTools: ["mcp__mixrpay__*"],
1447
+ * },
1448
+ * })) {
1449
+ * if (msg.type === "result" && msg.subtype === "success") console.log(msg.result);
1450
+ * }
1451
+ * ```
1452
+ */
1453
+ mcp(): McpServerConfig;
1454
+ /**
1455
+ * Get the API key if set (internal use only).
1456
+ *
1457
+ // ===========================================================================
1458
+ // Diagnostics
1459
+ // ===========================================================================
1460
+
1144
1461
  /**
1145
1462
  * Run diagnostics to verify the wallet is properly configured.
1146
1463
  *
@@ -1160,6 +1477,41 @@ declare class AgentWallet {
1160
1477
  * ```
1161
1478
  */
1162
1479
  runDiagnostics(): Promise<DiagnosticsResult>;
1480
+ /**
1481
+ * Generate a SIWE (Sign-In with Ethereum) message and signature.
1482
+ *
1483
+ * This implements EIP-4361 and can be used to authenticate with services
1484
+ * that support Sign-In with Ethereum, proving ownership of the session key.
1485
+ *
1486
+ * @param options - SIWE message options
1487
+ * @returns SIWE message and signature
1488
+ *
1489
+ * @example Basic usage
1490
+ * ```typescript
1491
+ * const { message, signature } = await wallet.generateSiwe({
1492
+ * domain: 'example.com',
1493
+ * uri: 'https://example.com/login',
1494
+ * statement: 'Sign in to Example App',
1495
+ * });
1496
+ *
1497
+ * // Send to server for verification
1498
+ * await fetch('/api/verify', {
1499
+ * method: 'POST',
1500
+ * body: JSON.stringify({ message, signature }),
1501
+ * });
1502
+ * ```
1503
+ *
1504
+ * @example With nonce and expiration
1505
+ * ```typescript
1506
+ * const { message, signature } = await wallet.generateSiwe({
1507
+ * domain: 'myapp.com',
1508
+ * uri: 'https://myapp.com',
1509
+ * nonce: 'abc123', // Server-provided nonce
1510
+ * expirationTime: new Date(Date.now() + 5 * 60 * 1000), // 5 min
1511
+ * });
1512
+ * ```
1513
+ */
1514
+ generateSiwe(options: SiweOptions): Promise<SiweResult>;
1163
1515
  /**
1164
1516
  * Enable or disable debug logging.
1165
1517
  *
@@ -1202,8 +1554,8 @@ declare class AgentWallet {
1202
1554
  * ```typescript
1203
1555
  * const session = await wallet.getOrCreateSession({
1204
1556
  * merchantPublicKey: 'pk_live_abc123...',
1205
- * spendingLimitUsd: 25.00,
1206
- * durationDays: 7,
1557
+ * spendingLimitUsd: 100,
1558
+ * durationDays: 30,
1207
1559
  * });
1208
1560
  *
1209
1561
  * console.log(`Session active: $${session.remainingLimitUsd} remaining`);
@@ -1353,19 +1705,23 @@ declare class AgentWallet {
1353
1705
  * Returns all tools exposed by MCP providers on the MixrPay marketplace.
1354
1706
  * Each tool includes pricing information.
1355
1707
  *
1356
- * @returns Array of MCP tools with pricing and metadata
1708
+ * @returns Array of tools with pricing and metadata
1357
1709
  *
1358
1710
  * @example
1359
1711
  * ```typescript
1360
- * const tools = await wallet.listMCPTools();
1712
+ * const tools = await wallet.listTools();
1361
1713
  * for (const tool of tools) {
1362
1714
  * console.log(`${tool.name}: $${tool.priceUsd} - ${tool.description}`);
1363
1715
  * }
1364
1716
  * ```
1365
1717
  */
1366
- listMCPTools(): Promise<MCPTool[]>;
1718
+ listTools(): Promise<Tool[]>;
1367
1719
  /**
1368
- * Call an MCP tool with wallet authentication (direct pay per call).
1720
+ * @deprecated Use listTools() instead.
1721
+ */
1722
+ listMCPTools(): Promise<Tool[]>;
1723
+ /**
1724
+ * Call a tool with wallet authentication (direct pay per call).
1369
1725
  *
1370
1726
  * This method signs a fresh auth message for each call, charging
1371
1727
  * directly from your wallet balance without needing a session.
@@ -1376,14 +1732,18 @@ declare class AgentWallet {
1376
1732
  *
1377
1733
  * @example
1378
1734
  * ```typescript
1379
- * const result = await wallet.callMCPTool('firecrawl/scrape', {
1735
+ * const result = await wallet.callTool('firecrawl/scrape', {
1380
1736
  * url: 'https://example.com',
1381
1737
  * });
1382
1738
  * console.log(result.data);
1383
1739
  * console.log(`Charged: $${result.chargedUsd}`);
1384
1740
  * ```
1385
1741
  */
1386
- callMCPTool(toolName: string, args?: Record<string, unknown>): Promise<MCPToolResult>;
1742
+ callTool(toolName: string, args?: Record<string, unknown>): Promise<ToolResult>;
1743
+ /**
1744
+ * @deprecated Use callTool() instead.
1745
+ */
1746
+ callMCPTool(toolName: string, args?: Record<string, unknown>): Promise<ToolResult>;
1387
1747
  /**
1388
1748
  * Deploy a JIT MCP server from the Glama directory.
1389
1749
  *
@@ -1446,19 +1806,196 @@ declare class AgentWallet {
1446
1806
  */
1447
1807
  private parseJitInstance;
1448
1808
  /**
1449
- * Get details of a specific JIT MCP server instance.
1809
+ * Get details of a specific JIT MCP server instance.
1810
+ *
1811
+ * @param instanceId - The instance ID to retrieve
1812
+ * @returns Full instance details including endpoint URL
1813
+ *
1814
+ * @example
1815
+ * ```typescript
1816
+ * const instance = await wallet.getJitInstance('inst_abc123');
1817
+ * console.log('Endpoint:', instance.endpointUrl);
1818
+ * console.log('Expires:', instance.expiresAt);
1819
+ * ```
1820
+ */
1821
+ getJitInstance(instanceId: string): Promise<JitInstance>;
1822
+ /**
1823
+ * Execute an on-chain transaction from the human's wallet.
1824
+ *
1825
+ * Submits arbitrary calldata to any contract, bounded by the session key's
1826
+ * budget limits (max_total, max_per_tx, max_daily). The platform validates
1827
+ * the budget, executes the transaction, and records a charge.
1828
+ *
1829
+ * @param params - Transaction parameters
1830
+ * @returns Transaction result with hash and remaining budget
1831
+ * @throws {MixrPayError} If budget exceeded, tx reverted, or auth fails
1832
+ *
1833
+ * @example
1834
+ * ```typescript
1835
+ * // Bridge USDC via deBridge
1836
+ * const quote = await deBridgeMcp.create_tx({ ... });
1837
+ * const result = await wallet.executeTransaction({
1838
+ * to: quote.contractAddress,
1839
+ * data: quote.calldata,
1840
+ * estimatedCostUsd: 25.0,
1841
+ * description: 'Bridge 25 USDC Base -> Avalanche via deBridge',
1842
+ * });
1843
+ * console.log('TX:', result.txHash);
1844
+ * console.log('Budget remaining:', result.remainingBudgetUsd);
1845
+ * ```
1846
+ */
1847
+ executeTransaction(params: {
1848
+ to: `0x${string}`;
1849
+ data: `0x${string}`;
1850
+ value?: bigint;
1851
+ chainId?: number;
1852
+ estimatedCostUsd: number;
1853
+ description?: string;
1854
+ idempotencyKey?: string;
1855
+ }): Promise<{
1856
+ success: boolean;
1857
+ txHash: string;
1858
+ chargeId: string;
1859
+ estimatedCostUsd: number;
1860
+ remainingBudgetUsd: number | null;
1861
+ }>;
1862
+ /**
1863
+ * Use a configured skill by deploying a JIT MCP server with your saved API keys.
1864
+ *
1865
+ * Skills are configured on the MixrPay dashboard with your API keys stored securely.
1866
+ * When you call useSkill(), MixrPay deploys an ephemeral MCP server with your keys
1867
+ * injected server-side - your keys are never exposed to the agent.
1868
+ *
1869
+ * @param skillId - The skill ID (e.g., 'github', 'notion', 'spotify')
1870
+ * @param options - Optional configuration
1871
+ * @returns Skill endpoint and available tools
1872
+ *
1873
+ * @example
1874
+ * ```typescript
1875
+ * // Use the GitHub skill
1876
+ * const github = await wallet.useSkill('github');
1877
+ *
1878
+ * console.log('Endpoint:', github.endpoint);
1879
+ * console.log('Tools:', github.tools);
1880
+ * console.log('Expires:', github.expiresAt);
1881
+ *
1882
+ * // Connect to the MCP endpoint and call tools
1883
+ * // The exact method depends on your MCP client
1884
+ * ```
1885
+ *
1886
+ * @example
1887
+ * ```typescript
1888
+ * // Use Notion with custom TTL
1889
+ * const notion = await wallet.useSkill('notion', { ttlHours: 48 });
1890
+ * ```
1891
+ *
1892
+ * @throws {MixrPayError} If skill is not configured or deployment fails
1893
+ */
1894
+ useSkill(skillId: string, options?: UseSkillOptions): Promise<UseSkillResult>;
1895
+ /**
1896
+ * List all available skills and their configuration status.
1897
+ *
1898
+ * @returns Array of skills with status
1899
+ *
1900
+ * @example
1901
+ * ```typescript
1902
+ * const skills = await wallet.listSkills();
1903
+ *
1904
+ * // Find configured skills
1905
+ * const configured = skills.filter(s => s.status === 'configured');
1906
+ * console.log(`${configured.length} skills ready to use`);
1907
+ *
1908
+ * // Find skills that need configuration
1909
+ * const needsConfig = skills.filter(s => s.status === 'not_configured' && s.envVars.length > 0);
1910
+ * for (const skill of needsConfig) {
1911
+ * console.log(`${skill.name} needs: ${skill.envVars.map(v => v.label).join(', ')}`);
1912
+ * }
1913
+ * ```
1914
+ */
1915
+ listSkills(): Promise<SkillInfo[]>;
1916
+ /**
1917
+ * Get apps connected via Composio (Gmail, Slack, GitHub, etc.).
1918
+ *
1919
+ * Use this to discover which apps the owner has connected before
1920
+ * attempting to use them via `wallet.useSkill('composio')`.
1921
+ *
1922
+ * @returns Object with connected app names and connection details
1923
+ *
1924
+ * @example
1925
+ * ```typescript
1926
+ * const apps = await wallet.getConnectedApps();
1927
+ *
1928
+ * if (apps.connected.length === 0) {
1929
+ * console.log('No apps connected. Ask your owner to connect apps at the dashboard.');
1930
+ * } else {
1931
+ * console.log('Connected apps:', apps.connected.join(', '));
1932
+ *
1933
+ * if (apps.connected.includes('gmail')) {
1934
+ * // Safe to use Composio for Gmail
1935
+ * const { endpoint, tools } = await wallet.useSkill('composio');
1936
+ * // tools will include 'gmail_read_emails', 'gmail_send_email', etc.
1937
+ * }
1938
+ * }
1939
+ * ```
1940
+ */
1941
+ getConnectedApps(): Promise<ConnectedAppsResult>;
1942
+ /**
1943
+ * Get configuration status for a specific skill.
1944
+ *
1945
+ * @param skillId - The skill ID
1946
+ * @returns Skill configuration status
1947
+ *
1948
+ * @example
1949
+ * ```typescript
1950
+ * const status = await wallet.getSkillStatus('github');
1951
+ *
1952
+ * if (status.status === 'configured') {
1953
+ * console.log('GitHub is ready!');
1954
+ * console.log('Configured vars:', status.configuredVars);
1955
+ * } else {
1956
+ * console.log('Please configure GitHub at the MixrPay dashboard');
1957
+ * }
1958
+ * ```
1959
+ */
1960
+ getSkillStatus(skillId: string): Promise<SkillStatus>;
1961
+ /**
1962
+ * Configure a skill with API keys.
1450
1963
  *
1451
- * @param instanceId - The instance ID to retrieve
1452
- * @returns Full instance details including endpoint URL
1964
+ * This allows agents to save API keys received via chat to the MixrPay platform.
1965
+ * Keys are encrypted at rest and will be available for use on subsequent deploy/redeploy.
1453
1966
  *
1454
- * @example
1967
+ * @param skillId - The skill ID (e.g., 'web-search', 'github', 'notion') or custom skill with 'custom-' prefix
1968
+ * @param envVars - Environment variables with API keys (e.g., { BRAVE_API_KEY: 'xxx' })
1969
+ * @returns Configuration result with list of configured variables
1970
+ *
1971
+ * @example Predefined skill
1455
1972
  * ```typescript
1456
- * const instance = await wallet.getJitInstance('inst_abc123');
1457
- * console.log('Endpoint:', instance.endpointUrl);
1458
- * console.log('Expires:', instance.expiresAt);
1973
+ * // User provides API key in chat, agent saves it
1974
+ * const result = await wallet.configureSkill('web-search', {
1975
+ * BRAVE_API_KEY: 'BSA_abc123xyz',
1976
+ * });
1977
+ *
1978
+ * console.log('Configured:', result.configuredVars);
1979
+ * // After next redeploy, the skill will be enabled with this key
1980
+ * ```
1981
+ *
1982
+ * @example Custom API key
1983
+ * ```typescript
1984
+ * // For APIs not in predefined skills, use custom- prefix
1985
+ * // User: "Here's my Polymarket API key: pk_abc123"
1986
+ * const result = await wallet.configureSkill('custom-polymarket', {
1987
+ * POLYMARKET_API_KEY: 'pk_abc123',
1988
+ * });
1989
+ *
1990
+ * // The key is now available in the agent's environment
1991
+ * // Access via: process.env.POLYMARKET_API_KEY
1459
1992
  * ```
1460
1993
  */
1461
- getJitInstance(instanceId: string): Promise<JitInstance>;
1994
+ configureSkill(skillId: string, envVars: Record<string, string>): Promise<{
1995
+ success: boolean;
1996
+ skillId: string;
1997
+ configuredVars: string[];
1998
+ }>;
1462
1999
  /**
1463
2000
  * Search the Glama MCP server directory.
1464
2001
  *
@@ -1779,7 +2316,7 @@ declare class AgentWallet {
1779
2316
  */
1780
2317
  getAgentRunStatus(runId: string, _sessionId?: string): Promise<AgentRunStatusResult>;
1781
2318
  /**
1782
- * Call an MCP tool using session authorization (pre-authorized spending limit).
2319
+ * Call a gateway tool using session authorization (pre-authorized spending limit).
1783
2320
  *
1784
2321
  * Use this when you've already created a session with the tool provider
1785
2322
  * and want to use that spending limit instead of direct wallet charges.
@@ -1798,14 +2335,18 @@ declare class AgentWallet {
1798
2335
  * });
1799
2336
  *
1800
2337
  * // Use session for multiple calls
1801
- * const result = await wallet.callMCPToolWithSession(
2338
+ * const result = await wallet.callToolWithSession(
1802
2339
  * session.id,
1803
2340
  * 'firecrawl/scrape',
1804
2341
  * { url: 'https://example.com' }
1805
2342
  * );
1806
2343
  * ```
1807
2344
  */
1808
- callMCPToolWithSession(sessionId: string, toolName: string, args?: Record<string, unknown>): Promise<MCPToolResult>;
2345
+ callToolWithSession(sessionId: string, toolName: string, args?: Record<string, unknown>): Promise<ToolResult>;
2346
+ /**
2347
+ * @deprecated Use callToolWithSession() instead.
2348
+ */
2349
+ callMCPToolWithSession(sessionId: string, toolName: string, args?: Record<string, unknown>): Promise<ToolResult>;
1809
2350
  /**
1810
2351
  * Create a new task on the Task Board.
1811
2352
  *
@@ -2138,6 +2679,161 @@ declare class AgentWallet {
2138
2679
  private parseApprovalRequest;
2139
2680
  /** Helper to parse task from API response */
2140
2681
  private parseTask;
2682
+ /**
2683
+ * Get token balances for the wallet.
2684
+ *
2685
+ * Returns balances for USDC, ETH, and other tokens on the current chain.
2686
+ * For delegation wallets, also includes budget information.
2687
+ *
2688
+ * @returns Multi-token balance information
2689
+ * @throws {MixrPayError} If the request fails
2690
+ *
2691
+ * @example
2692
+ * ```typescript
2693
+ * const balances = await wallet.getBalances();
2694
+ * console.log(`USDC: ${balances.balances.USDC.balance}`);
2695
+ * console.log(`ETH: ${balances.balances.ETH.balance}`);
2696
+ * if (balances.delegation) {
2697
+ * console.log(`Budget remaining: $${balances.delegation.remaining_usd}`);
2698
+ * }
2699
+ * ```
2700
+ */
2701
+ getBalances(): Promise<BalancesResponse>;
2702
+ /**
2703
+ * Transfer USDC to another address.
2704
+ *
2705
+ * For delegation wallets: Uses delegation signing (no local key needed).
2706
+ * For self-custody wallets: Use transferUSDC() instead.
2707
+ *
2708
+ * @param to - Recipient address
2709
+ * @param amount - Amount in USD (e.g., "10.50")
2710
+ * @param currency - Currency to transfer (default: "USDC")
2711
+ * @returns Transfer result with transaction hash
2712
+ * @throws {MixrPayError} If the transfer fails
2713
+ *
2714
+ * @example
2715
+ * ```typescript
2716
+ * const result = await wallet.transfer('0x1234...', '10.00');
2717
+ * console.log(`Transferred $${result.amount_usd}`);
2718
+ * console.log(`TX: ${result.tx_hash}`);
2719
+ * console.log(`Remaining budget: $${result.remaining_budget_usd}`);
2720
+ * ```
2721
+ */
2722
+ transfer(to: string, amount: string, currency?: string): Promise<TransferResponse>;
2723
+ /**
2724
+ * Swap tokens using 0x Protocol on Base.
2725
+ *
2726
+ * Supports any ERC-20 token pair. First swap of a token may require
2727
+ * an approval transaction (extra gas).
2728
+ *
2729
+ * @param sellToken - Token to sell (symbol or address, e.g., "USDC", "ETH")
2730
+ * @param buyToken - Token to buy (symbol or address, e.g., "WETH", "USDC")
2731
+ * @param sellAmount - Amount to sell in human-readable format (e.g., "100" for 100 USDC)
2732
+ * @param slippageBps - Slippage tolerance in basis points (default: 100 = 1%)
2733
+ * @returns Swap result with transaction hash and amounts
2734
+ * @throws {MixrPayError} If the swap fails
2735
+ *
2736
+ * @example
2737
+ * ```typescript
2738
+ * // Swap 100 USDC for ETH
2739
+ * const result = await wallet.swap('USDC', 'ETH', '100');
2740
+ * console.log(`Swapped ${result.sell_amount} ${result.sell_token}`);
2741
+ * console.log(`Received ${result.buy_amount} ${result.buy_token}`);
2742
+ * console.log(`Price: ${result.price}`);
2743
+ * ```
2744
+ */
2745
+ swap(sellToken: string, buyToken: string, sellAmount: string, slippageBps?: number): Promise<SwapResponse>;
2746
+ /**
2747
+ * Bridge tokens to another chain using deBridge.
2748
+ *
2749
+ * Currently supports bridging from Base to other EVM chains.
2750
+ * The bridge transaction is submitted on the source chain; use
2751
+ * getBridgeStatus() to check completion on the destination chain.
2752
+ *
2753
+ * @param token - Token to bridge (symbol, e.g., "USDC")
2754
+ * @param amount - Amount in human-readable format (e.g., "100")
2755
+ * @param destChain - Destination chain ID or name (e.g., "1" for Ethereum, "arbitrum")
2756
+ * @param destAddress - Destination address (defaults to same address)
2757
+ * @returns Bridge result with order ID for tracking
2758
+ * @throws {MixrPayError} If the bridge fails
2759
+ *
2760
+ * @example
2761
+ * ```typescript
2762
+ * // Bridge 100 USDC to Arbitrum
2763
+ * const result = await wallet.bridge('USDC', '100', 'arbitrum');
2764
+ * console.log(`Bridge order: ${result.order_id}`);
2765
+ * console.log(`Expected to receive: ${result.estimated_receive}`);
2766
+ *
2767
+ * // Check status later
2768
+ * const status = await wallet.getBridgeStatus(result.order_id);
2769
+ * if (status.status === 'fulfilled') {
2770
+ * console.log(`Completed! Dest TX: ${status.dest_tx_hash}`);
2771
+ * }
2772
+ * ```
2773
+ */
2774
+ bridge(token: string, amount: string, destChain: string, destAddress?: string): Promise<BridgeResponse>;
2775
+ /**
2776
+ * Check the status of a bridge order.
2777
+ *
2778
+ * @param orderId - The order ID from bridge()
2779
+ * @returns Bridge status information
2780
+ * @throws {MixrPayError} If the status check fails
2781
+ *
2782
+ * @example
2783
+ * ```typescript
2784
+ * const status = await wallet.getBridgeStatus('abc123');
2785
+ * switch (status.status) {
2786
+ * case 'pending':
2787
+ * console.log(`Still bridging... ETA: ${status.estimated_time_remaining}`);
2788
+ * break;
2789
+ * case 'fulfilled':
2790
+ * console.log(`Complete! TX: ${status.dest_tx_hash}`);
2791
+ * break;
2792
+ * case 'failed':
2793
+ * console.log('Bridge failed');
2794
+ * break;
2795
+ * }
2796
+ * ```
2797
+ */
2798
+ getBridgeStatus(orderId: string): Promise<BridgeStatusResponse>;
2799
+ /**
2800
+ * Fetch a URL with automatic x402 payment handling.
2801
+ *
2802
+ * If the server returns 402 Payment Required, this method automatically
2803
+ * handles the payment from the wallet's delegation budget and retries
2804
+ * the request. Zero x402 knowledge needed.
2805
+ *
2806
+ * This is the agent-facing version of x402 fetch. For the underlying
2807
+ * fetch() that uses session key auth for x402, see the standard fetch() method.
2808
+ *
2809
+ * @param url - URL to fetch
2810
+ * @param options - Fetch options (method, headers, body, maxPaymentUsd)
2811
+ * @returns Response with status, headers, body, and optional payment info
2812
+ * @throws {MixrPayError} If the fetch fails
2813
+ *
2814
+ * @example
2815
+ * ```typescript
2816
+ * // Fetch from an x402-enabled API
2817
+ * const result = await wallet.fetchPaid('https://api.example.com/data', {
2818
+ * method: 'POST',
2819
+ * body: { query: 'AI analysis' },
2820
+ * maxPaymentUsd: 1.0,
2821
+ * });
2822
+ *
2823
+ * console.log(`Status: ${result.status}`);
2824
+ * console.log(`Data: ${JSON.stringify(result.body)}`);
2825
+ *
2826
+ * if (result.payment?.paid) {
2827
+ * console.log(`Paid $${result.payment.amount_usd}`);
2828
+ * }
2829
+ * ```
2830
+ */
2831
+ fetchPaid(url: string, options?: FetchPaidOptions): Promise<FetchPaidResponse>;
2832
+ /**
2833
+ * Call the API with agent token auth (agt_live_xxx bearer token).
2834
+ * Used by DeFi methods that require delegation auth.
2835
+ */
2836
+ private callApiWithAuth;
2141
2837
  /** Helper to call our API with auth */
2142
2838
  private callApi;
2143
2839
  }
@@ -2369,9 +3065,9 @@ interface MyTasksResult {
2369
3065
  };
2370
3066
  }
2371
3067
  /**
2372
- * MCP Tool definition returned by listMCPTools()
3068
+ * Tool definition returned by listTools()
2373
3069
  */
2374
- interface MCPTool {
3070
+ interface Tool {
2375
3071
  /** Tool name in format "merchant/tool" */
2376
3072
  name: string;
2377
3073
  /** Human-readable description with price */
@@ -2387,10 +3083,12 @@ interface MCPTool {
2387
3083
  /** Whether the provider is domain-verified */
2388
3084
  verified: boolean;
2389
3085
  }
3086
+ /** @deprecated Use Tool instead */
3087
+ type MCPTool = Tool;
2390
3088
  /**
2391
- * Result from calling an MCP tool
3089
+ * Result from calling a tool
2392
3090
  */
2393
- interface MCPToolResult {
3091
+ interface ToolResult {
2394
3092
  /** The tool's response data */
2395
3093
  data: unknown;
2396
3094
  /** Amount charged in USD */
@@ -2400,6 +3098,8 @@ interface MCPToolResult {
2400
3098
  /** Execution latency in milliseconds */
2401
3099
  latencyMs?: number;
2402
3100
  }
3101
+ /** @deprecated Use ToolResult instead */
3102
+ type MCPToolResult = ToolResult;
2403
3103
  /**
2404
3104
  * Message in an agent conversation
2405
3105
  */
@@ -2468,6 +3168,115 @@ interface JitInstance {
2468
3168
  /** Creation time */
2469
3169
  createdAt: Date;
2470
3170
  }
3171
+ /**
3172
+ * Options for using a skill
3173
+ */
3174
+ interface UseSkillOptions {
3175
+ /** Time-to-live in hours for the MCP server (default: 24, max: 48) */
3176
+ ttlHours?: number;
3177
+ }
3178
+ /**
3179
+ * Result from using a skill
3180
+ */
3181
+ interface UseSkillResult {
3182
+ /** Skill ID */
3183
+ skillId: string;
3184
+ /** MCP server endpoint URL */
3185
+ endpoint: string;
3186
+ /** Available tool names */
3187
+ tools: string[];
3188
+ /** When the MCP server expires */
3189
+ expiresAt: Date;
3190
+ /** JIT instance ID for reference */
3191
+ instanceId: string;
3192
+ }
3193
+ /**
3194
+ * Skill information from the skills list
3195
+ */
3196
+ interface SkillInfo {
3197
+ /** Skill ID */
3198
+ id: string;
3199
+ /** Display name */
3200
+ name: string;
3201
+ /** Short description */
3202
+ description: string;
3203
+ /** Category */
3204
+ category: string;
3205
+ /** Category display name */
3206
+ categoryName: string;
3207
+ /** Icon name */
3208
+ icon: string;
3209
+ /** Whether this is a built-in skill */
3210
+ builtIn: boolean;
3211
+ /** Whether this skill requires MCP deployment */
3212
+ requiresMcp: boolean;
3213
+ /** Whether this skill is available */
3214
+ available: boolean;
3215
+ /** Configuration status */
3216
+ status: 'not_configured' | 'configured' | 'error';
3217
+ /** Last used timestamp */
3218
+ lastUsedAt?: string;
3219
+ /** Error message if status is 'error' */
3220
+ errorMessage?: string;
3221
+ /** Environment variables required */
3222
+ envVars: Array<{
3223
+ name: string;
3224
+ label: string;
3225
+ description: string;
3226
+ required: boolean;
3227
+ isSecret: boolean;
3228
+ configured: boolean;
3229
+ }>;
3230
+ }
3231
+ /**
3232
+ * Skill configuration status
3233
+ */
3234
+ interface SkillStatus {
3235
+ /** Skill ID */
3236
+ skillId: string;
3237
+ /** Configuration status */
3238
+ status: 'not_configured' | 'configured' | 'error';
3239
+ /** Names of configured environment variables */
3240
+ configuredVars: string[];
3241
+ /** Last used timestamp */
3242
+ lastUsedAt?: Date;
3243
+ /** Error message if status is 'error' */
3244
+ errorMessage?: string;
3245
+ }
3246
+ /**
3247
+ * Connected apps information from Composio
3248
+ */
3249
+ interface ConnectedAppsResult {
3250
+ /** Array of connected app IDs (e.g., ['gmail', 'slack', 'github']) */
3251
+ connected: string[];
3252
+ /** Full connection details */
3253
+ connections: Array<{
3254
+ id: string;
3255
+ app: string;
3256
+ app_name: string;
3257
+ type: 'oauth' | 'api_key';
3258
+ status: string;
3259
+ account_name: string | null;
3260
+ connected_at: string;
3261
+ }>;
3262
+ /** OAuth connections only */
3263
+ oauthConnections: Array<{
3264
+ id: string;
3265
+ app: string;
3266
+ app_name: string;
3267
+ status: string;
3268
+ account_name: string | null;
3269
+ connected_at: string;
3270
+ }>;
3271
+ /** API key connections only */
3272
+ apiKeyConnections: Array<{
3273
+ id: string;
3274
+ app: string;
3275
+ app_name: string;
3276
+ status: string;
3277
+ connected_at: string;
3278
+ }>;
3279
+ }
2471
3280
  /**
2472
3281
  * MCP server from the Glama directory
2473
3282
  */
@@ -3367,6 +4176,115 @@ declare class MerchantNotAllowedError extends MixrPayError {
3367
4176
  readonly allowedPatterns: string[];
3368
4177
  constructor(attempted: string, allowedPatterns: string[]);
3369
4178
  }
4179
+ /**
4180
+ * Thrown when the API returns a 429 rate limit response.
4181
+ *
4182
+ * This error includes a suggested retry delay. The operation can be retried
4183
+ * after waiting the specified time.
4184
+ *
4185
+ * ## Resolution
4186
+ * 1. Wait for `retryAfterMs` milliseconds
4187
+ * 2. Reduce request frequency
4188
+ * 3. Contact support if limits are too restrictive
4189
+ *
4190
+ * @example
4191
+ * ```typescript
4192
+ * try {
4193
+ * await wallet.fetch(...);
4194
+ * } catch (error) {
4195
+ * if (error instanceof RateLimitError) {
4196
+ * console.log(`Rate limited. Retry after ${error.retryAfterMs}ms`);
4197
+ * await sleep(error.retryAfterMs);
4198
+ * // Retry the operation
4199
+ * }
4200
+ * }
4201
+ * ```
4202
+ */
4203
+ declare class RateLimitError extends MixrPayError {
4204
+ constructor(retryAfterMs?: number, message?: string);
4205
+ /**
4206
+ * Rate limits are transient and operations can be retried after waiting.
4207
+ * @returns true - always retryable after the delay
4208
+ */
4209
+ isRetryable(): boolean;
4210
+ }
4211
+ /**
4212
+ * Thrown when a network error occurs during an API call.
4213
+ *
4214
+ * This includes:
4215
+ * - DNS resolution failures
4216
+ * - Connection timeouts
4217
+ * - Network disconnection
4218
+ * - SSL/TLS errors
4219
+ *
4220
+ * ## Resolution
4221
+ * 1. Check network connectivity
4222
+ * 2. Retry the operation with exponential backoff
4223
+ * 3. Check if the API endpoint is reachable
4224
+ *
4225
+ * @example
4226
+ * ```typescript
4227
+ * try {
4228
+ * await wallet.fetch(...);
4229
+ * } catch (error) {
4230
+ * if (error instanceof NetworkError) {
4231
+ * console.log(`Network error: ${error.reason}`);
4232
+ * if (error.isRetryable()) {
4233
+ * await retry();
4234
+ * }
4235
+ * }
4236
+ * }
4237
+ * ```
4238
+ */
4239
+ declare class NetworkError extends MixrPayError {
4240
+ /** The underlying error reason */
4241
+ readonly reason: string;
4242
+ constructor(reason: string, originalError?: Error);
4243
+ /**
4244
+ * Network errors are typically transient.
4245
+ * @returns true - network issues usually resolve
4246
+ */
4247
+ isRetryable(): boolean;
4248
+ }
4249
+ /**
4250
+ * Thrown when authentication fails (401/403 responses).
4251
+ *
4252
+ * This error indicates:
4253
+ * - Invalid API key or session key
4254
+ * - Expired credentials
4255
+ * - Missing authentication headers
4256
+ * - Insufficient permissions
4257
+ *
4258
+ * ## Resolution
4259
+ * 1. Verify your session key is correct
4260
+ * 2. Check if the key has expired
4261
+ * 3. Ensure the key has permissions for the operation
4262
+ * 4. Request a new session key if needed
4263
+ *
4264
+ * @example
4265
+ * ```typescript
4266
+ * try {
4267
+ * await wallet.fetch(...);
4268
+ * } catch (error) {
4269
+ * if (error instanceof AuthenticationError) {
4270
+ * console.log(`Auth failed: ${error.reason}`);
4271
+ * // Request new credentials
4272
+ * }
4273
+ * }
4274
+ * ```
4275
+ */
4276
+ declare class AuthenticationError extends MixrPayError {
4277
+ /** The specific authentication failure reason */
4278
+ readonly reason: string;
4279
+ /** HTTP status code (401 or 403) */
4280
+ readonly statusCode: number;
4281
+ constructor(reason: string, statusCode?: 401 | 403);
4282
+ /**
4283
+ * Authentication errors are not retryable without user action.
4284
+ * @returns false - requires new credentials
4285
+ */
4286
+ isRetryable(): boolean;
4287
+ }
3370
4288
  /**
3371
4289
  * Check if an error is a MixrPay SDK error.
3372
4290
  *
@@ -3403,4 +4321,199 @@ declare function isMixrPayError(error: unknown): error is MixrPayError;
3403
4321
  */
3404
4322
  declare function getErrorMessage(error: unknown): string;
3405
4323
 
3406
- export { type AgentClaimInviteOptions, type AgentClaimInviteResult, type AgentMessage, type AgentRunConfig, type AgentRunEvent, type AgentRunOptions, type AgentRunResult, type AgentRunStatusResult, AgentWallet, type AgentWalletConfig, type AvailableBudget, type CallMerchantApiOptions, type ChargeResult, type ChildSession, type CompleteOptions, type CompleteResult, type DeployJitMcpOptions, type DeployJitMcpResult, type DiagnosticsResult, type GlamaImportData, type GlamaSearchResult, type GlamaServer, InsufficientBalanceError, InvalidSessionKeyError, type JitInstance, MerchantNotAllowedError, MixrPayError, type PaymentEvent, PaymentFailedError, SDK_VERSION, type SessionAuthorization, SessionExpiredError, SessionKeyExpiredError, type SessionKeyInfo, SessionLimitExceededError, SessionNotFoundError, SessionRevokedError, type SessionStats, type SpawnChildOptions, type SpawnChildResult, SpendingLimitExceededError, type SpendingStats, X402ProtocolError, getErrorMessage, isMixrPayError };
4324
+ /**
4325
+ * MixrPay Agent SDK - Credential Management
4326
+ *
4327
+ * Platform-aware credential storage for session keys and API tokens.
4328
+ * Stores credentials securely with appropriate file permissions.
4329
+ *
4330
+ * Storage locations:
4331
+ * - Linux/macOS: ~/.config/mixrpay/credentials.json
4332
+ * - Windows: %APPDATA%/mixrpay/credentials.json
4333
+ *
4334
+ * File permissions: 0600 (read/write for owner only)
4335
+ */
4336
+ interface StoredCredentials {
4337
+ /** Session key (sk_live_xxx or sk_test_xxx) */
4338
+ sessionKey?: string;
4339
+ /** API token (agt_live_xxx) for API calls */
4340
+ apiToken?: string;
4341
+ /** @deprecated Use apiToken instead. Legacy connect token (ac_live_xxx) */
4342
+ connectToken?: string;
4343
+ /** Master key (mk_live_xxx) for multi-agent management */
4344
+ masterKey?: string;
4345
+ /** Default agent name (used with master key) */
4346
+ defaultAgentName?: string;
4347
+ /** Base URL override */
4348
+ baseUrl?: string;
4349
+ /** When credentials were last updated */
4350
+ updatedAt?: string;
4351
+ }
4352
+ type CredentialLoadResult = {
4353
+ success: true;
4354
+ credentials: StoredCredentials;
4355
+ } | {
4356
+ success: false;
4357
+ error: string;
4358
+ };
4359
+ /**
4360
+ * Save credentials to the platform-specific config location.
4361
+ *
4362
+ * @param credentials - Credentials to save (merged with existing)
4363
+ * @returns true if successful, false otherwise
4364
+ *
4365
+ * @example
4366
+ * ```typescript
4367
+ * // Save a session key
4368
+ * await saveCredentials({ sessionKey: 'sk_live_xxx' });
4369
+ *
4370
+ * // Save multiple credentials
4371
+ * await saveCredentials({
4372
+ * masterKey: 'mk_live_xxx',
4373
+ * defaultAgentName: 'my-agent',
4374
+ * });
4375
+ * ```
4376
+ */
4377
+ declare function saveCredentials(credentials: Partial<StoredCredentials>): boolean;
4378
+ /**
4379
+ * Load credentials from the platform-specific config location.
4380
+ *
4381
+ * @returns Loaded credentials or error
4382
+ *
4383
+ * @example
4384
+ * ```typescript
4385
+ * const result = loadCredentials();
4386
+ * if (result.success) {
4387
+ * console.log('Session key:', result.credentials.sessionKey);
4388
+ * }
4389
+ * ```
4390
+ */
4391
+ declare function loadCredentials(): CredentialLoadResult;
4392
+ /**
4393
+ * Delete stored credentials.
4394
+ *
4395
+ * @param keys - Specific keys to delete, or undefined to delete all
4396
+ * @returns true if successful
4397
+ *
4398
+ * @example
4399
+ * ```typescript
4400
+ * // Delete specific credentials
4401
+ * deleteCredentials(['sessionKey', 'apiToken']);
4402
+ *
4403
+ * // Delete all credentials
4404
+ * deleteCredentials();
4405
+ * ```
4406
+ */
4407
+ declare function deleteCredentials(keys?: (keyof StoredCredentials)[]): boolean;
4408
+ /**
4409
+ * Check if credentials are stored.
4410
+ *
4411
+ * @returns true if any credentials are stored
4412
+ */
4413
+ declare function hasCredentials(): boolean;
4414
+ /**
4415
+ * Get the path to the credentials file (for debugging/info).
4416
+ *
4417
+ * @returns The credentials file path
4418
+ */
4419
+ declare function getCredentialsFilePath(): string;
4420
+
4421
+ /**
4422
+ * MixrPay Agent SDK - Wallet Storage
4423
+ * @packageDocumentation
4424
+ */
4425
+ /**
4426
+ * Structure of the stored wallet file
4427
+ */
4428
+ interface StoredWallet {
4429
+ /** Wallet address (0x-prefixed) */
4430
+ address: string;
4431
+ /** Private key (0x-prefixed hex) */
4432
+ privateKey: string;
4433
+ /** ISO timestamp when wallet was created */
4434
+ createdAt: string;
4435
+ /** SDK version that created the wallet */
4436
+ sdkVersion: string;
4437
+ }
4438
+ /**
4439
+ * Save a wallet private key to local storage.
4440
+ *
4441
+ * Creates the config directory if it doesn't exist.
4442
+ * Sets file permissions to 0o600 (owner read/write only).
4443
+ *
4444
+ * @param privateKey - The wallet private key (0x-prefixed hex)
4445
+ * @param address - The wallet address (0x-prefixed)
4446
+ * @throws Error if unable to write to filesystem
4447
+ *
4448
+ * @example
4449
+ * ```typescript
4450
+ * import { saveWalletKey } from '@mixrpay/agent-sdk';
4451
+ * import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
4452
+ *
4453
+ * const privateKey = generatePrivateKey();
4454
+ * const account = privateKeyToAccount(privateKey);
4455
+ * await saveWalletKey(privateKey, account.address);
4456
+ * ```
4457
+ */
4458
+ declare function saveWalletKey(privateKey: `0x${string}`, address: string): Promise<void>;
4459
+ /**
4460
+ * Load the wallet private key from storage.
4461
+ *
4462
+ * Checks in order:
4463
+ * 1. MIXRPAY_WALLET_KEY environment variable
4464
+ * 2. Local wallet file
4465
+ *
4466
+ * @returns The private key (0x-prefixed hex) or null if not found
4467
+ *
4468
+ * @example
4469
+ * ```typescript
4470
+ * import { loadWalletKey } from '@mixrpay/agent-sdk';
4471
+ *
4472
+ * const privateKey = await loadWalletKey();
4473
+ * if (privateKey) {
4474
+ * console.log('Wallet loaded successfully');
4475
+ * }
4476
+ * ```
4477
+ */
4478
+ declare function loadWalletKey(): Promise<`0x${string}` | null>;
4479
+ /**
4480
+ * Load the full wallet data including address and metadata.
4481
+ *
4482
+ * @returns The stored wallet data or null if not found
4483
+ */
4484
+ declare function loadWalletData(): Promise<StoredWallet | null>;
4485
+ /**
4486
+ * Check if a wallet key exists in storage.
4487
+ *
4488
+ * @returns True if a wallet key is available
4489
+ *
4490
+ * @example
4491
+ * ```typescript
4492
+ * import { hasWalletKey, loadWalletKey } from '@mixrpay/agent-sdk';
4493
+ *
4494
+ * if (await hasWalletKey()) {
4495
+ * const key = await loadWalletKey();
4496
+ * // Use existing wallet
4497
+ * } else {
4498
+ * // Create new wallet
4499
+ * }
4500
+ * ```
4501
+ */
4502
+ declare function hasWalletKey(): Promise<boolean>;
4503
+ /**
4504
+ * Get the wallet storage path for debugging.
4505
+ *
4506
+ * @returns The path where the wallet would be stored
4507
+ */
4508
+ declare function getWalletStoragePath(): string;
4509
+ /**
4510
+ * Delete the stored wallet key.
4511
+ *
4512
+ * WARNING: This permanently deletes the wallet key. Make sure you have
4513
+ * backed up the key before calling this.
4514
+ *
4515
+ * @returns True if a wallet was deleted, false if no wallet existed
4516
+ */
4517
+ declare function deleteWalletKey(): Promise<boolean>;
4518
+
4519
+ export { type AgentClaimInviteOptions, type AgentClaimInviteResult, type AgentMessage, type AgentRunConfig, type AgentRunEvent, type AgentRunOptions, type AgentRunResult, type AgentRunStatusResult, AgentWallet, type AgentWalletConfig, AuthenticationError, type AvailableBudget, type BalancesResponse, type BridgeResponse, type BridgeStatusResponse, type CallMerchantApiOptions, type ChargeResult, type ChildSession, type CompleteOptions, type CompleteResult, type ConnectOptions, type CredentialLoadResult, type DelegationBudget, type DeployJitMcpOptions, type DeployJitMcpResult, type DiagnosticsResult, type FetchPaidOptions, type FetchPaidResponse, type FetchPaymentInfo, type GlamaImportData, type GlamaSearchResult, type GlamaServer, InsufficientBalanceError, InvalidSessionKeyError, type JitInstance, type MCPTool, type MCPToolResult, type McpServerConfig, MerchantNotAllowedError, MixrPayError, NetworkError, type PaymentEvent, PaymentFailedError, RateLimitError, SDK_VERSION, type SessionAuthorization, SessionExpiredError, SessionKeyExpiredError, type SessionKeyInfo, SessionLimitExceededError, SessionNotFoundError, SessionRevokedError, type SessionStats, type SiweOptions, type SiweResult, type SkillInfo, type SkillStatus, type SpawnChildOptions, type SpawnChildResult, SpendingLimitExceededError, type SpendingStats, type StoredCredentials, type StoredWallet, type SwapResponse, type TokenBalance, type Tool, type ToolResult, type TransferResponse, type UseSkillOptions, type UseSkillResult, X402ProtocolError, deleteCredentials, deleteWalletKey, getCredentialsFilePath, getErrorMessage, getWalletStoragePath, hasCredentials, hasWalletKey, isMixrPayError, loadCredentials, loadWalletData, loadWalletKey, saveCredentials, saveWalletKey };