agentcash 0.15.0 → 0.15.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.
- package/dist/cjs/run-server.cjs +4 -3
- package/dist/esm/{chunk-MZPHS3IS.js → chunk-66AVEFTO.js} +2 -2
- package/dist/esm/{chunk-5MITNOWT.js → chunk-7CV5CENJ.js} +2 -2
- package/dist/esm/{chunk-VGKAPM5S.js → chunk-BM5W5OV2.js} +2 -2
- package/dist/esm/{chunk-HNDMHX4B.js → chunk-EDI77S36.js} +3 -2
- package/dist/esm/chunk-EDI77S36.js.map +1 -0
- package/dist/esm/{chunk-ULB5PPKW.js → chunk-PQXKQJIU.js} +2 -2
- package/dist/esm/{fetch-QAVIWIRX.js → fetch-AFKCCCHZ.js} +2 -2
- package/dist/esm/index.js +10 -10
- package/dist/esm/{install-NJJZYBZU.js → install-LAWJMMPO.js} +3 -3
- package/dist/esm/{onboard-TYB4QZE4.js → onboard-W7CUGJJM.js} +3 -3
- package/dist/esm/{register-T6M2US4B.js → register-5KLJDRG4.js} +2 -2
- package/dist/esm/{report-error-BR7ETMF7.js → report-error-HN4YXEOC.js} +3 -3
- package/dist/esm/{search-KIPT62MB.js → search-MEGI3KJW.js} +3 -3
- package/dist/esm/{server-WJH536CN.js → server-7QJB55AW.js} +2 -2
- package/dist/esm/{server-MO3YMDHB.js → server-M7SLAGFR.js} +6 -6
- package/dist/esm/{try-2P5ZRXRT.js → try-4RHB5KHZ.js} +2 -2
- package/dist/esm/try-4RHB5KHZ.js.map +1 -0
- package/package.json +1 -1
- package/dist/esm/chunk-HNDMHX4B.js.map +0 -1
- package/dist/esm/try-2P5ZRXRT.js.map +0 -1
- /package/dist/esm/{chunk-MZPHS3IS.js.map → chunk-66AVEFTO.js.map} +0 -0
- /package/dist/esm/{chunk-5MITNOWT.js.map → chunk-7CV5CENJ.js.map} +0 -0
- /package/dist/esm/{chunk-VGKAPM5S.js.map → chunk-BM5W5OV2.js.map} +0 -0
- /package/dist/esm/{chunk-ULB5PPKW.js.map → chunk-PQXKQJIU.js.map} +0 -0
- /package/dist/esm/{fetch-QAVIWIRX.js.map → fetch-AFKCCCHZ.js.map} +0 -0
- /package/dist/esm/{install-NJJZYBZU.js.map → install-LAWJMMPO.js.map} +0 -0
- /package/dist/esm/{onboard-TYB4QZE4.js.map → onboard-W7CUGJJM.js.map} +0 -0
- /package/dist/esm/{register-T6M2US4B.js.map → register-5KLJDRG4.js.map} +0 -0
- /package/dist/esm/{report-error-BR7ETMF7.js.map → report-error-HN4YXEOC.js.map} +0 -0
- /package/dist/esm/{search-KIPT62MB.js.map → search-MEGI3KJW.js.map} +0 -0
- /package/dist/esm/{server-WJH536CN.js.map → server-7QJB55AW.js.map} +0 -0
- /package/dist/esm/{server-MO3YMDHB.js.map → server-M7SLAGFR.js.map} +0 -0
package/dist/cjs/run-server.cjs
CHANGED
|
@@ -140028,9 +140028,10 @@ var x402ResultFromPromise = (surface, promise4, error100) => resultFromPromise(e
|
|
|
140028
140028
|
var x402ResultFromThrowable = (surface, fn, error100) => resultFromThrowable(errorType3, surface, fn, error100);
|
|
140029
140029
|
var x402ProbeClient = new x402HTTPClient(new x402Client());
|
|
140030
140030
|
var safeGetPaymentRequired = (surface, response) => {
|
|
140031
|
+
const probe = response.clone();
|
|
140031
140032
|
return x402ResultFromPromise(
|
|
140032
140033
|
surface,
|
|
140033
|
-
|
|
140034
|
+
probe.json().then(
|
|
140034
140035
|
(json4) => x402ProbeClient.getPaymentRequiredResponse(
|
|
140035
140036
|
(name) => response.headers.get(name),
|
|
140036
140037
|
json4
|
|
@@ -185794,7 +185795,7 @@ var import_path2 = require("path");
|
|
|
185794
185795
|
var import_url2 = require("url");
|
|
185795
185796
|
function getVersion4() {
|
|
185796
185797
|
if (true) {
|
|
185797
|
-
return "0.15.
|
|
185798
|
+
return "0.15.1";
|
|
185798
185799
|
}
|
|
185799
185800
|
const __dirname2 = (0, import_path2.dirname)((0, import_url2.fileURLToPath)(importMetaUrl));
|
|
185800
185801
|
const pkg2 = JSON.parse(
|
|
@@ -193509,7 +193510,7 @@ var import_path3 = require("path");
|
|
|
193509
193510
|
var import_url6 = require("url");
|
|
193510
193511
|
function getVersion5() {
|
|
193511
193512
|
if (true) {
|
|
193512
|
-
return "0.15.
|
|
193513
|
+
return "0.15.1";
|
|
193513
193514
|
}
|
|
193514
193515
|
const __dirname2 = (0, import_path3.dirname)((0, import_url6.fileURLToPath)(importMetaUrl));
|
|
193515
193516
|
const pkg2 = JSON.parse(
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
} from "./chunk-W37JKCLN.js";
|
|
4
4
|
import {
|
|
5
5
|
executeFetch
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-EDI77S36.js";
|
|
7
7
|
import {
|
|
8
8
|
safeParseResponse
|
|
9
9
|
} from "./chunk-RAS5DZPQ.js";
|
|
@@ -89,4 +89,4 @@ export {
|
|
|
89
89
|
searchSchema,
|
|
90
90
|
search
|
|
91
91
|
};
|
|
92
|
-
//# sourceMappingURL=chunk-
|
|
92
|
+
//# sourceMappingURL=chunk-66AVEFTO.js.map
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
} from "./chunk-27DZCYDB.js";
|
|
7
7
|
import {
|
|
8
8
|
INSTALL_PACKAGE_SPECIFIER
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-PQXKQJIU.js";
|
|
10
10
|
import {
|
|
11
11
|
log,
|
|
12
12
|
safeReadFile,
|
|
@@ -628,4 +628,4 @@ export {
|
|
|
628
628
|
tryAddServer,
|
|
629
629
|
addServer
|
|
630
630
|
};
|
|
631
|
-
//# sourceMappingURL=chunk-
|
|
631
|
+
//# sourceMappingURL=chunk-7CV5CENJ.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
MCP_VERSION
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-PQXKQJIU.js";
|
|
4
4
|
import {
|
|
5
5
|
safeFetchJson
|
|
6
6
|
} from "./chunk-RAS5DZPQ.js";
|
|
@@ -51,4 +51,4 @@ async function submitErrorReport(surface, input, address, dev) {
|
|
|
51
51
|
export {
|
|
52
52
|
submitErrorReport
|
|
53
53
|
};
|
|
54
|
-
//# sourceMappingURL=chunk-
|
|
54
|
+
//# sourceMappingURL=chunk-BM5W5OV2.js.map
|
|
@@ -225,9 +225,10 @@ var x402ResultFromPromise = (surface, promise, error) => resultFromPromise(error
|
|
|
225
225
|
var x402ResultFromThrowable = (surface, fn, error) => resultFromThrowable(errorType, surface, fn, error);
|
|
226
226
|
var x402ProbeClient = new x402HTTPClient(new x402Client());
|
|
227
227
|
var safeGetPaymentRequired = (surface, response) => {
|
|
228
|
+
const probe = response.clone();
|
|
228
229
|
return x402ResultFromPromise(
|
|
229
230
|
surface,
|
|
230
|
-
|
|
231
|
+
probe.json().then(
|
|
231
232
|
(json) => x402ProbeClient.getPaymentRequiredResponse(
|
|
232
233
|
(name) => response.headers.get(name),
|
|
233
234
|
json
|
|
@@ -999,4 +1000,4 @@ async function executeFetch(input, options) {
|
|
|
999
1000
|
export {
|
|
1000
1001
|
executeFetch
|
|
1001
1002
|
};
|
|
1002
|
-
//# sourceMappingURL=chunk-
|
|
1003
|
+
//# sourceMappingURL=chunk-EDI77S36.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/operations/fetch/auth.ts","../../src/shared/protocols/x402/index.ts","../../src/shared/protocols/x402/patched-exact-svm-scheme.ts","../../src/shared/protocols/x402/policies.ts","../../src/shared/protocols/detect.ts","../../src/shared/protocols/mpp/handle-payment.ts","../../src/shared/protocols/before-payment.ts","../../src/shared/protocols/mpp/session/handle-session-payment.ts","../../src/shared/protocols/mpp/session/run-request-session.ts","../../src/shared/protocols/mpp/session/run-streaming-session.ts","../../src/shared/protocols/mpp/session/utils.ts","../../src/shared/protocols/pick.ts","../../src/shared/protocols/x402/choose-payment-requirement.ts","../../src/shared/protocols/x402/handle-payment.ts","../../src/operations/fetch/payment.ts","../../src/operations/fetch/index.ts"],"sourcesContent":["import { encodeSIWxHeader } from '@x402/extensions/sign-in-with-x';\n\nimport { fetchOk, safeFetch } from '@/shared/neverthrow/fetch';\nimport {\n getSiwxExtension,\n safeCreateSIWxPayload,\n safeGetPaymentRequired,\n} from '@/shared/protocols/x402';\n\nimport type { ExecuteFetchOptions } from './types';\n\nexport async function attemptSiwxAuth(\n response: Response,\n authRetryRequest: Request,\n paymentRetryRequest: Request,\n options: ExecuteFetchOptions\n) {\n const { surface, wallets } = options;\n const { timeout, paymentNetwork } = options.params;\n\n if (!response.headers.has('payment-required')) {\n return fetchOk({\n response,\n paymentRetryRequest,\n });\n }\n\n const paymentRequiredResult = await safeGetPaymentRequired(surface, response);\n\n if (paymentRequiredResult.isErr()) {\n return paymentRequiredResult;\n }\n\n const siwxExtension = getSiwxExtension(\n paymentRequiredResult.value.extensions,\n paymentNetwork\n );\n\n if (!siwxExtension) {\n return fetchOk({\n response,\n paymentRetryRequest,\n });\n }\n\n const payloadResult = await safeCreateSIWxPayload(\n surface,\n siwxExtension,\n wallets\n );\n\n if (payloadResult.isErr()) {\n return payloadResult;\n }\n\n const siwxHeader = encodeSIWxHeader(payloadResult.value);\n authRetryRequest.headers.set('SIGN-IN-WITH-X', siwxHeader);\n paymentRetryRequest.headers.set('SIGN-IN-WITH-X', siwxHeader);\n\n return (await safeFetch(surface, authRetryRequest, timeout)).andThen(\n authResponse =>\n fetchOk({\n response: authResponse,\n paymentRetryRequest,\n })\n );\n}\n","import {\n err,\n ok,\n resultFromPromise,\n resultFromThrowable,\n} from '@agentcash/neverthrow';\n\nimport type { SelectPaymentRequirements } from '@x402/core/client';\nimport { x402Client, x402HTTPClient } from '@x402/core/client';\n\nimport { toClientEvmSigner } from '@x402/evm';\nimport { toClientSvmSigner } from '@x402/svm';\n\nimport { ExactEvmScheme } from '@x402/evm/exact/client';\nimport { UptoEvmScheme } from '@x402/evm/upto/client';\nimport { PatchedExactSvmScheme } from './patched-exact-svm-scheme';\nimport { capUptoDeadline } from './policies';\n\nimport { createSIWxPayload } from '@x402/extensions/sign-in-with-x';\n\nimport type { BaseX402Error } from './types';\nimport type { PaymentRequired } from '@x402/core/types';\nimport type {\n CompleteSIWxInfo,\n SIWxExtensionInfo,\n SolanaSigner,\n SupportedChain,\n} from '@x402/extensions/sign-in-with-x';\nimport type { Wallets } from '@/wallet';\nimport { Network, networkToCaip2 } from '@agentcash/networks';\nimport type { Network as PaymentNetwork } from '@agentcash/networks';\nimport { createPublicClient, http } from 'viem';\nimport { base } from 'viem/chains';\n\nconst errorType = 'x402';\n\nexport const x402Ok = <T>(value: T) => ok(value);\nexport const x402Err = (cause: string, error: BaseX402Error) =>\n err(errorType, cause, error);\n\nconst x402ResultFromPromise = <T>(\n surface: string,\n promise: Promise<T>,\n error: (e: unknown) => BaseX402Error\n) => resultFromPromise(errorType, surface, promise, error);\n\nconst x402ResultFromThrowable = <T>(\n surface: string,\n fn: () => T,\n error: (e: unknown) => BaseX402Error\n) => resultFromThrowable(errorType, surface, fn, error);\n\nexport const x402ProbeClient = new x402HTTPClient(new x402Client());\n\nexport const safeGetPaymentRequired = (surface: string, response: Response) => {\n // Read the body from a clone so the caller's Response stays unconsumed.\n // Dual-protocol 402s (x402 header + MPP `WWW-Authenticate`) reuse the same\n // Response downstream, and mppx >=0.6 clones it internally when creating a\n // credential — consuming it here would make that clone throw.\n const probe = response.clone();\n return x402ResultFromPromise(\n surface,\n probe.json().then(\n json =>\n x402ProbeClient.getPaymentRequiredResponse(\n name => response.headers.get(name),\n json\n ),\n () =>\n x402ProbeClient.getPaymentRequiredResponse(name =>\n response.headers.get(name)\n )\n ),\n error => ({\n cause: 'parse_payment_required',\n message:\n error instanceof Error\n ? error.message\n : 'Failed to parse payment required',\n })\n );\n};\n\nexport const getSiwxExtension = (\n extensions: PaymentRequired['extensions'],\n paymentNetwork?: PaymentNetwork\n): CompleteSIWxInfo | undefined => {\n const siwx = extensions?.['sign-in-with-x'] as\n | { info?: SIWxExtensionInfo; supportedChains?: SupportedChain[] }\n | undefined;\n\n if (!siwx?.info) {\n return undefined;\n }\n\n const chain = siwx.supportedChains?.find(c =>\n paymentNetwork\n ? c.chainId === networkToCaip2(paymentNetwork)\n : c.chainId.startsWith('eip155:')\n );\n\n return {\n ...siwx.info,\n chainId: chain?.chainId ?? 'eip155:8453',\n type: chain?.type ?? 'eip191',\n signatureScheme: chain?.signatureScheme,\n };\n};\n\nexport const safeCreatePaymentPayload = (\n surface: string,\n wallets: Wallets,\n paymentRequired: PaymentRequired,\n paymentRequirementsSelector?: SelectPaymentRequirements\n) => {\n const client = new x402HTTPClient(\n x402Client.fromConfig({\n schemes: [\n {\n network: networkToCaip2(Network.BASE),\n client: new ExactEvmScheme(\n toClientEvmSigner(\n wallets.evm,\n createPublicClient({\n chain: base,\n transport: http(),\n })\n )\n ),\n },\n {\n network: networkToCaip2(Network.BASE),\n client: new UptoEvmScheme(\n toClientEvmSigner(\n wallets.evm,\n createPublicClient({\n chain: base,\n transport: http(),\n })\n )\n ),\n },\n {\n network: networkToCaip2(Network.SOLANA),\n client: new PatchedExactSvmScheme(toClientSvmSigner(wallets.svm)),\n },\n ],\n policies: [capUptoDeadline],\n paymentRequirementsSelector,\n })\n );\n return x402ResultFromPromise(\n surface,\n client.createPaymentPayload(paymentRequired),\n error => ({\n cause: 'create_payment_payload',\n message:\n error instanceof Error\n ? error.message\n : 'Failed to create payment payload',\n })\n );\n};\n\nexport const safeGetPaymentSettlement = (\n surface: string,\n response: Response\n) => {\n return x402ResultFromThrowable(\n surface,\n () =>\n x402ProbeClient.getPaymentSettleResponse(name =>\n response.headers.get(name)\n ),\n error => ({\n cause: 'get_payment_settlement',\n message:\n error instanceof Error\n ? error.message\n : 'Failed to get payment settlement',\n })\n );\n};\n\nexport const safeCreateSIWxPayload = (\n surface: string,\n serverInfo: CompleteSIWxInfo,\n wallets: Wallets\n) => {\n return x402ResultFromPromise(\n surface,\n createSIWxPayload(\n serverInfo,\n serverInfo.chainId.startsWith('eip155:')\n ? wallets.evm\n : (wallets.svm as unknown as SolanaSigner)\n ),\n error => ({\n cause: 'create_siwx_payload',\n message:\n error instanceof Error\n ? error.message\n : 'Failed to create SIWX payload',\n })\n );\n};\n","import {\n getSetComputeUnitLimitInstruction,\n setTransactionMessageComputeUnitPrice,\n} from '@solana-program/compute-budget';\nimport { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token';\nimport {\n fetchMint,\n findAssociatedTokenPda,\n getTransferCheckedInstruction,\n TOKEN_2022_PROGRAM_ADDRESS,\n} from '@solana-program/token-2022';\nimport {\n appendTransactionMessageInstructions,\n createTransactionMessage,\n getBase64EncodedWireTransaction,\n partiallySignTransactionMessageWithSigners,\n pipe,\n prependTransactionMessageInstruction,\n setTransactionMessageFeePayer,\n setTransactionMessageLifetimeUsingBlockhash,\n type Address,\n} from '@solana/kit';\n\nimport type {\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkClient,\n} from '@x402/core/types';\nimport {\n DEFAULT_COMPUTE_UNIT_LIMIT,\n DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS,\n createRpcClient,\n type ClientSvmConfig,\n type ClientSvmSigner,\n type ExactSvmPayloadV2,\n} from '@x402/svm';\n\ntype BlockhashLifetime = Parameters<\n typeof setTransactionMessageLifetimeUsingBlockhash\n>[0];\n\ninterface PatchedPaymentExtra {\n feePayer?: Address;\n recentBlockhash?:\n | string\n | Partial<{\n blockhash: string;\n lastValidBlockHeight: bigint | number | string;\n }>;\n lastValidBlockHeight?: bigint | number | string;\n}\n\nfunction parseLastValidBlockHeight(\n value: bigint | number | string | undefined\n): bigint | undefined {\n if (typeof value === 'bigint') {\n return value;\n }\n\n if (typeof value === 'number' && Number.isFinite(value)) {\n return BigInt(value);\n }\n\n if (typeof value === 'string' && value.length > 0) {\n return BigInt(value);\n }\n\n return undefined;\n}\n\nfunction asBlockhash(blockhash: string): BlockhashLifetime['blockhash'] {\n return blockhash as BlockhashLifetime['blockhash'];\n}\n\n/**\n * Local compatibility patch for Coinbase ExactSvmScheme.\n *\n * Changes from upstream:\n * - omits the trailing memo instruction\n * - prefers paymentRequirements.extra.recentBlockhash when provided\n */\nexport class PatchedExactSvmScheme implements SchemeNetworkClient {\n readonly scheme = 'exact';\n\n constructor(\n private readonly signer: ClientSvmSigner,\n private readonly config?: ClientSvmConfig\n ) {}\n\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements\n ): Promise<Pick<PaymentPayload, 'x402Version' | 'payload'>> {\n const rpc = createRpcClient(\n paymentRequirements.network,\n this.config?.rpcUrl\n );\n\n const tokenMint = await fetchMint(\n rpc,\n paymentRequirements.asset as Address\n );\n const tokenProgramAddress = tokenMint.programAddress;\n\n if (\n tokenProgramAddress.toString() !== TOKEN_PROGRAM_ADDRESS.toString() &&\n tokenProgramAddress.toString() !== TOKEN_2022_PROGRAM_ADDRESS.toString()\n ) {\n throw new Error('Asset was not created by a known token program');\n }\n\n const [sourceATA] = await findAssociatedTokenPda({\n mint: paymentRequirements.asset as Address,\n owner: this.signer.address,\n tokenProgram: tokenProgramAddress,\n });\n\n const [destinationATA] = await findAssociatedTokenPda({\n mint: paymentRequirements.asset as Address,\n owner: paymentRequirements.payTo as Address,\n tokenProgram: tokenProgramAddress,\n });\n\n const transferIx = getTransferCheckedInstruction(\n {\n source: sourceATA,\n mint: paymentRequirements.asset as Address,\n destination: destinationATA,\n authority: this.signer,\n amount: BigInt(paymentRequirements.amount),\n decimals: tokenMint.data.decimals,\n },\n { programAddress: tokenProgramAddress }\n );\n\n const extra = paymentRequirements.extra as PatchedPaymentExtra;\n const feePayer = extra.feePayer;\n\n if (!feePayer) {\n throw new Error(\n 'feePayer is required in paymentRequirements.extra for SVM transactions'\n );\n }\n\n const latestBlockhash = await this.resolveBlockhashLifetime(rpc, extra);\n\n const tx = pipe(\n createTransactionMessage({ version: 0 }),\n tx =>\n setTransactionMessageComputeUnitPrice(\n DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS,\n tx\n ),\n tx => setTransactionMessageFeePayer(feePayer, tx),\n tx =>\n prependTransactionMessageInstruction(\n getSetComputeUnitLimitInstruction({\n units: DEFAULT_COMPUTE_UNIT_LIMIT,\n }),\n tx\n ),\n tx => appendTransactionMessageInstructions([transferIx], tx),\n tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx)\n );\n\n const signedTransaction =\n await partiallySignTransactionMessageWithSigners(tx);\n const base64EncodedWireTransaction =\n getBase64EncodedWireTransaction(signedTransaction);\n\n const payload: ExactSvmPayloadV2 = {\n transaction: base64EncodedWireTransaction,\n };\n\n return {\n x402Version,\n payload,\n };\n }\n\n private async resolveBlockhashLifetime(\n rpc: ReturnType<typeof createRpcClient>,\n extra: PatchedPaymentExtra\n ): Promise<BlockhashLifetime> {\n const providedLastValidBlockHeight = parseLastValidBlockHeight(\n extra.lastValidBlockHeight\n );\n\n if (typeof extra.recentBlockhash === 'string') {\n if (providedLastValidBlockHeight !== undefined) {\n return {\n blockhash: asBlockhash(extra.recentBlockhash),\n lastValidBlockHeight: providedLastValidBlockHeight,\n };\n }\n\n const { value } = await rpc.getLatestBlockhash().send();\n return {\n blockhash: asBlockhash(extra.recentBlockhash),\n lastValidBlockHeight: value.lastValidBlockHeight,\n };\n }\n\n if (\n extra.recentBlockhash &&\n typeof extra.recentBlockhash === 'object' &&\n typeof extra.recentBlockhash.blockhash === 'string'\n ) {\n const lastValidBlockHeight =\n parseLastValidBlockHeight(extra.recentBlockhash.lastValidBlockHeight) ??\n providedLastValidBlockHeight;\n\n if (lastValidBlockHeight !== undefined) {\n return {\n blockhash: asBlockhash(extra.recentBlockhash.blockhash),\n lastValidBlockHeight,\n };\n }\n\n const { value } = await rpc.getLatestBlockhash().send();\n return {\n blockhash: asBlockhash(extra.recentBlockhash.blockhash),\n lastValidBlockHeight: value.lastValidBlockHeight,\n };\n }\n\n return (await rpc.getLatestBlockhash().send()).value;\n }\n}\n","import type { PaymentPolicy } from '@x402/core/client';\n\n/**\n * Maximum deadline (in seconds) we accept for `upto` payment requirements.\n *\n * The `upto` Permit2 signature is bound by `paymentRequirements.maxTimeoutSeconds`,\n * which the SDK passes straight through from the merchant's 402 response with no\n * upper bound. Within that window, the (merchant + facilitator) pair can settle\n * for any amount in `[0, cap]` — and the only on-chain check is the deadline.\n *\n * A long deadline therefore extends the window of facilitator-discretion settlement\n * at the signed cap. 7 days lets a long-running agent keep working without\n * re-signing, but bounds the trust window if a merchant declares an unreasonably\n * large `maxTimeoutSeconds` (accidentally or otherwise).\n *\n * `exact` requirements are unaffected: their amount is fixed in the signature, so\n * a long validity window is just an annoyance, not a discretion surface.\n */\nexport const MAX_UPTO_DEADLINE_SECONDS = 7 * 24 * 60 * 60; // 7 days\n\n/**\n * Caps `maxTimeoutSeconds` on `upto` requirements at {@link MAX_UPTO_DEADLINE_SECONDS}.\n * Leaves `exact` and any other scheme untouched. Pass to `x402Client.fromConfig({ policies })`.\n */\nexport const capUptoDeadline: PaymentPolicy = (_x402Version, requirements) =>\n requirements.map(r =>\n r.scheme === 'upto' && r.maxTimeoutSeconds > MAX_UPTO_DEADLINE_SECONDS\n ? { ...r, maxTimeoutSeconds: MAX_UPTO_DEADLINE_SECONDS }\n : r\n );\n","import { PaymentProtocol } from './types';\n\nexport function detectPaymentProtocols(response: Response): PaymentProtocol[] {\n const protocols: PaymentProtocol[] = [];\n\n const wwwAuth = response.headers.get('WWW-Authenticate');\n if (wwwAuth?.startsWith('Payment')) {\n protocols.push(PaymentProtocol.MPP);\n }\n\n const paymentRequired = response.headers.get('payment-required');\n if (paymentRequired) {\n protocols.push(PaymentProtocol.X402);\n }\n // If we couldn't detect either explicitly, default to x402\n if (protocols.length === 0) {\n protocols.push(PaymentProtocol.X402);\n }\n return protocols;\n}\n","import type { Address } from 'viem';\nimport { formatUnits } from 'viem';\n\nimport { safeFetch, safeReadResponseText } from '@/shared/neverthrow/fetch';\nimport {\n assertTempoUsdc,\n safeGetMppChallenge,\n safeCreateMppCredential,\n safeGetMppReceipt,\n mppErr,\n mppOk,\n} from '@/shared/protocols/mpp';\n\nimport { PaymentProtocol } from '../types';\nimport { Network } from '@agentcash/networks';\nimport { formatUsd } from '@/shared/utils';\n\nimport type { ExecuteFetchResult } from '@/operations/fetch/types';\nimport type { HandlePaymentParams } from '@/shared/protocols/types';\nimport { beforePayment } from '../before-payment';\nimport { handleMppSessionPayment } from './session/handle-session-payment';\n\nexport async function handleMppPayment(params: HandlePaymentParams) {\n const { response, request, options } = params;\n const { surface, wallets } = options;\n const { timeout } = options.params;\n\n // Prevent retry loops\n if (request.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 if (challenge.intent === 'session') {\n return handleMppSessionPayment(challenge, params);\n }\n\n const amount = Number(formatUnits(BigInt(challenge.request.amount), 6));\n const tokenAddress = challenge.request.currency as Address;\n\n const tokenCheck = assertTempoUsdc(surface, tokenAddress);\n if (tokenCheck.isErr()) {\n return tokenCheck;\n }\n\n const beforePaymentResult = await beforePayment({\n options,\n balanceInput: {\n address: wallets.evm.address,\n network: Network.TEMPO,\n tokenAddress,\n },\n amount,\n protocol: PaymentProtocol.MPP,\n });\n\n if (beforePaymentResult.isErr()) {\n return beforePaymentResult;\n }\n\n const credentialResult = await safeCreateMppCredential(\n surface,\n wallets,\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 request.headers.set('Authorization', credential);\n\n // Retry the fetch with the credential\n const paidFetchResult = await safeFetch(surface, request, timeout);\n if (paidFetchResult.isErr()) {\n return paidFetchResult;\n }\n\n const paidResponse = paidFetchResult.value;\n\n // If the server still returns 402, the payment was rejected\n if (paidResponse.status === 402) {\n const body = await safeReadResponseText(surface, paidResponse).unwrapOr('');\n const detail = body ? `: ${body}` : '';\n return mppErr(surface, {\n cause: 'mpp_payment_rejected',\n message: `MPP payment was rejected by the server (402)${detail}`,\n });\n }\n\n // Parse the receipt for transaction hash\n const receiptResult = safeGetMppReceipt(surface, paidResponse);\n\n return mppOk<ExecuteFetchResult>({\n response: paidResponse,\n paymentInfo: {\n protocol: PaymentProtocol.MPP,\n network: Network.TEMPO,\n price: formatUsd(amount),\n payment: receiptResult.isOk()\n ? {\n success: true,\n transactionHash: receiptResult.value.reference,\n }\n : null,\n },\n });\n}\n","import { err, ok } from '@agentcash/neverthrow';\n\nimport { getBalance } from '../balance';\nimport { getDepositLink } from '../utils';\nimport { getSettings } from '../settings';\n\nimport { DEFAULT_MAX_AMOUNT } from '@/operations/fetch/types';\n\nimport type { GetBalanceInput } from '@agentcash/balance';\nimport type { ExecuteFetchOptions } from '@/operations/fetch/types';\nimport type { PaymentProtocol } from './types';\n\ninterface BeforePaymentProps {\n options: ExecuteFetchOptions;\n balanceInput: GetBalanceInput;\n protocol: PaymentProtocol;\n amount: number;\n}\n\nexport const beforePayment = async (props: BeforePaymentProps) => {\n const { options, balanceInput, amount } = props;\n const maxAmount =\n options.params.maxAmount ?? getSettings().maxAmount ?? DEFAULT_MAX_AMOUNT;\n if (amount > maxAmount) {\n return err('before_payment', options.surface, {\n cause: 'amount_exceeds_max_amount' as const,\n message: `Endpoint requested $${amount} which exceeds the maximum allowed amount of $${maxAmount}. Pass a higher maxAmount on this call, or use update_settings to raise the default permanently.`,\n });\n }\n\n const balanceResult = await getBalance(\n options.surface,\n balanceInput,\n options.flags\n );\n\n if (balanceResult.isErr()) {\n return balanceResult;\n }\n\n const balance = balanceResult.value.balance;\n\n if (balance < amount) {\n return err('before_payment', options.surface, {\n cause: 'insufficient_balance' as const,\n message: insufficientBalanceErrorMessage(props, balance),\n });\n }\n\n return ok(true);\n};\n\nconst insufficientBalanceErrorMessage = (\n props: BeforePaymentProps,\n balance: number\n) => {\n const { options, balanceInput, amount } = props;\n return [\n `You are attempting to use an endpoint via ${props.protocol} that costs ${amount} USDC on ${balanceInput.network}.`,\n `Your current balance is ${balance} USDC.`,\n `You can bridge between accounts or deposit at ${getDepositLink(balanceInput.address, options.flags, balanceInput.network)} to top up your balance.`,\n `Before bridging, you can check the users account with npx agentcash@latest accounts or if you are within the MCP, you can use the list_accounts tool.`,\n ].join('\\n');\n};\n","import type { Address } from 'viem';\nimport { formatUnits } from 'viem';\n\nimport { tempo as tempoClient } from 'mppx/client';\n\nimport { Network } from '@agentcash/networks';\n\nimport type { ExecuteFetchResult } from '@/operations/fetch/types';\nimport { formatUsd, tokenStringToNumber } from '@/shared/utils';\n\nimport { beforePayment } from '../../before-payment';\nimport type { HandlePaymentParams } from '../../types';\nimport { PaymentProtocol } from '../../types';\nimport {\n assertTempoUsdc,\n createTempoClient,\n mppOk,\n mppResultFromPromise,\n sessionRequestFailedErr,\n} from '../index';\nimport { runRequestSession } from './run-request-session';\nimport { runStreamingSession } from './run-streaming-session';\nimport type { SessionChallenge } from './types';\nimport {\n USDC_DECIMALS,\n bufferRequestForReplay,\n formatDepositCap,\n resolveDepositUsd,\n} from './utils';\n\nexport async function handleMppSessionPayment(\n challenge: SessionChallenge,\n { request, options }: HandlePaymentParams\n) {\n const { surface, wallets } = options;\n\n const tickCostAtomic = BigInt(challenge.request.amount);\n const tickCostUsd = Number(formatUnits(tickCostAtomic, USDC_DECIMALS));\n const tokenAddress = challenge.request.currency as Address;\n\n const tokenCheck = assertTempoUsdc(surface, tokenAddress);\n if (tokenCheck.isErr()) return tokenCheck;\n\n const depositUsd = resolveDepositUsd(\n challenge.request.suggestedDeposit,\n tickCostUsd,\n options\n );\n\n const beforePaymentResult = await beforePayment({\n options,\n balanceInput: {\n address: wallets.evm.address,\n network: Network.TEMPO,\n tokenAddress,\n },\n amount: depositUsd,\n protocol: PaymentProtocol.MPP,\n });\n if (beforePaymentResult.isErr()) return beforePaymentResult;\n\n const replayInitResult = await mppResultFromPromise(\n surface,\n bufferRequestForReplay(request),\n e =>\n sessionRequestFailedErr(\n e,\n 'Failed to buffer request body for session replay'\n )\n );\n if (replayInitResult.isErr()) return replayInitResult;\n\n const sm = tempoClient.session({\n account: wallets.evm,\n client: createTempoClient(),\n maxDeposit: formatDepositCap(depositUsd),\n decimals: USDC_DECIMALS,\n });\n\n const isStreaming =\n challenge.meta?.streaming === 'true' || options.params.stream === true;\n\n const reuseChannelId = options.params.channelId;\n\n const sessionResult = isStreaming\n ? await runStreamingSession(\n surface,\n sm,\n request.url,\n replayInitResult.value,\n reuseChannelId\n )\n : await runRequestSession(\n surface,\n sm,\n request.url,\n replayInitResult.value,\n reuseChannelId\n );\n if (sessionResult.isErr()) return sessionResult;\n\n const { response: finalResponse, receipt } = sessionResult.value;\n\n const price = receipt\n ? formatUsd(tokenStringToNumber(receipt.spent, USDC_DECIMALS))\n : `from ${formatUsd(tickCostUsd)}/tick`;\n\n return mppOk<ExecuteFetchResult>({\n response: finalResponse,\n paymentInfo: {\n protocol: PaymentProtocol.MPP,\n network: Network.TEMPO,\n price,\n payment: receipt ? { success: true, channelId: receipt.channelId } : null,\n },\n });\n}\n","import { safeReadResponseText } from '@/shared/neverthrow/fetch';\n\nimport {\n mppErr,\n mppOk,\n mppResultFromPromise,\n sessionRequestFailedErr,\n} from '../index';\nimport type { SessionManager, SessionOutcome } from './types';\n\nexport async function runRequestSession(\n surface: string,\n sm: SessionManager,\n url: string,\n init: RequestInit,\n channelId?: string\n) {\n const fetchInit: RequestInit & { context?: { channelId?: string } } = {\n ...init,\n ...(channelId ? { context: { channelId } } : {}),\n };\n const fetchResult = await mppResultFromPromise(\n surface,\n sm.fetch(url, fetchInit),\n e => sessionRequestFailedErr(e)\n );\n if (fetchResult.isErr()) return fetchResult;\n\n const paymentResponse = fetchResult.value;\n\n if (paymentResponse.status === 402) {\n const body = await safeReadResponseText(surface, paymentResponse).unwrapOr(\n ''\n );\n const detail = body ? `: ${body}` : '';\n return mppErr(surface, {\n cause: 'mpp_payment_rejected',\n message: `MPP session payment was rejected by the server (402)${detail}`,\n });\n }\n\n return mppOk<SessionOutcome>({\n response: paymentResponse,\n receipt: paymentResponse.receipt,\n });\n}\n","import { mppErr, mppOk } from '../index';\nimport type { SessionManager, SessionOutcome, SessionReceipt } from './types';\n\nconst MAX_BUFFERED_BYTES = 50 * 1024 * 1024;\n\nexport async function runStreamingSession(\n surface: string,\n sm: SessionManager,\n url: string,\n init: RequestInit,\n channelId?: string\n) {\n let latestReceipt: SessionReceipt | null = null;\n\n const { signal, ...rest } = init;\n const sseResult = await sm.sse(url, {\n ...rest,\n ...(signal ? { signal } : {}),\n ...(channelId ? { context: { channelId } } : {}),\n onReceipt: receipt => {\n latestReceipt = receipt;\n },\n });\n\n const chunks: string[] = [];\n let bytes = 0;\n for await (const chunk of sseResult) {\n bytes += chunk.length;\n chunks.push(chunk);\n if (bytes > MAX_BUFFERED_BYTES) {\n return mppErr(surface, {\n cause: 'mpp_session_response_too_large',\n message: `Streaming response exceeded the ${MAX_BUFFERED_BYTES}-byte buffering cap (got ${bytes} bytes).`,\n });\n }\n }\n\n // mppx's `sm.sse()` yields the `data:` payloads of `message` events\n // (voucher/receipt events are consumed internally), so join with `\\n`\n // to keep object-yielding streams valid NDJSON.\n const response = new Response(chunks.join('\\n'), {\n status: 200,\n headers: {\n 'Content-Type': 'text/plain',\n 'Cache-Control': 'private',\n },\n });\n\n return mppOk<SessionOutcome>({ response, receipt: latestReceipt });\n}\n","import {\n DEFAULT_MAX_AMOUNT,\n type ExecuteFetchOptions,\n} from '@/operations/fetch/types';\nimport { getSettings } from '@/shared/settings';\nimport { tokenStringToNumber } from '@/shared/utils';\n\nexport const USDC_DECIMALS = 6;\nconst DEFAULT_TICK_BUDGET = 10;\n\nexport function resolveDepositUsd(\n suggestedDeposit: string | undefined,\n tickCostUsd: number,\n options: ExecuteFetchOptions\n): number {\n const maxAmount =\n options.params.maxAmount ?? getSettings().maxAmount ?? DEFAULT_MAX_AMOUNT;\n const desired =\n suggestedDeposit !== undefined\n ? tokenStringToNumber(suggestedDeposit, USDC_DECIMALS)\n : tickCostUsd * DEFAULT_TICK_BUDGET;\n return Math.min(desired, maxAmount);\n}\n\n// toFixed rather than toString so very small deposits don't serialize in\n// scientific notation, which viem's parseUnits rejects.\nexport function formatDepositCap(depositUsd: number): string {\n if (!Number.isFinite(depositUsd) || depositUsd <= 0) {\n return '0';\n }\n return depositUsd.toFixed(USDC_DECIMALS);\n}\n\nexport async function bufferRequestForReplay(\n request: Request\n): Promise<RequestInit> {\n const init: RequestInit = {\n method: request.method,\n headers: new Headers(request.headers),\n credentials: request.credentials,\n redirect: request.redirect,\n referrer: request.referrer === '' ? undefined : request.referrer,\n integrity: request.integrity || undefined,\n signal: request.signal,\n };\n\n const hasBody =\n request.method !== 'GET' &&\n request.method !== 'HEAD' &&\n request.body !== null;\n\n if (hasBody) {\n init.body = await request.arrayBuffer();\n }\n\n return init;\n}\n","import { safeGetMppChallenge } from '@/shared/protocols/mpp';\n\nimport { log } from '@/shared/log';\nimport { getBalance } from '@/shared/balance';\nimport { Network } from '@agentcash/networks';\n\nimport { PaymentProtocol } from './types';\n\nimport type { ExecuteFetchOptions } from '@/operations/fetch/types';\n\n/**\n * Pick the preferred protocol by comparing wallet balances.\n * Falls back to 'mpp' if both balances fail to fetch.\n */\nexport async function pickByBalance(\n response: Response,\n options: ExecuteFetchOptions\n): Promise<PaymentProtocol> {\n const { surface, wallets, flags } = options;\n\n // Get x402 (USDC on Base and Solana) balances in parallel\n const x402Balances = await Promise.all([\n getBalance(\n surface,\n {\n address: wallets.evm.address,\n network: Network.BASE,\n },\n flags\n ),\n getBalance(\n surface,\n {\n address: wallets.svm.address,\n network: Network.SOLANA,\n },\n flags\n ),\n ]);\n\n const x402Balance = x402Balances.reduce(\n (acc, balance) => acc + (balance.isOk() ? balance.value.balance : 0),\n 0\n );\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;\n if (currency) {\n const tempoResult = await getBalance(\n surface,\n {\n address: wallets.evm.address,\n network: Network.TEMPO,\n },\n flags\n );\n if (tempoResult.isOk()) {\n mppBalance = tempoResult.value.balance ?? 0;\n }\n }\n }\n\n log.info(`Protocol selection — x402: $${x402Balance}, mpp: $${mppBalance}`);\n return x402Balance >= mppBalance ? PaymentProtocol.X402 : PaymentProtocol.MPP;\n}\n","import { getBalance } from '@/shared/balance';\nimport { caip2ToNetwork, Network, networkToCaip2 } from '@agentcash/networks';\n\nimport type { PaymentRequirements } from '@x402/core/types';\nimport type { ExecuteFetchOptions } from '@/operations/fetch/types';\n\ninterface ChoosePaymentRequirementParams {\n paymentRequirements: PaymentRequirements[];\n options: ExecuteFetchOptions;\n}\n\n// Prefer `upto` over `exact` when a server offers both on the same network.\n// `upto` authorizes a maximum via Permit2 and settles for actual usage, which\n// matches usage-priced endpoints (e.g. per-token LLM inference) better than\n// `exact`, which charges the upper bound regardless. Servers that surface\n// both schemes — like Surplus Intelligence — explicitly recommend preferring\n// `upto`. Falls back to the first match when `upto` isn't offered.\nexport const preferUpto = (\n requirements: PaymentRequirements[]\n): PaymentRequirements | undefined => {\n return requirements.find(pr => pr.scheme === 'upto') ?? requirements[0];\n};\n\nexport const choosePaymentRequirement = async ({\n paymentRequirements,\n options,\n}: ChoosePaymentRequirementParams) => {\n const { surface, wallets, flags } = options;\n const { paymentNetwork } = options.params;\n if (paymentNetwork) {\n const caip2 = networkToCaip2(paymentNetwork);\n return preferUpto(paymentRequirements.filter(pr => pr.network === caip2));\n }\n\n const requirementsWithBalance = await Promise.all(\n paymentRequirements.map(async pr => {\n const network = caip2ToNetwork(pr.network);\n if (network === null) {\n return {\n balance: 0,\n requirement: pr,\n };\n }\n if (network === Network.SOLANA) {\n const balanceResult = await getBalance(\n surface,\n {\n address: wallets.svm.address,\n network,\n },\n flags\n );\n return {\n requirement: pr,\n balance: balanceResult.isOk() ? balanceResult.value.balance : 0,\n };\n } else {\n const balanceResult = await getBalance(\n surface,\n {\n address: wallets.evm.address,\n network,\n },\n flags\n );\n return {\n requirement: pr,\n balance: balanceResult.isOk() ? balanceResult.value.balance : 0,\n };\n }\n })\n );\n const bestNetwork = requirementsWithBalance.sort(\n (a, b) => b.balance - a.balance\n )[0]!.requirement.network;\n return preferUpto(\n paymentRequirements.filter(pr => pr.network === bestNetwork)\n );\n};\n","import { caip2ToNetwork, Network } from '@agentcash/networks';\n\nimport { choosePaymentRequirement } from './choose-payment-requirement';\n\nimport { safeFetch, safeReadResponseText } from '@/shared/neverthrow/fetch';\nimport {\n safeCreatePaymentPayload,\n safeGetPaymentRequired,\n safeGetPaymentSettlement,\n x402Err,\n x402Ok,\n x402ProbeClient,\n} from '@/shared/protocols/x402';\nimport { tokenStringToNumber, formatUsd } from '@/shared/utils';\n\nimport { beforePayment } from '../before-payment';\n\nimport { PaymentProtocol } from '../types';\n\nimport type { ExecuteFetchResult } from '@/operations/fetch/types';\nimport type { HandlePaymentParams } from '../types';\nimport type { BaseX402Error } from './types';\n\nexport const isPermit2AllowanceFailureBody = (body: string): boolean =>\n body.includes('permit2') && body.includes('allowance_required');\n\nexport const buildPermit2AllowanceErrorMessage = (params: {\n walletAddress: string;\n scheme: string;\n}): string => {\n const { walletAddress, scheme } = params;\n return [\n `Payment failed: this endpoint's \\`${scheme}\\` scheme settles via the Permit2 contract, but your agentcash wallet (${walletAddress}) has not approved Permit2 to spend USDC.`,\n '',\n 'The clean fix is server-side. The merchant should adopt the EIP-2612 gas-sponsoring extension — agentcash will then auto-sign an off-chain permit on each call and the facilitator pays the approval gas, with no setup required from the user. See https://docs.x402.org/extensions/eip2612-gas-sponsoring',\n '',\n `Until the merchant adopts that extension, you can do a one-time \\`USDC.approve(0x000000000022D473030F116dDEE9F6B43aC78BA3, MAX_UINT256)\\` on Base from this wallet (requires a small amount of ETH for gas, ~$0.01–0.10). After that, all future Permit2-based payments from this wallet work without further on-chain transactions.`,\n ].join('\\n');\n};\n\nexport async function handleX402Payment({\n response,\n request,\n options,\n}: HandlePaymentParams) {\n const { surface, wallets } = options;\n const { timeout } = options.params;\n\n const paymentRequiredResult = await safeGetPaymentRequired(surface, response);\n\n if (paymentRequiredResult.isErr()) {\n return paymentRequiredResult;\n }\n\n const paymentRequired = paymentRequiredResult.value;\n\n if (paymentRequired.x402Version === 1) {\n return x402Err(surface, {\n cause: 'parse_payment_required' as const,\n message:\n 'This endpoint uses the x402 v1 format, which is not supported by agentcash. Only x402 v2 servers (with an `accepts` array in the Payment-Required header) are supported.',\n });\n }\n\n if (!paymentRequired.accepts || !Array.isArray(paymentRequired.accepts)) {\n return x402Err(surface, {\n cause: 'parse_payment_required' as const,\n message:\n 'This endpoint has a missing or malformed accepts array in the Payment-Required header.',\n });\n }\n\n // Check amount against maxAmount before any payment logic\n const accept = await choosePaymentRequirement({\n options,\n paymentRequirements: paymentRequired.accepts,\n });\n\n if (accept) {\n const amount = tokenStringToNumber(accept.amount);\n\n const typedNetwork = caip2ToNetwork(accept.network)!;\n if (!typedNetwork) {\n return x402Err(surface, {\n cause: 'parse_payment_required' as const,\n message: `Invalid network: ${accept.network}`,\n });\n }\n\n const beforePaymentResult = await beforePayment({\n options,\n balanceInput:\n typedNetwork === Network.SOLANA\n ? {\n address: wallets.svm.address,\n network: Network.SOLANA,\n }\n : {\n address: wallets.evm.address,\n network: typedNetwork,\n },\n amount,\n protocol: PaymentProtocol.X402,\n });\n\n if (beforePaymentResult.isErr()) {\n return beforePaymentResult;\n }\n }\n\n const paymentPayloadResult = await safeCreatePaymentPayload(\n surface,\n wallets,\n paymentRequired,\n accept ? () => accept : undefined\n );\n\n if (paymentPayloadResult.isErr()) {\n return paymentPayloadResult;\n }\n\n const paymentPayload = paymentPayloadResult.value;\n\n const paymentHeaders =\n x402ProbeClient.encodePaymentSignatureHeader(paymentPayload);\n\n if (\n request.headers.has('PAYMENT-SIGNATURE') ||\n request.headers.has('X-PAYMENT')\n ) {\n return x402Err(surface, {\n cause: 'payment_already_attempted',\n message: 'Payment already attempted',\n });\n }\n\n for (const [key, value] of Object.entries(paymentHeaders)) {\n request.headers.set(key, value);\n }\n request.headers.set(\n 'Access-Control-Expose-Headers',\n 'PAYMENT-RESPONSE,X-PAYMENT-RESPONSE'\n );\n\n const paidResult = await safeFetch(surface, request, timeout);\n if (paidResult.isErr()) {\n return paidResult;\n }\n const paidResponse = paidResult.value;\n\n const permit2Error = await detectPermit2AllowanceError(\n surface,\n paidResponse,\n {\n walletAddress: wallets.evm.address,\n scheme: paymentPayload.accepted.scheme,\n }\n );\n if (permit2Error) {\n return x402Err(surface, permit2Error);\n }\n\n const settlementResult = safeGetPaymentSettlement(surface, paidResponse);\n\n const settlement = settlementResult.isOk() ? settlementResult.value : null;\n\n const maxAmount = tokenStringToNumber(paymentPayload.accepted.amount);\n const settledAmount = settlement?.amount\n ? tokenStringToNumber(settlement.amount)\n : null;\n const isUpTo = paymentPayload.accepted.scheme === 'upto';\n\n const price =\n settledAmount != null\n ? formatUsd(settledAmount)\n : isUpTo\n ? `up to ${formatUsd(maxAmount)}`\n : formatUsd(maxAmount);\n\n return x402Ok<ExecuteFetchResult>({\n response: paidResponse,\n paymentInfo: {\n protocol: PaymentProtocol.X402,\n network: caip2ToNetwork(paymentPayload.accepted.network)!,\n price,\n payment: settlement\n ? {\n success: settlement.success,\n transactionHash: settlement.transaction,\n }\n : null,\n },\n });\n}\n\nasync function detectPermit2AllowanceError(\n surface: string,\n response: Response,\n context: { walletAddress: string; scheme: string }\n): Promise<BaseX402Error | null> {\n if (response.ok) {\n return null;\n }\n const body = await safeReadResponseText(surface, response).unwrapOr('');\n if (!isPermit2AllowanceFailureBody(body)) {\n return null;\n }\n return {\n cause: 'permit2_allowance_required',\n message: buildPermit2AllowanceErrorMessage(context),\n };\n}\n","import { detectPaymentProtocols } from '@/shared/protocols/detect';\nimport { handleMppPayment } from '@/shared/protocols/mpp/handle-payment';\nimport { pickByBalance } from '@/shared/protocols/pick';\nimport { PaymentProtocol } from '@/shared/protocols/types';\nimport { handleX402Payment } from '@/shared/protocols/x402/handle-payment';\n\nimport type { ExecuteFetchOptions } from './types';\n\nexport async function executePayment(\n response: Response,\n request: Request,\n options: ExecuteFetchOptions\n) {\n const { paymentProtocol } = options.params;\n\n const params = {\n response,\n request,\n options,\n };\n\n if (paymentProtocol) {\n return handlerMap[paymentProtocol](params);\n }\n\n const available = detectPaymentProtocols(response);\n const preferred =\n available.length === 1\n ? available[0]!\n : await pickByBalance(response, options);\n const fallback =\n available.length > 1\n ? preferred === PaymentProtocol.MPP\n ? PaymentProtocol.X402\n : PaymentProtocol.MPP\n : null;\n\n const fallbackRetryRequest = fallback ? request.clone() : null;\n const result = await handlerMap[preferred](params);\n\n if (result.isErr() && fallback && fallbackRetryRequest) {\n return handlerMap[fallback]({\n ...params,\n request: fallbackRetryRequest,\n });\n }\n\n return result;\n}\n\nconst handlerMap = {\n [PaymentProtocol.MPP]: handleMppPayment,\n [PaymentProtocol.X402]: handleX402Payment,\n};\n","import { fetchErr, fetchOk, safeFetch } from '@/shared/neverthrow/fetch';\nimport { BLACKLISTED_ORIGINS } from '@/shared/origins';\n\nimport { attemptSiwxAuth } from './auth';\nimport { executePayment } from './payment';\n\nimport type { ExecuteFetchOptions } from './types';\nimport { buildRequest } from '@/shared/request/build';\nimport type { RequestInput } from '@/shared/request/types';\n\n/**\n * Executes a request with automatic SIWX authentication and payment handling.\n *\n * 1. Probe the endpoint\n * 2. If 402 with SIWX challenge, retry with SIGN-IN-WITH-X\n * 3. If still 402, execute payment\n */\nexport async function executeFetch(\n input: RequestInput,\n options: ExecuteFetchOptions\n) {\n const request = buildRequest(input, options);\n\n const { surface } = options;\n const { timeout } = options.params;\n\n const blocked = BLACKLISTED_ORIGINS.find(origin =>\n request.url.startsWith(origin)\n );\n if (blocked) {\n return fetchErr(surface, {\n cause: 'network',\n message: `${blocked} is no longer available. This origin has been deprecated.`,\n });\n }\n\n const authRetryRequest = request.clone();\n const paymentRetryRequest = 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 const initialResponse = probeResult.value;\n if (initialResponse.status !== 402) {\n return fetchOk({\n response: initialResponse,\n paymentInfo: null,\n });\n }\n\n const authResult = await attemptSiwxAuth(\n initialResponse,\n authRetryRequest,\n paymentRetryRequest,\n options\n );\n\n if (authResult.isErr()) {\n return authResult;\n }\n\n const latestResponse = authResult.value.response;\n if (latestResponse.status !== 402) {\n return fetchOk({\n response: latestResponse,\n paymentInfo: null,\n });\n }\n\n return executePayment(\n latestResponse,\n authResult.value.paymentRetryRequest,\n options\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,wBAAwB;;;ACQjC,SAAS,YAAY,sBAAsB;AAE3C,SAAS,yBAAyB;AAClC,SAAS,yBAAyB;AAElC,SAAS,sBAAsB;AAC/B,SAAS,qBAAqB;;;ACd9B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAOP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAiBP,SAAS,0BACP,OACoB;AACpB,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO;AAAA,EACT;AAEA,MAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,GAAG;AACvD,WAAO,OAAO,KAAK;AAAA,EACrB;AAEA,MAAI,OAAO,UAAU,YAAY,MAAM,SAAS,GAAG;AACjD,WAAO,OAAO,KAAK;AAAA,EACrB;AAEA,SAAO;AACT;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MAAI,SAAS;AACX,WAAO,SAAS,SAAS;AAAA,MACvB,OAAO;AAAA,MACP,SAAS,GAAG,OAAO;AAAA,IACrB,CAAC;AAAA,EACH;AAEA,QAAM,mBAAmB,QAAQ,MAAM;AACvC,QAAM,sBAAsB,QAAQ,MAAM;AAE1C,QAAM,cAAc,MAAM,UAAU,SAAS,SAAS,OAAO;AAE7D,MAAI,YAAY,MAAM,GAAG;AACvB,WAAO,SAAS,SAAS,YAAY,KAAK;AAAA,EAC5C;AAEA,QAAM,kBAAkB,YAAY;AACpC,MAAI,gBAAgB,WAAW,KAAK;AAClC,WAAO,QAAQ;AAAA,MACb,UAAU;AAAA,MACV,aAAa;AAAA,IACf,CAAC;AAAA,EACH;AAEA,QAAM,aAAa,MAAM;AAAA,IACvB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,MAAI,WAAW,MAAM,GAAG;AACtB,WAAO;AAAA,EACT;AAEA,QAAM,iBAAiB,WAAW,MAAM;AACxC,MAAI,eAAe,WAAW,KAAK;AACjC,WAAO,QAAQ;AAAA,MACb,UAAU;AAAA,MACV,aAAa;AAAA,IACf,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL;AAAA,IACA,WAAW,MAAM;AAAA,IACjB;AAAA,EACF;AACF;","names":["tx","formatUnits","formatUnits"]}
|
|
@@ -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.15.
|
|
7
|
+
return "0.15.1";
|
|
8
8
|
}
|
|
9
9
|
const __dirname2 = dirname(fileURLToPath(import.meta.url));
|
|
10
10
|
const pkg = JSON.parse(
|
|
@@ -23,4 +23,4 @@ export {
|
|
|
23
23
|
MCP_VERSION,
|
|
24
24
|
INSTALL_PACKAGE_SPECIFIER
|
|
25
25
|
};
|
|
26
|
-
//# sourceMappingURL=chunk-
|
|
26
|
+
//# sourceMappingURL=chunk-PQXKQJIU.js.map
|
|
@@ -5,7 +5,7 @@ import "./chunk-SLTRGQ7W.js";
|
|
|
5
5
|
import "./chunk-W37JKCLN.js";
|
|
6
6
|
import {
|
|
7
7
|
executeFetch
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-EDI77S36.js";
|
|
9
9
|
import "./chunk-FBGNOXFP.js";
|
|
10
10
|
import "./chunk-4TIYIVZF.js";
|
|
11
11
|
import "./chunk-IKPLMFAK.js";
|
|
@@ -90,4 +90,4 @@ var fetchCommand = async (input) => {
|
|
|
90
90
|
export {
|
|
91
91
|
fetchCommand
|
|
92
92
|
};
|
|
93
|
-
//# sourceMappingURL=fetch-
|
|
93
|
+
//# sourceMappingURL=fetch-AFKCCCHZ.js.map
|
package/dist/esm/index.js
CHANGED
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
} from "./chunk-27DZCYDB.js";
|
|
8
8
|
import {
|
|
9
9
|
MCP_VERSION
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-PQXKQJIU.js";
|
|
11
11
|
import {
|
|
12
12
|
paymentNetworks,
|
|
13
13
|
paymentProtocols,
|
|
@@ -123,7 +123,7 @@ void yargs(hideBin(process.argv)).scriptName("agentcash").usage("$0 [command] [o
|
|
|
123
123
|
DESCRIPTIONS.fetch.epilogue
|
|
124
124
|
),
|
|
125
125
|
async (args) => {
|
|
126
|
-
const { fetchCommand } = await import("./fetch-
|
|
126
|
+
const { fetchCommand } = await import("./fetch-AFKCCCHZ.js");
|
|
127
127
|
await fetchCommand(args);
|
|
128
128
|
}
|
|
129
129
|
).command(
|
|
@@ -135,7 +135,7 @@ void yargs(hideBin(process.argv)).scriptName("agentcash").usage("$0 [command] [o
|
|
|
135
135
|
DESCRIPTIONS.fetchWithAuth.epilogue
|
|
136
136
|
),
|
|
137
137
|
async (args) => {
|
|
138
|
-
const { fetchCommand } = await import("./fetch-
|
|
138
|
+
const { fetchCommand } = await import("./fetch-AFKCCCHZ.js");
|
|
139
139
|
await fetchCommand(args);
|
|
140
140
|
}
|
|
141
141
|
).command(
|
|
@@ -179,7 +179,7 @@ void yargs(hideBin(process.argv)).scriptName("agentcash").usage("$0 [command] [o
|
|
|
179
179
|
demandOption: true
|
|
180
180
|
}),
|
|
181
181
|
async (args) => {
|
|
182
|
-
const { tryCommand } = await import("./try-
|
|
182
|
+
const { tryCommand } = await import("./try-4RHB5KHZ.js");
|
|
183
183
|
await tryCommand(args);
|
|
184
184
|
}
|
|
185
185
|
).command(
|
|
@@ -201,7 +201,7 @@ void yargs(hideBin(process.argv)).scriptName("agentcash").usage("$0 [command] [o
|
|
|
201
201
|
description: TOOL_PARAMS.search.page
|
|
202
202
|
}),
|
|
203
203
|
async (args) => {
|
|
204
|
-
const { searchCommand } = await import("./search-
|
|
204
|
+
const { searchCommand } = await import("./search-MEGI3KJW.js");
|
|
205
205
|
await searchCommand(args);
|
|
206
206
|
}
|
|
207
207
|
).command(
|
|
@@ -228,7 +228,7 @@ void yargs(hideBin(process.argv)).scriptName("agentcash").usage("$0 [command] [o
|
|
|
228
228
|
demandOption: true
|
|
229
229
|
}),
|
|
230
230
|
async (args) => {
|
|
231
|
-
const { registerCommand } = await import("./register-
|
|
231
|
+
const { registerCommand } = await import("./register-5KLJDRG4.js");
|
|
232
232
|
await registerCommand(args);
|
|
233
233
|
}
|
|
234
234
|
).command(
|
|
@@ -319,7 +319,7 @@ void yargs(hideBin(process.argv)).scriptName("agentcash").usage("$0 [command] [o
|
|
|
319
319
|
description: "The invite code to redeem (optional)"
|
|
320
320
|
}),
|
|
321
321
|
async (args) => {
|
|
322
|
-
const { onboardCommand } = await import("./onboard-
|
|
322
|
+
const { onboardCommand } = await import("./onboard-W7CUGJJM.js");
|
|
323
323
|
await onboardCommand({ ...args, code: args.code ?? args.invite });
|
|
324
324
|
}
|
|
325
325
|
).command(
|
|
@@ -448,7 +448,7 @@ void yargs(hideBin(process.argv)).scriptName("agentcash").usage("$0 [command] [o
|
|
|
448
448
|
description: TOOL_PARAMS.reportError.fullReport
|
|
449
449
|
}),
|
|
450
450
|
async (args) => {
|
|
451
|
-
const { reportErrorCommand } = await import("./report-error-
|
|
451
|
+
const { reportErrorCommand } = await import("./report-error-HN4YXEOC.js");
|
|
452
452
|
await reportErrorCommand(args);
|
|
453
453
|
}
|
|
454
454
|
).command(
|
|
@@ -478,7 +478,7 @@ void yargs(hideBin(process.argv)).scriptName("agentcash").usage("$0 [command] [o
|
|
|
478
478
|
"Start the MCP server (default when no command specified)",
|
|
479
479
|
(yargs2) => yargs2,
|
|
480
480
|
async (args) => {
|
|
481
|
-
const { serverCommand } = await import("./server-
|
|
481
|
+
const { serverCommand } = await import("./server-7QJB55AW.js");
|
|
482
482
|
await serverCommand(args);
|
|
483
483
|
}
|
|
484
484
|
).command(
|
|
@@ -492,7 +492,7 @@ void yargs(hideBin(process.argv)).scriptName("agentcash").usage("$0 [command] [o
|
|
|
492
492
|
default: isClaudeCode ? "claude-code" /* ClaudeCode */ : void 0
|
|
493
493
|
}),
|
|
494
494
|
async (args) => {
|
|
495
|
-
const { installMcpServer } = await import("./install-
|
|
495
|
+
const { installMcpServer } = await import("./install-LAWJMMPO.js");
|
|
496
496
|
await installMcpServer(args);
|
|
497
497
|
}
|
|
498
498
|
).command(
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
} from "./chunk-C7B6LEPE.js";
|
|
4
4
|
import {
|
|
5
5
|
addServer
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-7CV5CENJ.js";
|
|
7
7
|
import {
|
|
8
8
|
wait
|
|
9
9
|
} from "./chunk-DZNSJ2BA.js";
|
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
Clients,
|
|
15
15
|
clientMetadata
|
|
16
16
|
} from "./chunk-27DZCYDB.js";
|
|
17
|
-
import "./chunk-
|
|
17
|
+
import "./chunk-PQXKQJIU.js";
|
|
18
18
|
import "./chunk-ISF2WVEZ.js";
|
|
19
19
|
import {
|
|
20
20
|
getBalance
|
|
@@ -176,4 +176,4 @@ var installMcpServer = async (args) => {
|
|
|
176
176
|
export {
|
|
177
177
|
installMcpServer
|
|
178
178
|
};
|
|
179
|
-
//# sourceMappingURL=install-
|
|
179
|
+
//# sourceMappingURL=install-LAWJMMPO.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
getPlatformPath,
|
|
3
3
|
tryAddServer
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-7CV5CENJ.js";
|
|
5
5
|
import "./chunk-DZNSJ2BA.js";
|
|
6
6
|
import {
|
|
7
7
|
installGitHubSkill
|
|
@@ -13,7 +13,7 @@ import {
|
|
|
13
13
|
detectAgents
|
|
14
14
|
} from "./chunk-FVVSNDQR.js";
|
|
15
15
|
import "./chunk-27DZCYDB.js";
|
|
16
|
-
import "./chunk-
|
|
16
|
+
import "./chunk-PQXKQJIU.js";
|
|
17
17
|
import {
|
|
18
18
|
getOnboardingCta,
|
|
19
19
|
getWalletInfo
|
|
@@ -381,4 +381,4 @@ var onboardCommand = async (args) => {
|
|
|
381
381
|
export {
|
|
382
382
|
onboardCommand
|
|
383
383
|
};
|
|
384
|
-
//# sourceMappingURL=onboard-
|
|
384
|
+
//# sourceMappingURL=onboard-W7CUGJJM.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
executeFetch
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-EDI77S36.js";
|
|
4
4
|
import "./chunk-FBGNOXFP.js";
|
|
5
5
|
import "./chunk-4TIYIVZF.js";
|
|
6
6
|
import "./chunk-IKPLMFAK.js";
|
|
@@ -189,4 +189,4 @@ var registerCommand = async (args) => {
|
|
|
189
189
|
export {
|
|
190
190
|
registerCommand
|
|
191
191
|
};
|
|
192
|
-
//# sourceMappingURL=register-
|
|
192
|
+
//# sourceMappingURL=register-5KLJDRG4.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
submitErrorReport
|
|
3
|
-
} from "./chunk-
|
|
4
|
-
import "./chunk-
|
|
3
|
+
} from "./chunk-BM5W5OV2.js";
|
|
4
|
+
import "./chunk-PQXKQJIU.js";
|
|
5
5
|
import "./chunk-RAS5DZPQ.js";
|
|
6
6
|
import {
|
|
7
7
|
getWalletOrExit
|
|
@@ -33,4 +33,4 @@ var reportErrorCommand = async (args) => {
|
|
|
33
33
|
export {
|
|
34
34
|
reportErrorCommand
|
|
35
35
|
};
|
|
36
|
-
//# sourceMappingURL=report-error-
|
|
36
|
+
//# sourceMappingURL=report-error-HN4YXEOC.js.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
2
|
search
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-66AVEFTO.js";
|
|
4
4
|
import "./chunk-W37JKCLN.js";
|
|
5
|
-
import "./chunk-
|
|
5
|
+
import "./chunk-EDI77S36.js";
|
|
6
6
|
import "./chunk-FBGNOXFP.js";
|
|
7
7
|
import "./chunk-4TIYIVZF.js";
|
|
8
8
|
import "./chunk-IKPLMFAK.js";
|
|
@@ -55,4 +55,4 @@ var searchCommand = async (input) => {
|
|
|
55
55
|
export {
|
|
56
56
|
searchCommand
|
|
57
57
|
};
|
|
58
|
-
//# sourceMappingURL=search-
|
|
58
|
+
//# sourceMappingURL=search-MEGI3KJW.js.map
|
|
@@ -5,10 +5,10 @@ var serverCommand = async (args) => {
|
|
|
5
5
|
"MCP server started. If you meant to explore the CLI, run: npx agentcash --help\n"
|
|
6
6
|
);
|
|
7
7
|
}
|
|
8
|
-
const { startServer } = await import("./server-
|
|
8
|
+
const { startServer } = await import("./server-M7SLAGFR.js");
|
|
9
9
|
await startServer(args);
|
|
10
10
|
};
|
|
11
11
|
export {
|
|
12
12
|
serverCommand
|
|
13
13
|
};
|
|
14
|
-
//# sourceMappingURL=server-
|
|
14
|
+
//# sourceMappingURL=server-7QJB55AW.js.map
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
} from "./chunk-BIO4Y27B.js";
|
|
7
7
|
import {
|
|
8
8
|
submitErrorReport
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-BM5W5OV2.js";
|
|
10
10
|
import {
|
|
11
11
|
bridge,
|
|
12
12
|
bridgeSchema
|
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
import {
|
|
15
15
|
loadUserOrigins
|
|
16
16
|
} from "./chunk-YIU364NZ.js";
|
|
17
|
-
import "./chunk-
|
|
17
|
+
import "./chunk-PQXKQJIU.js";
|
|
18
18
|
import {
|
|
19
19
|
checkEndpoint
|
|
20
20
|
} from "./chunk-5CMVFNXO.js";
|
|
@@ -30,7 +30,7 @@ import "./chunk-ISF2WVEZ.js";
|
|
|
30
30
|
import {
|
|
31
31
|
search,
|
|
32
32
|
searchSchema
|
|
33
|
-
} from "./chunk-
|
|
33
|
+
} from "./chunk-66AVEFTO.js";
|
|
34
34
|
import {
|
|
35
35
|
discoverResources,
|
|
36
36
|
discoverResourcesSchema
|
|
@@ -42,7 +42,7 @@ import {
|
|
|
42
42
|
} from "./chunk-W37JKCLN.js";
|
|
43
43
|
import {
|
|
44
44
|
executeFetch
|
|
45
|
-
} from "./chunk-
|
|
45
|
+
} from "./chunk-EDI77S36.js";
|
|
46
46
|
import "./chunk-FBGNOXFP.js";
|
|
47
47
|
import {
|
|
48
48
|
DEFAULT_MAX_AMOUNT,
|
|
@@ -737,7 +737,7 @@ import { dirname, join } from "path";
|
|
|
737
737
|
import { fileURLToPath } from "url";
|
|
738
738
|
function getVersion() {
|
|
739
739
|
if (true) {
|
|
740
|
-
return "0.15.
|
|
740
|
+
return "0.15.1";
|
|
741
741
|
}
|
|
742
742
|
const __dirname2 = dirname(fileURLToPath(import.meta.url));
|
|
743
743
|
const pkg = JSON.parse(
|
|
@@ -804,4 +804,4 @@ var startServer = async (flags) => {
|
|
|
804
804
|
export {
|
|
805
805
|
startServer
|
|
806
806
|
};
|
|
807
|
-
//# sourceMappingURL=server-
|
|
807
|
+
//# sourceMappingURL=server-M7SLAGFR.js.map
|
|
@@ -56,7 +56,7 @@ var tryCommand = async (args) => {
|
|
|
56
56
|
const title = discoverResult.info?.title ?? discoverResult.origin;
|
|
57
57
|
const description = discoverResult.info?.description;
|
|
58
58
|
const sampleLines = sampleEndpoints.map((e) => {
|
|
59
|
-
const price = e.price ? ` (${e.price})` : "";
|
|
59
|
+
const price = e.price ? ` (${e.price.replace(/(\.\d{2,}?)0+(?=$|\D)/g, "$1")})` : "";
|
|
60
60
|
return ` - ${e.summary}${price}`;
|
|
61
61
|
});
|
|
62
62
|
const originSummary = [
|
|
@@ -101,4 +101,4 @@ var tryCommand = async (args) => {
|
|
|
101
101
|
export {
|
|
102
102
|
tryCommand
|
|
103
103
|
};
|
|
104
|
-
//# sourceMappingURL=try-
|
|
104
|
+
//# sourceMappingURL=try-4RHB5KHZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/cli/commands/try.ts"],"sourcesContent":["import { successResponse, outputAndExit } from '@/cli/output';\n\nimport { discoverResources } from '@/operations/discover';\nimport { getWalletInfo } from '@/operations/wallet';\nimport { getWalletOrExit } from '../lib/get-wallet-or-exit';\n\nimport type { Command } from '@/types';\nimport type { DiscoverResourcesInput } from '@/operations/discover';\n\nconst surface = 'cli:try';\n\nexport const tryCommand: Command<DiscoverResourcesInput> = async args => {\n const wallets = await getWalletOrExit(args);\n\n const discoverResult = await discoverResources(surface, args, {\n flags: args,\n });\n const walletInfo = await getWalletInfo(surface, wallets, args);\n\n const onboardingCta = walletInfo.onboardingCta;\n\n if (!discoverResult.found) {\n const origin =\n 'origin' in discoverResult ? discoverResult.origin : args.url;\n return outputAndExit(\n successResponse({\n ...(onboardingCta\n ? {\n onboardMessage: onboardingCta.message,\n onboardLink: onboardingCta.onboardLink,\n }\n : {}),\n notice: `No endpoints found for ${origin}. The origin may not support x402 or SIWX.`,\n resources: `Browse supported APIs at https://agentcash.dev/resources`,\n }),\n args\n );\n }\n\n // Pick up to 3 sample endpoints (prefer paid)\n const paidEndpoints = discoverResult.endpoints.filter(\n e => e.authMode === 'paid'\n );\n const sampleEndpoints = (\n paidEndpoints.length > 0 ? paidEndpoints : discoverResult.endpoints\n ).slice(0, 3);\n const totalCount = discoverResult.endpoints.length;\n\n const title = discoverResult.info?.title ?? discoverResult.origin;\n const description = discoverResult.info?.description;\n\n const sampleLines = sampleEndpoints.map(e => {\n const price = e.price\n ? ` (${e.price.replace(/(\\.\\d{2,}?)0+(?=$|\\D)/g, '$1')})`\n : '';\n return ` - ${e.summary}${price}`;\n });\n\n const originSummary = [\n `${title}${description ? ` — ${description}` : ''}`,\n '',\n 'Sample endpoints:',\n ...sampleLines,\n ...(totalCount > sampleEndpoints.length\n ? [\n ` ...and ${totalCount - sampleEndpoints.length} more. Run \\`npx agentcash discover ${discoverResult.origin}\\` to see all endpoints.`,\n ]\n : []),\n ].join('\\n');\n\n // Call to action using the first paid endpoint\n const firstEndpoint =\n discoverResult.endpoints.find(e => e.authMode === 'paid') ??\n discoverResult.endpoints[0];\n\n let callToAction: string | undefined;\n if (firstEndpoint) {\n const endpointUrl = `${discoverResult.origin}${firstEndpoint.path}`;\n callToAction = [\n `To call your first endpoint:`,\n ` 1. Run \\`npx agentcash check \"${endpointUrl}\"\\` to get the input schema and pricing.`,\n ` 2. Run \\`npx agentcash fetch \"${endpointUrl}\" -m ${firstEndpoint.method}\\` with the required body to make the call.`,\n `If you have the AgentCash MCP installed, you can also call this directly using the check_endpoint_schema and fetch tools.`,\n ].join('\\n');\n }\n\n const modelInstructions = [\n `Present the originSummary to the user, then ask them what they would like to do — e.g. \"What would you like to do with ${title}?\"`,\n ...(onboardingCta\n ? [\n `IMPORTANT: The user has not yet onboarded. Show the onboard link VERBATIM as a clickable URL so the user can click it: ${onboardingCta.onboardLink}`,\n ]\n : []),\n ].join('\\n');\n\n return outputAndExit(\n successResponse({\n ...(onboardingCta\n ? {\n onboardMessage: onboardingCta.message,\n onboardLink: onboardingCta.onboardLink,\n }\n : {}),\n originSummary,\n callToAction,\n modelInstructions,\n }),\n args\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,IAAM,UAAU;AAET,IAAM,aAA8C,OAAM,SAAQ;AACvE,QAAM,UAAU,MAAM,gBAAgB,IAAI;AAE1C,QAAM,iBAAiB,MAAM,kBAAkB,SAAS,MAAM;AAAA,IAC5D,OAAO;AAAA,EACT,CAAC;AACD,QAAM,aAAa,MAAM,cAAc,SAAS,SAAS,IAAI;AAE7D,QAAM,gBAAgB,WAAW;AAEjC,MAAI,CAAC,eAAe,OAAO;AACzB,UAAM,SACJ,YAAY,iBAAiB,eAAe,SAAS,KAAK;AAC5D,WAAO;AAAA,MACL,gBAAgB;AAAA,QACd,GAAI,gBACA;AAAA,UACE,gBAAgB,cAAc;AAAA,UAC9B,aAAa,cAAc;AAAA,QAC7B,IACA,CAAC;AAAA,QACL,QAAQ,0BAA0B,MAAM;AAAA,QACxC,WAAW;AAAA,MACb,CAAC;AAAA,MACD;AAAA,IACF;AAAA,EACF;AAGA,QAAM,gBAAgB,eAAe,UAAU;AAAA,IAC7C,OAAK,EAAE,aAAa;AAAA,EACtB;AACA,QAAM,mBACJ,cAAc,SAAS,IAAI,gBAAgB,eAAe,WAC1D,MAAM,GAAG,CAAC;AACZ,QAAM,aAAa,eAAe,UAAU;AAE5C,QAAM,QAAQ,eAAe,MAAM,SAAS,eAAe;AAC3D,QAAM,cAAc,eAAe,MAAM;AAEzC,QAAM,cAAc,gBAAgB,IAAI,OAAK;AAC3C,UAAM,QAAQ,EAAE,QACZ,KAAK,EAAE,MAAM,QAAQ,0BAA0B,IAAI,CAAC,MACpD;AACJ,WAAO,OAAO,EAAE,OAAO,GAAG,KAAK;AAAA,EACjC,CAAC;AAED,QAAM,gBAAgB;AAAA,IACpB,GAAG,KAAK,GAAG,cAAc,WAAM,WAAW,KAAK,EAAE;AAAA,IACjD;AAAA,IACA;AAAA,IACA,GAAG;AAAA,IACH,GAAI,aAAa,gBAAgB,SAC7B;AAAA,MACE,YAAY,aAAa,gBAAgB,MAAM,uCAAuC,eAAe,MAAM;AAAA,IAC7G,IACA,CAAC;AAAA,EACP,EAAE,KAAK,IAAI;AAGX,QAAM,gBACJ,eAAe,UAAU,KAAK,OAAK,EAAE,aAAa,MAAM,KACxD,eAAe,UAAU,CAAC;AAE5B,MAAI;AACJ,MAAI,eAAe;AACjB,UAAM,cAAc,GAAG,eAAe,MAAM,GAAG,cAAc,IAAI;AACjE,mBAAe;AAAA,MACb;AAAA,MACA,mCAAmC,WAAW;AAAA,MAC9C,mCAAmC,WAAW,QAAQ,cAAc,MAAM;AAAA,MAC1E;AAAA,IACF,EAAE,KAAK,IAAI;AAAA,EACb;AAEA,QAAM,oBAAoB;AAAA,IACxB,+HAA0H,KAAK;AAAA,IAC/H,GAAI,gBACA;AAAA,MACE,0HAA0H,cAAc,WAAW;AAAA,IACrJ,IACA,CAAC;AAAA,EACP,EAAE,KAAK,IAAI;AAEX,SAAO;AAAA,IACL,gBAAgB;AAAA,MACd,GAAI,gBACA;AAAA,QACE,gBAAgB,cAAc;AAAA,QAC9B,aAAa,cAAc;AAAA,MAC7B,IACA,CAAC;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AAAA,IACD;AAAA,EACF;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/operations/fetch/auth.ts","../../src/shared/protocols/x402/index.ts","../../src/shared/protocols/x402/patched-exact-svm-scheme.ts","../../src/shared/protocols/x402/policies.ts","../../src/shared/protocols/detect.ts","../../src/shared/protocols/mpp/handle-payment.ts","../../src/shared/protocols/before-payment.ts","../../src/shared/protocols/mpp/session/handle-session-payment.ts","../../src/shared/protocols/mpp/session/run-request-session.ts","../../src/shared/protocols/mpp/session/run-streaming-session.ts","../../src/shared/protocols/mpp/session/utils.ts","../../src/shared/protocols/pick.ts","../../src/shared/protocols/x402/choose-payment-requirement.ts","../../src/shared/protocols/x402/handle-payment.ts","../../src/operations/fetch/payment.ts","../../src/operations/fetch/index.ts"],"sourcesContent":["import { encodeSIWxHeader } from '@x402/extensions/sign-in-with-x';\n\nimport { fetchOk, safeFetch } from '@/shared/neverthrow/fetch';\nimport {\n getSiwxExtension,\n safeCreateSIWxPayload,\n safeGetPaymentRequired,\n} from '@/shared/protocols/x402';\n\nimport type { ExecuteFetchOptions } from './types';\n\nexport async function attemptSiwxAuth(\n response: Response,\n authRetryRequest: Request,\n paymentRetryRequest: Request,\n options: ExecuteFetchOptions\n) {\n const { surface, wallets } = options;\n const { timeout, paymentNetwork } = options.params;\n\n if (!response.headers.has('payment-required')) {\n return fetchOk({\n response,\n paymentRetryRequest,\n });\n }\n\n const paymentRequiredResult = await safeGetPaymentRequired(surface, response);\n\n if (paymentRequiredResult.isErr()) {\n return paymentRequiredResult;\n }\n\n const siwxExtension = getSiwxExtension(\n paymentRequiredResult.value.extensions,\n paymentNetwork\n );\n\n if (!siwxExtension) {\n return fetchOk({\n response,\n paymentRetryRequest,\n });\n }\n\n const payloadResult = await safeCreateSIWxPayload(\n surface,\n siwxExtension,\n wallets\n );\n\n if (payloadResult.isErr()) {\n return payloadResult;\n }\n\n const siwxHeader = encodeSIWxHeader(payloadResult.value);\n authRetryRequest.headers.set('SIGN-IN-WITH-X', siwxHeader);\n paymentRetryRequest.headers.set('SIGN-IN-WITH-X', siwxHeader);\n\n return (await safeFetch(surface, authRetryRequest, timeout)).andThen(\n authResponse =>\n fetchOk({\n response: authResponse,\n paymentRetryRequest,\n })\n );\n}\n","import {\n err,\n ok,\n resultFromPromise,\n resultFromThrowable,\n} from '@agentcash/neverthrow';\n\nimport type { SelectPaymentRequirements } from '@x402/core/client';\nimport { x402Client, x402HTTPClient } from '@x402/core/client';\n\nimport { toClientEvmSigner } from '@x402/evm';\nimport { toClientSvmSigner } from '@x402/svm';\n\nimport { ExactEvmScheme } from '@x402/evm/exact/client';\nimport { UptoEvmScheme } from '@x402/evm/upto/client';\nimport { PatchedExactSvmScheme } from './patched-exact-svm-scheme';\nimport { capUptoDeadline } from './policies';\n\nimport { createSIWxPayload } from '@x402/extensions/sign-in-with-x';\n\nimport type { BaseX402Error } from './types';\nimport type { PaymentRequired } from '@x402/core/types';\nimport type {\n CompleteSIWxInfo,\n SIWxExtensionInfo,\n SolanaSigner,\n SupportedChain,\n} from '@x402/extensions/sign-in-with-x';\nimport type { Wallets } from '@/wallet';\nimport { Network, networkToCaip2 } from '@agentcash/networks';\nimport type { Network as PaymentNetwork } from '@agentcash/networks';\nimport { createPublicClient, http } from 'viem';\nimport { base } from 'viem/chains';\n\nconst errorType = 'x402';\n\nexport const x402Ok = <T>(value: T) => ok(value);\nexport const x402Err = (cause: string, error: BaseX402Error) =>\n err(errorType, cause, error);\n\nconst x402ResultFromPromise = <T>(\n surface: string,\n promise: Promise<T>,\n error: (e: unknown) => BaseX402Error\n) => resultFromPromise(errorType, surface, promise, error);\n\nconst x402ResultFromThrowable = <T>(\n surface: string,\n fn: () => T,\n error: (e: unknown) => BaseX402Error\n) => resultFromThrowable(errorType, surface, fn, error);\n\nexport const x402ProbeClient = new x402HTTPClient(new x402Client());\n\nexport const safeGetPaymentRequired = (surface: string, response: Response) => {\n return x402ResultFromPromise(\n surface,\n response.json().then(\n json =>\n x402ProbeClient.getPaymentRequiredResponse(\n name => response.headers.get(name),\n json\n ),\n () =>\n x402ProbeClient.getPaymentRequiredResponse(name =>\n response.headers.get(name)\n )\n ),\n error => ({\n cause: 'parse_payment_required',\n message:\n error instanceof Error\n ? error.message\n : 'Failed to parse payment required',\n })\n );\n};\n\nexport const getSiwxExtension = (\n extensions: PaymentRequired['extensions'],\n paymentNetwork?: PaymentNetwork\n): CompleteSIWxInfo | undefined => {\n const siwx = extensions?.['sign-in-with-x'] as\n | { info?: SIWxExtensionInfo; supportedChains?: SupportedChain[] }\n | undefined;\n\n if (!siwx?.info) {\n return undefined;\n }\n\n const chain = siwx.supportedChains?.find(c =>\n paymentNetwork\n ? c.chainId === networkToCaip2(paymentNetwork)\n : c.chainId.startsWith('eip155:')\n );\n\n return {\n ...siwx.info,\n chainId: chain?.chainId ?? 'eip155:8453',\n type: chain?.type ?? 'eip191',\n signatureScheme: chain?.signatureScheme,\n };\n};\n\nexport const safeCreatePaymentPayload = (\n surface: string,\n wallets: Wallets,\n paymentRequired: PaymentRequired,\n paymentRequirementsSelector?: SelectPaymentRequirements\n) => {\n const client = new x402HTTPClient(\n x402Client.fromConfig({\n schemes: [\n {\n network: networkToCaip2(Network.BASE),\n client: new ExactEvmScheme(\n toClientEvmSigner(\n wallets.evm,\n createPublicClient({\n chain: base,\n transport: http(),\n })\n )\n ),\n },\n {\n network: networkToCaip2(Network.BASE),\n client: new UptoEvmScheme(\n toClientEvmSigner(\n wallets.evm,\n createPublicClient({\n chain: base,\n transport: http(),\n })\n )\n ),\n },\n {\n network: networkToCaip2(Network.SOLANA),\n client: new PatchedExactSvmScheme(toClientSvmSigner(wallets.svm)),\n },\n ],\n policies: [capUptoDeadline],\n paymentRequirementsSelector,\n })\n );\n return x402ResultFromPromise(\n surface,\n client.createPaymentPayload(paymentRequired),\n error => ({\n cause: 'create_payment_payload',\n message:\n error instanceof Error\n ? error.message\n : 'Failed to create payment payload',\n })\n );\n};\n\nexport const safeGetPaymentSettlement = (\n surface: string,\n response: Response\n) => {\n return x402ResultFromThrowable(\n surface,\n () =>\n x402ProbeClient.getPaymentSettleResponse(name =>\n response.headers.get(name)\n ),\n error => ({\n cause: 'get_payment_settlement',\n message:\n error instanceof Error\n ? error.message\n : 'Failed to get payment settlement',\n })\n );\n};\n\nexport const safeCreateSIWxPayload = (\n surface: string,\n serverInfo: CompleteSIWxInfo,\n wallets: Wallets\n) => {\n return x402ResultFromPromise(\n surface,\n createSIWxPayload(\n serverInfo,\n serverInfo.chainId.startsWith('eip155:')\n ? wallets.evm\n : (wallets.svm as unknown as SolanaSigner)\n ),\n error => ({\n cause: 'create_siwx_payload',\n message:\n error instanceof Error\n ? error.message\n : 'Failed to create SIWX payload',\n })\n );\n};\n","import {\n getSetComputeUnitLimitInstruction,\n setTransactionMessageComputeUnitPrice,\n} from '@solana-program/compute-budget';\nimport { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token';\nimport {\n fetchMint,\n findAssociatedTokenPda,\n getTransferCheckedInstruction,\n TOKEN_2022_PROGRAM_ADDRESS,\n} from '@solana-program/token-2022';\nimport {\n appendTransactionMessageInstructions,\n createTransactionMessage,\n getBase64EncodedWireTransaction,\n partiallySignTransactionMessageWithSigners,\n pipe,\n prependTransactionMessageInstruction,\n setTransactionMessageFeePayer,\n setTransactionMessageLifetimeUsingBlockhash,\n type Address,\n} from '@solana/kit';\n\nimport type {\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkClient,\n} from '@x402/core/types';\nimport {\n DEFAULT_COMPUTE_UNIT_LIMIT,\n DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS,\n createRpcClient,\n type ClientSvmConfig,\n type ClientSvmSigner,\n type ExactSvmPayloadV2,\n} from '@x402/svm';\n\ntype BlockhashLifetime = Parameters<\n typeof setTransactionMessageLifetimeUsingBlockhash\n>[0];\n\ninterface PatchedPaymentExtra {\n feePayer?: Address;\n recentBlockhash?:\n | string\n | Partial<{\n blockhash: string;\n lastValidBlockHeight: bigint | number | string;\n }>;\n lastValidBlockHeight?: bigint | number | string;\n}\n\nfunction parseLastValidBlockHeight(\n value: bigint | number | string | undefined\n): bigint | undefined {\n if (typeof value === 'bigint') {\n return value;\n }\n\n if (typeof value === 'number' && Number.isFinite(value)) {\n return BigInt(value);\n }\n\n if (typeof value === 'string' && value.length > 0) {\n return BigInt(value);\n }\n\n return undefined;\n}\n\nfunction asBlockhash(blockhash: string): BlockhashLifetime['blockhash'] {\n return blockhash as BlockhashLifetime['blockhash'];\n}\n\n/**\n * Local compatibility patch for Coinbase ExactSvmScheme.\n *\n * Changes from upstream:\n * - omits the trailing memo instruction\n * - prefers paymentRequirements.extra.recentBlockhash when provided\n */\nexport class PatchedExactSvmScheme implements SchemeNetworkClient {\n readonly scheme = 'exact';\n\n constructor(\n private readonly signer: ClientSvmSigner,\n private readonly config?: ClientSvmConfig\n ) {}\n\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements\n ): Promise<Pick<PaymentPayload, 'x402Version' | 'payload'>> {\n const rpc = createRpcClient(\n paymentRequirements.network,\n this.config?.rpcUrl\n );\n\n const tokenMint = await fetchMint(\n rpc,\n paymentRequirements.asset as Address\n );\n const tokenProgramAddress = tokenMint.programAddress;\n\n if (\n tokenProgramAddress.toString() !== TOKEN_PROGRAM_ADDRESS.toString() &&\n tokenProgramAddress.toString() !== TOKEN_2022_PROGRAM_ADDRESS.toString()\n ) {\n throw new Error('Asset was not created by a known token program');\n }\n\n const [sourceATA] = await findAssociatedTokenPda({\n mint: paymentRequirements.asset as Address,\n owner: this.signer.address,\n tokenProgram: tokenProgramAddress,\n });\n\n const [destinationATA] = await findAssociatedTokenPda({\n mint: paymentRequirements.asset as Address,\n owner: paymentRequirements.payTo as Address,\n tokenProgram: tokenProgramAddress,\n });\n\n const transferIx = getTransferCheckedInstruction(\n {\n source: sourceATA,\n mint: paymentRequirements.asset as Address,\n destination: destinationATA,\n authority: this.signer,\n amount: BigInt(paymentRequirements.amount),\n decimals: tokenMint.data.decimals,\n },\n { programAddress: tokenProgramAddress }\n );\n\n const extra = paymentRequirements.extra as PatchedPaymentExtra;\n const feePayer = extra.feePayer;\n\n if (!feePayer) {\n throw new Error(\n 'feePayer is required in paymentRequirements.extra for SVM transactions'\n );\n }\n\n const latestBlockhash = await this.resolveBlockhashLifetime(rpc, extra);\n\n const tx = pipe(\n createTransactionMessage({ version: 0 }),\n tx =>\n setTransactionMessageComputeUnitPrice(\n DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS,\n tx\n ),\n tx => setTransactionMessageFeePayer(feePayer, tx),\n tx =>\n prependTransactionMessageInstruction(\n getSetComputeUnitLimitInstruction({\n units: DEFAULT_COMPUTE_UNIT_LIMIT,\n }),\n tx\n ),\n tx => appendTransactionMessageInstructions([transferIx], tx),\n tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx)\n );\n\n const signedTransaction =\n await partiallySignTransactionMessageWithSigners(tx);\n const base64EncodedWireTransaction =\n getBase64EncodedWireTransaction(signedTransaction);\n\n const payload: ExactSvmPayloadV2 = {\n transaction: base64EncodedWireTransaction,\n };\n\n return {\n x402Version,\n payload,\n };\n }\n\n private async resolveBlockhashLifetime(\n rpc: ReturnType<typeof createRpcClient>,\n extra: PatchedPaymentExtra\n ): Promise<BlockhashLifetime> {\n const providedLastValidBlockHeight = parseLastValidBlockHeight(\n extra.lastValidBlockHeight\n );\n\n if (typeof extra.recentBlockhash === 'string') {\n if (providedLastValidBlockHeight !== undefined) {\n return {\n blockhash: asBlockhash(extra.recentBlockhash),\n lastValidBlockHeight: providedLastValidBlockHeight,\n };\n }\n\n const { value } = await rpc.getLatestBlockhash().send();\n return {\n blockhash: asBlockhash(extra.recentBlockhash),\n lastValidBlockHeight: value.lastValidBlockHeight,\n };\n }\n\n if (\n extra.recentBlockhash &&\n typeof extra.recentBlockhash === 'object' &&\n typeof extra.recentBlockhash.blockhash === 'string'\n ) {\n const lastValidBlockHeight =\n parseLastValidBlockHeight(extra.recentBlockhash.lastValidBlockHeight) ??\n providedLastValidBlockHeight;\n\n if (lastValidBlockHeight !== undefined) {\n return {\n blockhash: asBlockhash(extra.recentBlockhash.blockhash),\n lastValidBlockHeight,\n };\n }\n\n const { value } = await rpc.getLatestBlockhash().send();\n return {\n blockhash: asBlockhash(extra.recentBlockhash.blockhash),\n lastValidBlockHeight: value.lastValidBlockHeight,\n };\n }\n\n return (await rpc.getLatestBlockhash().send()).value;\n }\n}\n","import type { PaymentPolicy } from '@x402/core/client';\n\n/**\n * Maximum deadline (in seconds) we accept for `upto` payment requirements.\n *\n * The `upto` Permit2 signature is bound by `paymentRequirements.maxTimeoutSeconds`,\n * which the SDK passes straight through from the merchant's 402 response with no\n * upper bound. Within that window, the (merchant + facilitator) pair can settle\n * for any amount in `[0, cap]` — and the only on-chain check is the deadline.\n *\n * A long deadline therefore extends the window of facilitator-discretion settlement\n * at the signed cap. 7 days lets a long-running agent keep working without\n * re-signing, but bounds the trust window if a merchant declares an unreasonably\n * large `maxTimeoutSeconds` (accidentally or otherwise).\n *\n * `exact` requirements are unaffected: their amount is fixed in the signature, so\n * a long validity window is just an annoyance, not a discretion surface.\n */\nexport const MAX_UPTO_DEADLINE_SECONDS = 7 * 24 * 60 * 60; // 7 days\n\n/**\n * Caps `maxTimeoutSeconds` on `upto` requirements at {@link MAX_UPTO_DEADLINE_SECONDS}.\n * Leaves `exact` and any other scheme untouched. Pass to `x402Client.fromConfig({ policies })`.\n */\nexport const capUptoDeadline: PaymentPolicy = (_x402Version, requirements) =>\n requirements.map(r =>\n r.scheme === 'upto' && r.maxTimeoutSeconds > MAX_UPTO_DEADLINE_SECONDS\n ? { ...r, maxTimeoutSeconds: MAX_UPTO_DEADLINE_SECONDS }\n : r\n );\n","import { PaymentProtocol } from './types';\n\nexport function detectPaymentProtocols(response: Response): PaymentProtocol[] {\n const protocols: PaymentProtocol[] = [];\n\n const wwwAuth = response.headers.get('WWW-Authenticate');\n if (wwwAuth?.startsWith('Payment')) {\n protocols.push(PaymentProtocol.MPP);\n }\n\n const paymentRequired = response.headers.get('payment-required');\n if (paymentRequired) {\n protocols.push(PaymentProtocol.X402);\n }\n // If we couldn't detect either explicitly, default to x402\n if (protocols.length === 0) {\n protocols.push(PaymentProtocol.X402);\n }\n return protocols;\n}\n","import type { Address } from 'viem';\nimport { formatUnits } from 'viem';\n\nimport { safeFetch, safeReadResponseText } from '@/shared/neverthrow/fetch';\nimport {\n assertTempoUsdc,\n safeGetMppChallenge,\n safeCreateMppCredential,\n safeGetMppReceipt,\n mppErr,\n mppOk,\n} from '@/shared/protocols/mpp';\n\nimport { PaymentProtocol } from '../types';\nimport { Network } from '@agentcash/networks';\nimport { formatUsd } from '@/shared/utils';\n\nimport type { ExecuteFetchResult } from '@/operations/fetch/types';\nimport type { HandlePaymentParams } from '@/shared/protocols/types';\nimport { beforePayment } from '../before-payment';\nimport { handleMppSessionPayment } from './session/handle-session-payment';\n\nexport async function handleMppPayment(params: HandlePaymentParams) {\n const { response, request, options } = params;\n const { surface, wallets } = options;\n const { timeout } = options.params;\n\n // Prevent retry loops\n if (request.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 if (challenge.intent === 'session') {\n return handleMppSessionPayment(challenge, params);\n }\n\n const amount = Number(formatUnits(BigInt(challenge.request.amount), 6));\n const tokenAddress = challenge.request.currency as Address;\n\n const tokenCheck = assertTempoUsdc(surface, tokenAddress);\n if (tokenCheck.isErr()) {\n return tokenCheck;\n }\n\n const beforePaymentResult = await beforePayment({\n options,\n balanceInput: {\n address: wallets.evm.address,\n network: Network.TEMPO,\n tokenAddress,\n },\n amount,\n protocol: PaymentProtocol.MPP,\n });\n\n if (beforePaymentResult.isErr()) {\n return beforePaymentResult;\n }\n\n const credentialResult = await safeCreateMppCredential(\n surface,\n wallets,\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 request.headers.set('Authorization', credential);\n\n // Retry the fetch with the credential\n const paidFetchResult = await safeFetch(surface, request, timeout);\n if (paidFetchResult.isErr()) {\n return paidFetchResult;\n }\n\n const paidResponse = paidFetchResult.value;\n\n // If the server still returns 402, the payment was rejected\n if (paidResponse.status === 402) {\n const body = await safeReadResponseText(surface, paidResponse).unwrapOr('');\n const detail = body ? `: ${body}` : '';\n return mppErr(surface, {\n cause: 'mpp_payment_rejected',\n message: `MPP payment was rejected by the server (402)${detail}`,\n });\n }\n\n // Parse the receipt for transaction hash\n const receiptResult = safeGetMppReceipt(surface, paidResponse);\n\n return mppOk<ExecuteFetchResult>({\n response: paidResponse,\n paymentInfo: {\n protocol: PaymentProtocol.MPP,\n network: Network.TEMPO,\n price: formatUsd(amount),\n payment: receiptResult.isOk()\n ? {\n success: true,\n transactionHash: receiptResult.value.reference,\n }\n : null,\n },\n });\n}\n","import { err, ok } from '@agentcash/neverthrow';\n\nimport { getBalance } from '../balance';\nimport { getDepositLink } from '../utils';\nimport { getSettings } from '../settings';\n\nimport { DEFAULT_MAX_AMOUNT } from '@/operations/fetch/types';\n\nimport type { GetBalanceInput } from '@agentcash/balance';\nimport type { ExecuteFetchOptions } from '@/operations/fetch/types';\nimport type { PaymentProtocol } from './types';\n\ninterface BeforePaymentProps {\n options: ExecuteFetchOptions;\n balanceInput: GetBalanceInput;\n protocol: PaymentProtocol;\n amount: number;\n}\n\nexport const beforePayment = async (props: BeforePaymentProps) => {\n const { options, balanceInput, amount } = props;\n const maxAmount =\n options.params.maxAmount ?? getSettings().maxAmount ?? DEFAULT_MAX_AMOUNT;\n if (amount > maxAmount) {\n return err('before_payment', options.surface, {\n cause: 'amount_exceeds_max_amount' as const,\n message: `Endpoint requested $${amount} which exceeds the maximum allowed amount of $${maxAmount}. Pass a higher maxAmount on this call, or use update_settings to raise the default permanently.`,\n });\n }\n\n const balanceResult = await getBalance(\n options.surface,\n balanceInput,\n options.flags\n );\n\n if (balanceResult.isErr()) {\n return balanceResult;\n }\n\n const balance = balanceResult.value.balance;\n\n if (balance < amount) {\n return err('before_payment', options.surface, {\n cause: 'insufficient_balance' as const,\n message: insufficientBalanceErrorMessage(props, balance),\n });\n }\n\n return ok(true);\n};\n\nconst insufficientBalanceErrorMessage = (\n props: BeforePaymentProps,\n balance: number\n) => {\n const { options, balanceInput, amount } = props;\n return [\n `You are attempting to use an endpoint via ${props.protocol} that costs ${amount} USDC on ${balanceInput.network}.`,\n `Your current balance is ${balance} USDC.`,\n `You can bridge between accounts or deposit at ${getDepositLink(balanceInput.address, options.flags, balanceInput.network)} to top up your balance.`,\n `Before bridging, you can check the users account with npx agentcash@latest accounts or if you are within the MCP, you can use the list_accounts tool.`,\n ].join('\\n');\n};\n","import type { Address } from 'viem';\nimport { formatUnits } from 'viem';\n\nimport { tempo as tempoClient } from 'mppx/client';\n\nimport { Network } from '@agentcash/networks';\n\nimport type { ExecuteFetchResult } from '@/operations/fetch/types';\nimport { formatUsd, tokenStringToNumber } from '@/shared/utils';\n\nimport { beforePayment } from '../../before-payment';\nimport type { HandlePaymentParams } from '../../types';\nimport { PaymentProtocol } from '../../types';\nimport {\n assertTempoUsdc,\n createTempoClient,\n mppOk,\n mppResultFromPromise,\n sessionRequestFailedErr,\n} from '../index';\nimport { runRequestSession } from './run-request-session';\nimport { runStreamingSession } from './run-streaming-session';\nimport type { SessionChallenge } from './types';\nimport {\n USDC_DECIMALS,\n bufferRequestForReplay,\n formatDepositCap,\n resolveDepositUsd,\n} from './utils';\n\nexport async function handleMppSessionPayment(\n challenge: SessionChallenge,\n { request, options }: HandlePaymentParams\n) {\n const { surface, wallets } = options;\n\n const tickCostAtomic = BigInt(challenge.request.amount);\n const tickCostUsd = Number(formatUnits(tickCostAtomic, USDC_DECIMALS));\n const tokenAddress = challenge.request.currency as Address;\n\n const tokenCheck = assertTempoUsdc(surface, tokenAddress);\n if (tokenCheck.isErr()) return tokenCheck;\n\n const depositUsd = resolveDepositUsd(\n challenge.request.suggestedDeposit,\n tickCostUsd,\n options\n );\n\n const beforePaymentResult = await beforePayment({\n options,\n balanceInput: {\n address: wallets.evm.address,\n network: Network.TEMPO,\n tokenAddress,\n },\n amount: depositUsd,\n protocol: PaymentProtocol.MPP,\n });\n if (beforePaymentResult.isErr()) return beforePaymentResult;\n\n const replayInitResult = await mppResultFromPromise(\n surface,\n bufferRequestForReplay(request),\n e =>\n sessionRequestFailedErr(\n e,\n 'Failed to buffer request body for session replay'\n )\n );\n if (replayInitResult.isErr()) return replayInitResult;\n\n const sm = tempoClient.session({\n account: wallets.evm,\n client: createTempoClient(),\n maxDeposit: formatDepositCap(depositUsd),\n decimals: USDC_DECIMALS,\n });\n\n const isStreaming =\n challenge.meta?.streaming === 'true' || options.params.stream === true;\n\n const reuseChannelId = options.params.channelId;\n\n const sessionResult = isStreaming\n ? await runStreamingSession(\n surface,\n sm,\n request.url,\n replayInitResult.value,\n reuseChannelId\n )\n : await runRequestSession(\n surface,\n sm,\n request.url,\n replayInitResult.value,\n reuseChannelId\n );\n if (sessionResult.isErr()) return sessionResult;\n\n const { response: finalResponse, receipt } = sessionResult.value;\n\n const price = receipt\n ? formatUsd(tokenStringToNumber(receipt.spent, USDC_DECIMALS))\n : `from ${formatUsd(tickCostUsd)}/tick`;\n\n return mppOk<ExecuteFetchResult>({\n response: finalResponse,\n paymentInfo: {\n protocol: PaymentProtocol.MPP,\n network: Network.TEMPO,\n price,\n payment: receipt ? { success: true, channelId: receipt.channelId } : null,\n },\n });\n}\n","import { safeReadResponseText } from '@/shared/neverthrow/fetch';\n\nimport {\n mppErr,\n mppOk,\n mppResultFromPromise,\n sessionRequestFailedErr,\n} from '../index';\nimport type { SessionManager, SessionOutcome } from './types';\n\nexport async function runRequestSession(\n surface: string,\n sm: SessionManager,\n url: string,\n init: RequestInit,\n channelId?: string\n) {\n const fetchInit: RequestInit & { context?: { channelId?: string } } = {\n ...init,\n ...(channelId ? { context: { channelId } } : {}),\n };\n const fetchResult = await mppResultFromPromise(\n surface,\n sm.fetch(url, fetchInit),\n e => sessionRequestFailedErr(e)\n );\n if (fetchResult.isErr()) return fetchResult;\n\n const paymentResponse = fetchResult.value;\n\n if (paymentResponse.status === 402) {\n const body = await safeReadResponseText(surface, paymentResponse).unwrapOr(\n ''\n );\n const detail = body ? `: ${body}` : '';\n return mppErr(surface, {\n cause: 'mpp_payment_rejected',\n message: `MPP session payment was rejected by the server (402)${detail}`,\n });\n }\n\n return mppOk<SessionOutcome>({\n response: paymentResponse,\n receipt: paymentResponse.receipt,\n });\n}\n","import { mppErr, mppOk } from '../index';\nimport type { SessionManager, SessionOutcome, SessionReceipt } from './types';\n\nconst MAX_BUFFERED_BYTES = 50 * 1024 * 1024;\n\nexport async function runStreamingSession(\n surface: string,\n sm: SessionManager,\n url: string,\n init: RequestInit,\n channelId?: string\n) {\n let latestReceipt: SessionReceipt | null = null;\n\n const { signal, ...rest } = init;\n const sseResult = await sm.sse(url, {\n ...rest,\n ...(signal ? { signal } : {}),\n ...(channelId ? { context: { channelId } } : {}),\n onReceipt: receipt => {\n latestReceipt = receipt;\n },\n });\n\n const chunks: string[] = [];\n let bytes = 0;\n for await (const chunk of sseResult) {\n bytes += chunk.length;\n chunks.push(chunk);\n if (bytes > MAX_BUFFERED_BYTES) {\n return mppErr(surface, {\n cause: 'mpp_session_response_too_large',\n message: `Streaming response exceeded the ${MAX_BUFFERED_BYTES}-byte buffering cap (got ${bytes} bytes).`,\n });\n }\n }\n\n // mppx's `sm.sse()` yields the `data:` payloads of `message` events\n // (voucher/receipt events are consumed internally), so join with `\\n`\n // to keep object-yielding streams valid NDJSON.\n const response = new Response(chunks.join('\\n'), {\n status: 200,\n headers: {\n 'Content-Type': 'text/plain',\n 'Cache-Control': 'private',\n },\n });\n\n return mppOk<SessionOutcome>({ response, receipt: latestReceipt });\n}\n","import {\n DEFAULT_MAX_AMOUNT,\n type ExecuteFetchOptions,\n} from '@/operations/fetch/types';\nimport { getSettings } from '@/shared/settings';\nimport { tokenStringToNumber } from '@/shared/utils';\n\nexport const USDC_DECIMALS = 6;\nconst DEFAULT_TICK_BUDGET = 10;\n\nexport function resolveDepositUsd(\n suggestedDeposit: string | undefined,\n tickCostUsd: number,\n options: ExecuteFetchOptions\n): number {\n const maxAmount =\n options.params.maxAmount ?? getSettings().maxAmount ?? DEFAULT_MAX_AMOUNT;\n const desired =\n suggestedDeposit !== undefined\n ? tokenStringToNumber(suggestedDeposit, USDC_DECIMALS)\n : tickCostUsd * DEFAULT_TICK_BUDGET;\n return Math.min(desired, maxAmount);\n}\n\n// toFixed rather than toString so very small deposits don't serialize in\n// scientific notation, which viem's parseUnits rejects.\nexport function formatDepositCap(depositUsd: number): string {\n if (!Number.isFinite(depositUsd) || depositUsd <= 0) {\n return '0';\n }\n return depositUsd.toFixed(USDC_DECIMALS);\n}\n\nexport async function bufferRequestForReplay(\n request: Request\n): Promise<RequestInit> {\n const init: RequestInit = {\n method: request.method,\n headers: new Headers(request.headers),\n credentials: request.credentials,\n redirect: request.redirect,\n referrer: request.referrer === '' ? undefined : request.referrer,\n integrity: request.integrity || undefined,\n signal: request.signal,\n };\n\n const hasBody =\n request.method !== 'GET' &&\n request.method !== 'HEAD' &&\n request.body !== null;\n\n if (hasBody) {\n init.body = await request.arrayBuffer();\n }\n\n return init;\n}\n","import { safeGetMppChallenge } from '@/shared/protocols/mpp';\n\nimport { log } from '@/shared/log';\nimport { getBalance } from '@/shared/balance';\nimport { Network } from '@agentcash/networks';\n\nimport { PaymentProtocol } from './types';\n\nimport type { ExecuteFetchOptions } from '@/operations/fetch/types';\n\n/**\n * Pick the preferred protocol by comparing wallet balances.\n * Falls back to 'mpp' if both balances fail to fetch.\n */\nexport async function pickByBalance(\n response: Response,\n options: ExecuteFetchOptions\n): Promise<PaymentProtocol> {\n const { surface, wallets, flags } = options;\n\n // Get x402 (USDC on Base and Solana) balances in parallel\n const x402Balances = await Promise.all([\n getBalance(\n surface,\n {\n address: wallets.evm.address,\n network: Network.BASE,\n },\n flags\n ),\n getBalance(\n surface,\n {\n address: wallets.svm.address,\n network: Network.SOLANA,\n },\n flags\n ),\n ]);\n\n const x402Balance = x402Balances.reduce(\n (acc, balance) => acc + (balance.isOk() ? balance.value.balance : 0),\n 0\n );\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;\n if (currency) {\n const tempoResult = await getBalance(\n surface,\n {\n address: wallets.evm.address,\n network: Network.TEMPO,\n },\n flags\n );\n if (tempoResult.isOk()) {\n mppBalance = tempoResult.value.balance ?? 0;\n }\n }\n }\n\n log.info(`Protocol selection — x402: $${x402Balance}, mpp: $${mppBalance}`);\n return x402Balance >= mppBalance ? PaymentProtocol.X402 : PaymentProtocol.MPP;\n}\n","import { getBalance } from '@/shared/balance';\nimport { caip2ToNetwork, Network, networkToCaip2 } from '@agentcash/networks';\n\nimport type { PaymentRequirements } from '@x402/core/types';\nimport type { ExecuteFetchOptions } from '@/operations/fetch/types';\n\ninterface ChoosePaymentRequirementParams {\n paymentRequirements: PaymentRequirements[];\n options: ExecuteFetchOptions;\n}\n\n// Prefer `upto` over `exact` when a server offers both on the same network.\n// `upto` authorizes a maximum via Permit2 and settles for actual usage, which\n// matches usage-priced endpoints (e.g. per-token LLM inference) better than\n// `exact`, which charges the upper bound regardless. Servers that surface\n// both schemes — like Surplus Intelligence — explicitly recommend preferring\n// `upto`. Falls back to the first match when `upto` isn't offered.\nexport const preferUpto = (\n requirements: PaymentRequirements[]\n): PaymentRequirements | undefined => {\n return requirements.find(pr => pr.scheme === 'upto') ?? requirements[0];\n};\n\nexport const choosePaymentRequirement = async ({\n paymentRequirements,\n options,\n}: ChoosePaymentRequirementParams) => {\n const { surface, wallets, flags } = options;\n const { paymentNetwork } = options.params;\n if (paymentNetwork) {\n const caip2 = networkToCaip2(paymentNetwork);\n return preferUpto(paymentRequirements.filter(pr => pr.network === caip2));\n }\n\n const requirementsWithBalance = await Promise.all(\n paymentRequirements.map(async pr => {\n const network = caip2ToNetwork(pr.network);\n if (network === null) {\n return {\n balance: 0,\n requirement: pr,\n };\n }\n if (network === Network.SOLANA) {\n const balanceResult = await getBalance(\n surface,\n {\n address: wallets.svm.address,\n network,\n },\n flags\n );\n return {\n requirement: pr,\n balance: balanceResult.isOk() ? balanceResult.value.balance : 0,\n };\n } else {\n const balanceResult = await getBalance(\n surface,\n {\n address: wallets.evm.address,\n network,\n },\n flags\n );\n return {\n requirement: pr,\n balance: balanceResult.isOk() ? balanceResult.value.balance : 0,\n };\n }\n })\n );\n const bestNetwork = requirementsWithBalance.sort(\n (a, b) => b.balance - a.balance\n )[0]!.requirement.network;\n return preferUpto(\n paymentRequirements.filter(pr => pr.network === bestNetwork)\n );\n};\n","import { caip2ToNetwork, Network } from '@agentcash/networks';\n\nimport { choosePaymentRequirement } from './choose-payment-requirement';\n\nimport { safeFetch, safeReadResponseText } from '@/shared/neverthrow/fetch';\nimport {\n safeCreatePaymentPayload,\n safeGetPaymentRequired,\n safeGetPaymentSettlement,\n x402Err,\n x402Ok,\n x402ProbeClient,\n} from '@/shared/protocols/x402';\nimport { tokenStringToNumber, formatUsd } from '@/shared/utils';\n\nimport { beforePayment } from '../before-payment';\n\nimport { PaymentProtocol } from '../types';\n\nimport type { ExecuteFetchResult } from '@/operations/fetch/types';\nimport type { HandlePaymentParams } from '../types';\nimport type { BaseX402Error } from './types';\n\nexport const isPermit2AllowanceFailureBody = (body: string): boolean =>\n body.includes('permit2') && body.includes('allowance_required');\n\nexport const buildPermit2AllowanceErrorMessage = (params: {\n walletAddress: string;\n scheme: string;\n}): string => {\n const { walletAddress, scheme } = params;\n return [\n `Payment failed: this endpoint's \\`${scheme}\\` scheme settles via the Permit2 contract, but your agentcash wallet (${walletAddress}) has not approved Permit2 to spend USDC.`,\n '',\n 'The clean fix is server-side. The merchant should adopt the EIP-2612 gas-sponsoring extension — agentcash will then auto-sign an off-chain permit on each call and the facilitator pays the approval gas, with no setup required from the user. See https://docs.x402.org/extensions/eip2612-gas-sponsoring',\n '',\n `Until the merchant adopts that extension, you can do a one-time \\`USDC.approve(0x000000000022D473030F116dDEE9F6B43aC78BA3, MAX_UINT256)\\` on Base from this wallet (requires a small amount of ETH for gas, ~$0.01–0.10). After that, all future Permit2-based payments from this wallet work without further on-chain transactions.`,\n ].join('\\n');\n};\n\nexport async function handleX402Payment({\n response,\n request,\n options,\n}: HandlePaymentParams) {\n const { surface, wallets } = options;\n const { timeout } = options.params;\n\n const paymentRequiredResult = await safeGetPaymentRequired(surface, response);\n\n if (paymentRequiredResult.isErr()) {\n return paymentRequiredResult;\n }\n\n const paymentRequired = paymentRequiredResult.value;\n\n if (paymentRequired.x402Version === 1) {\n return x402Err(surface, {\n cause: 'parse_payment_required' as const,\n message:\n 'This endpoint uses the x402 v1 format, which is not supported by agentcash. Only x402 v2 servers (with an `accepts` array in the Payment-Required header) are supported.',\n });\n }\n\n if (!paymentRequired.accepts || !Array.isArray(paymentRequired.accepts)) {\n return x402Err(surface, {\n cause: 'parse_payment_required' as const,\n message:\n 'This endpoint has a missing or malformed accepts array in the Payment-Required header.',\n });\n }\n\n // Check amount against maxAmount before any payment logic\n const accept = await choosePaymentRequirement({\n options,\n paymentRequirements: paymentRequired.accepts,\n });\n\n if (accept) {\n const amount = tokenStringToNumber(accept.amount);\n\n const typedNetwork = caip2ToNetwork(accept.network)!;\n if (!typedNetwork) {\n return x402Err(surface, {\n cause: 'parse_payment_required' as const,\n message: `Invalid network: ${accept.network}`,\n });\n }\n\n const beforePaymentResult = await beforePayment({\n options,\n balanceInput:\n typedNetwork === Network.SOLANA\n ? {\n address: wallets.svm.address,\n network: Network.SOLANA,\n }\n : {\n address: wallets.evm.address,\n network: typedNetwork,\n },\n amount,\n protocol: PaymentProtocol.X402,\n });\n\n if (beforePaymentResult.isErr()) {\n return beforePaymentResult;\n }\n }\n\n const paymentPayloadResult = await safeCreatePaymentPayload(\n surface,\n wallets,\n paymentRequired,\n accept ? () => accept : undefined\n );\n\n if (paymentPayloadResult.isErr()) {\n return paymentPayloadResult;\n }\n\n const paymentPayload = paymentPayloadResult.value;\n\n const paymentHeaders =\n x402ProbeClient.encodePaymentSignatureHeader(paymentPayload);\n\n if (\n request.headers.has('PAYMENT-SIGNATURE') ||\n request.headers.has('X-PAYMENT')\n ) {\n return x402Err(surface, {\n cause: 'payment_already_attempted',\n message: 'Payment already attempted',\n });\n }\n\n for (const [key, value] of Object.entries(paymentHeaders)) {\n request.headers.set(key, value);\n }\n request.headers.set(\n 'Access-Control-Expose-Headers',\n 'PAYMENT-RESPONSE,X-PAYMENT-RESPONSE'\n );\n\n const paidResult = await safeFetch(surface, request, timeout);\n if (paidResult.isErr()) {\n return paidResult;\n }\n const paidResponse = paidResult.value;\n\n const permit2Error = await detectPermit2AllowanceError(\n surface,\n paidResponse,\n {\n walletAddress: wallets.evm.address,\n scheme: paymentPayload.accepted.scheme,\n }\n );\n if (permit2Error) {\n return x402Err(surface, permit2Error);\n }\n\n const settlementResult = safeGetPaymentSettlement(surface, paidResponse);\n\n const settlement = settlementResult.isOk() ? settlementResult.value : null;\n\n const maxAmount = tokenStringToNumber(paymentPayload.accepted.amount);\n const settledAmount = settlement?.amount\n ? tokenStringToNumber(settlement.amount)\n : null;\n const isUpTo = paymentPayload.accepted.scheme === 'upto';\n\n const price =\n settledAmount != null\n ? formatUsd(settledAmount)\n : isUpTo\n ? `up to ${formatUsd(maxAmount)}`\n : formatUsd(maxAmount);\n\n return x402Ok<ExecuteFetchResult>({\n response: paidResponse,\n paymentInfo: {\n protocol: PaymentProtocol.X402,\n network: caip2ToNetwork(paymentPayload.accepted.network)!,\n price,\n payment: settlement\n ? {\n success: settlement.success,\n transactionHash: settlement.transaction,\n }\n : null,\n },\n });\n}\n\nasync function detectPermit2AllowanceError(\n surface: string,\n response: Response,\n context: { walletAddress: string; scheme: string }\n): Promise<BaseX402Error | null> {\n if (response.ok) {\n return null;\n }\n const body = await safeReadResponseText(surface, response).unwrapOr('');\n if (!isPermit2AllowanceFailureBody(body)) {\n return null;\n }\n return {\n cause: 'permit2_allowance_required',\n message: buildPermit2AllowanceErrorMessage(context),\n };\n}\n","import { detectPaymentProtocols } from '@/shared/protocols/detect';\nimport { handleMppPayment } from '@/shared/protocols/mpp/handle-payment';\nimport { pickByBalance } from '@/shared/protocols/pick';\nimport { PaymentProtocol } from '@/shared/protocols/types';\nimport { handleX402Payment } from '@/shared/protocols/x402/handle-payment';\n\nimport type { ExecuteFetchOptions } from './types';\n\nexport async function executePayment(\n response: Response,\n request: Request,\n options: ExecuteFetchOptions\n) {\n const { paymentProtocol } = options.params;\n\n const params = {\n response,\n request,\n options,\n };\n\n if (paymentProtocol) {\n return handlerMap[paymentProtocol](params);\n }\n\n const available = detectPaymentProtocols(response);\n const preferred =\n available.length === 1\n ? available[0]!\n : await pickByBalance(response, options);\n const fallback =\n available.length > 1\n ? preferred === PaymentProtocol.MPP\n ? PaymentProtocol.X402\n : PaymentProtocol.MPP\n : null;\n\n const fallbackRetryRequest = fallback ? request.clone() : null;\n const result = await handlerMap[preferred](params);\n\n if (result.isErr() && fallback && fallbackRetryRequest) {\n return handlerMap[fallback]({\n ...params,\n request: fallbackRetryRequest,\n });\n }\n\n return result;\n}\n\nconst handlerMap = {\n [PaymentProtocol.MPP]: handleMppPayment,\n [PaymentProtocol.X402]: handleX402Payment,\n};\n","import { fetchErr, fetchOk, safeFetch } from '@/shared/neverthrow/fetch';\nimport { BLACKLISTED_ORIGINS } from '@/shared/origins';\n\nimport { attemptSiwxAuth } from './auth';\nimport { executePayment } from './payment';\n\nimport type { ExecuteFetchOptions } from './types';\nimport { buildRequest } from '@/shared/request/build';\nimport type { RequestInput } from '@/shared/request/types';\n\n/**\n * Executes a request with automatic SIWX authentication and payment handling.\n *\n * 1. Probe the endpoint\n * 2. If 402 with SIWX challenge, retry with SIGN-IN-WITH-X\n * 3. If still 402, execute payment\n */\nexport async function executeFetch(\n input: RequestInput,\n options: ExecuteFetchOptions\n) {\n const request = buildRequest(input, options);\n\n const { surface } = options;\n const { timeout } = options.params;\n\n const blocked = BLACKLISTED_ORIGINS.find(origin =>\n request.url.startsWith(origin)\n );\n if (blocked) {\n return fetchErr(surface, {\n cause: 'network',\n message: `${blocked} is no longer available. This origin has been deprecated.`,\n });\n }\n\n const authRetryRequest = request.clone();\n const paymentRetryRequest = 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 const initialResponse = probeResult.value;\n if (initialResponse.status !== 402) {\n return fetchOk({\n response: initialResponse,\n paymentInfo: null,\n });\n }\n\n const authResult = await attemptSiwxAuth(\n initialResponse,\n authRetryRequest,\n paymentRetryRequest,\n options\n );\n\n if (authResult.isErr()) {\n return authResult;\n }\n\n const latestResponse = authResult.value.response;\n if (latestResponse.status !== 402) {\n return fetchOk({\n response: latestResponse,\n paymentInfo: null,\n });\n }\n\n return executePayment(\n latestResponse,\n authResult.value.paymentRetryRequest,\n options\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,wBAAwB;;;ACQjC,SAAS,YAAY,sBAAsB;AAE3C,SAAS,yBAAyB;AAClC,SAAS,yBAAyB;AAElC,SAAS,sBAAsB;AAC/B,SAAS,qBAAqB;;;ACd9B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAOP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAiBP,SAAS,0BACP,OACoB;AACpB,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO;AAAA,EACT;AAEA,MAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,GAAG;AACvD,WAAO,OAAO,KAAK;AAAA,EACrB;AAEA,MAAI,OAAO,UAAU,YAAY,MAAM,SAAS,GAAG;AACjD,WAAO,OAAO,KAAK;AAAA,EACrB;AAEA,SAAO;AACT;AAEA,SAAS,YAAY,WAAmD;AACtE,SAAO;AACT;AASO,IAAM,wBAAN,MAA2D;AAAA,EAGhE,YACmB,QACA,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BAAmB,QAAQ,MAAM;AACvC,QAAM,sBAAsB,QAAQ,MAAM;AAE1C,QAAM,cAAc,MAAM,UAAU,SAAS,SAAS,OAAO;AAE7D,MAAI,YAAY,MAAM,GAAG;AACvB,WAAO,SAAS,SAAS,YAAY,KAAK;AAAA,EAC5C;AAEA,QAAM,kBAAkB,YAAY;AACpC,MAAI,gBAAgB,WAAW,KAAK;AAClC,WAAO,QAAQ;AAAA,MACb,UAAU;AAAA,MACV,aAAa;AAAA,IACf,CAAC;AAAA,EACH;AAEA,QAAM,aAAa,MAAM;AAAA,IACvB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,MAAI,WAAW,MAAM,GAAG;AACtB,WAAO;AAAA,EACT;AAEA,QAAM,iBAAiB,WAAW,MAAM;AACxC,MAAI,eAAe,WAAW,KAAK;AACjC,WAAO,QAAQ;AAAA,MACb,UAAU;AAAA,MACV,aAAa;AAAA,IACf,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL;AAAA,IACA,WAAW,MAAM;AAAA,IACjB;AAAA,EACF;AACF;","names":["tx","formatUnits","formatUnits"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/commands/try.ts"],"sourcesContent":["import { successResponse, outputAndExit } from '@/cli/output';\n\nimport { discoverResources } from '@/operations/discover';\nimport { getWalletInfo } from '@/operations/wallet';\nimport { getWalletOrExit } from '../lib/get-wallet-or-exit';\n\nimport type { Command } from '@/types';\nimport type { DiscoverResourcesInput } from '@/operations/discover';\n\nconst surface = 'cli:try';\n\nexport const tryCommand: Command<DiscoverResourcesInput> = async args => {\n const wallets = await getWalletOrExit(args);\n\n const discoverResult = await discoverResources(surface, args, {\n flags: args,\n });\n const walletInfo = await getWalletInfo(surface, wallets, args);\n\n const onboardingCta = walletInfo.onboardingCta;\n\n if (!discoverResult.found) {\n const origin =\n 'origin' in discoverResult ? discoverResult.origin : args.url;\n return outputAndExit(\n successResponse({\n ...(onboardingCta\n ? {\n onboardMessage: onboardingCta.message,\n onboardLink: onboardingCta.onboardLink,\n }\n : {}),\n notice: `No endpoints found for ${origin}. The origin may not support x402 or SIWX.`,\n resources: `Browse supported APIs at https://agentcash.dev/resources`,\n }),\n args\n );\n }\n\n // Pick up to 3 sample endpoints (prefer paid)\n const paidEndpoints = discoverResult.endpoints.filter(\n e => e.authMode === 'paid'\n );\n const sampleEndpoints = (\n paidEndpoints.length > 0 ? paidEndpoints : discoverResult.endpoints\n ).slice(0, 3);\n const totalCount = discoverResult.endpoints.length;\n\n const title = discoverResult.info?.title ?? discoverResult.origin;\n const description = discoverResult.info?.description;\n\n const sampleLines = sampleEndpoints.map(e => {\n const price = e.price ? ` (${e.price})` : '';\n return ` - ${e.summary}${price}`;\n });\n\n const originSummary = [\n `${title}${description ? ` — ${description}` : ''}`,\n '',\n 'Sample endpoints:',\n ...sampleLines,\n ...(totalCount > sampleEndpoints.length\n ? [\n ` ...and ${totalCount - sampleEndpoints.length} more. Run \\`npx agentcash discover ${discoverResult.origin}\\` to see all endpoints.`,\n ]\n : []),\n ].join('\\n');\n\n // Call to action using the first paid endpoint\n const firstEndpoint =\n discoverResult.endpoints.find(e => e.authMode === 'paid') ??\n discoverResult.endpoints[0];\n\n let callToAction: string | undefined;\n if (firstEndpoint) {\n const endpointUrl = `${discoverResult.origin}${firstEndpoint.path}`;\n callToAction = [\n `To call your first endpoint:`,\n ` 1. Run \\`npx agentcash check \"${endpointUrl}\"\\` to get the input schema and pricing.`,\n ` 2. Run \\`npx agentcash fetch \"${endpointUrl}\" -m ${firstEndpoint.method}\\` with the required body to make the call.`,\n `If you have the AgentCash MCP installed, you can also call this directly using the check_endpoint_schema and fetch tools.`,\n ].join('\\n');\n }\n\n const modelInstructions = [\n `Present the originSummary to the user, then ask them what they would like to do — e.g. \"What would you like to do with ${title}?\"`,\n ...(onboardingCta\n ? [\n `IMPORTANT: The user has not yet onboarded. Show the onboard link VERBATIM as a clickable URL so the user can click it: ${onboardingCta.onboardLink}`,\n ]\n : []),\n ].join('\\n');\n\n return outputAndExit(\n successResponse({\n ...(onboardingCta\n ? {\n onboardMessage: onboardingCta.message,\n onboardLink: onboardingCta.onboardLink,\n }\n : {}),\n originSummary,\n callToAction,\n modelInstructions,\n }),\n args\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,IAAM,UAAU;AAET,IAAM,aAA8C,OAAM,SAAQ;AACvE,QAAM,UAAU,MAAM,gBAAgB,IAAI;AAE1C,QAAM,iBAAiB,MAAM,kBAAkB,SAAS,MAAM;AAAA,IAC5D,OAAO;AAAA,EACT,CAAC;AACD,QAAM,aAAa,MAAM,cAAc,SAAS,SAAS,IAAI;AAE7D,QAAM,gBAAgB,WAAW;AAEjC,MAAI,CAAC,eAAe,OAAO;AACzB,UAAM,SACJ,YAAY,iBAAiB,eAAe,SAAS,KAAK;AAC5D,WAAO;AAAA,MACL,gBAAgB;AAAA,QACd,GAAI,gBACA;AAAA,UACE,gBAAgB,cAAc;AAAA,UAC9B,aAAa,cAAc;AAAA,QAC7B,IACA,CAAC;AAAA,QACL,QAAQ,0BAA0B,MAAM;AAAA,QACxC,WAAW;AAAA,MACb,CAAC;AAAA,MACD;AAAA,IACF;AAAA,EACF;AAGA,QAAM,gBAAgB,eAAe,UAAU;AAAA,IAC7C,OAAK,EAAE,aAAa;AAAA,EACtB;AACA,QAAM,mBACJ,cAAc,SAAS,IAAI,gBAAgB,eAAe,WAC1D,MAAM,GAAG,CAAC;AACZ,QAAM,aAAa,eAAe,UAAU;AAE5C,QAAM,QAAQ,eAAe,MAAM,SAAS,eAAe;AAC3D,QAAM,cAAc,eAAe,MAAM;AAEzC,QAAM,cAAc,gBAAgB,IAAI,OAAK;AAC3C,UAAM,QAAQ,EAAE,QAAQ,KAAK,EAAE,KAAK,MAAM;AAC1C,WAAO,OAAO,EAAE,OAAO,GAAG,KAAK;AAAA,EACjC,CAAC;AAED,QAAM,gBAAgB;AAAA,IACpB,GAAG,KAAK,GAAG,cAAc,WAAM,WAAW,KAAK,EAAE;AAAA,IACjD;AAAA,IACA;AAAA,IACA,GAAG;AAAA,IACH,GAAI,aAAa,gBAAgB,SAC7B;AAAA,MACE,YAAY,aAAa,gBAAgB,MAAM,uCAAuC,eAAe,MAAM;AAAA,IAC7G,IACA,CAAC;AAAA,EACP,EAAE,KAAK,IAAI;AAGX,QAAM,gBACJ,eAAe,UAAU,KAAK,OAAK,EAAE,aAAa,MAAM,KACxD,eAAe,UAAU,CAAC;AAE5B,MAAI;AACJ,MAAI,eAAe;AACjB,UAAM,cAAc,GAAG,eAAe,MAAM,GAAG,cAAc,IAAI;AACjE,mBAAe;AAAA,MACb;AAAA,MACA,mCAAmC,WAAW;AAAA,MAC9C,mCAAmC,WAAW,QAAQ,cAAc,MAAM;AAAA,MAC1E;AAAA,IACF,EAAE,KAAK,IAAI;AAAA,EACb;AAEA,QAAM,oBAAoB;AAAA,IACxB,+HAA0H,KAAK;AAAA,IAC/H,GAAI,gBACA;AAAA,MACE,0HAA0H,cAAc,WAAW;AAAA,IACrJ,IACA,CAAC;AAAA,EACP,EAAE,KAAK,IAAI;AAEX,SAAO;AAAA,IACL,gBAAgB;AAAA,MACd,GAAI,gBACA;AAAA,QACE,gBAAgB,cAAc;AAAA,QAC9B,aAAa,cAAc;AAAA,MAC7B,IACA,CAAC;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AAAA,IACD;AAAA,EACF;AACF;","names":[]}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|