agentcash 0.3.7 → 0.4.1

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 (33) hide show
  1. package/dist/cjs/run-server.cjs +692 -657
  2. package/dist/esm/{chunk-ED4QVIZH.js → chunk-2CFQ7ILC.js} +2 -2
  3. package/dist/esm/chunk-2CFQ7ILC.js.map +1 -0
  4. package/dist/esm/{chunk-7E4JDDBW.js → chunk-7DEM3OEU.js} +109 -61
  5. package/dist/esm/chunk-7DEM3OEU.js.map +1 -0
  6. package/dist/esm/{chunk-SBLBP4FH.js → chunk-7LPATNAW.js} +2 -2
  7. package/dist/esm/{chunk-PCCYUD6X.js → chunk-DCP6SZGV.js} +3 -3
  8. package/dist/esm/{chunk-PJFATGPH.js → chunk-EO4BIJAO.js} +22 -9
  9. package/dist/esm/{chunk-PJFATGPH.js.map → chunk-EO4BIJAO.js.map} +1 -1
  10. package/dist/esm/{chunk-RP5AGYAT.js → chunk-SHAJ42CH.js} +111 -118
  11. package/dist/esm/chunk-SHAJ42CH.js.map +1 -0
  12. package/dist/esm/{chunk-EVE4PTLY.js → chunk-TRGCJSV2.js} +2 -2
  13. package/dist/esm/{commands-JXKV7VMY.js → commands-WXPPIUX3.js} +9 -8
  14. package/dist/esm/{commands-JXKV7VMY.js.map → commands-WXPPIUX3.js.map} +1 -1
  15. package/dist/esm/{fund-IALSHTLH.js → fund-3DJLQ6CN.js} +4 -4
  16. package/dist/esm/index.js +9 -9
  17. package/dist/esm/{install-IP2RBDST.js → install-N5BZ677Y.js} +5 -5
  18. package/dist/esm/lib.d.ts +45 -4
  19. package/dist/esm/lib.js +4 -4
  20. package/dist/esm/{server-BEKXJWYB.js → server-PMG7V6KQ.js} +26 -22
  21. package/dist/esm/server-PMG7V6KQ.js.map +1 -0
  22. package/dist/esm/shared/operations/index.d.ts +1 -1
  23. package/dist/esm/shared/operations/index.js +4 -4
  24. package/package.json +10 -10
  25. package/dist/esm/chunk-7E4JDDBW.js.map +0 -1
  26. package/dist/esm/chunk-ED4QVIZH.js.map +0 -1
  27. package/dist/esm/chunk-RP5AGYAT.js.map +0 -1
  28. package/dist/esm/server-BEKXJWYB.js.map +0 -1
  29. /package/dist/esm/{chunk-SBLBP4FH.js.map → chunk-7LPATNAW.js.map} +0 -0
  30. /package/dist/esm/{chunk-PCCYUD6X.js.map → chunk-DCP6SZGV.js.map} +0 -0
  31. /package/dist/esm/{chunk-EVE4PTLY.js.map → chunk-TRGCJSV2.js.map} +0 -0
  32. /package/dist/esm/{fund-IALSHTLH.js.map → fund-3DJLQ6CN.js.map} +0 -0
  33. /package/dist/esm/{install-IP2RBDST.js.map → install-N5BZ677Y.js.map} +0 -0
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  getWalletInfo,
3
3
  submitErrorReport
4
- } from "./chunk-RP5AGYAT.js";
4
+ } from "./chunk-SHAJ42CH.js";
5
5
 
6
6
  // src/shared/operations/index.ts
7
7
  async function getWalletInfo2(surface, address, flags) {
@@ -19,4 +19,4 @@ export {
19
19
  getWalletInfo2 as getWalletInfo,
20
20
  submitErrorReport2 as submitErrorReport
21
21
  };
22
- //# sourceMappingURL=chunk-ED4QVIZH.js.map
22
+ //# sourceMappingURL=chunk-2CFQ7ILC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/shared/operations/index.ts"],"sourcesContent":["/**\n * Published entry point: `agentcash/operations`\n *\n * All exports return plain types (no Result<> from neverthrow) to avoid\n * leaking @agentcash/neverthrow/types into published .d.ts files.\n */\n\nimport type { Address } from 'viem';\nimport type { GlobalFlags } from '@/types';\n\n// ── Discover ──\n// Already returns plain type (DiscoveryResult | null)\nexport {\n discoverResources,\n type DiscoveryResult,\n type OpenApiInfo,\n} from './discover';\n\n// ── Check Endpoint ──\nexport {\n checkEndpoint,\n type CheckEndpointOptions,\n type CheckEndpointResult,\n type ProbeMethodResult,\n type PaymentOption,\n type MppPaymentOption,\n type X402PaymentOption,\n type SupportedMethod,\n SUPPORTED_METHODS,\n} from './check-endpoint';\n\n// ── Wallet Info ──\nimport { getWalletInfo as _getWalletInfo } from './wallet-info';\nexport type { WalletInfoResult } from './wallet-info';\n\nexport async function getWalletInfo(\n surface: string,\n address: Address,\n flags: GlobalFlags\n) {\n const result = await _getWalletInfo(surface, address, flags);\n if (result.isErr()) throw new Error(result.error.message);\n return result.value;\n}\n\n// ── Report Error ──\nimport { submitErrorReport as _submitErrorReport } from './report-error';\nexport type { ErrorReportResult } from './report-error';\n\nexport async function submitErrorReport(\n surface: string,\n input: {\n tool: string;\n summary: string;\n errorMessage: string;\n resource?: string;\n stack?: string;\n fullReport?: string;\n },\n address: Address,\n dev: boolean\n) {\n const result = await _submitErrorReport(surface, input, address, dev);\n if (result.isErr()) throw new Error(result.error.message);\n return result.value;\n}\n"],"mappings":";;;;;;AAmCA,eAAsBA,eACpB,SACA,SACA,OACA;AACA,QAAM,SAAS,MAAM,cAAe,SAAS,SAAS,KAAK;AAC3D,MAAI,OAAO,MAAM,EAAG,OAAM,IAAI,MAAM,OAAO,MAAM,OAAO;AACxD,SAAO,OAAO;AAChB;AAMA,eAAsBC,mBACpB,SACA,OAQA,SACA,KACA;AACA,QAAM,SAAS,MAAM,kBAAmB,SAAS,OAAO,SAAS,GAAG;AACpE,MAAI,OAAO,MAAM,EAAG,OAAM,IAAI,MAAM,OAAO,MAAM,OAAO;AACxD,SAAO,OAAO;AAChB;","names":["getWalletInfo","submitErrorReport"]}
@@ -1,26 +1,24 @@
1
1
  import {
2
2
  detectPaymentProtocols,
3
3
  getTempoBalance,
4
- mppErr,
5
- mppOk,
6
- safeCreateMppCredential,
7
4
  safeCreatePaymentPayload,
8
- safeGetMppChallenge,
9
- safeGetMppReceipt,
10
5
  safeGetPaymentRequired,
11
6
  safeGetPaymentSettlement,
12
7
  tokenStringToNumber,
13
8
  x402Err,
14
9
  x402Ok
15
- } from "./chunk-RP5AGYAT.js";
10
+ } from "./chunk-SHAJ42CH.js";
16
11
  import {
12
+ err,
17
13
  fetchErr,
18
14
  fetchOk,
19
15
  getBalance,
20
16
  log,
17
+ ok,
21
18
  resultFromPromise,
19
+ resultFromThrowable,
22
20
  safeFetch
23
- } from "./chunk-PJFATGPH.js";
21
+ } from "./chunk-EO4BIJAO.js";
24
22
 
25
23
  // src/server/tools/lib/request.ts
26
24
  import z from "zod";
@@ -28,7 +26,8 @@ var requestSchema = z.object({
28
26
  url: z.url().describe("The endpoint URL"),
29
27
  method: z.enum(["GET", "POST", "PUT", "DELETE", "PATCH"]).optional().describe("HTTP method. Defaults to GET for fetch operations."),
30
28
  body: z.unknown().optional().describe("Request body for POST/PUT/PATCH methods"),
31
- headers: z.record(z.string(), z.string()).optional().describe("Additional headers to include").default({})
29
+ headers: z.record(z.string(), z.string()).optional().describe("Additional headers to include").default({}),
30
+ timeout: z.number().int().positive().optional().describe("Request timeout in milliseconds")
32
31
  });
33
32
  var buildRequest = ({
34
33
  input,
@@ -48,14 +47,52 @@ var buildRequest = ({
48
47
  });
49
48
  };
50
49
 
50
+ // src/shared/neverthrow/mpp/index.ts
51
+ import { Challenge, Receipt } from "mppx";
52
+ var errorType = "mpp";
53
+ var mppOk = (value) => ok(value);
54
+ var mppErr = (surface, error) => err(errorType, surface, error);
55
+ var mppResultFromPromise = (surface, promise, error) => resultFromPromise(errorType, surface, promise, error);
56
+ var mppResultFromThrowable = (surface, fn, error) => resultFromThrowable(errorType, surface, fn, error);
57
+ var safeGetMppChallenge = (surface, response) => {
58
+ return mppResultFromThrowable(
59
+ surface,
60
+ () => Challenge.fromResponse(response),
61
+ (error) => ({
62
+ cause: "parse_mpp_challenge",
63
+ message: error instanceof Error ? error.message : "Failed to parse MPP challenge from response"
64
+ })
65
+ );
66
+ };
67
+ var safeCreateMppCredential = (surface, mppxClient, response) => {
68
+ return mppResultFromPromise(
69
+ surface,
70
+ mppxClient.createCredential(response),
71
+ (error) => ({
72
+ cause: "create_mpp_credential",
73
+ message: error instanceof Error ? error.message : "Failed to create MPP credential"
74
+ })
75
+ );
76
+ };
77
+ var safeGetMppReceipt = (surface, response) => {
78
+ return mppResultFromThrowable(
79
+ surface,
80
+ () => Receipt.fromResponse(response),
81
+ (error) => ({
82
+ cause: "parse_mpp_receipt",
83
+ message: error instanceof Error ? error.message : "Failed to parse MPP receipt from response"
84
+ })
85
+ );
86
+ };
87
+
51
88
  // src/shared/operations/fetch-with-payment.ts
52
89
  import { formatUnits } from "viem";
53
90
  function createFetchWithPayment(options) {
54
- const { surface, clients, paymentMethod, beforePayment } = options;
91
+ const { surface, clients, paymentMethod, beforePayment, timeout } = options;
55
92
  return async (request) => {
56
93
  const clonedRequest = request.clone();
57
94
  const fallbackRequest = request.clone();
58
- const probeResult = await safeFetch(surface, request);
95
+ const probeResult = await safeFetch(surface, request, timeout);
59
96
  if (probeResult.isErr()) {
60
97
  return fetchErr(surface, probeResult.error);
61
98
  }
@@ -74,7 +111,8 @@ function createFetchWithPayment(options) {
74
111
  response,
75
112
  clonedRequest,
76
113
  clients.x402,
77
- beforePayment
114
+ beforePayment,
115
+ timeout
78
116
  );
79
117
  }
80
118
  const available = detectPaymentProtocols(response);
@@ -90,7 +128,8 @@ function createFetchWithPayment(options) {
90
128
  response,
91
129
  clonedRequest,
92
130
  clients.x402,
93
- beforePayment
131
+ beforePayment,
132
+ timeout
94
133
  );
95
134
  if (result.isErr() && fallback) {
96
135
  return fallback === "mpp" ? handleMppPayment(surface, response, fallbackRequest, options) : handleX402Payment(
@@ -98,7 +137,8 @@ function createFetchWithPayment(options) {
98
137
  response,
99
138
  fallbackRequest,
100
139
  clients.x402,
101
- beforePayment
140
+ beforePayment,
141
+ timeout
102
142
  );
103
143
  }
104
144
  return result;
@@ -150,7 +190,7 @@ async function pickByBalance(surface, response, options) {
150
190
  log.info(`Protocol selection \u2014 x402: $${x402Balance}, mpp: $${mppBalance}`);
151
191
  return x402Balance >= mppBalance ? "x402" : "mpp";
152
192
  }
153
- async function handleX402Payment(surface, response, clonedRequest, client, beforePayment) {
193
+ async function handleX402Payment(surface, response, clonedRequest, client, beforePayment, timeout) {
154
194
  const paymentRequiredResult = await safeGetPaymentRequired(
155
195
  surface,
156
196
  client,
@@ -206,34 +246,36 @@ async function handleX402Payment(surface, response, clonedRequest, client, befor
206
246
  "Access-Control-Expose-Headers",
207
247
  "PAYMENT-RESPONSE,X-PAYMENT-RESPONSE"
208
248
  );
209
- return await safeFetch(surface, clonedRequest).andThen((paidResponse) => {
210
- const settlementResult = safeGetPaymentSettlement(
211
- surface,
212
- client,
213
- paidResponse
214
- );
215
- return x402Ok({
216
- response: paidResponse,
217
- paymentInfo: {
218
- protocol: "x402",
219
- price: tokenStringToNumber(
220
- paymentPayload.accepted.amount
221
- ).toLocaleString("en-US", {
222
- style: "currency",
223
- currency: "USD"
224
- }),
225
- ...settlementResult.isOk() ? {
226
- payment: {
227
- success: settlementResult.value.success,
228
- transactionHash: settlementResult.value.transaction
229
- }
230
- } : {}
231
- }
232
- });
233
- });
249
+ return await safeFetch(surface, clonedRequest, timeout).andThen(
250
+ (paidResponse) => {
251
+ const settlementResult = safeGetPaymentSettlement(
252
+ surface,
253
+ client,
254
+ paidResponse
255
+ );
256
+ return x402Ok({
257
+ response: paidResponse,
258
+ paymentInfo: {
259
+ protocol: "x402",
260
+ price: tokenStringToNumber(
261
+ paymentPayload.accepted.amount
262
+ ).toLocaleString("en-US", {
263
+ style: "currency",
264
+ currency: "USD"
265
+ }),
266
+ ...settlementResult.isOk() ? {
267
+ payment: {
268
+ success: settlementResult.value.success,
269
+ transactionHash: settlementResult.value.transaction
270
+ }
271
+ } : {}
272
+ }
273
+ });
274
+ }
275
+ );
234
276
  }
235
277
  async function handleMppPayment(surface, response, clonedRequest, options) {
236
- const { clients, beforePayment } = options;
278
+ const { clients, beforePayment, timeout } = options;
237
279
  const mppxClient = clients.mpp;
238
280
  if (clonedRequest.headers.has("Authorization")) {
239
281
  return mppErr(surface, {
@@ -279,31 +321,37 @@ async function handleMppPayment(surface, response, clonedRequest, options) {
279
321
  }
280
322
  const credential = credentialResult.value;
281
323
  clonedRequest.headers.set("Authorization", credential);
282
- return await safeFetch(surface, clonedRequest).andThen((paidResponse) => {
283
- const receiptResult = safeGetMppReceipt(surface, paidResponse);
284
- const priceDisplay = amount ? Number(formatUnits(BigInt(amount), decimals)).toLocaleString("en-US", {
285
- style: "currency",
286
- currency: "USD"
287
- }) : void 0;
288
- return mppOk({
289
- response: paidResponse,
290
- paymentInfo: {
291
- protocol: "mpp",
292
- ...priceDisplay ? { price: priceDisplay } : {},
293
- ...receiptResult.isOk() ? {
294
- payment: {
295
- success: true,
296
- transactionHash: receiptResult.value.reference
297
- }
298
- } : {}
299
- }
300
- });
301
- });
324
+ return await safeFetch(surface, clonedRequest, timeout).andThen(
325
+ (paidResponse) => {
326
+ const receiptResult = safeGetMppReceipt(surface, paidResponse);
327
+ const priceDisplay = amount ? Number(formatUnits(BigInt(amount), decimals)).toLocaleString(
328
+ "en-US",
329
+ {
330
+ style: "currency",
331
+ currency: "USD"
332
+ }
333
+ ) : void 0;
334
+ return mppOk({
335
+ response: paidResponse,
336
+ paymentInfo: {
337
+ protocol: "mpp",
338
+ ...priceDisplay ? { price: priceDisplay } : {},
339
+ ...receiptResult.isOk() ? {
340
+ payment: {
341
+ success: true,
342
+ transactionHash: receiptResult.value.reference
343
+ }
344
+ } : {}
345
+ }
346
+ });
347
+ }
348
+ );
302
349
  }
303
350
 
304
351
  export {
305
352
  requestSchema,
306
353
  buildRequest,
354
+ safeGetMppChallenge,
307
355
  createFetchWithPayment
308
356
  };
309
- //# sourceMappingURL=chunk-7E4JDDBW.js.map
357
+ //# sourceMappingURL=chunk-7DEM3OEU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/server/tools/lib/request.ts","../../src/shared/neverthrow/mpp/index.ts","../../src/shared/operations/fetch-with-payment.ts"],"sourcesContent":["import z from 'zod';\n\nimport type { Address } from 'viem';\n\nexport const requestSchema = z.object({\n url: z.url().describe('The endpoint URL'),\n method: z\n .enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH'])\n .optional()\n .describe('HTTP method. Defaults to GET for fetch operations.'),\n body: z\n .unknown()\n .optional()\n .describe('Request body for POST/PUT/PATCH methods'),\n headers: z\n .record(z.string(), z.string())\n .optional()\n .describe('Additional headers to include')\n .default({}),\n timeout: z\n .number()\n .int()\n .positive()\n .optional()\n .describe('Request timeout in milliseconds'),\n});\n\ninterface BuildRequestProps {\n input: z.infer<typeof requestSchema>;\n address?: Address;\n sessionId?: string;\n provider?: string;\n}\n\nexport const buildRequest = ({\n input,\n address,\n sessionId,\n provider,\n}: BuildRequestProps) => {\n return new Request(input.url, {\n method: input.method ?? 'GET',\n body: input.body\n ? typeof input.body === 'string'\n ? input.body\n : JSON.stringify(input.body)\n : undefined,\n headers: {\n ...(input.body ? { 'Content-Type': 'application/json' } : {}),\n ...input.headers,\n ...(address\n ? { 'X-Wallet-Address': address, 'X-Client-ID': provider }\n : {}),\n ...(sessionId ? { 'X-Session-ID': sessionId } : {}),\n },\n });\n};\n","import { Challenge, Receipt } from 'mppx';\nimport {\n err,\n ok,\n resultFromPromise,\n resultFromThrowable,\n} from '@agentcash/neverthrow';\n\nimport type { BaseMppError } from './types';\nconst errorType = 'mpp';\n\nexport const mppOk = <T>(value: T) => ok(value);\nexport const mppErr = (surface: string, error: BaseMppError) =>\n err(errorType, surface, error);\n\nconst mppResultFromPromise = <T>(\n surface: string,\n promise: Promise<T>,\n error: (e: unknown) => BaseMppError\n) => resultFromPromise(errorType, surface, promise, error);\n\nconst mppResultFromThrowable = <T>(\n surface: string,\n fn: () => T,\n error: (e: unknown) => BaseMppError\n) => resultFromThrowable(errorType, surface, fn, error);\n\nexport const safeGetMppChallenge = (surface: string, response: Response) => {\n return mppResultFromThrowable(\n surface,\n () => Challenge.fromResponse(response),\n error => ({\n cause: 'parse_mpp_challenge',\n message:\n error instanceof Error\n ? error.message\n : 'Failed to parse MPP challenge from response',\n })\n );\n};\n\nexport const safeCreateMppCredential = (\n surface: string,\n mppxClient: { createCredential: (response: Response) => Promise<string> },\n response: Response\n) => {\n return mppResultFromPromise(\n surface,\n mppxClient.createCredential(response),\n error => ({\n cause: 'create_mpp_credential',\n message:\n error instanceof Error\n ? error.message\n : 'Failed to create MPP credential',\n })\n );\n};\n\nexport const safeGetMppReceipt = (surface: string, response: Response) => {\n return mppResultFromThrowable(\n surface,\n () => Receipt.fromResponse(response),\n error => ({\n cause: 'parse_mpp_receipt',\n message:\n error instanceof Error\n ? error.message\n : 'Failed to parse MPP receipt from response',\n })\n );\n};\n","import { formatUnits } from 'viem';\n\nimport type { x402HTTPClient } from '@x402/core/client';\nimport type { Address } from 'viem';\nimport type { GlobalFlags } from '@/types';\n\nimport { resultFromPromise } from '@agentcash/neverthrow';\n\nimport { fetchErr, fetchOk, safeFetch } from '@/shared/neverthrow/fetch';\nimport {\n safeCreatePaymentPayload,\n safeGetPaymentRequired,\n safeGetPaymentSettlement,\n x402Err,\n x402Ok,\n} from '@/shared/neverthrow/x402';\nimport {\n safeGetMppChallenge,\n safeCreateMppCredential,\n safeGetMppReceipt,\n mppErr,\n mppOk,\n} from '@/shared/neverthrow/mpp';\n\nimport { log } from '@/shared/log';\nimport { detectPaymentProtocols } from '@/shared/protocol';\nimport { tokenStringToNumber } from '@/shared/token';\nimport { getBalance } from '@/shared/balance';\nimport { getTempoBalance } from '@/shared/tempo-balance';\n\n/**\n * Hook called before a payment is executed.\n * Throw to abort. Return to proceed.\n * Matches existing checkBalance/checkTempoBalance throw-to-abort behavior.\n */\nexport type BeforePaymentHook = (ctx: {\n protocol: 'x402' | 'mpp';\n amount: number;\n currency: string;\n network: string;\n}) => Promise<void>;\n\nexport interface PaymentClients {\n x402: x402HTTPClient;\n mpp: { createCredential: (response: Response) => Promise<string> };\n}\n\nexport interface PaymentInfo {\n protocol: 'x402' | 'mpp';\n price?: string;\n payment?: {\n success: boolean;\n transactionHash?: string;\n };\n}\n\nexport interface FetchWithPaymentResult {\n response: Response;\n paymentInfo: PaymentInfo | null;\n}\n\nexport interface FetchWithPaymentOptions {\n surface: string;\n clients: PaymentClients;\n paymentMethod: 'x402' | 'mpp' | 'auto';\n account: { address: Address };\n flags: GlobalFlags;\n beforePayment?: BeforePaymentHook;\n timeout?: number;\n}\n\n/**\n * Create a fetch function with automatic dual-protocol payment handling.\n *\n * 1. Makes initial request\n * 2. If 402 response, detects protocol(s)\n * 3. Calls beforePayment hook (for balance checks)\n * 4. Creates payment credential/payload\n * 5. Retries request with payment headers\n */\nexport function createFetchWithPayment(options: FetchWithPaymentOptions) {\n const { surface, clients, paymentMethod, beforePayment, timeout } = options;\n\n return async (request: Request) => {\n const clonedRequest = request.clone();\n const fallbackRequest = request.clone();\n\n const probeResult = await safeFetch(surface, request, timeout);\n\n if (probeResult.isErr()) {\n return fetchErr(surface, probeResult.error);\n }\n\n // Not a 402 response — return as-is\n if (probeResult.value.status !== 402) {\n return probeResult.andThen(response =>\n fetchOk<FetchWithPaymentResult>({ response, paymentInfo: null })\n );\n }\n\n const response = probeResult.value;\n\n // User explicitly chose a protocol — use that, no fallback\n if (paymentMethod !== 'auto') {\n if (paymentMethod === 'mpp') {\n return handleMppPayment(surface, response, clonedRequest, options);\n }\n return handleX402Payment(\n surface,\n response,\n clonedRequest,\n clients.x402,\n beforePayment,\n timeout\n );\n }\n\n // Auto: detect available protocols, pick by higher balance\n const available = detectPaymentProtocols(response);\n\n let preferred: 'x402' | 'mpp';\n\n if (available.length === 1) {\n preferred = available[0]!;\n } else {\n // Both protocols available — pick by balance\n preferred = await pickByBalance(surface, response, options);\n }\n\n const fallback =\n available.length > 1 ? (preferred === 'mpp' ? 'x402' : 'mpp') : null;\n\n const result =\n preferred === 'mpp'\n ? await handleMppPayment(surface, response, clonedRequest, options)\n : await handleX402Payment(\n surface,\n response,\n clonedRequest,\n clients.x402,\n beforePayment,\n timeout\n );\n\n if (result.isErr() && fallback) {\n // Preferred failed — try fallback with a fresh request clone\n return fallback === 'mpp'\n ? handleMppPayment(surface, response, fallbackRequest, options)\n : handleX402Payment(\n surface,\n response,\n fallbackRequest,\n clients.x402,\n beforePayment,\n timeout\n );\n }\n\n return result;\n };\n}\n\n/**\n * Pick the preferred protocol by comparing wallet balances.\n * Falls back to 'mpp' if both balances fail to fetch.\n */\nasync function pickByBalance(\n surface: string,\n response: Response,\n options: FetchWithPaymentOptions\n): Promise<'x402' | 'mpp'> {\n const { account, flags } = options;\n\n // Get x402 (USDC on Base) balance\n const x402BalanceResult = await resultFromPromise(\n 'balance',\n surface,\n getBalance({\n address: account.address,\n flags,\n surface,\n }).then(r => (r.isOk() ? r.value.balance : 0)),\n () => ({\n cause: 'x402_balance' as const,\n message: 'Failed to get x402 balance',\n })\n );\n\n if (x402BalanceResult.isErr()) {\n log.debug('Balance comparison failed, defaulting to mpp');\n return 'mpp';\n }\n\n const x402Balance = x402BalanceResult.value;\n\n // Get MPP (Tempo) balance — need token address from the challenge\n let mppBalance = 0;\n const challengeResult = safeGetMppChallenge(surface, response);\n if (challengeResult.isOk()) {\n const currency = challengeResult.value.request.currency as\n | string\n | undefined;\n const decimals =\n (challengeResult.value.request.decimals as number | undefined) ?? 6;\n if (currency) {\n const tempoResult = await resultFromPromise(\n 'tempo',\n surface,\n getTempoBalance({\n address: account.address,\n tokenAddress: currency as Address,\n }),\n () => ({\n cause: 'tempo_balance' as const,\n message: 'Tempo balance check failed',\n })\n );\n if (tempoResult.isOk()) {\n mppBalance = Number(formatUnits(tempoResult.value.balance, decimals));\n }\n }\n }\n\n log.info(`Protocol selection — x402: $${x402Balance}, mpp: $${mppBalance}`);\n return x402Balance >= mppBalance ? 'x402' : 'mpp';\n}\n\nasync function handleX402Payment(\n surface: string,\n response: Response,\n clonedRequest: Request,\n client: x402HTTPClient,\n beforePayment?: BeforePaymentHook,\n timeout?: number\n) {\n const paymentRequiredResult = await safeGetPaymentRequired(\n surface,\n client,\n response\n );\n\n if (paymentRequiredResult.isErr()) {\n return paymentRequiredResult;\n }\n\n const paymentRequired = paymentRequiredResult.value;\n\n // Call beforePayment hook (e.g. balance check) before signing\n if (beforePayment) {\n const accept = paymentRequired.accepts[0];\n if (accept) {\n const amount = tokenStringToNumber(accept.amount);\n const hookResult = await resultFromPromise(\n 'x402',\n surface,\n beforePayment({\n protocol: 'x402',\n amount,\n currency: 'USDC',\n network: accept.network,\n }),\n e => ({\n cause: 'payment_already_attempted' as const,\n message:\n e instanceof Error ? e.message : 'Before-payment hook failed',\n })\n );\n if (hookResult.isErr()) {\n return x402Err(surface, hookResult.error);\n }\n }\n }\n\n const paymentPayloadResult = await safeCreatePaymentPayload(\n surface,\n client,\n paymentRequired\n );\n\n if (paymentPayloadResult.isErr()) {\n return paymentPayloadResult;\n }\n\n const paymentPayload = paymentPayloadResult.value;\n\n // Encode payment header\n const paymentHeaders = client.encodePaymentSignatureHeader(paymentPayload);\n\n // Check if this is already a retry to prevent infinite loops\n if (\n clonedRequest.headers.has('PAYMENT-SIGNATURE') ||\n clonedRequest.headers.has('X-PAYMENT')\n ) {\n return x402Err(surface, {\n cause: 'payment_already_attempted',\n message: 'Payment already attempted',\n });\n }\n\n // Add payment headers to cloned request\n for (const [key, value] of Object.entries(paymentHeaders)) {\n clonedRequest.headers.set(key, value);\n }\n clonedRequest.headers.set(\n 'Access-Control-Expose-Headers',\n 'PAYMENT-RESPONSE,X-PAYMENT-RESPONSE'\n );\n\n // Retry the request with payment\n return await safeFetch(surface, clonedRequest, timeout).andThen(\n paidResponse => {\n const settlementResult = safeGetPaymentSettlement(\n surface,\n client,\n paidResponse\n );\n\n return x402Ok<FetchWithPaymentResult>({\n response: paidResponse,\n paymentInfo: {\n protocol: 'x402',\n price: tokenStringToNumber(\n paymentPayload.accepted.amount\n ).toLocaleString('en-US', {\n style: 'currency',\n currency: 'USD',\n }),\n ...(settlementResult.isOk()\n ? {\n payment: {\n success: settlementResult.value.success,\n transactionHash: settlementResult.value.transaction,\n },\n }\n : {}),\n },\n });\n }\n );\n}\n\nasync function handleMppPayment(\n surface: string,\n response: Response,\n clonedRequest: Request,\n options: FetchWithPaymentOptions\n) {\n const { clients, beforePayment, timeout } = options;\n const mppxClient = clients.mpp;\n\n // Prevent retry loops\n if (clonedRequest.headers.has('Authorization')) {\n return mppErr(surface, {\n cause: 'mpp_payment_already_attempted',\n message: 'MPP payment already attempted',\n });\n }\n\n // Parse the challenge from the WWW-Authenticate header\n const challengeResult = safeGetMppChallenge(surface, response);\n\n if (challengeResult.isErr()) {\n return challengeResult;\n }\n\n const challenge = challengeResult.value;\n\n // Extract payment info from challenge request\n const amount = challenge.request.amount as string | undefined;\n const decimals = (challenge.request.decimals as number | undefined) ?? 6;\n const currency = challenge.request.currency as string | undefined;\n\n // Call beforePayment hook (e.g. balance check)\n if (beforePayment && amount && currency) {\n const numericAmount = Number(formatUnits(BigInt(amount), decimals));\n const hookResult = await resultFromPromise(\n 'mpp',\n surface,\n beforePayment({\n protocol: 'mpp',\n amount: numericAmount,\n currency,\n network: `tempo:${challenge.method}`,\n }),\n e => ({\n cause: 'mpp_payment_already_attempted' as const,\n message: e instanceof Error ? e.message : 'Before-payment hook failed',\n })\n );\n if (hookResult.isErr()) {\n return mppErr(surface, hookResult.error);\n }\n }\n\n // Create credential (signs transaction on Tempo)\n const credentialResult = await safeCreateMppCredential(\n surface,\n mppxClient,\n response\n );\n\n if (credentialResult.isErr()) {\n return credentialResult;\n }\n\n const credential = credentialResult.value;\n\n // Set Authorization header on cloned request\n clonedRequest.headers.set('Authorization', credential);\n\n // Retry the fetch with the credential\n return await safeFetch(surface, clonedRequest, timeout).andThen(\n paidResponse => {\n // Parse the receipt for transaction hash\n const receiptResult = safeGetMppReceipt(surface, paidResponse);\n\n const priceDisplay = amount\n ? Number(formatUnits(BigInt(amount), decimals)).toLocaleString(\n 'en-US',\n {\n style: 'currency',\n currency: 'USD',\n }\n )\n : undefined;\n\n return mppOk<FetchWithPaymentResult>({\n response: paidResponse,\n paymentInfo: {\n protocol: 'mpp',\n ...(priceDisplay ? { price: priceDisplay } : {}),\n ...(receiptResult.isOk()\n ? {\n payment: {\n success: true,\n transactionHash: receiptResult.value.reference,\n },\n }\n : {}),\n },\n });\n }\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,OAAO;AAIP,IAAM,gBAAgB,EAAE,OAAO;AAAA,EACpC,KAAK,EAAE,IAAI,EAAE,SAAS,kBAAkB;AAAA,EACxC,QAAQ,EACL,KAAK,CAAC,OAAO,QAAQ,OAAO,UAAU,OAAO,CAAC,EAC9C,SAAS,EACT,SAAS,oDAAoD;AAAA,EAChE,MAAM,EACH,QAAQ,EACR,SAAS,EACT,SAAS,yCAAyC;AAAA,EACrD,SAAS,EACN,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,EAC7B,SAAS,EACT,SAAS,+BAA+B,EACxC,QAAQ,CAAC,CAAC;AAAA,EACb,SAAS,EACN,OAAO,EACP,IAAI,EACJ,SAAS,EACT,SAAS,EACT,SAAS,iCAAiC;AAC/C,CAAC;AASM,IAAM,eAAe,CAAC;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAAyB;AACvB,SAAO,IAAI,QAAQ,MAAM,KAAK;AAAA,IAC5B,QAAQ,MAAM,UAAU;AAAA,IACxB,MAAM,MAAM,OACR,OAAO,MAAM,SAAS,WACpB,MAAM,OACN,KAAK,UAAU,MAAM,IAAI,IAC3B;AAAA,IACJ,SAAS;AAAA,MACP,GAAI,MAAM,OAAO,EAAE,gBAAgB,mBAAmB,IAAI,CAAC;AAAA,MAC3D,GAAG,MAAM;AAAA,MACT,GAAI,UACA,EAAE,oBAAoB,SAAS,eAAe,SAAS,IACvD,CAAC;AAAA,MACL,GAAI,YAAY,EAAE,gBAAgB,UAAU,IAAI,CAAC;AAAA,IACnD;AAAA,EACF,CAAC;AACH;;;ACxDA,SAAS,WAAW,eAAe;AASnC,IAAM,YAAY;AAEX,IAAM,QAAQ,CAAI,UAAa,GAAG,KAAK;AACvC,IAAM,SAAS,CAAC,S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AM,eAAe,SACjB,OAAO,YAAY,OAAO,MAAM,GAAG,QAAQ,CAAC,EAAE;AAAA,QAC5C;AAAA,QACA;AAAA,UACE,OAAO;AAAA,UACP,UAAU;AAAA,QACZ;AAAA,MACF,IACA;AAEJ,aAAO,MAA8B;AAAA,QACnC,UAAU;AAAA,QACV,aAAa;AAAA,UACX,UAAU;AAAA,UACV,GAAI,eAAe,EAAE,OAAO,aAAa,IAAI,CAAC;AAAA,UAC9C,GAAI,cAAc,KAAK,IACnB;AAAA,YACE,SAAS;AAAA,cACP,SAAS;AAAA,cACT,iBAAiB,cAAc,MAAM;AAAA,YACvC;AAAA,UACF,IACA,CAAC;AAAA,QACP;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["response"]}
@@ -4,7 +4,7 @@ import { dirname, join } from "path";
4
4
  import { fileURLToPath } from "url";
5
5
  function getVersion() {
6
6
  if (true) {
7
- return "0.3.7";
7
+ return "0.4.1";
8
8
  }
9
9
  const __dirname2 = dirname(fileURLToPath(import.meta.url));
10
10
  const pkg = JSON.parse(
@@ -19,4 +19,4 @@ export {
19
19
  MCP_VERSION,
20
20
  DIST_TAG
21
21
  };
22
- //# sourceMappingURL=chunk-SBLBP4FH.js.map
22
+ //# sourceMappingURL=chunk-7LPATNAW.js.map
@@ -2,10 +2,10 @@ import {
2
2
  DEFAULT_NETWORK,
3
3
  getChainName,
4
4
  redeemInviteCode
5
- } from "./chunk-EVE4PTLY.js";
5
+ } from "./chunk-TRGCJSV2.js";
6
6
  import {
7
7
  getDepositLink
8
- } from "./chunk-PJFATGPH.js";
8
+ } from "./chunk-EO4BIJAO.js";
9
9
 
10
10
  // src/cli/lib/deposit.ts
11
11
  import chalk from "chalk";
@@ -111,4 +111,4 @@ export {
111
111
  wait,
112
112
  promptDeposit
113
113
  };
114
- //# sourceMappingURL=chunk-PCCYUD6X.js.map
114
+ //# sourceMappingURL=chunk-DCP6SZGV.js.map
@@ -616,6 +616,8 @@ var safeParse = (surface, schema, value) => {
616
616
 
617
617
  // src/shared/neverthrow/fetch/index.ts
618
618
  import contentType from "content-type";
619
+ var DEFAULT_FETCH_TIMEOUT = 1e4;
620
+ var DEFAULT_USER_FETCH_TIMEOUT = 3e4;
619
621
  var IMAGE_TYPES = /* @__PURE__ */ new Set([
620
622
  "image/png",
621
623
  "image/jpeg",
@@ -635,19 +637,28 @@ var fetchHttpErr = (surface, response) => fetchErr(surface, {
635
637
  message: response.statusText,
636
638
  response
637
639
  });
638
- var safeFetch = (surface, request) => {
640
+ var safeFetch = (surface, request, timeout) => {
641
+ const signal = timeout ? AbortSignal.timeout(timeout) : void 0;
639
642
  return resultFromPromise(
640
643
  errorType2,
641
644
  surface,
642
- fetch(request),
643
- (error) => ({
644
- cause: "network",
645
- message: error instanceof Error ? error.message : "Network error"
646
- })
645
+ fetch(request, ...signal ? [{ signal }] : []),
646
+ (error) => {
647
+ if (error instanceof DOMException && (error.name === "TimeoutError" || error.name === "AbortError")) {
648
+ return {
649
+ cause: "timeout",
650
+ message: timeout ? `Request timed out after ${timeout}ms. You can increase the timeout by passing a larger value in the 'timeout' parameter.` : "Request was aborted"
651
+ };
652
+ }
653
+ return {
654
+ cause: "network",
655
+ message: error instanceof Error ? error.message : "Network error"
656
+ };
657
+ }
647
658
  );
648
659
  };
649
- var safeFetchJson = (surface, request, schema) => {
650
- return safeFetch(surface, request).andThen((response) => {
660
+ var safeFetchJson = (surface, request, schema, timeout) => {
661
+ return safeFetch(surface, request, timeout).andThen((response) => {
651
662
  if (!response.ok) {
652
663
  return fetchHttpErr(surface, response);
653
664
  }
@@ -768,6 +779,8 @@ export {
768
779
  ok2 as ok,
769
780
  err2 as err,
770
781
  safeParse,
782
+ DEFAULT_FETCH_TIMEOUT,
783
+ DEFAULT_USER_FETCH_TIMEOUT,
771
784
  fetchErr,
772
785
  fetchOk,
773
786
  fetchHttpErr,
@@ -787,4 +800,4 @@ export {
787
800
  openDepositLink,
788
801
  getBalance
789
802
  };
790
- //# sourceMappingURL=chunk-PJFATGPH.js.map
803
+ //# sourceMappingURL=chunk-EO4BIJAO.js.map