@sly_ai/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +346 -0
  2. package/dist/a2a.d.mts +108 -0
  3. package/dist/a2a.d.ts +108 -0
  4. package/dist/a2a.js +173 -0
  5. package/dist/a2a.js.map +1 -0
  6. package/dist/a2a.mjs +171 -0
  7. package/dist/a2a.mjs.map +1 -0
  8. package/dist/acp.d.mts +201 -0
  9. package/dist/acp.d.ts +201 -0
  10. package/dist/acp.js +143 -0
  11. package/dist/acp.js.map +1 -0
  12. package/dist/acp.mjs +141 -0
  13. package/dist/acp.mjs.map +1 -0
  14. package/dist/ap2.d.mts +188 -0
  15. package/dist/ap2.d.ts +188 -0
  16. package/dist/ap2.js +135 -0
  17. package/dist/ap2.js.map +1 -0
  18. package/dist/ap2.mjs +133 -0
  19. package/dist/ap2.mjs.map +1 -0
  20. package/dist/cards.d.mts +750 -0
  21. package/dist/cards.d.ts +750 -0
  22. package/dist/cards.js +373 -0
  23. package/dist/cards.js.map +1 -0
  24. package/dist/cards.mjs +369 -0
  25. package/dist/cards.mjs.map +1 -0
  26. package/dist/client-Cwe2CLU7.d.mts +41 -0
  27. package/dist/client-CyJe3uWO.d.ts +41 -0
  28. package/dist/index.d.mts +662 -0
  29. package/dist/index.d.ts +662 -0
  30. package/dist/index.js +2709 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/index.mjs +2700 -0
  33. package/dist/index.mjs.map +1 -0
  34. package/dist/langchain.d.mts +11 -0
  35. package/dist/langchain.d.ts +11 -0
  36. package/dist/langchain.js +25 -0
  37. package/dist/langchain.js.map +1 -0
  38. package/dist/langchain.mjs +23 -0
  39. package/dist/langchain.mjs.map +1 -0
  40. package/dist/types-df1EICn_.d.mts +165 -0
  41. package/dist/types-df1EICn_.d.ts +165 -0
  42. package/dist/ucp.d.mts +844 -0
  43. package/dist/ucp.d.ts +844 -0
  44. package/dist/ucp.js +616 -0
  45. package/dist/ucp.js.map +1 -0
  46. package/dist/ucp.mjs +614 -0
  47. package/dist/ucp.mjs.map +1 -0
  48. package/dist/vercel.d.mts +178 -0
  49. package/dist/vercel.d.ts +178 -0
  50. package/dist/vercel.js +143 -0
  51. package/dist/vercel.js.map +1 -0
  52. package/dist/vercel.mjs +138 -0
  53. package/dist/vercel.mjs.map +1 -0
  54. package/dist/x402.d.mts +209 -0
  55. package/dist/x402.d.ts +209 -0
  56. package/dist/x402.js +476 -0
  57. package/dist/x402.js.map +1 -0
  58. package/dist/x402.mjs +471 -0
  59. package/dist/x402.mjs.map +1 -0
  60. package/package.json +118 -0
package/dist/index.js ADDED
@@ -0,0 +1,2709 @@
1
+ 'use strict';
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __esm = (fn, res) => function __init() {
6
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
7
+ };
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+
13
+ // src/config.ts
14
+ function inferEnvironmentFromKey(apiKey) {
15
+ if (apiKey.startsWith("pk_test_") || apiKey.startsWith("pk_sandbox_")) {
16
+ return "sandbox";
17
+ }
18
+ if (apiKey.startsWith("pk_live_")) {
19
+ return "production";
20
+ }
21
+ return void 0;
22
+ }
23
+ function getEnvironmentConfig(environment) {
24
+ return exports.ENVIRONMENT_CONFIGS[environment];
25
+ }
26
+ function validateEnvironment(environment, evmPrivateKey) {
27
+ if (environment !== "sandbox" && !evmPrivateKey) {
28
+ throw new Error(
29
+ `EVM private key is required for ${environment} environment. Use sandbox mode for local development without blockchain.`
30
+ );
31
+ }
32
+ }
33
+ exports.ENVIRONMENT_CONFIGS = void 0;
34
+ var init_config = __esm({
35
+ "src/config.ts"() {
36
+ exports.ENVIRONMENT_CONFIGS = {
37
+ sandbox: {
38
+ apiUrl: "https://sandbox.getsly.ai",
39
+ facilitatorUrl: "https://facilitator.x402.org"
40
+ // x402.org Base Sepolia
41
+ },
42
+ testnet: {
43
+ apiUrl: "https://sandbox.getsly.ai",
44
+ facilitatorUrl: "https://facilitator.x402.org"
45
+ // x402.org Base Sepolia
46
+ },
47
+ production: {
48
+ apiUrl: "https://api.getsly.ai",
49
+ facilitatorUrl: "https://facilitator.coinbase.com"
50
+ // Coinbase CDP Base mainnet
51
+ }
52
+ };
53
+ }
54
+ });
55
+
56
+ // src/client.ts
57
+ exports.SlyClient = void 0;
58
+ var init_client = __esm({
59
+ "src/client.ts"() {
60
+ init_config();
61
+ exports.SlyClient = class {
62
+ constructor(config) {
63
+ this.apiKey = config.apiKey;
64
+ const environment = config.environment ?? inferEnvironmentFromKey(config.apiKey) ?? "sandbox";
65
+ const envConfig = getEnvironmentConfig(environment);
66
+ this.apiUrl = config.apiUrl || envConfig.apiUrl;
67
+ }
68
+ /**
69
+ * Make an authenticated API request
70
+ */
71
+ async request(path, options = {}) {
72
+ const url = `${this.apiUrl}${path}`;
73
+ const response = await fetch(url, {
74
+ ...options,
75
+ headers: {
76
+ "Authorization": `Bearer ${this.apiKey}`,
77
+ "Content-Type": "application/json",
78
+ ...options.headers
79
+ }
80
+ });
81
+ if (!response.ok) {
82
+ const errorData = await response.json().catch(() => ({
83
+ message: response.statusText
84
+ }));
85
+ const error = new Error(errorData.error || errorData.message || `HTTP ${response.status}`);
86
+ error.status = response.status;
87
+ error.data = errorData;
88
+ throw error;
89
+ }
90
+ return response.json();
91
+ }
92
+ /**
93
+ * Get a settlement quote
94
+ */
95
+ async getSettlementQuote(request) {
96
+ return this.request("/v1/settlements/quote", {
97
+ method: "POST",
98
+ body: JSON.stringify(request)
99
+ });
100
+ }
101
+ /**
102
+ * Create a settlement
103
+ */
104
+ async createSettlement(request) {
105
+ return this.request("/v1/settlements", {
106
+ method: "POST",
107
+ body: JSON.stringify(request)
108
+ });
109
+ }
110
+ /**
111
+ * Get settlement status
112
+ */
113
+ async getSettlement(settlementId) {
114
+ return this.request(`/v1/settlements/${settlementId}`);
115
+ }
116
+ /**
117
+ * Check compliance for a recipient
118
+ */
119
+ async checkCompliance(request) {
120
+ return this.request("/v1/compliance/check", {
121
+ method: "POST",
122
+ body: JSON.stringify(request)
123
+ });
124
+ }
125
+ /**
126
+ * Get API capabilities
127
+ */
128
+ async getCapabilities() {
129
+ return this.request("/v1/capabilities");
130
+ }
131
+ };
132
+ }
133
+ });
134
+
135
+ // src/facilitator/sandbox-facilitator.ts
136
+ var SandboxFacilitator;
137
+ var init_sandbox_facilitator = __esm({
138
+ "src/facilitator/sandbox-facilitator.ts"() {
139
+ SandboxFacilitator = class {
140
+ constructor(config) {
141
+ this.config = {
142
+ apiUrl: config.apiUrl,
143
+ apiKey: config.apiKey,
144
+ settlementDelayMs: config.settlementDelayMs ?? 0,
145
+ failureRate: config.failureRate ?? 0,
146
+ debug: config.debug ?? false,
147
+ supportedSchemes: config.supportedSchemes ?? [
148
+ {
149
+ scheme: "exact-evm",
150
+ networks: ["eip155:8453", "eip155:84532"]
151
+ // Base mainnet and Sepolia
152
+ }
153
+ ]
154
+ };
155
+ if (this.config.debug) {
156
+ console.log("[SandboxFacilitator] Initialized with config:", {
157
+ apiUrl: this.config.apiUrl,
158
+ settlementDelayMs: this.config.settlementDelayMs,
159
+ failureRate: this.config.failureRate
160
+ });
161
+ }
162
+ }
163
+ /**
164
+ * Verify a payment payload
165
+ *
166
+ * In sandbox mode, this validates the structure but skips signature verification
167
+ */
168
+ async verify(request) {
169
+ const { payment } = request;
170
+ if (this.config.debug) {
171
+ console.log("[SandboxFacilitator] Verifying payment:", payment);
172
+ }
173
+ const requiredFields = ["scheme", "network", "amount", "token", "from", "to"];
174
+ for (const field of requiredFields) {
175
+ if (!payment[field]) {
176
+ return {
177
+ valid: false,
178
+ reason: `Missing required field: ${field}`
179
+ };
180
+ }
181
+ }
182
+ const schemeSupported = this.config.supportedSchemes.some(
183
+ (s) => s.scheme === payment.scheme
184
+ );
185
+ if (!schemeSupported) {
186
+ return {
187
+ valid: false,
188
+ reason: `Unsupported scheme: ${payment.scheme}`,
189
+ details: {
190
+ supportedSchemes: this.config.supportedSchemes.map((s) => s.scheme)
191
+ }
192
+ };
193
+ }
194
+ const scheme = this.config.supportedSchemes.find(
195
+ (s) => s.scheme === payment.scheme
196
+ );
197
+ if (scheme && !scheme.networks.includes(payment.network)) {
198
+ return {
199
+ valid: false,
200
+ reason: `Unsupported network: ${payment.network} for scheme: ${payment.scheme}`,
201
+ details: {
202
+ supportedNetworks: scheme.networks
203
+ }
204
+ };
205
+ }
206
+ const amount = parseFloat(payment.amount);
207
+ if (isNaN(amount) || amount <= 0) {
208
+ return {
209
+ valid: false,
210
+ reason: `Invalid amount: ${payment.amount}`
211
+ };
212
+ }
213
+ return {
214
+ valid: true
215
+ };
216
+ }
217
+ /**
218
+ * Settle a payment
219
+ *
220
+ * In sandbox mode, this generates a mock transaction hash and
221
+ * optionally records the payment in PayOS
222
+ */
223
+ async settle(request) {
224
+ const { payment } = request;
225
+ if (this.config.debug) {
226
+ console.log("[SandboxFacilitator] Settling payment:", payment);
227
+ }
228
+ const verification = await this.verify({ payment });
229
+ if (!verification.valid) {
230
+ throw new Error(`Payment verification failed: ${verification.reason}`);
231
+ }
232
+ if (this.config.failureRate > 0) {
233
+ const random = Math.random() * 100;
234
+ if (random < this.config.failureRate) {
235
+ throw new Error("Simulated settlement failure");
236
+ }
237
+ }
238
+ if (this.config.settlementDelayMs > 0) {
239
+ await new Promise(
240
+ (resolve) => setTimeout(resolve, this.config.settlementDelayMs)
241
+ );
242
+ }
243
+ const txHash = this.generateMockTxHash();
244
+ if (this.config.debug) {
245
+ console.log("[SandboxFacilitator] Settlement complete:", {
246
+ txHash,
247
+ amount: payment.amount,
248
+ from: payment.from,
249
+ to: payment.to
250
+ });
251
+ }
252
+ return {
253
+ transactionHash: txHash,
254
+ settled: true,
255
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
256
+ };
257
+ }
258
+ /**
259
+ * Get supported schemes and networks
260
+ */
261
+ async supported() {
262
+ return {
263
+ schemes: this.config.supportedSchemes
264
+ };
265
+ }
266
+ /**
267
+ * Generate a realistic-looking mock transaction hash
268
+ */
269
+ generateMockTxHash() {
270
+ const chars = "0123456789abcdef";
271
+ let hash = "0x";
272
+ for (let i = 0; i < 64; i++) {
273
+ hash += chars[Math.floor(Math.random() * chars.length)];
274
+ }
275
+ return hash;
276
+ }
277
+ };
278
+ }
279
+ });
280
+
281
+ // src/protocols/x402/client.ts
282
+ var SlyX402Client;
283
+ var init_client2 = __esm({
284
+ "src/protocols/x402/client.ts"() {
285
+ init_config();
286
+ init_sandbox_facilitator();
287
+ SlyX402Client = class {
288
+ constructor(config) {
289
+ this.dailySpent = 0;
290
+ validateEnvironment(config.environment, config.evmPrivateKey);
291
+ const envConfig = getEnvironmentConfig(config.environment);
292
+ this.config = {
293
+ apiKey: config.apiKey,
294
+ environment: config.environment,
295
+ evmPrivateKey: config.evmPrivateKey,
296
+ facilitatorUrl: config.facilitatorUrl || envConfig.facilitatorUrl || "",
297
+ maxAutoPayAmount: config.maxAutoPayAmount || "1.00",
298
+ maxDailySpend: config.maxDailySpend || "100.00",
299
+ onPayment: config.onPayment,
300
+ onSettlement: config.onSettlement,
301
+ settleToRail: config.settleToRail
302
+ };
303
+ this.lastResetDate = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
304
+ if (this.config.environment === "sandbox") {
305
+ this.sandboxFacilitator = new SandboxFacilitator({
306
+ apiUrl: envConfig.apiUrl,
307
+ apiKey: this.config.apiKey
308
+ });
309
+ }
310
+ }
311
+ /**
312
+ * Fetch a resource with automatic 402 payment handling
313
+ */
314
+ async fetch(url, options = {}) {
315
+ const { maxPayment, ...fetchOptions } = options;
316
+ let response = await fetch(url, fetchOptions);
317
+ if (response.status !== 402) {
318
+ return response;
319
+ }
320
+ const paymentRequired = await this.parse402Response(response);
321
+ const acceptedOption = paymentRequired.accepts[0];
322
+ if (!acceptedOption) {
323
+ throw new Error("No acceptable payment options in 402 response");
324
+ }
325
+ const amount = parseFloat(acceptedOption.amount);
326
+ const maxAmount = parseFloat(maxPayment || this.config.maxAutoPayAmount);
327
+ if (amount > maxAmount) {
328
+ throw new Error(
329
+ `Payment amount ${acceptedOption.amount} exceeds max auto-pay amount ${maxPayment || this.config.maxAutoPayAmount}`
330
+ );
331
+ }
332
+ this.resetDailySpendIfNeeded();
333
+ if (this.dailySpent + amount > parseFloat(this.config.maxDailySpend)) {
334
+ throw new Error(
335
+ `Payment would exceed daily limit. Spent: ${this.dailySpent}, Limit: ${this.config.maxDailySpend}`
336
+ );
337
+ }
338
+ const payment = await this.createPayment(acceptedOption);
339
+ if (this.config.onPayment) {
340
+ await this.config.onPayment({
341
+ amount: acceptedOption.amount,
342
+ currency: acceptedOption.token,
343
+ from: payment.from,
344
+ to: payment.to,
345
+ scheme: acceptedOption.scheme,
346
+ network: acceptedOption.network,
347
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
348
+ });
349
+ }
350
+ this.dailySpent += amount;
351
+ response = await fetch(url, {
352
+ ...fetchOptions,
353
+ headers: {
354
+ ...fetchOptions.headers,
355
+ "X-Payment": JSON.stringify(payment)
356
+ }
357
+ });
358
+ if (this.config.onSettlement && payment.transactionHash) {
359
+ await this.config.onSettlement({
360
+ transactionHash: payment.transactionHash,
361
+ amount: acceptedOption.amount,
362
+ currency: acceptedOption.token,
363
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
364
+ });
365
+ }
366
+ return response;
367
+ }
368
+ /**
369
+ * Get client status
370
+ */
371
+ getStatus() {
372
+ this.resetDailySpendIfNeeded();
373
+ return {
374
+ environment: this.config.environment,
375
+ dailySpent: this.dailySpent.toFixed(2),
376
+ dailyLimit: this.config.maxDailySpend,
377
+ walletAddress: this.getWalletAddress()
378
+ };
379
+ }
380
+ /**
381
+ * Parse 402 response
382
+ */
383
+ async parse402Response(response) {
384
+ const body = await response.json();
385
+ if (!body.accepts || !Array.isArray(body.accepts)) {
386
+ throw new Error("Invalid 402 response: missing accepts array");
387
+ }
388
+ return {
389
+ statusCode: 402,
390
+ accepts: body.accepts
391
+ };
392
+ }
393
+ /**
394
+ * Create payment based on environment
395
+ */
396
+ async createPayment(option) {
397
+ if (this.config.environment === "sandbox") {
398
+ return this.createSandboxPayment(option);
399
+ } else {
400
+ return this.createBlockchainPayment(option);
401
+ }
402
+ }
403
+ /**
404
+ * Create sandbox payment (mock)
405
+ */
406
+ async createSandboxPayment(option) {
407
+ if (!this.sandboxFacilitator) {
408
+ throw new Error("Sandbox facilitator not initialized");
409
+ }
410
+ const payment = {
411
+ scheme: option.scheme,
412
+ network: option.network,
413
+ amount: option.amount,
414
+ token: option.token,
415
+ from: "0x0000000000000000000000000000000000000001",
416
+ // Mock address
417
+ to: "0x0000000000000000000000000000000000000002"
418
+ // Mock address
419
+ };
420
+ const settlement = await this.sandboxFacilitator.settle({ payment });
421
+ return {
422
+ ...payment,
423
+ transactionHash: settlement.transactionHash
424
+ };
425
+ }
426
+ /**
427
+ * Create blockchain payment (real EVM)
428
+ */
429
+ async createBlockchainPayment(_option) {
430
+ if (!this.config.evmPrivateKey) {
431
+ throw new Error("EVM private key required for blockchain payments");
432
+ }
433
+ throw new Error("Blockchain payments not yet implemented - use sandbox mode");
434
+ }
435
+ /**
436
+ * Get wallet address based on environment
437
+ */
438
+ getWalletAddress() {
439
+ if (this.config.environment === "sandbox") {
440
+ return "0x0000000000000000000000000000000000000001";
441
+ }
442
+ return void 0;
443
+ }
444
+ /**
445
+ * Reset daily spend if date has changed
446
+ */
447
+ resetDailySpendIfNeeded() {
448
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
449
+ if (today !== this.lastResetDate) {
450
+ this.dailySpent = 0;
451
+ this.lastResetDate = today;
452
+ }
453
+ }
454
+ };
455
+ }
456
+ });
457
+
458
+ // src/protocols/x402/provider.ts
459
+ var SlyX402Provider;
460
+ var init_provider = __esm({
461
+ "src/protocols/x402/provider.ts"() {
462
+ init_config();
463
+ init_sandbox_facilitator();
464
+ SlyX402Provider = class {
465
+ constructor(config) {
466
+ const envConfig = getEnvironmentConfig(config.environment);
467
+ this.config = {
468
+ apiKey: config.apiKey,
469
+ environment: config.environment,
470
+ routes: config.routes,
471
+ facilitatorUrl: config.facilitatorUrl || envConfig.facilitatorUrl
472
+ };
473
+ if (this.config.environment === "sandbox") {
474
+ this.sandboxFacilitator = new SandboxFacilitator({
475
+ apiUrl: envConfig.apiUrl,
476
+ apiKey: this.config.apiKey
477
+ });
478
+ }
479
+ }
480
+ /**
481
+ * Create Express middleware
482
+ */
483
+ middleware() {
484
+ return async (req, res, next) => {
485
+ try {
486
+ const routeConfig = this.getRouteConfig(req);
487
+ if (!routeConfig) {
488
+ return next();
489
+ }
490
+ const paymentHeader = req.headers["x-payment"];
491
+ if (!paymentHeader) {
492
+ return this.return402(req, res, routeConfig);
493
+ }
494
+ const isValid = await this.verifyPayment(paymentHeader, routeConfig);
495
+ if (!isValid) {
496
+ return this.return402(req, res, routeConfig);
497
+ }
498
+ next();
499
+ } catch (error) {
500
+ res.status(500).json({
501
+ error: "Payment verification failed",
502
+ message: error.message
503
+ });
504
+ }
505
+ };
506
+ }
507
+ /**
508
+ * Get route configuration for request
509
+ */
510
+ getRouteConfig(req) {
511
+ const routeKey = `${req.method} ${req.path}`;
512
+ if (this.config.routes[routeKey]) {
513
+ return this.config.routes[routeKey];
514
+ }
515
+ for (const [pattern, config] of Object.entries(this.config.routes)) {
516
+ if (this.matchRoute(pattern, routeKey)) {
517
+ return config;
518
+ }
519
+ }
520
+ return null;
521
+ }
522
+ /**
523
+ * Simple route pattern matching
524
+ */
525
+ matchRoute(pattern, route) {
526
+ const regexPattern = pattern.replace(/\*/g, ".*").replace(/\//g, "\\/");
527
+ const regex = new RegExp(`^${regexPattern}$`);
528
+ return regex.test(route);
529
+ }
530
+ /**
531
+ * Return 402 Payment Required response
532
+ */
533
+ return402(_req, res, routeConfig) {
534
+ const scheme = "exact-evm";
535
+ const network = this.config.environment === "sandbox" ? "eip155:8453" : "eip155:8453";
536
+ res.status(402).json({
537
+ statusCode: 402,
538
+ message: "Payment Required",
539
+ accepts: [
540
+ {
541
+ scheme,
542
+ network,
543
+ token: routeConfig.token || "USDC",
544
+ amount: routeConfig.price,
545
+ facilitator: this.config.facilitatorUrl,
546
+ description: routeConfig.description
547
+ }
548
+ ]
549
+ });
550
+ }
551
+ /**
552
+ * Verify payment
553
+ */
554
+ async verifyPayment(paymentHeader, routeConfig) {
555
+ try {
556
+ const payment = JSON.parse(paymentHeader);
557
+ if (payment.amount !== routeConfig.price) {
558
+ return false;
559
+ }
560
+ const expectedToken = routeConfig.token || "USDC";
561
+ if (payment.token !== expectedToken) {
562
+ return false;
563
+ }
564
+ if (this.config.environment === "sandbox") {
565
+ return this.verifySandboxPayment(payment);
566
+ } else {
567
+ return this.verifyBlockchainPayment(payment);
568
+ }
569
+ } catch (error) {
570
+ return false;
571
+ }
572
+ }
573
+ /**
574
+ * Verify sandbox payment
575
+ */
576
+ async verifySandboxPayment(payment) {
577
+ if (!this.sandboxFacilitator) {
578
+ return false;
579
+ }
580
+ const result = await this.sandboxFacilitator.verify({ payment });
581
+ return result.valid;
582
+ }
583
+ /**
584
+ * Verify blockchain payment
585
+ */
586
+ async verifyBlockchainPayment(_payment) {
587
+ throw new Error("Blockchain payment verification not yet implemented - use sandbox mode");
588
+ }
589
+ };
590
+ }
591
+ });
592
+
593
+ // src/protocols/ap2/client.ts
594
+ var AP2Client;
595
+ var init_client3 = __esm({
596
+ "src/protocols/ap2/client.ts"() {
597
+ AP2Client = class {
598
+ constructor(client) {
599
+ this.client = client;
600
+ }
601
+ /**
602
+ * Create a new AP2 mandate
603
+ *
604
+ * @example
605
+ * ```typescript
606
+ * const mandate = await payos.ap2.createMandate({
607
+ * mandate_id: 'mdt_unique_123',
608
+ * mandate_type: 'payment',
609
+ * agent_id: 'agent_ai_assistant',
610
+ * account_id: 'acct_uuid',
611
+ * authorized_amount: 100.00,
612
+ * currency: 'USD',
613
+ * });
614
+ * ```
615
+ */
616
+ async createMandate(request) {
617
+ const response = await this.client.request(
618
+ "/v1/ap2/mandates",
619
+ {
620
+ method: "POST",
621
+ body: JSON.stringify(request)
622
+ }
623
+ );
624
+ return response.data;
625
+ }
626
+ /**
627
+ * List mandates with optional filtering
628
+ *
629
+ * @example
630
+ * ```typescript
631
+ * const { data, pagination } = await payos.ap2.listMandates({
632
+ * status: 'active',
633
+ * agent_id: 'agent_ai_assistant',
634
+ * limit: 50,
635
+ * });
636
+ * ```
637
+ */
638
+ async listMandates(options = {}) {
639
+ const params = new URLSearchParams();
640
+ if (options.status) params.append("status", options.status);
641
+ if (options.agent_id) params.append("agent_id", options.agent_id);
642
+ if (options.account_id) params.append("account_id", options.account_id);
643
+ if (options.page) params.append("page", options.page.toString());
644
+ if (options.limit) params.append("limit", options.limit.toString());
645
+ const queryString = params.toString();
646
+ const path = queryString ? `/v1/ap2/mandates?${queryString}` : "/v1/ap2/mandates";
647
+ return this.client.request(path);
648
+ }
649
+ /**
650
+ * Get mandate details with execution history
651
+ *
652
+ * @example
653
+ * ```typescript
654
+ * const mandate = await payos.ap2.getMandate('mdt_id');
655
+ * console.log(mandate.remaining_amount);
656
+ * console.log(mandate.executions.length);
657
+ * ```
658
+ */
659
+ async getMandate(mandateId) {
660
+ const response = await this.client.request(
661
+ `/v1/ap2/mandates/${mandateId}`
662
+ );
663
+ return response.data;
664
+ }
665
+ /**
666
+ * Execute a payment against a mandate
667
+ *
668
+ * @example
669
+ * ```typescript
670
+ * const result = await payos.ap2.executeMandate('mdt_id', {
671
+ * amount: 25.00,
672
+ * currency: 'USD',
673
+ * description: 'Monthly subscription',
674
+ * });
675
+ *
676
+ * console.log(result.transfer_id);
677
+ * console.log(result.mandate.remaining_amount);
678
+ * ```
679
+ */
680
+ async executeMandate(mandateId, request) {
681
+ const response = await this.client.request(
682
+ `/v1/ap2/mandates/${mandateId}/execute`,
683
+ {
684
+ method: "POST",
685
+ body: JSON.stringify(request)
686
+ }
687
+ );
688
+ return response.data;
689
+ }
690
+ /**
691
+ * Cancel an active mandate
692
+ *
693
+ * @example
694
+ * ```typescript
695
+ * const result = await payos.ap2.cancelMandate('mdt_id');
696
+ * console.log(result.status); // 'cancelled'
697
+ * ```
698
+ */
699
+ async cancelMandate(mandateId) {
700
+ const response = await this.client.request(
701
+ `/v1/ap2/mandates/${mandateId}/cancel`,
702
+ {
703
+ method: "PATCH"
704
+ }
705
+ );
706
+ return response.data;
707
+ }
708
+ /**
709
+ * Get AP2 analytics
710
+ *
711
+ * @example
712
+ * ```typescript
713
+ * const analytics = await payos.ap2.getAnalytics('30d');
714
+ * console.log(analytics.summary.totalRevenue);
715
+ * console.log(analytics.summary.activeMandates);
716
+ * ```
717
+ */
718
+ async getAnalytics(period = "30d") {
719
+ const response = await this.client.request(
720
+ `/v1/ap2/analytics?period=${period}`
721
+ );
722
+ return response.data;
723
+ }
724
+ };
725
+ }
726
+ });
727
+
728
+ // src/protocols/acp/client.ts
729
+ var ACPClient;
730
+ var init_client4 = __esm({
731
+ "src/protocols/acp/client.ts"() {
732
+ ACPClient = class {
733
+ constructor(client) {
734
+ this.client = client;
735
+ }
736
+ /**
737
+ * Create a new ACP checkout session
738
+ *
739
+ * @example
740
+ * ```typescript
741
+ * const checkout = await payos.acp.createCheckout({
742
+ * checkout_id: 'checkout_unique_123',
743
+ * agent_id: 'agent_shopping_assistant',
744
+ * account_id: 'acct_uuid',
745
+ * merchant_id: 'merchant_store',
746
+ * items: [
747
+ * {
748
+ * name: 'Product 1',
749
+ * quantity: 2,
750
+ * unit_price: 50.00,
751
+ * total_price: 100.00,
752
+ * },
753
+ * ],
754
+ * tax_amount: 10.00,
755
+ * shipping_amount: 5.00,
756
+ * });
757
+ * ```
758
+ */
759
+ async createCheckout(request) {
760
+ const response = await this.client.request(
761
+ "/v1/acp/checkouts",
762
+ {
763
+ method: "POST",
764
+ body: JSON.stringify(request)
765
+ }
766
+ );
767
+ return response.data;
768
+ }
769
+ /**
770
+ * List checkouts with optional filtering
771
+ *
772
+ * @example
773
+ * ```typescript
774
+ * const { data, pagination } = await payos.acp.listCheckouts({
775
+ * status: 'pending',
776
+ * agent_id: 'agent_shopping_assistant',
777
+ * limit: 20,
778
+ * });
779
+ * ```
780
+ */
781
+ async listCheckouts(options = {}) {
782
+ const params = new URLSearchParams();
783
+ if (options.status) params.append("status", options.status);
784
+ if (options.agent_id) params.append("agent_id", options.agent_id);
785
+ if (options.merchant_id) params.append("merchant_id", options.merchant_id);
786
+ if (options.customer_id) params.append("customer_id", options.customer_id);
787
+ if (options.limit) params.append("limit", options.limit.toString());
788
+ if (options.offset) params.append("offset", options.offset.toString());
789
+ const queryString = params.toString();
790
+ const path = queryString ? `/v1/acp/checkouts?${queryString}` : "/v1/acp/checkouts";
791
+ return this.client.request(path);
792
+ }
793
+ /**
794
+ * Get checkout details with items
795
+ *
796
+ * @example
797
+ * ```typescript
798
+ * const checkout = await payos.acp.getCheckout('checkout_id');
799
+ * console.log(checkout.items);
800
+ * console.log(checkout.total_amount);
801
+ * ```
802
+ */
803
+ async getCheckout(checkoutId) {
804
+ const response = await this.client.request(
805
+ `/v1/acp/checkouts/${checkoutId}`
806
+ );
807
+ return response.data;
808
+ }
809
+ /**
810
+ * Complete a checkout with SharedPaymentToken
811
+ *
812
+ * @example
813
+ * ```typescript
814
+ * const result = await payos.acp.completeCheckout('checkout_id', {
815
+ * shared_payment_token: 'spt_...',
816
+ * payment_method: 'card',
817
+ * });
818
+ *
819
+ * console.log(result.transfer_id);
820
+ * console.log(result.status); // 'completed'
821
+ * ```
822
+ */
823
+ async completeCheckout(checkoutId, request) {
824
+ const response = await this.client.request(
825
+ `/v1/acp/checkouts/${checkoutId}/complete`,
826
+ {
827
+ method: "POST",
828
+ body: JSON.stringify(request)
829
+ }
830
+ );
831
+ return response.data;
832
+ }
833
+ /**
834
+ * Cancel a checkout
835
+ *
836
+ * @example
837
+ * ```typescript
838
+ * const result = await payos.acp.cancelCheckout('checkout_id');
839
+ * console.log(result.status); // 'cancelled'
840
+ * ```
841
+ */
842
+ async cancelCheckout(checkoutId) {
843
+ const response = await this.client.request(
844
+ `/v1/acp/checkouts/${checkoutId}/cancel`,
845
+ {
846
+ method: "PATCH"
847
+ }
848
+ );
849
+ return response.data;
850
+ }
851
+ /**
852
+ * Get ACP analytics
853
+ *
854
+ * @example
855
+ * ```typescript
856
+ * const analytics = await payos.acp.getAnalytics('30d');
857
+ * console.log(analytics.summary.totalRevenue);
858
+ * console.log(analytics.summary.averageOrderValue);
859
+ * ```
860
+ */
861
+ async getAnalytics(period = "30d") {
862
+ const response = await this.client.request(
863
+ `/v1/acp/analytics?period=${period}`
864
+ );
865
+ return response.data;
866
+ }
867
+ };
868
+ }
869
+ });
870
+
871
+ // src/protocols/ucp/client.ts
872
+ var profileCache, PROFILE_CACHE_TTL_MS, UCPClient;
873
+ var init_client5 = __esm({
874
+ "src/protocols/ucp/client.ts"() {
875
+ profileCache = /* @__PURE__ */ new Map();
876
+ PROFILE_CACHE_TTL_MS = 60 * 60 * 1e3;
877
+ UCPClient = class {
878
+ constructor(client) {
879
+ this.client = client;
880
+ }
881
+ // ===========================================================================
882
+ // Discovery
883
+ // ===========================================================================
884
+ /**
885
+ * Discover a UCP merchant's capabilities
886
+ *
887
+ * Fetches and caches the merchant's UCP profile from /.well-known/ucp
888
+ *
889
+ * @example
890
+ * ```typescript
891
+ * const merchant = await payos.ucp.discover('https://shop.example.com');
892
+ * console.log(merchant.ucp.version);
893
+ * console.log(merchant.payment?.handlers);
894
+ * ```
895
+ */
896
+ async discover(merchantUrl) {
897
+ const baseUrl = merchantUrl.replace(/\/$/, "");
898
+ const profileUrl = `${baseUrl}/.well-known/ucp`;
899
+ const cached = profileCache.get(profileUrl);
900
+ if (cached && Date.now() - cached.fetchedAt < PROFILE_CACHE_TTL_MS) {
901
+ return cached.profile;
902
+ }
903
+ const response = await fetch(profileUrl, {
904
+ headers: {
905
+ Accept: "application/json",
906
+ "User-Agent": "PayOS-SDK/1.0"
907
+ }
908
+ });
909
+ if (!response.ok) {
910
+ throw new Error(`Failed to discover UCP profile: ${response.status} ${response.statusText}`);
911
+ }
912
+ const profile = await response.json();
913
+ if (!profile.ucp?.version) {
914
+ throw new Error("Invalid UCP profile: missing ucp.version");
915
+ }
916
+ profileCache.set(profileUrl, {
917
+ profile,
918
+ fetchedAt: Date.now()
919
+ });
920
+ return profile;
921
+ }
922
+ /**
923
+ * Get PayOS's own UCP profile
924
+ *
925
+ * @example
926
+ * ```typescript
927
+ * const profile = await payos.ucp.getProfile();
928
+ * console.log(profile.payment?.handlers);
929
+ * ```
930
+ */
931
+ async getProfile() {
932
+ return this.client.request("/.well-known/ucp");
933
+ }
934
+ /**
935
+ * Get available settlement corridors
936
+ *
937
+ * @example
938
+ * ```typescript
939
+ * const corridors = await payos.ucp.getCorridors();
940
+ * console.log(corridors.find(c => c.rail === 'pix'));
941
+ * ```
942
+ */
943
+ async getCorridors() {
944
+ const response = await this.client.request(
945
+ "/v1/ucp/corridors"
946
+ );
947
+ return response.corridors;
948
+ }
949
+ /**
950
+ * Get UCP handler info
951
+ *
952
+ * @example
953
+ * ```typescript
954
+ * const info = await payos.ucp.getHandlerInfo();
955
+ * console.log(info.handler.name); // com.payos.latam_settlement
956
+ * ```
957
+ */
958
+ async getHandlerInfo() {
959
+ return this.client.request("/v1/ucp/info");
960
+ }
961
+ // ===========================================================================
962
+ // Quotes
963
+ // ===========================================================================
964
+ /**
965
+ * Get an FX quote for a settlement corridor
966
+ *
967
+ * @example
968
+ * ```typescript
969
+ * const quote = await payos.ucp.getQuote({
970
+ * corridor: 'pix',
971
+ * amount: 100,
972
+ * currency: 'USD',
973
+ * });
974
+ * console.log(`${quote.from_amount} USD = ${quote.to_amount} BRL`);
975
+ * ```
976
+ */
977
+ async getQuote(request) {
978
+ return this.client.request("/v1/ucp/quote", {
979
+ method: "POST",
980
+ body: JSON.stringify(request)
981
+ });
982
+ }
983
+ // ===========================================================================
984
+ // Token Acquisition (Payment Handler flow)
985
+ // ===========================================================================
986
+ /**
987
+ * Acquire a settlement token for completing a UCP checkout
988
+ *
989
+ * Tokens are valid for 15 minutes and lock in the FX rate.
990
+ *
991
+ * @example
992
+ * ```typescript
993
+ * const token = await payos.ucp.acquireToken({
994
+ * corridor: 'pix',
995
+ * amount: 100,
996
+ * currency: 'USD',
997
+ * recipient: {
998
+ * type: 'pix',
999
+ * pix_key: '12345678901',
1000
+ * pix_key_type: 'cpf',
1001
+ * name: 'Maria Silva',
1002
+ * },
1003
+ * });
1004
+ *
1005
+ * console.log(token.token); // ucp_tok_...
1006
+ * console.log(token.quote.to_amount); // 595.00 BRL
1007
+ * ```
1008
+ */
1009
+ async acquireToken(request) {
1010
+ return this.client.request("/v1/ucp/tokens", {
1011
+ method: "POST",
1012
+ body: JSON.stringify(request)
1013
+ });
1014
+ }
1015
+ // ===========================================================================
1016
+ // Settlement Execution
1017
+ // ===========================================================================
1018
+ /**
1019
+ * Complete settlement using a previously acquired token
1020
+ *
1021
+ * @example
1022
+ * ```typescript
1023
+ * const settlement = await payos.ucp.settle({
1024
+ * token: 'ucp_tok_...',
1025
+ * idempotency_key: 'checkout_12345',
1026
+ * });
1027
+ *
1028
+ * console.log(settlement.status); // pending
1029
+ * console.log(settlement.id); // Use this to track status
1030
+ * ```
1031
+ */
1032
+ async settle(request) {
1033
+ return this.client.request("/v1/ucp/settle", {
1034
+ method: "POST",
1035
+ body: JSON.stringify(request)
1036
+ });
1037
+ }
1038
+ /**
1039
+ * Get settlement status by ID
1040
+ *
1041
+ * @example
1042
+ * ```typescript
1043
+ * const settlement = await payos.ucp.getSettlement('uuid');
1044
+ * if (settlement.status === 'completed') {
1045
+ * console.log(`Completed at ${settlement.completed_at}`);
1046
+ * }
1047
+ * ```
1048
+ */
1049
+ async getSettlement(settlementId) {
1050
+ return this.client.request(`/v1/ucp/settlements/${settlementId}`);
1051
+ }
1052
+ /**
1053
+ * List settlements with optional filtering
1054
+ *
1055
+ * @example
1056
+ * ```typescript
1057
+ * const { data, pagination } = await payos.ucp.listSettlements({
1058
+ * status: 'completed',
1059
+ * corridor: 'pix',
1060
+ * limit: 50,
1061
+ * });
1062
+ * ```
1063
+ */
1064
+ async listSettlements(options = {}) {
1065
+ const params = new URLSearchParams();
1066
+ if (options.status) params.append("status", options.status);
1067
+ if (options.corridor) params.append("corridor", options.corridor);
1068
+ if (options.limit) params.append("limit", options.limit.toString());
1069
+ if (options.offset) params.append("offset", options.offset.toString());
1070
+ const queryString = params.toString();
1071
+ const path = queryString ? `/v1/ucp/settlements?${queryString}` : "/v1/ucp/settlements";
1072
+ return this.client.request(path);
1073
+ }
1074
+ // ===========================================================================
1075
+ // Checkout (Consuming UCP Merchants)
1076
+ // ===========================================================================
1077
+ /**
1078
+ * Create a checkout session with a UCP merchant
1079
+ *
1080
+ * @example
1081
+ * ```typescript
1082
+ * const checkout = await payos.ucp.createCheckout('https://shop.example.com', {
1083
+ * line_items: [
1084
+ * { product_id: 'prod_123', quantity: 2 },
1085
+ * ],
1086
+ * buyer: { email: 'buyer@example.com' },
1087
+ * });
1088
+ *
1089
+ * console.log(checkout.totals.total);
1090
+ * ```
1091
+ */
1092
+ async createCheckout(merchantUrl, request) {
1093
+ const profile = await this.discover(merchantUrl);
1094
+ if (!profile.checkout?.endpoint) {
1095
+ throw new Error("Merchant does not support UCP checkout");
1096
+ }
1097
+ const response = await fetch(profile.checkout.endpoint, {
1098
+ method: "POST",
1099
+ headers: {
1100
+ "Content-Type": "application/json",
1101
+ "User-Agent": "PayOS-SDK/1.0"
1102
+ },
1103
+ body: JSON.stringify(request)
1104
+ });
1105
+ if (!response.ok) {
1106
+ const error = await response.json().catch(() => ({}));
1107
+ throw new Error(`Failed to create checkout: ${response.status} - ${JSON.stringify(error)}`);
1108
+ }
1109
+ return await response.json();
1110
+ }
1111
+ /**
1112
+ * Complete a checkout with PayOS LATAM settlement
1113
+ *
1114
+ * This is a convenience method that:
1115
+ * 1. Acquires a settlement token
1116
+ * 2. Completes the checkout with the merchant
1117
+ *
1118
+ * @example
1119
+ * ```typescript
1120
+ * const order = await payos.ucp.completeCheckout(
1121
+ * 'https://shop.example.com',
1122
+ * checkout.id,
1123
+ * {
1124
+ * corridor: 'pix',
1125
+ * recipient: {
1126
+ * type: 'pix',
1127
+ * pix_key: '12345678901',
1128
+ * pix_key_type: 'cpf',
1129
+ * name: 'Maria Silva',
1130
+ * },
1131
+ * }
1132
+ * );
1133
+ *
1134
+ * console.log(order.id);
1135
+ * console.log(order.payment.settlement_id);
1136
+ * ```
1137
+ */
1138
+ async completeCheckout(merchantUrl, checkoutId, settlement) {
1139
+ const profile = await this.discover(merchantUrl);
1140
+ if (!profile.checkout?.endpoint) {
1141
+ throw new Error("Merchant does not support UCP checkout");
1142
+ }
1143
+ const checkoutResponse = await fetch(`${profile.checkout.endpoint}/${checkoutId}`, {
1144
+ headers: {
1145
+ "User-Agent": "PayOS-SDK/1.0"
1146
+ }
1147
+ });
1148
+ if (!checkoutResponse.ok) {
1149
+ throw new Error(`Failed to fetch checkout: ${checkoutResponse.status}`);
1150
+ }
1151
+ const checkout = await checkoutResponse.json();
1152
+ const token = await this.acquireToken({
1153
+ corridor: settlement.corridor,
1154
+ amount: checkout.totals.total,
1155
+ currency: checkout.totals.currency,
1156
+ recipient: settlement.recipient
1157
+ });
1158
+ const completeRequest = {
1159
+ payment_handler: "payos_latam",
1160
+ payment_data: {
1161
+ token: token.token
1162
+ }
1163
+ };
1164
+ const completeResponse = await fetch(`${profile.checkout.endpoint}/${checkoutId}/complete`, {
1165
+ method: "POST",
1166
+ headers: {
1167
+ "Content-Type": "application/json",
1168
+ "User-Agent": "PayOS-SDK/1.0"
1169
+ },
1170
+ body: JSON.stringify(completeRequest)
1171
+ });
1172
+ if (!completeResponse.ok) {
1173
+ const error = await completeResponse.json().catch(() => ({}));
1174
+ throw new Error(`Failed to complete checkout: ${completeResponse.status} - ${JSON.stringify(error)}`);
1175
+ }
1176
+ return await completeResponse.json();
1177
+ }
1178
+ // ===========================================================================
1179
+ // Utilities
1180
+ // ===========================================================================
1181
+ /**
1182
+ * Clear the profile cache (useful for testing)
1183
+ */
1184
+ clearCache() {
1185
+ profileCache.clear();
1186
+ }
1187
+ /**
1188
+ * Check if PayOS supports a specific corridor
1189
+ *
1190
+ * @example
1191
+ * ```typescript
1192
+ * if (await payos.ucp.supportsCorridors('USD', 'BRL', 'pix')) {
1193
+ * // Can settle via Pix
1194
+ * }
1195
+ * ```
1196
+ */
1197
+ async supportsCorridor(sourceCurrency, destinationCurrency, rail) {
1198
+ const corridors = await this.getCorridors();
1199
+ return corridors.some(
1200
+ (c) => c.source_currency === sourceCurrency && c.destination_currency === destinationCurrency && c.rail === rail
1201
+ );
1202
+ }
1203
+ /**
1204
+ * Create Pix recipient helper
1205
+ *
1206
+ * @example
1207
+ * ```typescript
1208
+ * const recipient = payos.ucp.createPixRecipient({
1209
+ * pix_key: '12345678901',
1210
+ * pix_key_type: 'cpf',
1211
+ * name: 'Maria Silva',
1212
+ * });
1213
+ * ```
1214
+ */
1215
+ createPixRecipient(params) {
1216
+ return {
1217
+ type: "pix",
1218
+ ...params
1219
+ };
1220
+ }
1221
+ /**
1222
+ * Create SPEI recipient helper
1223
+ *
1224
+ * @example
1225
+ * ```typescript
1226
+ * const recipient = payos.ucp.createSpeiRecipient({
1227
+ * clabe: '012345678901234567',
1228
+ * name: 'Juan Garcia',
1229
+ * });
1230
+ * ```
1231
+ */
1232
+ createSpeiRecipient(params) {
1233
+ return {
1234
+ type: "spei",
1235
+ ...params
1236
+ };
1237
+ }
1238
+ // ===========================================================================
1239
+ // PayOS-Hosted Checkout Sessions (Phase 2)
1240
+ // ===========================================================================
1241
+ /**
1242
+ * Create a PayOS-hosted checkout session
1243
+ *
1244
+ * @example
1245
+ * ```typescript
1246
+ * const checkout = await payos.ucp.checkouts.create({
1247
+ * currency: 'USD',
1248
+ * line_items: [
1249
+ * { id: 'item_1', name: 'Product', quantity: 1, unit_price: 1000, total_price: 1000, currency: 'USD' }
1250
+ * ],
1251
+ * buyer: { email: 'buyer@example.com' },
1252
+ * });
1253
+ * ```
1254
+ */
1255
+ get checkouts() {
1256
+ return {
1257
+ create: async (request) => {
1258
+ return this.client.request("/v1/ucp/checkouts", {
1259
+ method: "POST",
1260
+ body: JSON.stringify(request)
1261
+ });
1262
+ },
1263
+ get: async (checkoutId) => {
1264
+ return this.client.request(`/v1/ucp/checkouts/${checkoutId}`);
1265
+ },
1266
+ update: async (checkoutId, request) => {
1267
+ return this.client.request(`/v1/ucp/checkouts/${checkoutId}`, {
1268
+ method: "PUT",
1269
+ body: JSON.stringify(request)
1270
+ });
1271
+ },
1272
+ complete: async (checkoutId) => {
1273
+ return this.client.request(`/v1/ucp/checkouts/${checkoutId}/complete`, {
1274
+ method: "POST"
1275
+ });
1276
+ },
1277
+ cancel: async (checkoutId) => {
1278
+ return this.client.request(`/v1/ucp/checkouts/${checkoutId}/cancel`, {
1279
+ method: "POST"
1280
+ });
1281
+ },
1282
+ addPaymentInstrument: async (checkoutId, instrument) => {
1283
+ return this.client.request(`/v1/ucp/checkouts/${checkoutId}/instruments`, {
1284
+ method: "POST",
1285
+ body: JSON.stringify(instrument)
1286
+ });
1287
+ }
1288
+ };
1289
+ }
1290
+ // ===========================================================================
1291
+ // PayOS Orders (Phase 3)
1292
+ // ===========================================================================
1293
+ /**
1294
+ * Manage PayOS orders
1295
+ *
1296
+ * @example
1297
+ * ```typescript
1298
+ * const order = await payos.ucp.orders.get('ord_123');
1299
+ * const orders = await payos.ucp.orders.list({ status: 'processing' });
1300
+ * ```
1301
+ */
1302
+ get orders() {
1303
+ return {
1304
+ get: async (orderId) => {
1305
+ return this.client.request(`/v1/ucp/orders/${orderId}`);
1306
+ },
1307
+ list: async (options = {}) => {
1308
+ const params = new URLSearchParams();
1309
+ if (options.status) params.append("status", options.status);
1310
+ if (options.limit) params.append("limit", options.limit.toString());
1311
+ if (options.offset) params.append("offset", options.offset.toString());
1312
+ const queryString = params.toString();
1313
+ const path = queryString ? `/v1/ucp/orders?${queryString}` : "/v1/ucp/orders";
1314
+ return this.client.request(path);
1315
+ },
1316
+ updateStatus: async (orderId, status) => {
1317
+ return this.client.request(`/v1/ucp/orders/${orderId}/status`, {
1318
+ method: "PUT",
1319
+ body: JSON.stringify({ status })
1320
+ });
1321
+ },
1322
+ cancel: async (orderId, reason) => {
1323
+ return this.client.request(`/v1/ucp/orders/${orderId}/cancel`, {
1324
+ method: "POST",
1325
+ body: JSON.stringify({ reason })
1326
+ });
1327
+ },
1328
+ addExpectation: async (orderId, expectation) => {
1329
+ return this.client.request(`/v1/ucp/orders/${orderId}/expectations`, {
1330
+ method: "POST",
1331
+ body: JSON.stringify(expectation)
1332
+ });
1333
+ },
1334
+ updateExpectation: async (orderId, expectationId, updates) => {
1335
+ return this.client.request(
1336
+ `/v1/ucp/orders/${orderId}/expectations/${expectationId}`,
1337
+ {
1338
+ method: "PUT",
1339
+ body: JSON.stringify(updates)
1340
+ }
1341
+ );
1342
+ },
1343
+ addEvent: async (orderId, event) => {
1344
+ return this.client.request(`/v1/ucp/orders/${orderId}/events`, {
1345
+ method: "POST",
1346
+ body: JSON.stringify(event)
1347
+ });
1348
+ },
1349
+ getEvents: async (orderId) => {
1350
+ return this.client.request(
1351
+ `/v1/ucp/orders/${orderId}/events`
1352
+ );
1353
+ },
1354
+ addAdjustment: async (orderId, adjustment) => {
1355
+ return this.client.request(`/v1/ucp/orders/${orderId}/adjustments`, {
1356
+ method: "POST",
1357
+ body: JSON.stringify(adjustment)
1358
+ });
1359
+ }
1360
+ };
1361
+ }
1362
+ // ===========================================================================
1363
+ // Identity Linking (Phase 4)
1364
+ // ===========================================================================
1365
+ /**
1366
+ * OAuth 2.0 identity linking for AI agents/platforms
1367
+ *
1368
+ * @example
1369
+ * ```typescript
1370
+ * // Register an OAuth client
1371
+ * const { client, client_secret } = await payos.ucp.identity.registerClient({
1372
+ * name: 'My AI Agent',
1373
+ * redirect_uris: ['https://myagent.com/callback'],
1374
+ * });
1375
+ *
1376
+ * // List linked accounts
1377
+ * const accounts = await payos.ucp.identity.listLinkedAccounts({ buyer_id: 'buyer_123' });
1378
+ * ```
1379
+ */
1380
+ get identity() {
1381
+ return {
1382
+ /**
1383
+ * Register an OAuth client (platform/agent)
1384
+ */
1385
+ registerClient: async (request) => {
1386
+ return this.client.request("/v1/ucp/identity/clients", {
1387
+ method: "POST",
1388
+ body: JSON.stringify(request)
1389
+ });
1390
+ },
1391
+ /**
1392
+ * Get authorization info for consent screen
1393
+ */
1394
+ getAuthorizationInfo: async (params) => {
1395
+ const searchParams = new URLSearchParams();
1396
+ searchParams.append("response_type", params.response_type);
1397
+ searchParams.append("client_id", params.client_id);
1398
+ searchParams.append("redirect_uri", params.redirect_uri);
1399
+ searchParams.append("scope", params.scope);
1400
+ searchParams.append("state", params.state);
1401
+ if (params.code_challenge) {
1402
+ searchParams.append("code_challenge", params.code_challenge);
1403
+ }
1404
+ if (params.code_challenge_method) {
1405
+ searchParams.append("code_challenge_method", params.code_challenge_method);
1406
+ }
1407
+ return this.client.request(
1408
+ `/v1/ucp/identity/authorize?${searchParams.toString()}`
1409
+ );
1410
+ },
1411
+ /**
1412
+ * Submit consent decision (after user authenticates)
1413
+ */
1414
+ submitConsent: async (request) => {
1415
+ return this.client.request("/v1/ucp/identity/authorize/consent", {
1416
+ method: "POST",
1417
+ body: JSON.stringify(request)
1418
+ });
1419
+ },
1420
+ /**
1421
+ * Exchange authorization code for tokens
1422
+ */
1423
+ exchangeCode: async (params) => {
1424
+ return this.client.request("/v1/ucp/identity/token", {
1425
+ method: "POST",
1426
+ body: JSON.stringify({
1427
+ grant_type: "authorization_code",
1428
+ ...params
1429
+ })
1430
+ });
1431
+ },
1432
+ /**
1433
+ * Refresh tokens
1434
+ */
1435
+ refreshTokens: async (params) => {
1436
+ return this.client.request("/v1/ucp/identity/token", {
1437
+ method: "POST",
1438
+ body: JSON.stringify({
1439
+ grant_type: "refresh_token",
1440
+ ...params
1441
+ })
1442
+ });
1443
+ },
1444
+ /**
1445
+ * Revoke a token
1446
+ */
1447
+ revokeToken: async (params) => {
1448
+ return this.client.request("/v1/ucp/identity/revoke", {
1449
+ method: "POST",
1450
+ body: JSON.stringify(params)
1451
+ });
1452
+ },
1453
+ /**
1454
+ * List linked accounts
1455
+ */
1456
+ listLinkedAccounts: async (params) => {
1457
+ const searchParams = new URLSearchParams();
1458
+ if (params.buyer_id) searchParams.append("buyer_id", params.buyer_id);
1459
+ if (params.platform_id) searchParams.append("platform_id", params.platform_id);
1460
+ if (params.limit) searchParams.append("limit", params.limit.toString());
1461
+ if (params.offset) searchParams.append("offset", params.offset.toString());
1462
+ return this.client.request(
1463
+ `/v1/ucp/identity/linked-accounts?${searchParams.toString()}`
1464
+ );
1465
+ },
1466
+ /**
1467
+ * Unlink an account
1468
+ */
1469
+ unlinkAccount: async (accountId, buyerId) => {
1470
+ return this.client.request(
1471
+ `/v1/ucp/identity/linked-accounts/${accountId}?buyer_id=${buyerId}`,
1472
+ { method: "DELETE" }
1473
+ );
1474
+ },
1475
+ /**
1476
+ * Get available scopes
1477
+ */
1478
+ getScopes: async () => {
1479
+ return this.client.request("/v1/ucp/identity/scopes");
1480
+ }
1481
+ };
1482
+ }
1483
+ };
1484
+ }
1485
+ });
1486
+
1487
+ // src/capabilities/formatters.ts
1488
+ var formatters_exports = {};
1489
+ __export(formatters_exports, {
1490
+ getClaudeSystemMessage: () => getClaudeSystemMessage,
1491
+ getOpenAISystemMessage: () => getOpenAISystemMessage,
1492
+ toClaudeTool: () => toClaudeTool,
1493
+ toClaudeTools: () => toClaudeTools,
1494
+ toLangChainTool: () => toLangChainTool,
1495
+ toLangChainTools: () => toLangChainTools,
1496
+ toOpenAIFunction: () => toOpenAIFunction,
1497
+ toOpenAIFunctions: () => toOpenAIFunctions
1498
+ });
1499
+ function createSchemaFromParameterType(paramType) {
1500
+ return {
1501
+ properties: {
1502
+ data: {
1503
+ type: "object",
1504
+ description: `${paramType} object`
1505
+ }
1506
+ },
1507
+ required: ["data"]
1508
+ };
1509
+ }
1510
+ function toOpenAIFunction(capability) {
1511
+ const schema = typeof capability.parameters === "string" ? createSchemaFromParameterType(capability.parameters) : { properties: {}, required: [] };
1512
+ return {
1513
+ name: capability.name,
1514
+ description: `${capability.description}. Endpoint: ${capability.endpoint}. Errors: ${capability.errors.join(", ")}`,
1515
+ parameters: {
1516
+ type: "object",
1517
+ properties: schema.properties,
1518
+ required: schema.required
1519
+ }
1520
+ };
1521
+ }
1522
+ function toClaudeTool(capability) {
1523
+ const schema = typeof capability.parameters === "string" ? createSchemaFromParameterType(capability.parameters) : { properties: {}, required: [] };
1524
+ return {
1525
+ name: capability.name,
1526
+ description: `${capability.description}. Endpoint: ${capability.endpoint}. Possible errors: ${capability.errors.join(", ")}`,
1527
+ input_schema: {
1528
+ type: "object",
1529
+ properties: schema.properties,
1530
+ required: schema.required
1531
+ }
1532
+ };
1533
+ }
1534
+ function toLangChainTool(capability) {
1535
+ const schema = typeof capability.parameters === "string" ? createSchemaFromParameterType(capability.parameters) : { properties: {}, required: [] };
1536
+ return {
1537
+ name: capability.name,
1538
+ description: `${capability.description}. Endpoint: ${capability.endpoint}`,
1539
+ schema: {
1540
+ type: "object",
1541
+ properties: schema.properties,
1542
+ required: schema.required
1543
+ }
1544
+ };
1545
+ }
1546
+ function toOpenAIFunctions(capabilities) {
1547
+ const caps = Array.isArray(capabilities) ? capabilities : capabilities.capabilities;
1548
+ return caps.map(toOpenAIFunction);
1549
+ }
1550
+ function toClaudeTools(capabilities) {
1551
+ const caps = Array.isArray(capabilities) ? capabilities : capabilities.capabilities;
1552
+ return caps.map(toClaudeTool);
1553
+ }
1554
+ function toLangChainTools(capabilities) {
1555
+ const caps = Array.isArray(capabilities) ? capabilities : capabilities.capabilities;
1556
+ return caps.map(toLangChainTool);
1557
+ }
1558
+ function getOpenAISystemMessage() {
1559
+ return `You are a helpful AI assistant with access to PayOS payment operations. You can help users:
1560
+ - Get settlement quotes for cross-border payments
1561
+ - Create settlements and transfers
1562
+ - Check account balances
1563
+ - Verify compliance for recipients
1564
+
1565
+ When a user asks about payments or transfers, use the available functions to help them. Always confirm important actions before executing them.`;
1566
+ }
1567
+ function getClaudeSystemMessage() {
1568
+ return `You are a helpful AI assistant with access to PayOS payment operations. You can help users:
1569
+ - Get settlement quotes for cross-border payments
1570
+ - Create settlements and transfers
1571
+ - Check account balances
1572
+ - Verify compliance for recipients
1573
+
1574
+ When a user asks about payments or transfers, use the available tools to help them. Always confirm important actions before executing them.`;
1575
+ }
1576
+ var init_formatters = __esm({
1577
+ "src/capabilities/formatters.ts"() {
1578
+ }
1579
+ });
1580
+
1581
+ // src/capabilities/client.ts
1582
+ var CapabilitiesClient;
1583
+ var init_client6 = __esm({
1584
+ "src/capabilities/client.ts"() {
1585
+ CapabilitiesClient = class {
1586
+ // 1 hour
1587
+ constructor(client) {
1588
+ this.cachedCapabilities = null;
1589
+ this.cacheTimestamp = 0;
1590
+ this.cacheTTL = 36e5;
1591
+ this.client = client;
1592
+ }
1593
+ /**
1594
+ * Get all PayOS capabilities
1595
+ * Results are cached for 1 hour by default
1596
+ */
1597
+ async getAll(forceFresh = false) {
1598
+ const now = Date.now();
1599
+ if (!forceFresh && this.cachedCapabilities && now - this.cacheTimestamp < this.cacheTTL) {
1600
+ return this.cachedCapabilities;
1601
+ }
1602
+ const capabilities = await this.client.getCapabilities();
1603
+ this.cachedCapabilities = capabilities;
1604
+ this.cacheTimestamp = now;
1605
+ return capabilities;
1606
+ }
1607
+ /**
1608
+ * Get capabilities filtered by category or name
1609
+ */
1610
+ async filter(filter) {
1611
+ const all = await this.getAll();
1612
+ return all.capabilities.filter((cap) => {
1613
+ if (filter.category && cap.category !== filter.category) {
1614
+ return false;
1615
+ }
1616
+ if (filter.name && cap.name !== filter.name) {
1617
+ return false;
1618
+ }
1619
+ return true;
1620
+ });
1621
+ }
1622
+ /**
1623
+ * Get a single capability by name
1624
+ */
1625
+ async get(name) {
1626
+ const all = await this.getAll();
1627
+ return all.capabilities.find((cap) => cap.name === name);
1628
+ }
1629
+ /**
1630
+ * Get all available categories
1631
+ */
1632
+ async getCategories() {
1633
+ const all = await this.getAll();
1634
+ const categories = new Set(all.capabilities.map((cap) => cap.category));
1635
+ return Array.from(categories);
1636
+ }
1637
+ /**
1638
+ * Clear the capabilities cache
1639
+ */
1640
+ clearCache() {
1641
+ this.cachedCapabilities = null;
1642
+ this.cacheTimestamp = 0;
1643
+ }
1644
+ /**
1645
+ * Get capabilities in OpenAI function-calling format
1646
+ */
1647
+ async toOpenAI() {
1648
+ const response = await this.getAll();
1649
+ const { toOpenAIFunctions: toOpenAIFunctions2, getOpenAISystemMessage: getOpenAISystemMessage2 } = await Promise.resolve().then(() => (init_formatters(), formatters_exports));
1650
+ return {
1651
+ functions: toOpenAIFunctions2(response.capabilities),
1652
+ systemMessage: getOpenAISystemMessage2()
1653
+ };
1654
+ }
1655
+ /**
1656
+ * Get capabilities in OpenAI function-calling format (alias)
1657
+ */
1658
+ async toOpenAIFunctions() {
1659
+ const response = await this.getAll();
1660
+ const { toOpenAIFunctions: toOpenAIFunctions2 } = await Promise.resolve().then(() => (init_formatters(), formatters_exports));
1661
+ return toOpenAIFunctions2(response.capabilities);
1662
+ }
1663
+ /**
1664
+ * Get capabilities in Claude tool format
1665
+ */
1666
+ async toClaude() {
1667
+ const response = await this.getAll();
1668
+ const { toClaudeTools: toClaudeTools2, getClaudeSystemMessage: getClaudeSystemMessage2 } = await Promise.resolve().then(() => (init_formatters(), formatters_exports));
1669
+ return {
1670
+ tools: toClaudeTools2(response.capabilities),
1671
+ systemMessage: getClaudeSystemMessage2()
1672
+ };
1673
+ }
1674
+ /**
1675
+ * Get capabilities in Claude tool format (alias)
1676
+ */
1677
+ async toClaudeTools() {
1678
+ const response = await this.getAll();
1679
+ const { toClaudeTools: toClaudeTools2 } = await Promise.resolve().then(() => (init_formatters(), formatters_exports));
1680
+ return toClaudeTools2(response.capabilities);
1681
+ }
1682
+ /**
1683
+ * Get capabilities in LangChain tool format
1684
+ */
1685
+ async toLangChain() {
1686
+ const response = await this.getAll();
1687
+ const { toLangChainTools: toLangChainTools2 } = await Promise.resolve().then(() => (init_formatters(), formatters_exports));
1688
+ return toLangChainTools2(response.capabilities);
1689
+ }
1690
+ };
1691
+ }
1692
+ });
1693
+
1694
+ // src/capabilities/types.ts
1695
+ var init_types = __esm({
1696
+ "src/capabilities/types.ts"() {
1697
+ }
1698
+ });
1699
+
1700
+ // src/capabilities/index.ts
1701
+ var init_capabilities = __esm({
1702
+ "src/capabilities/index.ts"() {
1703
+ init_client6();
1704
+ init_types();
1705
+ init_formatters();
1706
+ }
1707
+ });
1708
+
1709
+ // src/langchain/tools.ts
1710
+ var LangChainTools;
1711
+ var init_tools = __esm({
1712
+ "src/langchain/tools.ts"() {
1713
+ LangChainTools = class {
1714
+ constructor(payos) {
1715
+ this.payos = payos;
1716
+ }
1717
+ /**
1718
+ * Get all PayOS capabilities as LangChain tools
1719
+ */
1720
+ async getTools() {
1721
+ return this.payos.capabilities.toLangChain();
1722
+ }
1723
+ /**
1724
+ * Get a specific tool by name
1725
+ */
1726
+ async getTool(name) {
1727
+ const tools = await this.getTools();
1728
+ return tools.find((tool) => tool.name === name);
1729
+ }
1730
+ };
1731
+ }
1732
+ });
1733
+
1734
+ // src/cards/types.ts
1735
+ var init_types2 = __esm({
1736
+ "src/cards/types.ts"() {
1737
+ }
1738
+ });
1739
+
1740
+ // src/cards/index.ts
1741
+ var VisaClient, MastercardClient, CardsClient;
1742
+ var init_cards = __esm({
1743
+ "src/cards/index.ts"() {
1744
+ init_types2();
1745
+ VisaClient = class {
1746
+ constructor(client) {
1747
+ this.client = client;
1748
+ }
1749
+ /**
1750
+ * Create a Visa VIC payment instruction
1751
+ */
1752
+ async createInstruction(params) {
1753
+ return this.client.request("/v1/cards/visa/instructions", {
1754
+ method: "POST",
1755
+ body: JSON.stringify(params)
1756
+ });
1757
+ }
1758
+ /**
1759
+ * Get a specific Visa payment instruction
1760
+ */
1761
+ async getInstruction(instructionId) {
1762
+ return this.client.request(
1763
+ `/v1/cards/visa/instructions/${instructionId}`
1764
+ );
1765
+ }
1766
+ /**
1767
+ * List Visa payment instructions
1768
+ */
1769
+ async listInstructions(options) {
1770
+ const params = new URLSearchParams();
1771
+ if (options?.status) params.set("status", options.status);
1772
+ if (options?.limit) params.set("limit", String(options.limit));
1773
+ if (options?.offset) params.set("offset", String(options.offset));
1774
+ const query = params.toString();
1775
+ return this.client.request(
1776
+ `/v1/cards/visa/instructions${query ? `?${query}` : ""}`
1777
+ );
1778
+ }
1779
+ /**
1780
+ * Provision a VTS token for an instruction
1781
+ */
1782
+ async createToken(params) {
1783
+ return this.client.request("/v1/cards/visa/tokens", {
1784
+ method: "POST",
1785
+ body: JSON.stringify(params)
1786
+ });
1787
+ }
1788
+ /**
1789
+ * Get a specific Visa token
1790
+ */
1791
+ async getToken(tokenId) {
1792
+ return this.client.request(`/v1/cards/visa/tokens/${tokenId}`);
1793
+ }
1794
+ /**
1795
+ * List Visa tokens
1796
+ */
1797
+ async listTokens(options) {
1798
+ const params = new URLSearchParams();
1799
+ if (options?.status) params.set("status", options.status);
1800
+ if (options?.limit) params.set("limit", String(options.limit));
1801
+ if (options?.offset) params.set("offset", String(options.offset));
1802
+ const query = params.toString();
1803
+ return this.client.request(
1804
+ `/v1/cards/visa/tokens${query ? `?${query}` : ""}`
1805
+ );
1806
+ }
1807
+ /**
1808
+ * Suspend a Visa token
1809
+ */
1810
+ async suspendToken(tokenId) {
1811
+ return this.client.request(
1812
+ `/v1/cards/visa/tokens/${tokenId}`,
1813
+ { method: "DELETE" }
1814
+ );
1815
+ }
1816
+ };
1817
+ MastercardClient = class {
1818
+ constructor(client) {
1819
+ this.client = client;
1820
+ }
1821
+ /**
1822
+ * Register an agent with Mastercard Agent Pay
1823
+ */
1824
+ async registerAgent(params) {
1825
+ return this.client.request("/v1/cards/mastercard/agents", {
1826
+ method: "POST",
1827
+ body: JSON.stringify(params)
1828
+ });
1829
+ }
1830
+ /**
1831
+ * Get a specific Mastercard agent registration
1832
+ */
1833
+ async getAgent(agentId) {
1834
+ return this.client.request(
1835
+ `/v1/cards/mastercard/agents/${agentId}`
1836
+ );
1837
+ }
1838
+ /**
1839
+ * List registered Mastercard agents
1840
+ */
1841
+ async listAgents() {
1842
+ return this.client.request(
1843
+ "/v1/cards/mastercard/agents"
1844
+ );
1845
+ }
1846
+ /**
1847
+ * Create a Mastercard agentic token with DTVC
1848
+ */
1849
+ async createToken(params) {
1850
+ return this.client.request("/v1/cards/mastercard/tokens", {
1851
+ method: "POST",
1852
+ body: JSON.stringify(params)
1853
+ });
1854
+ }
1855
+ /**
1856
+ * Get a Mastercard token, optionally refreshing the DTVC
1857
+ */
1858
+ async getToken(tokenReference, options) {
1859
+ const query = options?.refresh ? "?refresh=true" : "";
1860
+ return this.client.request(
1861
+ `/v1/cards/mastercard/tokens/${tokenReference}${query}`
1862
+ );
1863
+ }
1864
+ /**
1865
+ * List Mastercard tokens
1866
+ */
1867
+ async listTokens(options) {
1868
+ const params = new URLSearchParams();
1869
+ if (options?.status) params.set("status", options.status);
1870
+ if (options?.limit) params.set("limit", String(options.limit));
1871
+ if (options?.offset) params.set("offset", String(options.offset));
1872
+ const query = params.toString();
1873
+ return this.client.request(
1874
+ `/v1/cards/mastercard/tokens${query ? `?${query}` : ""}`
1875
+ );
1876
+ }
1877
+ /**
1878
+ * Revoke a Mastercard token
1879
+ */
1880
+ async revokeToken(tokenReference) {
1881
+ return this.client.request(
1882
+ `/v1/cards/mastercard/tokens/${tokenReference}`,
1883
+ { method: "DELETE" }
1884
+ );
1885
+ }
1886
+ };
1887
+ CardsClient = class {
1888
+ constructor(client) {
1889
+ this.client = client;
1890
+ this.visa = new VisaClient(client);
1891
+ this.mastercard = new MastercardClient(client);
1892
+ }
1893
+ /**
1894
+ * Verify an AI agent's Web Bot Auth signature
1895
+ *
1896
+ * @example
1897
+ * ```typescript
1898
+ * const result = await payos.cards.verifyAgentSignature({
1899
+ * method: 'POST',
1900
+ * path: '/checkout',
1901
+ * headers: req.headers,
1902
+ * signatureInput: req.headers['signature-input'],
1903
+ * signature: req.headers['signature'],
1904
+ * });
1905
+ *
1906
+ * if (result.valid) {
1907
+ * console.log(`Verified ${result.network} agent from ${result.agentProvider}`);
1908
+ * }
1909
+ * ```
1910
+ */
1911
+ async verifyAgentSignature(params) {
1912
+ return this.client.request("/v1/cards/verify", {
1913
+ method: "POST",
1914
+ body: JSON.stringify(params)
1915
+ });
1916
+ }
1917
+ /**
1918
+ * Get configured card networks and their status
1919
+ *
1920
+ * @example
1921
+ * ```typescript
1922
+ * const { networks, capabilities } = await payos.cards.getNetworks();
1923
+ *
1924
+ * if (networks.visa.configured) {
1925
+ * console.log(`Visa: ${networks.visa.status}`);
1926
+ * }
1927
+ * ```
1928
+ */
1929
+ async getNetworks() {
1930
+ return this.client.request("/v1/cards/networks");
1931
+ }
1932
+ /**
1933
+ * Test connection to a card network
1934
+ */
1935
+ async testNetwork(network) {
1936
+ return this.client.request(`/v1/cards/networks/${network}/test`, {
1937
+ method: "POST"
1938
+ });
1939
+ }
1940
+ /**
1941
+ * Configure Visa VIC credentials
1942
+ */
1943
+ async configureVisa(params) {
1944
+ return this.client.request("/v1/cards/networks/visa/configure", {
1945
+ method: "POST",
1946
+ body: JSON.stringify(params)
1947
+ });
1948
+ }
1949
+ /**
1950
+ * Configure Mastercard Agent Pay credentials
1951
+ */
1952
+ async configureMastercard(params) {
1953
+ return this.client.request("/v1/cards/networks/mastercard/configure", {
1954
+ method: "POST",
1955
+ body: JSON.stringify(params)
1956
+ });
1957
+ }
1958
+ /**
1959
+ * Disconnect a card network
1960
+ */
1961
+ async disconnectNetwork(network) {
1962
+ return this.client.request(
1963
+ `/v1/cards/networks/${network}/disconnect`,
1964
+ { method: "DELETE" }
1965
+ );
1966
+ }
1967
+ /**
1968
+ * Get comprehensive card network analytics
1969
+ *
1970
+ * @param days - Number of days to analyze (default: 30)
1971
+ *
1972
+ * @example
1973
+ * ```typescript
1974
+ * const analytics = await payos.cards.getAnalytics(30);
1975
+ *
1976
+ * console.log(`Success rate: ${analytics.verifications.successRate}%`);
1977
+ * console.log(`Total volume: $${analytics.transactions.volume}`);
1978
+ * ```
1979
+ */
1980
+ async getAnalytics(days = 30) {
1981
+ return this.client.request(`/v1/cards/analytics?days=${days}`);
1982
+ }
1983
+ /**
1984
+ * Get verification statistics
1985
+ *
1986
+ * @param days - Number of days to analyze (default: 30)
1987
+ */
1988
+ async getVerificationStats(days = 30) {
1989
+ return this.client.request(`/v1/cards/verifications/stats?days=${days}`);
1990
+ }
1991
+ /**
1992
+ * List card network transactions
1993
+ */
1994
+ async listTransactions(options) {
1995
+ const params = new URLSearchParams();
1996
+ if (options?.network) params.set("network", options.network);
1997
+ if (options?.status) params.set("status", options.status);
1998
+ if (options?.limit) params.set("limit", String(options.limit));
1999
+ if (options?.offset) params.set("offset", String(options.offset));
2000
+ const query = params.toString();
2001
+ return this.client.request(
2002
+ `/v1/cards/transactions${query ? `?${query}` : ""}`
2003
+ );
2004
+ }
2005
+ /**
2006
+ * Get a specific transaction
2007
+ */
2008
+ async getTransaction(transactionId) {
2009
+ return this.client.request(`/v1/cards/transactions/${transactionId}`);
2010
+ }
2011
+ // ============================================
2012
+ // Agent Signing Methods
2013
+ // ============================================
2014
+ /**
2015
+ * Generate a signing key for an agent
2016
+ *
2017
+ * Creates an Ed25519 or RSA-SHA256 key pair for the agent to sign
2018
+ * payment requests according to RFC 9421 (HTTP Message Signatures).
2019
+ *
2020
+ * @example
2021
+ * ```typescript
2022
+ * const key = await payos.cards.generateSigningKey('agent_123');
2023
+ * console.log(`Public key: ${key.publicKey}`);
2024
+ * // Register this public key with card networks (Visa TAP, MC Agent Pay)
2025
+ * ```
2026
+ */
2027
+ async generateSigningKey(agentId, options) {
2028
+ return this.client.request(
2029
+ `/v1/agents/${agentId}/signing-keys`,
2030
+ {
2031
+ method: "POST",
2032
+ body: JSON.stringify(options || {})
2033
+ }
2034
+ );
2035
+ }
2036
+ /**
2037
+ * Get the signing key status for an agent
2038
+ *
2039
+ * @example
2040
+ * ```typescript
2041
+ * const status = await payos.cards.getSigningKey('agent_123');
2042
+ * if (status.hasKey) {
2043
+ * console.log(`Key: ${status.keyId}, Uses: ${status.stats.useCount}`);
2044
+ * }
2045
+ * ```
2046
+ */
2047
+ async getSigningKey(agentId) {
2048
+ return this.client.request(`/v1/agents/${agentId}/signing-keys`);
2049
+ }
2050
+ /**
2051
+ * Revoke an agent's signing key
2052
+ *
2053
+ * After revocation, the agent will need a new key to sign requests.
2054
+ */
2055
+ async revokeSigningKey(agentId) {
2056
+ return this.client.request(
2057
+ `/v1/agents/${agentId}/signing-keys`,
2058
+ { method: "DELETE" }
2059
+ );
2060
+ }
2061
+ /**
2062
+ * Sign a payment request for an agent
2063
+ *
2064
+ * Signs an HTTP request according to RFC 9421 so the agent can
2065
+ * authenticate with merchants and card networks.
2066
+ *
2067
+ * Requirements:
2068
+ * - Agent must have KYA tier >= 1
2069
+ * - Agent must be active
2070
+ * - Agent must have a signing key
2071
+ * - Payment must be within spending limits
2072
+ *
2073
+ * @example
2074
+ * ```typescript
2075
+ * // Sign a payment request
2076
+ * const signed = await payos.cards.signRequest('agent_123', {
2077
+ * method: 'POST',
2078
+ * path: '/api/checkout',
2079
+ * host: 'merchant.com',
2080
+ * body: JSON.stringify({ items: [...], total: 99.99 }),
2081
+ * payment: {
2082
+ * amount: 99.99,
2083
+ * currency: 'USD',
2084
+ * merchantName: 'Acme Store',
2085
+ * },
2086
+ * });
2087
+ *
2088
+ * // Agent uses signed headers to call merchant
2089
+ * const response = await fetch('https://merchant.com/api/checkout', {
2090
+ * method: 'POST',
2091
+ * headers: {
2092
+ * ...signed.headers,
2093
+ * 'Content-Type': 'application/json',
2094
+ * },
2095
+ * body: JSON.stringify({ items: [...], total: 99.99 }),
2096
+ * });
2097
+ * ```
2098
+ */
2099
+ async signRequest(agentId, request) {
2100
+ return this.client.request(
2101
+ `/v1/agents/${agentId}/sign-request`,
2102
+ {
2103
+ method: "POST",
2104
+ body: JSON.stringify(request)
2105
+ }
2106
+ );
2107
+ }
2108
+ };
2109
+ }
2110
+ });
2111
+
2112
+ // src/protocols/a2a/client.ts
2113
+ var A2AClient;
2114
+ var init_client7 = __esm({
2115
+ "src/protocols/a2a/client.ts"() {
2116
+ A2AClient = class {
2117
+ constructor(client) {
2118
+ this.client = client;
2119
+ }
2120
+ /**
2121
+ * Discover an agent's capabilities via its Agent Card.
2122
+ *
2123
+ * @example
2124
+ * ```typescript
2125
+ * const card = await sly.a2a.discover('agent-uuid');
2126
+ * console.log(card.skills);
2127
+ * ```
2128
+ */
2129
+ async discover(agentId) {
2130
+ return this.client.request(
2131
+ `/v1/a2a/${agentId}/.well-known/agent.json`
2132
+ );
2133
+ }
2134
+ /**
2135
+ * Send a message to an agent, creating or continuing a task.
2136
+ *
2137
+ * @example
2138
+ * ```typescript
2139
+ * const task = await sly.a2a.sendMessage('agent-uuid', {
2140
+ * message: 'Check my wallet balance',
2141
+ * });
2142
+ * console.log(task.status.state); // 'submitted' or 'completed'
2143
+ * ```
2144
+ */
2145
+ async sendMessage(agentId, params) {
2146
+ const parts = typeof params.message === "string" ? [{ text: params.message }] : params.message;
2147
+ const body = {
2148
+ jsonrpc: "2.0",
2149
+ method: "message/send",
2150
+ params: {
2151
+ message: { role: "user", parts, metadata: params.metadata },
2152
+ ...params.contextId && { contextId: params.contextId },
2153
+ ...params.configuration && { configuration: params.configuration },
2154
+ ...params.skillId && { skill_id: params.skillId }
2155
+ },
2156
+ id: crypto.randomUUID()
2157
+ };
2158
+ const response = await this.client.request(
2159
+ `/v1/a2a/${agentId}`,
2160
+ { method: "POST", body: JSON.stringify(body) }
2161
+ );
2162
+ return response.result;
2163
+ }
2164
+ /**
2165
+ * Get a task by ID.
2166
+ *
2167
+ * @example
2168
+ * ```typescript
2169
+ * const task = await sly.a2a.getTask('agent-uuid', 'task-uuid');
2170
+ * console.log(task.status.state);
2171
+ * ```
2172
+ */
2173
+ async getTask(agentId, taskId, historyLength) {
2174
+ const body = {
2175
+ jsonrpc: "2.0",
2176
+ method: "tasks/get",
2177
+ params: { id: taskId, ...historyLength && { historyLength } },
2178
+ id: crypto.randomUUID()
2179
+ };
2180
+ const response = await this.client.request(
2181
+ `/v1/a2a/${agentId}`,
2182
+ { method: "POST", body: JSON.stringify(body) }
2183
+ );
2184
+ return response.result;
2185
+ }
2186
+ /**
2187
+ * Cancel a task.
2188
+ */
2189
+ async cancelTask(agentId, taskId) {
2190
+ const body = {
2191
+ jsonrpc: "2.0",
2192
+ method: "tasks/cancel",
2193
+ params: { id: taskId },
2194
+ id: crypto.randomUUID()
2195
+ };
2196
+ const response = await this.client.request(
2197
+ `/v1/a2a/${agentId}`,
2198
+ { method: "POST", body: JSON.stringify(body) }
2199
+ );
2200
+ return response.result;
2201
+ }
2202
+ /**
2203
+ * List tasks for an agent (REST endpoint).
2204
+ *
2205
+ * @example
2206
+ * ```typescript
2207
+ * const { data, pagination } = await sly.a2a.listTasks({
2208
+ * agentId: 'agent-uuid',
2209
+ * state: 'completed',
2210
+ * limit: 20,
2211
+ * });
2212
+ * ```
2213
+ */
2214
+ async listTasks(options = {}) {
2215
+ const params = new URLSearchParams();
2216
+ if (options.agentId) params.append("agent_id", options.agentId);
2217
+ if (options.state) params.append("state", options.state);
2218
+ if (options.direction) params.append("direction", options.direction);
2219
+ if (options.contextId) params.append("context_id", options.contextId);
2220
+ if (options.page) params.append("page", options.page.toString());
2221
+ if (options.limit) params.append("limit", options.limit.toString());
2222
+ const qs = params.toString();
2223
+ return this.client.request(
2224
+ qs ? `/v1/a2a/tasks?${qs}` : "/v1/a2a/tasks"
2225
+ );
2226
+ }
2227
+ /**
2228
+ * Respond to a task in input-required state (human-in-the-loop).
2229
+ */
2230
+ async respond(taskId, message) {
2231
+ return this.client.request(
2232
+ `/v1/a2a/tasks/${taskId}/respond`,
2233
+ { method: "POST", body: JSON.stringify({ message }) }
2234
+ );
2235
+ }
2236
+ // =========================================================================
2237
+ // Custom Tools (Story 58.15)
2238
+ // =========================================================================
2239
+ /**
2240
+ * Register a custom tool for an agent.
2241
+ *
2242
+ * @example
2243
+ * ```typescript
2244
+ * const tool = await sly.a2a.createCustomTool('agent-uuid', {
2245
+ * toolName: 'lookup_inventory',
2246
+ * description: 'Check product inventory levels',
2247
+ * inputSchema: {
2248
+ * type: 'object',
2249
+ * properties: { sku: { type: 'string' } },
2250
+ * required: ['sku'],
2251
+ * },
2252
+ * handlerUrl: 'https://api.example.com/inventory',
2253
+ * });
2254
+ * ```
2255
+ */
2256
+ async createCustomTool(agentId, request) {
2257
+ const response = await this.client.request(
2258
+ `/v1/a2a/agents/${agentId}/tools`,
2259
+ { method: "POST", body: JSON.stringify(request) }
2260
+ );
2261
+ return response.data;
2262
+ }
2263
+ /**
2264
+ * List custom tools for an agent.
2265
+ */
2266
+ async listCustomTools(agentId) {
2267
+ const response = await this.client.request(
2268
+ `/v1/a2a/agents/${agentId}/tools`
2269
+ );
2270
+ return response.data;
2271
+ }
2272
+ /**
2273
+ * Delete a custom tool.
2274
+ */
2275
+ async deleteCustomTool(agentId, toolId) {
2276
+ await this.client.request(
2277
+ `/v1/a2a/agents/${agentId}/tools/${toolId}`,
2278
+ { method: "DELETE" }
2279
+ );
2280
+ }
2281
+ };
2282
+ }
2283
+ });
2284
+
2285
+ // src/protocols/agent-wallets/client.ts
2286
+ var AgentWalletsClient;
2287
+ var init_client8 = __esm({
2288
+ "src/protocols/agent-wallets/client.ts"() {
2289
+ AgentWalletsClient = class {
2290
+ constructor(client) {
2291
+ this.client = client;
2292
+ }
2293
+ /**
2294
+ * Evaluate a contract policy in dry-run mode (negotiation guardrails).
2295
+ *
2296
+ * @example
2297
+ * ```typescript
2298
+ * const result = await sly.agentWallets.evaluatePolicy('agent-uuid', {
2299
+ * amount: 150,
2300
+ * actionType: 'payment',
2301
+ * counterpartyAgentId: 'other-agent-uuid',
2302
+ * });
2303
+ * console.log(result.decision); // 'approve' | 'escalate' | 'deny'
2304
+ * ```
2305
+ */
2306
+ async evaluatePolicy(agentId, request) {
2307
+ const response = await this.client.request(
2308
+ `/v1/agents/${agentId}/wallet/policy/evaluate`,
2309
+ {
2310
+ method: "POST",
2311
+ body: JSON.stringify({
2312
+ amount: request.amount,
2313
+ currency: request.currency || "USDC",
2314
+ action_type: request.actionType,
2315
+ contract_type: request.contractType,
2316
+ counterparty_agent_id: request.counterpartyAgentId,
2317
+ counterparty_address: request.counterpartyAddress,
2318
+ protocol: request.protocol
2319
+ })
2320
+ }
2321
+ );
2322
+ const d = response.data || response;
2323
+ return {
2324
+ decision: d.decision,
2325
+ reasons: d.reasons,
2326
+ checks: d.checks,
2327
+ suggestedCounterOffer: d.suggested_counter_offer ? {
2328
+ maxAmount: d.suggested_counter_offer.max_amount,
2329
+ reason: d.suggested_counter_offer.reason
2330
+ } : null,
2331
+ evaluationMs: d.evaluation_ms
2332
+ };
2333
+ }
2334
+ /**
2335
+ * List counterparty exposures for an agent's wallet.
2336
+ *
2337
+ * @example
2338
+ * ```typescript
2339
+ * const exposures = await sly.agentWallets.getExposures('agent-uuid');
2340
+ * for (const exp of exposures) {
2341
+ * console.log(`${exp.counterpartyAgentId}: ${exp.exposure24h} (24h)`);
2342
+ * }
2343
+ * ```
2344
+ */
2345
+ async getExposures(agentId) {
2346
+ const response = await this.client.request(
2347
+ `/v1/agents/${agentId}/wallet/exposures`
2348
+ );
2349
+ const items = response.data || [];
2350
+ return items.map((e) => ({
2351
+ id: e.id,
2352
+ walletId: e.wallet_id,
2353
+ counterpartyAgentId: e.counterparty_agent_id,
2354
+ counterpartyAddress: e.counterparty_address,
2355
+ exposure24h: e.exposure_24h,
2356
+ exposure7d: e.exposure_7d,
2357
+ exposure30d: e.exposure_30d,
2358
+ activeContracts: e.active_contracts,
2359
+ activeEscrows: e.active_escrows,
2360
+ totalVolume: e.total_volume,
2361
+ transactionCount: e.transaction_count,
2362
+ currency: e.currency
2363
+ }));
2364
+ }
2365
+ /**
2366
+ * Get policy evaluation audit log for an agent's wallet.
2367
+ */
2368
+ async getEvaluations(agentId, options) {
2369
+ const params = new URLSearchParams();
2370
+ if (options?.page) params.set("page", options.page.toString());
2371
+ if (options?.limit) params.set("limit", options.limit.toString());
2372
+ const qs = params.toString();
2373
+ const response = await this.client.request(
2374
+ `/v1/agents/${agentId}/wallet/policy/evaluations${qs ? `?${qs}` : ""}`
2375
+ );
2376
+ return {
2377
+ data: (response.data || []).map((e) => ({
2378
+ id: e.id,
2379
+ actionType: e.action_type,
2380
+ amount: e.amount,
2381
+ currency: e.currency,
2382
+ contractType: e.contract_type,
2383
+ counterpartyAgentId: e.counterparty_agent_id,
2384
+ counterpartyAddress: e.counterparty_address,
2385
+ decision: e.decision,
2386
+ decisionReasons: e.decision_reasons,
2387
+ suggestedCounterOffer: e.suggested_counter_offer,
2388
+ checksPerformed: e.checks_performed,
2389
+ evaluationMs: e.evaluation_ms,
2390
+ createdAt: e.created_at
2391
+ })),
2392
+ pagination: response.pagination
2393
+ };
2394
+ }
2395
+ /**
2396
+ * Get an agent's wallet details.
2397
+ */
2398
+ async getWallet(agentId) {
2399
+ const response = await this.client.request(
2400
+ `/v1/agents/${agentId}/wallet`
2401
+ );
2402
+ return response.data || response;
2403
+ }
2404
+ /**
2405
+ * Freeze an agent's wallet (disables all payments).
2406
+ */
2407
+ async freezeWallet(agentId) {
2408
+ const response = await this.client.request(
2409
+ `/v1/agents/${agentId}/wallet/freeze`,
2410
+ { method: "POST" }
2411
+ );
2412
+ return response.data || response;
2413
+ }
2414
+ /**
2415
+ * Unfreeze an agent's wallet (re-enables payments).
2416
+ */
2417
+ async unfreezeWallet(agentId) {
2418
+ const response = await this.client.request(
2419
+ `/v1/agents/${agentId}/wallet/unfreeze`,
2420
+ { method: "POST" }
2421
+ );
2422
+ return response.data || response;
2423
+ }
2424
+ /**
2425
+ * Set or update the contract policy on an agent's wallet.
2426
+ *
2427
+ * @example
2428
+ * ```typescript
2429
+ * await sly.agentWallets.setContractPolicy('agent-uuid', {
2430
+ * dailySpendLimit: 500,
2431
+ * contractPolicy: {
2432
+ * counterpartyBlocklist: ['bad-agent-id'],
2433
+ * maxExposure24h: 200,
2434
+ * escalateAbove: 100,
2435
+ * },
2436
+ * });
2437
+ * ```
2438
+ */
2439
+ async setContractPolicy(agentId, policy) {
2440
+ const response = await this.client.request(
2441
+ `/v1/agents/${agentId}/wallet/policy`,
2442
+ {
2443
+ method: "PUT",
2444
+ body: JSON.stringify(policy)
2445
+ }
2446
+ );
2447
+ return response.data || response;
2448
+ }
2449
+ };
2450
+ }
2451
+ });
2452
+
2453
+ // src/protocols/mpp/client.ts
2454
+ var MPPClient;
2455
+ var init_client9 = __esm({
2456
+ "src/protocols/mpp/client.ts"() {
2457
+ MPPClient = class {
2458
+ constructor(client) {
2459
+ this.client = client;
2460
+ }
2461
+ /**
2462
+ * Make a one-shot MPP payment to a service
2463
+ *
2464
+ * @example
2465
+ * ```typescript
2466
+ * const result = await sly.mpp.pay({
2467
+ * service_url: 'https://api.example.com',
2468
+ * amount: 0.50,
2469
+ * agent_id: 'agent-uuid',
2470
+ * });
2471
+ * ```
2472
+ */
2473
+ async pay(request) {
2474
+ return this.client.request("/v1/mpp/pay", {
2475
+ method: "POST",
2476
+ body: JSON.stringify(request)
2477
+ });
2478
+ }
2479
+ /**
2480
+ * Open a streaming payment session
2481
+ *
2482
+ * @example
2483
+ * ```typescript
2484
+ * const session = await sly.mpp.openSession({
2485
+ * service_url: 'https://api.example.com',
2486
+ * deposit_amount: 10.00,
2487
+ * agent_id: 'agent-uuid',
2488
+ * wallet_id: 'wallet-uuid',
2489
+ * });
2490
+ * ```
2491
+ */
2492
+ async openSession(request) {
2493
+ return this.client.request("/v1/mpp/sessions", {
2494
+ method: "POST",
2495
+ body: JSON.stringify(request)
2496
+ });
2497
+ }
2498
+ /**
2499
+ * Get session details with voucher history
2500
+ */
2501
+ async getSession(sessionId) {
2502
+ return this.client.request(`/v1/mpp/sessions/${sessionId}`);
2503
+ }
2504
+ /**
2505
+ * List MPP sessions with optional filtering
2506
+ */
2507
+ async listSessions(options = {}) {
2508
+ const params = new URLSearchParams();
2509
+ if (options.agent_id) params.append("agent_id", options.agent_id);
2510
+ if (options.status) params.append("status", options.status);
2511
+ if (options.limit) params.append("limit", options.limit.toString());
2512
+ if (options.offset) params.append("offset", options.offset.toString());
2513
+ const queryString = params.toString();
2514
+ const path = queryString ? `/v1/mpp/sessions?${queryString}` : "/v1/mpp/sessions";
2515
+ return this.client.request(path);
2516
+ }
2517
+ /**
2518
+ * Close an active session
2519
+ */
2520
+ async closeSession(sessionId) {
2521
+ return this.client.request(`/v1/mpp/sessions/${sessionId}/close`, {
2522
+ method: "POST"
2523
+ });
2524
+ }
2525
+ /**
2526
+ * List MPP payment transfers
2527
+ */
2528
+ async listTransfers(options = {}) {
2529
+ const params = new URLSearchParams();
2530
+ if (options.service_url) params.append("service_url", options.service_url);
2531
+ if (options.session_id) params.append("session_id", options.session_id);
2532
+ if (options.limit) params.append("limit", options.limit.toString());
2533
+ if (options.offset) params.append("offset", options.offset.toString());
2534
+ const queryString = params.toString();
2535
+ const path = queryString ? `/v1/mpp/transfers?${queryString}` : "/v1/mpp/transfers";
2536
+ return this.client.request(path);
2537
+ }
2538
+ /**
2539
+ * Verify an MPP payment receipt
2540
+ */
2541
+ async verifyReceipt(receiptId) {
2542
+ return this.client.request("/v1/mpp/receipts/verify", {
2543
+ method: "POST",
2544
+ body: JSON.stringify({ receipt_id: receiptId })
2545
+ });
2546
+ }
2547
+ /**
2548
+ * Provision a wallet for MPP payments
2549
+ */
2550
+ async provisionWallet(request) {
2551
+ return this.client.request("/v1/mpp/wallets/provision", {
2552
+ method: "POST",
2553
+ body: JSON.stringify(request)
2554
+ });
2555
+ }
2556
+ /**
2557
+ * Browse the MPP service directory
2558
+ */
2559
+ async browseServices(options) {
2560
+ const params = new URLSearchParams();
2561
+ if (options?.category) params.append("category", options.category);
2562
+ if (options?.limit) params.append("limit", options.limit.toString());
2563
+ const queryString = params.toString();
2564
+ const path = queryString ? `/v1/mpp/services?${queryString}` : "/v1/mpp/services";
2565
+ return this.client.request(path);
2566
+ }
2567
+ /**
2568
+ * Get pricing info for a service
2569
+ */
2570
+ async getServicePricing(domain) {
2571
+ return this.client.request(`/v1/mpp/services/${domain}/pricing`);
2572
+ }
2573
+ };
2574
+ }
2575
+ });
2576
+
2577
+ // src/types.ts
2578
+ var init_types3 = __esm({
2579
+ "src/types.ts"() {
2580
+ }
2581
+ });
2582
+
2583
+ // src/auth.ts
2584
+ async function loginWithPassword(credentials, apiUrl = "http://localhost:4000") {
2585
+ const response = await fetch(`${apiUrl}/v1/auth/login`, {
2586
+ method: "POST",
2587
+ headers: {
2588
+ "Content-Type": "application/json"
2589
+ },
2590
+ body: JSON.stringify(credentials)
2591
+ });
2592
+ if (!response.ok) {
2593
+ const error = await response.json().catch(() => ({
2594
+ error: response.statusText
2595
+ }));
2596
+ throw new Error(error.error || `Login failed: ${response.status}`);
2597
+ }
2598
+ return response.json();
2599
+ }
2600
+ async function createWithPassword(credentials, environment = "sandbox", apiUrl) {
2601
+ const { PayOS } = await Promise.resolve().then(() => (init_src(), src_exports));
2602
+ const auth = await loginWithPassword(credentials, apiUrl);
2603
+ return new PayOS({
2604
+ apiKey: auth.access_token,
2605
+ environment,
2606
+ apiUrl
2607
+ });
2608
+ }
2609
+ async function verifyApiKey(apiKey, apiUrl = "http://localhost:4000") {
2610
+ try {
2611
+ const response = await fetch(`${apiUrl}/v1/auth/me`, {
2612
+ headers: {
2613
+ "Authorization": `Bearer ${apiKey}`
2614
+ }
2615
+ });
2616
+ return response.ok;
2617
+ } catch {
2618
+ return false;
2619
+ }
2620
+ }
2621
+ var init_auth = __esm({
2622
+ "src/auth.ts"() {
2623
+ }
2624
+ });
2625
+
2626
+ // src/index.ts
2627
+ var src_exports = {};
2628
+ __export(src_exports, {
2629
+ ENVIRONMENT_CONFIGS: () => exports.ENVIRONMENT_CONFIGS,
2630
+ PayOS: () => exports.Sly,
2631
+ PayOSClient: () => exports.SlyClient,
2632
+ Sly: () => exports.Sly,
2633
+ SlyClient: () => exports.SlyClient,
2634
+ createWithPassword: () => createWithPassword,
2635
+ getEnvironmentConfig: () => getEnvironmentConfig,
2636
+ inferEnvironmentFromKey: () => inferEnvironmentFromKey,
2637
+ loginWithPassword: () => loginWithPassword,
2638
+ validateEnvironment: () => validateEnvironment,
2639
+ verifyApiKey: () => verifyApiKey
2640
+ });
2641
+ exports.Sly = void 0;
2642
+ var init_src = __esm({
2643
+ "src/index.ts"() {
2644
+ init_client();
2645
+ init_config();
2646
+ init_client2();
2647
+ init_provider();
2648
+ init_client3();
2649
+ init_client4();
2650
+ init_client5();
2651
+ init_capabilities();
2652
+ init_tools();
2653
+ init_cards();
2654
+ init_client7();
2655
+ init_client8();
2656
+ init_client9();
2657
+ init_types3();
2658
+ init_config();
2659
+ init_client();
2660
+ init_auth();
2661
+ exports.Sly = class extends exports.SlyClient {
2662
+ constructor(config) {
2663
+ if (!config.apiKey || config.apiKey.trim() === "") {
2664
+ throw new Error("API key is required");
2665
+ }
2666
+ const resolvedEnvironment = config.environment ?? inferEnvironmentFromKey(config.apiKey) ?? "sandbox";
2667
+ const resolvedConfig = { ...config, environment: resolvedEnvironment };
2668
+ super(resolvedConfig);
2669
+ this.x402 = {
2670
+ createClient: (overrides) => {
2671
+ return new SlyX402Client({
2672
+ ...resolvedConfig,
2673
+ ...overrides
2674
+ });
2675
+ },
2676
+ createProvider: (routes) => {
2677
+ return new SlyX402Provider({
2678
+ apiKey: config.apiKey,
2679
+ environment: resolvedEnvironment,
2680
+ routes,
2681
+ facilitatorUrl: config.facilitatorUrl
2682
+ });
2683
+ }
2684
+ };
2685
+ this.ap2 = new AP2Client(this);
2686
+ this.acp = new ACPClient(this);
2687
+ this.ucp = new UCPClient(this);
2688
+ this.capabilities = new CapabilitiesClient(this);
2689
+ this.langchain = new LangChainTools(this);
2690
+ this.cards = new CardsClient(this);
2691
+ this.a2a = new A2AClient(this);
2692
+ this.agentWallets = new AgentWalletsClient(this);
2693
+ this.mpp = new MPPClient(this);
2694
+ }
2695
+ };
2696
+ }
2697
+ });
2698
+ init_src();
2699
+
2700
+ exports.PayOS = exports.Sly;
2701
+ exports.PayOSClient = exports.SlyClient;
2702
+ exports.createWithPassword = createWithPassword;
2703
+ exports.getEnvironmentConfig = getEnvironmentConfig;
2704
+ exports.inferEnvironmentFromKey = inferEnvironmentFromKey;
2705
+ exports.loginWithPassword = loginWithPassword;
2706
+ exports.validateEnvironment = validateEnvironment;
2707
+ exports.verifyApiKey = verifyApiKey;
2708
+ //# sourceMappingURL=index.js.map
2709
+ //# sourceMappingURL=index.js.map