agentcash 0.8.3 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/dist/cjs/run-server.cjs +17 -5
  2. package/dist/esm/chunk-36HB4WY2.js +7 -0
  3. package/dist/esm/{chunk-S5HW6SFM.js → chunk-ECZS3TJG.js} +3 -3
  4. package/dist/esm/{chunk-AFAWW7YZ.js → chunk-F5TWCY6D.js} +2 -2
  5. package/dist/esm/{chunk-4ALGXM6F.js → chunk-LSDMWRFT.js} +2 -2
  6. package/dist/esm/chunk-LSDMWRFT.js.map +1 -0
  7. package/dist/esm/{chunk-W65V5DL2.js → chunk-P6XPLUQA.js} +16 -4
  8. package/dist/esm/chunk-P6XPLUQA.js.map +1 -0
  9. package/dist/esm/{chunk-BDGWC3Y4.js → chunk-R64IV5GT.js} +2 -2
  10. package/dist/esm/{commands-D4LB6MQN.js → commands-JDEJKVYM.js} +8 -8
  11. package/dist/esm/{commands-D4LB6MQN.js.map → commands-JDEJKVYM.js.map} +1 -1
  12. package/dist/esm/index.js +23 -26
  13. package/dist/esm/index.js.map +1 -1
  14. package/dist/esm/{install-3EASO5YD.js → install-HSBNOB2O.js} +3 -3
  15. package/dist/esm/{server-P5FI6GYD.js → server-NSKHFPDM.js} +8 -8
  16. package/dist/esm/{server-P5FI6GYD.js.map → server-NSKHFPDM.js.map} +1 -1
  17. package/dist/esm/shared/operations/index.js +3 -3
  18. package/package.json +3 -3
  19. package/dist/esm/chunk-4ALGXM6F.js.map +0 -1
  20. package/dist/esm/chunk-DKMBMJQA.js +0 -7
  21. package/dist/esm/chunk-W65V5DL2.js.map +0 -1
  22. /package/dist/esm/{chunk-DKMBMJQA.js.map → chunk-36HB4WY2.js.map} +0 -0
  23. /package/dist/esm/{chunk-S5HW6SFM.js.map → chunk-ECZS3TJG.js.map} +0 -0
  24. /package/dist/esm/{chunk-AFAWW7YZ.js.map → chunk-F5TWCY6D.js.map} +0 -0
  25. /package/dist/esm/{chunk-BDGWC3Y4.js.map → chunk-R64IV5GT.js.map} +0 -0
  26. /package/dist/esm/{install-3EASO5YD.js.map → install-HSBNOB2O.js.map} +0 -0
@@ -114005,7 +114005,7 @@ var import_path2 = require("path");
114005
114005
  var import_url = require("url");
114006
114006
  function getVersion2() {
114007
114007
  if (true) {
114008
- return "0.8.3";
114008
+ return "0.8.4";
114009
114009
  }
114010
114010
  const __dirname3 = (0, import_path2.dirname)((0, import_url.fileURLToPath)(importMetaUrl));
114011
114011
  const pkg2 = JSON.parse(
@@ -114168,7 +114168,7 @@ var TEMPO_TOKEN_ADDRESS = "0x20c0000000000000000000000000000000000000";
114168
114168
 
114169
114169
  // src/shared/mpp-enabled.ts
114170
114170
  init_cjs_shims();
114171
- var isMppEnabled = () => "0.8.3".includes("-mpp");
114171
+ var isMppEnabled = () => "0.8.4".includes("-mpp");
114172
114172
 
114173
114173
  // src/shared/operations/fetch-with-payment.ts
114174
114174
  init_cjs_shims();
@@ -115198,6 +115198,18 @@ async function handleX402Payment(surface2, response, clonedRequest, client, befo
115198
115198
  return paymentRequiredResult;
115199
115199
  }
115200
115200
  const paymentRequired = paymentRequiredResult.value;
115201
+ if (paymentRequired.x402Version === 1) {
115202
+ return x402Err(surface2, {
115203
+ cause: "parse_payment_required",
115204
+ message: "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."
115205
+ });
115206
+ }
115207
+ if (!paymentRequired.accepts || !Array.isArray(paymentRequired.accepts)) {
115208
+ return x402Err(surface2, {
115209
+ cause: "parse_payment_required",
115210
+ message: "This endpoint has a missing or malformed accepts array in the Payment-Required header."
115211
+ });
115212
+ }
115201
115213
  const accept = paymentRequired.accepts[0];
115202
115214
  if (accept) {
115203
115215
  const amount2 = tokenStringToNumber(accept.amount);
@@ -115553,7 +115565,7 @@ var ORIGINS = [
115553
115565
  var ORIGIN_METADATA = {
115554
115566
  ["https://stableenrich.dev" /* StableEnrich */]: {
115555
115567
  title: "StableEnrich",
115556
- description: "People/org search, Google Maps, Grok twitter search, Exa web search, LinkedIn data, Firecrawl scrape, WhitePages, email enrichment"
115568
+ description: "People/org search, Google Maps, Exa web search, LinkedIn data, Firecrawl scrape, WhitePages, email enrichment"
115557
115569
  },
115558
115570
  ["https://stablesocial.dev" /* StableSocial */]: {
115559
115571
  title: "StableSocial",
@@ -118005,7 +118017,7 @@ var PROMPT_CONTENT2 = `To start, you should check this resource page: ${"https:/
118005
118017
  - You should use these paid endpoints to find useful information whenever possible.
118006
118018
  - Opt to use the paid endpoints as often as possible, as they speed up your research and provide higher quality information than traditional WebFetch.
118007
118019
 
118008
- - **IMPORTANT:** All the API endpoints below (Exa, Firecrawl, Clado, Google Maps, Apollo, Grok, Whitepages, Hunter) are accessed via mcp__x402__fetch. They are NOT separate MCP tools. Call them like: mcp__x402__fetch(url="${"https://stableenrich.dev" /* StableEnrich */}/api/clado/contacts-enrich", method="POST", body={...})
118020
+ - **IMPORTANT:** All the API endpoints below (Exa, Firecrawl, Clado, Google Maps, Apollo, Whitepages, Hunter) are accessed via mcp__x402__fetch. They are NOT separate MCP tools. Call them like: mcp__x402__fetch(url="${"https://stableenrich.dev" /* StableEnrich */}/api/clado/contacts-enrich", method="POST", body={...})
118009
118021
  - Use the Exa and Firecrawl endpoints as advanced / better WebFetch. They will often return data that would otherwise return only javascript or blocked content.
118010
118022
  - If you get a 403 or error when using WebSearch or WebFetch on a website, try with Exa/Firecrawl endpoints immediately as they likely can get around the blockage.
118011
118023
  - Use the Clado endpoints (/api/clado/contacts-enrich, /api/clado/linkedin-scrape) to enrich information about people and find their linkedin or email addresses. If linkedin returns an error code, immediately try with the Clado endpoints.
@@ -118080,7 +118092,7 @@ var import_path3 = require("path");
118080
118092
  var import_url2 = require("url");
118081
118093
  function getVersion3() {
118082
118094
  if (true) {
118083
- return "0.8.3";
118095
+ return "0.8.4";
118084
118096
  }
118085
118097
  const __dirname3 = (0, import_path3.dirname)((0, import_url2.fileURLToPath)(importMetaUrl));
118086
118098
  const pkg2 = JSON.parse(
@@ -0,0 +1,7 @@
1
+ // src/shared/mpp-enabled.ts
2
+ var isMppEnabled = () => "0.8.4".includes("-mpp");
3
+
4
+ export {
5
+ isMppEnabled
6
+ };
7
+ //# sourceMappingURL=chunk-36HB4WY2.js.map
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  isMppEnabled
3
- } from "./chunk-DKMBMJQA.js";
3
+ } from "./chunk-36HB4WY2.js";
4
4
  import {
5
5
  MCP_VERSION
6
- } from "./chunk-AFAWW7YZ.js";
6
+ } from "./chunk-F5TWCY6D.js";
7
7
  import {
8
8
  getBalance,
9
9
  getBaseUrl,
@@ -138,4 +138,4 @@ export {
138
138
  getWalletInfo,
139
139
  submitErrorReport
140
140
  };
141
- //# sourceMappingURL=chunk-S5HW6SFM.js.map
141
+ //# sourceMappingURL=chunk-ECZS3TJG.js.map
@@ -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.8.3";
7
+ return "0.8.4";
8
8
  }
9
9
  const __dirname2 = dirname(fileURLToPath(import.meta.url));
10
10
  const pkg = JSON.parse(
@@ -19,4 +19,4 @@ export {
19
19
  MCP_VERSION,
20
20
  DIST_TAG
21
21
  };
22
- //# sourceMappingURL=chunk-AFAWW7YZ.js.map
22
+ //# sourceMappingURL=chunk-F5TWCY6D.js.map
@@ -21,7 +21,7 @@ var ORIGINS = [
21
21
  var ORIGIN_METADATA = {
22
22
  ["https://stableenrich.dev" /* StableEnrich */]: {
23
23
  title: "StableEnrich",
24
- description: "People/org search, Google Maps, Grok twitter search, Exa web search, LinkedIn data, Firecrawl scrape, WhitePages, email enrichment"
24
+ description: "People/org search, Google Maps, Exa web search, LinkedIn data, Firecrawl scrape, WhitePages, email enrichment"
25
25
  },
26
26
  ["https://stablesocial.dev" /* StableSocial */]: {
27
27
  title: "StableSocial",
@@ -270,4 +270,4 @@ export {
270
270
  addUserOrigin,
271
271
  removeUserOrigin
272
272
  };
273
- //# sourceMappingURL=chunk-4ALGXM6F.js.map
273
+ //# sourceMappingURL=chunk-LSDMWRFT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/shared/origins.ts","../../src/shared/descriptions.ts","../../src/shared/user-origins.ts"],"sourcesContent":["/**\n * Known x402-protected API origins.\n * Using const enum so values are inlined at build time.\n */\nexport const enum Origin {\n StableEnrich = 'https://stableenrich.dev',\n StableSocial = 'https://stablesocial.dev',\n StableStudio = 'https://stablestudio.dev',\n StableUpload = 'https://stableupload.dev',\n StableEmail = 'https://stableemail.dev',\n X402Scan = 'https://x402scan.com',\n Shirt = 'https://shirt.sh',\n X402Puppet = 'https://x402puppet.com',\n X402Facilitator = 'https://x402facilitator.com',\n}\n\n/**\n * Array of all known origins for iteration.\n * Const enums are erased at compile time, so we need a regular array for runtime iteration.\n */\nexport const ORIGINS = [\n Origin.StableEnrich,\n Origin.StableSocial,\n Origin.StableStudio,\n Origin.StableUpload,\n Origin.StableEmail,\n Origin.X402Scan,\n Origin.Shirt,\n Origin.X402Puppet,\n] as const;\n","/**\n * Single source of truth for all LLM-facing text in the MCP package.\n *\n * `DESCRIPTIONS` covers every tool with both an `mcp` variant (detailed,\n * AI-audience) and a `cli` variant (concise, human-readable for --help).\n * `serverInstructions` is shared across both surfaces.\n *\n * Additional exports cover parameter/output schema descriptions, origin\n * metadata, and prompt content — all LLM-facing text in one place.\n */\n\nimport { Origin } from './origins';\nimport type { UserOrigin } from './user-origins';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Origin metadata (used for MCP resource registration descriptions)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const ORIGIN_METADATA: Record<\n string,\n { title: string; description: string }\n> = {\n [Origin.StableEnrich]: {\n title: 'StableEnrich',\n description:\n 'People/org search, Google Maps, Exa web search, LinkedIn data, Firecrawl scrape, WhitePages, email enrichment',\n },\n [Origin.StableSocial]: {\n title: 'StableSocial',\n description:\n 'Social media data for Twitter, Instagram, TikTok, YouTube, Facebook, Reddit',\n },\n [Origin.StableStudio]: {\n title: 'StableStudio',\n description: 'Generate and edit images and videos',\n },\n [Origin.StableUpload]: {\n title: 'StableUpload',\n description: 'Pay to upload files, get a permanent download URL.',\n },\n [Origin.StableEmail]: {\n title: 'StableEmail',\n description: 'Send emails',\n },\n [Origin.X402Scan]: {\n title: 'X402 Scan',\n description: 'x402 protocol explorer',\n },\n [Origin.Shirt]: {\n title: 'Shirt',\n description: 'Shirt.sh',\n },\n [Origin.X402Puppet]: {\n title: 'X402 Puppet',\n description: 'Browser automation',\n },\n [Origin.X402Facilitator]: {\n title: 'X402 Facilitator',\n description: 'Payment facilitation',\n },\n};\n\nexport const PRIMARY_ORIGINS = [\n Origin.StableEnrich,\n Origin.StableSocial,\n Origin.StableStudio,\n Origin.StableUpload,\n Origin.StableEmail,\n] as const;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Tool descriptions — { mcp, cli } per tool + shared serverInstructions\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const DESCRIPTIONS = {\n fetch: {\n mcp: `HTTP fetch with automatic x402 payment handling. Makes the request and, if the endpoint returns 402, signs payment and retries with payment headers. Returns response data along with payment details (price, tx hash) if a payment was made.\\n\\nFor endpoints you haven't called before in this session, you MUST call check_endpoint_schema first to confirm the request body schema. Skipping this causes 400 errors from wrong field names.`,\n cli: `HTTP fetch with automatic x402 payment handling. If the endpoint returns 402, signs payment and retries — no manual payment steps needed. Run 'check <url>' first to confirm the request body schema; skipping this causes 400 errors from wrong field names.`,\n epilogue: `Workflow: check <url> → fetch <url> -m POST -b '{\"field\":\"value\"}'\\nUse 'fetch-auth' instead if the endpoint requires identity (SIWX) rather than payment.`,\n },\n\n fetchWithAuth: {\n mcp: `HTTP fetch with automatic SIWX (Sign-In With X) authentication. Sends an authenticated request to a SIWX-protected endpoint. Returns response data gated by the endpoint's authentication requirements.\\n\\nFor endpoints you haven't called before in this session, you MUST call check_endpoint_schema first to confirm the request body schema. Skipping this causes 400 errors from wrong field names.`,\n cli: `HTTP fetch with automatic SIWX (Sign-In With X) authentication for identity-gated endpoints. No payment required — the wallet is used as an identity proof only. Run 'check <url>' first to confirm the request body schema; skipping this causes 400 errors from wrong field names.`,\n epilogue: `Workflow: check <url> → fetch-auth <url> -m POST -b '{\"field\":\"value\"}'\\nUse 'fetch' instead if the endpoint requires payment (x402) rather than identity.`,\n },\n\n getWalletInfo: {\n mcp: `Get wallet address and USDC balance. Auto-creates wallet on first use (~/.agentcash/wallet.json). Returns a deposit link if funding is needed. If onboardingCta is present, show its message to the user — it means they haven't onboarded yet and need to either visit the onboard link or deposit directly.`,\n cli: `Get wallet address, USDC balance, and deposit link. Creates the wallet on first use (~/.agentcash/wallet.json). Check this before making paid API calls — if balance is zero, deposit USDC using the returned link.`,\n },\n\n checkEndpointSchema: {\n mcp: [\n `Get the input/output schema and auth mode (paid or SIWX) for a single endpoint.`,\n `Call this to see exactly what fields the request body expects and what the response contains.`,\n `Returns the schema from the origin's OpenAPI spec. Optionally pass sample_input_body to probe the endpoint live (without payment) for an exact price quote — do this when pricing is range-based or quote-based, or when you're unsure about the input schema.`,\n ].join('\\n\\n'),\n cli: `Get the input/output schema and auth mode (paid or SIWX) for an endpoint. Returns exact field names from the OpenAPI spec — call this before 'fetch' or 'fetch-auth' to avoid 400 errors. Pass --body to probe the endpoint live for an exact price quote when pricing is range-based or unclear.`,\n epilogue: `Auth mode tells you which command to use:\\n paid → agentcash fetch <url>\\n SIWX → agentcash fetch-auth <url>`,\n },\n\n discoverApiEndpoints: {\n mcp: [\n `List available endpoints at an API origin. Returns endpoint URLs with descriptions of what each does and the auth mode for each (paid or SIWX). Works with any origin, not just the registered ones.`,\n `Call this when you need to see what routes are available at an origin — whether it's one of the registered origins or any other origin you've identified as useful.`,\n `The response always indicates whether guidance is available. Guidance is documentation published by the API provider explaining how endpoints work together, edge cases, and usage tips. compact guidance is included automatically; set include_guidance=true to force-include full usage documentation when you need to compose two or more endpoints or need clarification on how the origin works.`,\n ].join('\\n\\n'),\n cli: `List available endpoints at an API origin with descriptions and auth modes (paid or SIWX). Works with any origin, not just registered ones. Add --include-guidance for full provider docs when composing multiple endpoints or when usage is unclear.`,\n epilogue: `Registered origins:\\n${PRIMARY_ORIGINS.flatMap(o => (ORIGIN_METADATA[o] ? [` ${o} — ${ORIGIN_METADATA[o].description}`] : [])).join('\\n')}`,\n },\n\n redeemInvite: {\n mcp: `Redeem an invite code for free USDC on Base. One-time use per code. Returns amount received and transaction hash. Use get_wallet_info after to verify balance.`,\n cli: `Redeem an invite code for free USDC on Base. One-time use per code. Run 'wallet info' after to verify the balance landed.`,\n },\n\n try: {\n cli: `Fetch a new origin for its resources and return a prompt guiding the user through the process of calling the first endpoint.`,\n },\n\n reportError: {\n mcp: `EMERGENCY ONLY. Report critical MCP tool bugs. Do NOT use for normal errors (balance, network, 4xx) — those are recoverable.`,\n cli: `Report a critical bug to the agentcash team (emergency only). Do NOT use for normal errors like low balance, network timeouts, or 4xx responses — those are recoverable without filing a report.`,\n },\n\n updateSettings: {\n mcp: `Update user settings (persisted to ~/.agentcash/settings.json). Currently supports maxAmount — the maximum USD amount allowed per fetch request. If a fetch response requests more than this, the payment is rejected. Returns the current settings after applying changes.`,\n },\n\n getSettings: {\n mcp: `Get current user settings. Returns persisted values from ~/.agentcash/settings.json with defaults applied.`,\n },\n} as const;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Dynamic server instructions (includes user-added origins at runtime)\n// ─────────────────────────────────────────────────────────────────────────────\n\nconst WORKFLOW = [\n `Workflow:`,\n `1. If you don't already know your balance, call get_wallet_info. You need a balance for paid endpoints — if it's zero, share the deposit link with the user. SIWX endpoints don't require a balance. You don't need to call this every turn, just before your first paid call or whenever you're unsure.`,\n `2. Call discover_api_endpoints() to get the endpoint index — a list of available routes with descriptions and auth modes. The auth mode for each endpoint tells you whether to use fetch (paid) or fetch_with_auth (SIWX).`,\n `3. Call check_endpoint_schema() to get the exact input/output schema and auth mode for the endpoint you want to call, so you know what fields to pass and what the response contains. Both discover_api_endpoints and check_endpoint_schema return the auth mode.`,\n `4. Call fetch (paid) or fetch_with_auth (SIWX) based on the auth mode, and with the correct input schema.`,\n].join('\\n');\n\nexport function buildServerInstructions(\n userOrigins: UserOrigin[] = []\n): string {\n const allOrigins = [\n ...userOrigins.map(o => ` - ${o.url} — ${o.description}`),\n ...PRIMARY_ORIGINS.flatMap(o =>\n ORIGIN_METADATA[o] ? [` - ${o} — ${ORIGIN_METADATA[o].description}`] : []\n ),\n ].join('\\n');\n\n return [\n `AgentCash lets you call protected APIs — handling both x402 micropayments and SIWX authentication seamlessly. It manages a USDC wallet for paid endpoints (fetch) and signs wallet proofs for identity-gated endpoints (fetch_with_auth).`,\n `The user has installed agentcash because they want to use paid and SIWX-protected APIs as their preferred way to accomplish related tasks.`,\n `Paid endpoints require a wallet balance. SIWX endpoints are free — they only require a wallet identity.`,\n `If a task could be accomplished by one of these registered origins, run the workflow below:\\n${allOrigins}`,\n `discover_api_endpoints also works with any origin beyond this list. If you identify another origin that would be useful for a task, you can use it.`,\n WORKFLOW,\n `If you need to compose multiple endpoints in sequence, or anything about the origin's capabilities is unclear, call discover_api_endpoints with include_guidance=true to retrieve the origin's full usage documentation.`,\n ].join('\\n\\n');\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Shared request schema parameter descriptions\n// (used by fetch, fetch_with_auth tools)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const REQUEST_PARAMS = {\n url: 'The endpoint URL',\n method: 'HTTP method. Defaults to GET for fetch operations.',\n body: 'Request body for POST/PUT/PATCH methods',\n headers: 'Additional headers to include',\n timeout: 'Request timeout in milliseconds',\n} as const;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Per-tool parameter and output schema descriptions\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const TOOL_PARAMS = {\n fetch: {\n paymentMethod: 'Payment protocol to use. Defaults to auto-detect.',\n maxAmount:\n 'Maximum amount (in USD) to pay per request. Aborts if the endpoint requests more. Defaults to $5. Pass a higher value for known-expensive endpoints.',\n },\n\n checkEndpointSchema: {\n url: 'Full URL of the endpoint to inspect',\n method:\n 'HTTP method to check. If omitted, all methods declared in the spec are returned.',\n sampleInputBody:\n 'Optional. A sample request body to probe the endpoint live (without payment) for exact pricing. Use when pricing is range-based or quote-based, or when you need to verify the input schema. Omit to get the static schema and advisory pricing from the spec.',\n headers: 'Additional headers to include in the probe request',\n },\n\n getWalletInfo: {\n output: {\n address: 'Wallet address (0x...)',\n balance: 'Total USDC balance across all chains',\n chains: 'Balance breakdown by chain',\n isNewWallet: 'Whether the wallet is new and needs to be funded',\n depositLink: 'Link to deposit USDC directly into the wallet',\n onboardingCta:\n 'Present when the user has not yet redeemed an invite code. Show the message to the user — it directs them to onboard or deposit.',\n onboardingCtaOnboardLink: 'Link to the onboarding page',\n onboardingCtaDepositLink: 'Link to deposit USDC directly',\n onboardingCtaMessage: 'Human-readable CTA to show the user',\n message: 'Warning if balance is low',\n chain: 'Chain name',\n chainBalance: 'USDC balance on this chain',\n },\n },\n\n redeemInvite: {\n code: 'The invite code',\n output: {\n amount: 'Amount with unit (e.g., \"5 USDC\")',\n txHash: 'Transaction hash on Base',\n },\n },\n\n discoverApiEndpoints: {\n url: 'The origin URL to discover endpoints on (e.g. https://stableenrich.dev)',\n includeGuidance:\n \"Request the origin's usage guidance. true=always include, false=never include, omit=auto (included when compact). Guidance explains how to compose multiple endpoints and covers edge cases.\",\n },\n\n reportError: {\n tool: 'MCP tool name',\n resource: 'Resource URL',\n summary: '1-2 sentence summary',\n errorMessage: 'Error message',\n stack: 'Stack trace',\n fullReport: 'Detailed report with context, logs, repro steps',\n output: {\n reportId: 'Unique report ID for tracking',\n message: 'Confirmation message',\n },\n },\n} as const;\n","import * as fs from 'fs';\n\nimport z from 'zod';\n\nimport { configFile } from './fs';\nimport { safeParseJson } from './neverthrow/json';\n\nconst ORIGINS_FILE = configFile('origins.json');\n\nconst userOriginSchema = z.object({\n url: z.string(),\n title: z.string(),\n description: z.string(),\n addedAt: z.string(),\n});\n\nconst originsFileSchema = z.object({\n added: z.array(userOriginSchema),\n});\n\nexport type UserOrigin = z.infer<typeof userOriginSchema>;\n\nfunction readOriginsFile(): UserOrigin[] {\n if (!fs.existsSync(ORIGINS_FILE)) return [];\n const raw = fs.readFileSync(ORIGINS_FILE, 'utf-8');\n const json = safeParseJson('user-origins', raw);\n if (!json.isOk()) return [];\n const parsed = originsFileSchema.safeParse(json.value);\n return parsed.success ? parsed.data.added : [];\n}\n\nfunction writeOriginsFile(origins: UserOrigin[]): void {\n fs.writeFileSync(\n ORIGINS_FILE,\n JSON.stringify({ added: origins }, null, 2),\n 'utf-8'\n );\n}\n\nexport function loadUserOrigins(): UserOrigin[] {\n return readOriginsFile();\n}\n\nexport function addUserOrigin(origin: Omit<UserOrigin, 'addedAt'>): UserOrigin {\n const origins = readOriginsFile();\n const entry: UserOrigin = { ...origin, addedAt: new Date().toISOString() };\n const existing = origins.findIndex(o => o.url === origin.url);\n if (existing >= 0) {\n origins[existing] = entry;\n } else {\n origins.push(entry);\n }\n writeOriginsFile(origins);\n return entry;\n}\n\nexport function removeUserOrigin(url: string): { removed: boolean } {\n const origins = readOriginsFile();\n const filtered = origins.filter(o => o.url !== url);\n if (filtered.length === origins.length) return { removed: false };\n writeOriginsFile(filtered);\n return { removed: true };\n}\n"],"mappings":";;;;;;;;AAoBO,IAAM,UAAU;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;ACXO,IAAM,kBAGT;AAAA,EACF,8CAAoB,GAAG;AAAA,IACrB,OAAO;AAAA,IACP,aACE;AAAA,EACJ;AAAA,EACA,8CAAoB,GAAG;AAAA,IACrB,OAAO;AAAA,IACP,aACE;AAAA,EACJ;AAAA,EACA,8CAAoB,GAAG;AAAA,IACrB,OAAO;AAAA,IACP,a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,OAAO,QAAQ,GAAG,MAAM,CAAC;AAAA,IAC1C;AAAA,EACF;AACF;AAEO,SAAS,kBAAgC;AAC9C,SAAO,gBAAgB;AACzB;AAEO,SAAS,cAAc,QAAiD;AAC7E,QAAM,UAAU,gBAAgB;AAChC,QAAM,QAAoB,EAAE,GAAG,QAAQ,UAAS,oBAAI,KAAK,GAAE,YAAY,EAAE;AACzE,QAAM,WAAW,QAAQ,UAAU,OAAK,EAAE,QAAQ,OAAO,GAAG;AAC5D,MAAI,YAAY,GAAG;AACjB,YAAQ,QAAQ,IAAI;AAAA,EACtB,OAAO;AACL,YAAQ,KAAK,KAAK;AAAA,EACpB;AACA,mBAAiB,OAAO;AACxB,SAAO;AACT;AAEO,SAAS,iBAAiB,KAAmC;AAClE,QAAM,UAAU,gBAAgB;AAChC,QAAM,WAAW,QAAQ,OAAO,OAAK,EAAE,QAAQ,GAAG;AAClD,MAAI,SAAS,WAAW,QAAQ,OAAQ,QAAO,EAAE,SAAS,MAAM;AAChE,mBAAiB,QAAQ;AACzB,SAAO,EAAE,SAAS,KAAK;AACzB;","names":[]}
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  REQUEST_PARAMS
3
- } from "./chunk-4ALGXM6F.js";
3
+ } from "./chunk-LSDMWRFT.js";
4
4
  import {
5
5
  getTempoBalance
6
- } from "./chunk-S5HW6SFM.js";
6
+ } from "./chunk-ECZS3TJG.js";
7
7
  import {
8
8
  isMppEnabled
9
- } from "./chunk-DKMBMJQA.js";
9
+ } from "./chunk-36HB4WY2.js";
10
10
  import {
11
11
  getBalance
12
12
  } from "./chunk-B2JUF6FK.js";
@@ -333,6 +333,18 @@ async function handleX402Payment(surface, response, clonedRequest, client, befor
333
333
  return paymentRequiredResult;
334
334
  }
335
335
  const paymentRequired = paymentRequiredResult.value;
336
+ if (paymentRequired.x402Version === 1) {
337
+ return x402Err(surface, {
338
+ cause: "parse_payment_required",
339
+ message: "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."
340
+ });
341
+ }
342
+ if (!paymentRequired.accepts || !Array.isArray(paymentRequired.accepts)) {
343
+ return x402Err(surface, {
344
+ cause: "parse_payment_required",
345
+ message: "This endpoint has a missing or malformed accepts array in the Payment-Required header."
346
+ });
347
+ }
336
348
  const accept = paymentRequired.accepts[0];
337
349
  if (accept) {
338
350
  const amount = tokenStringToNumber(accept.amount);
@@ -587,4 +599,4 @@ export {
587
599
  getInputSchema,
588
600
  createFetchWithAuth
589
601
  };
590
- //# sourceMappingURL=chunk-W65V5DL2.js.map
602
+ //# sourceMappingURL=chunk-P6XPLUQA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/server/tools/lib/request.ts","../../src/shared/neverthrow/x402/index.ts","../../src/shared/neverthrow/mpp/index.ts","../../src/shared/protocol.ts","../../src/shared/settings.ts","../../src/shared/operations/fetch-with-payment.ts","../../src/shared/token.ts","../../src/server/lib/x402-extensions.ts","../../src/shared/operations/fetch-with-auth.ts"],"sourcesContent":["import z from 'zod';\n\nimport type { Address } from 'viem';\n\nimport { REQUEST_PARAMS } from '@/shared/descriptions';\n\nexport const requestSchema = z.object({\n url: z.string().describe(REQUEST_PARAMS.url),\n method: z\n .enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH'])\n .optional()\n .describe(REQUEST_PARAMS.method),\n body: z.unknown().optional().describe(REQUEST_PARAMS.body),\n headers: z\n .record(z.string(), z.string())\n .optional()\n .describe(REQUEST_PARAMS.headers)\n .default({}),\n timeout: z\n .number()\n .int()\n .positive()\n .optional()\n .describe(REQUEST_PARAMS.timeout),\n});\n\ninterface BuildRequestProps {\n input: z.infer<typeof requestSchema>;\n address?: Address;\n sessionId?: string;\n provider?: string;\n}\n\nexport const buildRequest = ({\n input,\n address,\n sessionId,\n provider,\n}: BuildRequestProps) => {\n return new Request(input.url, {\n method: input.method ?? 'GET',\n body: input.body\n ? typeof input.body === 'string'\n ? input.body\n : JSON.stringify(input.body)\n : undefined,\n headers: {\n ...(input.body ? { 'Content-Type': 'application/json' } : {}),\n ...input.headers,\n ...(address\n ? { 'X-Wallet-Address': address, 'X-Client-ID': provider }\n : {}),\n ...(sessionId ? { 'X-Session-ID': sessionId } : {}),\n },\n });\n};\n","import {\n err,\n ok,\n resultFromPromise,\n resultFromThrowable,\n} from '@agentcash/neverthrow';\nimport { createSIWxPayload } from '@x402/extensions/sign-in-with-x';\n\nimport type { BaseX402Error } from './types';\nimport type { x402HTTPClient } from '@x402/core/http';\nimport type { PaymentRequired } from '@x402/core/types';\nimport type { CompleteSIWxInfo } from '@x402/extensions/sign-in-with-x';\nimport type { PrivateKeyAccount } from 'viem';\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 safeGetPaymentRequired = (\n surface: string,\n client: x402HTTPClient,\n response: Response\n) => {\n return x402ResultFromPromise(\n surface,\n response.json().then(\n json =>\n client.getPaymentRequiredResponse(\n name => response.headers.get(name),\n json\n ),\n () =>\n client.getPaymentRequiredResponse(name => response.headers.get(name))\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 safeCreatePaymentPayload = (\n surface: string,\n client: x402HTTPClient,\n paymentRequired: PaymentRequired\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 client: x402HTTPClient,\n response: Response\n) => {\n return x402ResultFromThrowable(\n surface,\n () => client.getPaymentSettleResponse(name => response.headers.get(name)),\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 signer: PrivateKeyAccount\n) => {\n return x402ResultFromPromise(\n surface,\n createSIWxPayload(serverInfo, signer),\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 { Challenge, Receipt } from 'mppx';\nimport {\n err,\n ok,\n resultFromPromise,\n resultFromThrowable,\n} from '@agentcash/neverthrow';\n\nimport type { BaseMppError } from './types';\nconst errorType = 'mpp';\n\nexport const mppOk = <T>(value: T) => ok(value);\nexport const mppErr = (surface: string, error: BaseMppError) =>\n err(errorType, surface, error);\n\nconst mppResultFromPromise = <T>(\n surface: string,\n promise: Promise<T>,\n error: (e: unknown) => BaseMppError\n) => resultFromPromise(errorType, surface, promise, error);\n\nconst mppResultFromThrowable = <T>(\n surface: string,\n fn: () => T,\n error: (e: unknown) => BaseMppError\n) => resultFromThrowable(errorType, surface, fn, error);\n\nexport const safeGetMppChallenge = (surface: string, response: Response) => {\n return mppResultFromThrowable(\n surface,\n () => Challenge.fromResponse(response),\n error => ({\n cause: 'parse_mpp_challenge',\n message:\n error instanceof Error\n ? error.message\n : 'Failed to parse MPP challenge from response',\n })\n );\n};\n\nexport const safeCreateMppCredential = (\n surface: string,\n mppxClient: { createCredential: (response: Response) => Promise<string> },\n response: Response\n) => {\n return mppResultFromPromise(\n surface,\n mppxClient.createCredential(response),\n error => ({\n cause: 'create_mpp_credential',\n message:\n error instanceof Error\n ? error.message\n : 'Failed to create MPP credential',\n })\n );\n};\n\nexport const safeGetMppReceipt = (surface: string, response: Response) => {\n return mppResultFromThrowable(\n surface,\n () => Receipt.fromResponse(response),\n error => ({\n cause: 'parse_mpp_receipt',\n message:\n error instanceof Error\n ? error.message\n : 'Failed to parse MPP receipt from response',\n })\n );\n};\n","import { isMppEnabled } from '@/shared/mpp-enabled';\n\nexport type PaymentProtocol = 'x402' | 'mpp';\n\n/**\n * Detects all payment protocols present in a 402 response.\n * MPP responses include a `WWW-Authenticate` header starting with \"Payment\".\n * x402 responses include a `payment-required` header.\n * If neither is explicitly detected, defaults to x402.\n *\n * MPP detection is gated behind {@link isMppEnabled} so it never surfaces\n * in agent context on the `latest` dist-tag.\n */\nexport function detectPaymentProtocols(response: Response): PaymentProtocol[] {\n const protocols: PaymentProtocol[] = [];\n if (isMppEnabled()) {\n const wwwAuth = response.headers.get('WWW-Authenticate');\n if (wwwAuth?.startsWith('Payment')) {\n protocols.push('mpp');\n }\n }\n const paymentRequired = response.headers.get('payment-required');\n if (paymentRequired) {\n protocols.push('x402');\n }\n // If we couldn't detect either explicitly, default to x402\n if (protocols.length === 0) {\n protocols.push('x402');\n }\n return protocols;\n}\n\n/**\n * Convenience: returns the first/preferred protocol from a 402 response.\n * Useful when a single protocol must be chosen (e.g. for payment).\n */\nexport function detectPaymentProtocol(response: Response): PaymentProtocol {\n return detectPaymentProtocols(response)[0]!;\n}\n","import z from 'zod';\nimport fs from 'fs';\n\nimport { configFile } from './fs';\n\nconst SETTINGS_FILE = configFile('settings.json');\n\nconst settingsSchema = z\n .looseObject({\n maxAmount: z.number().positive(),\n })\n .partial();\n\nexport type Settings = z.infer<typeof settingsSchema>;\n\nexport const getSettings = (): Settings => {\n if (!fs.existsSync(SETTINGS_FILE)) {\n return {};\n }\n\n const content = fs.readFileSync(SETTINGS_FILE, 'utf-8');\n const result = settingsSchema.safeParse(JSON.parse(content));\n if (!result.success) {\n return {};\n }\n return result.data;\n};\n\nexport const setSettings = (settings: Settings) => {\n const existing = getSettings();\n const newSettings = settingsSchema.parse({ ...existing, ...settings });\n fs.writeFileSync(SETTINGS_FILE, JSON.stringify(newSettings, null, 2));\n};\n","import { formatUnits } from 'viem';\n\nimport type { x402HTTPClient } from '@x402/core/client';\nimport type { Address } from 'viem';\nimport type { GlobalFlags } from '@/types';\n\nimport { resultFromPromise } from '@agentcash/neverthrow';\n\nimport { fetchErr, fetchOk, safeFetch } from '@/shared/neverthrow/fetch';\nimport {\n safeCreatePaymentPayload,\n safeGetPaymentRequired,\n safeGetPaymentSettlement,\n x402Err,\n x402Ok,\n} from '@/shared/neverthrow/x402';\nimport {\n safeGetMppChallenge,\n safeCreateMppCredential,\n safeGetMppReceipt,\n mppErr,\n mppOk,\n} from '@/shared/neverthrow/mpp';\n\nimport { log } from '@/shared/log';\nimport { detectPaymentProtocols } from '@/shared/protocol';\nimport { tokenStringToNumber } from '@/shared/token';\nimport { getBalance } from '@/shared/balance';\nimport { getTempoBalance } from '@/shared/tempo-balance';\nimport { getSettings } from '@/shared/settings';\n\n/**\n * Hook called before a payment is executed.\n * Throw to abort. Return to proceed.\n * Matches existing checkBalance/checkTempoBalance throw-to-abort behavior.\n */\nexport type BeforePaymentHook = (ctx: {\n protocol: 'x402' | 'mpp';\n amount: number;\n currency: string;\n network: string;\n}) => Promise<void>;\n\nexport interface PaymentClients {\n x402: x402HTTPClient;\n mpp: { createCredential: (response: Response) => Promise<string> };\n}\n\nexport interface PaymentInfo {\n protocol: 'x402' | 'mpp';\n price?: string;\n payment?: {\n success: boolean;\n transactionHash?: string;\n };\n}\n\nexport interface FetchWithPaymentResult {\n response: Response;\n paymentInfo: PaymentInfo | null;\n}\n\n/** Default max amount (in USD/USDC) allowed without explicit opt-in. */\nexport const DEFAULT_MAX_AMOUNT = 5;\n\nexport interface FetchWithPaymentOptions {\n surface: string;\n clients: PaymentClients;\n paymentMethod: 'x402' | 'mpp' | 'auto';\n account: { address: Address };\n flags: GlobalFlags;\n beforePayment?: BeforePaymentHook;\n timeout?: number;\n /**\n * Maximum amount (in USD/USDC) to pay without aborting.\n * Protects against endpoints that inflate prices in their 402 response.\n * Defaults to DEFAULT_MAX_AMOUNT ($1).\n */\n maxAmount?: number;\n}\n\n/**\n * Create a fetch function with automatic dual-protocol payment handling.\n *\n * 1. Makes initial request\n * 2. If 402 response, detects protocol(s)\n * 3. Calls beforePayment hook (for balance checks)\n * 4. Creates payment credential/payload\n * 5. Retries request with payment headers\n */\nexport function createFetchWithPayment(options: FetchWithPaymentOptions) {\n const { surface, clients, paymentMethod, beforePayment, timeout, maxAmount } =\n options;\n const effectiveMaxAmount =\n maxAmount ?? getSettings().maxAmount ?? DEFAULT_MAX_AMOUNT;\n\n return async (request: Request) => {\n const clonedRequest = request.clone();\n const fallbackRequest = request.clone();\n\n const probeResult = await safeFetch(surface, request, timeout);\n\n if (probeResult.isErr()) {\n return fetchErr(surface, probeResult.error);\n }\n\n // Not a 402 response — return as-is\n if (probeResult.value.status !== 402) {\n return probeResult.andThen(response =>\n fetchOk<FetchWithPaymentResult>({ response, paymentInfo: null })\n );\n }\n\n const response = probeResult.value;\n\n // User explicitly chose a protocol — use that, no fallback\n if (paymentMethod !== 'auto') {\n if (paymentMethod === 'mpp') {\n return handleMppPayment(\n surface,\n response,\n clonedRequest,\n options,\n effectiveMaxAmount\n );\n }\n return handleX402Payment(\n surface,\n response,\n clonedRequest,\n clients.x402,\n beforePayment,\n timeout,\n effectiveMaxAmount\n );\n }\n\n // Auto: detect available protocols, pick by higher balance\n const available = detectPaymentProtocols(response);\n\n let preferred: 'x402' | 'mpp';\n\n if (available.length === 1) {\n preferred = available[0]!;\n } else {\n // Both protocols available — pick by balance\n preferred = await pickByBalance(surface, response, options);\n }\n\n const fallback =\n available.length > 1 ? (preferred === 'mpp' ? 'x402' : 'mpp') : null;\n\n const result =\n preferred === 'mpp'\n ? await handleMppPayment(\n surface,\n response,\n clonedRequest,\n options,\n effectiveMaxAmount\n )\n : await handleX402Payment(\n surface,\n response,\n clonedRequest,\n clients.x402,\n beforePayment,\n timeout,\n effectiveMaxAmount\n );\n\n if (result.isErr() && fallback) {\n // Preferred failed — try fallback with a fresh request clone\n return fallback === 'mpp'\n ? handleMppPayment(\n surface,\n response,\n fallbackRequest,\n options,\n effectiveMaxAmount\n )\n : handleX402Payment(\n surface,\n response,\n fallbackRequest,\n clients.x402,\n beforePayment,\n timeout,\n effectiveMaxAmount\n );\n }\n\n return result;\n };\n}\n\n/**\n * Pick the preferred protocol by comparing wallet balances.\n * Falls back to 'mpp' if both balances fail to fetch.\n */\nasync function pickByBalance(\n surface: string,\n response: Response,\n options: FetchWithPaymentOptions\n): Promise<'x402' | 'mpp'> {\n const { account, flags } = options;\n\n // Get x402 (USDC on Base) balance\n const x402BalanceResult = await resultFromPromise(\n 'balance',\n surface,\n getBalance({\n address: account.address,\n surface,\n dev: flags.dev,\n }).then(r => (r.isOk() ? r.value.balance : 0)),\n () => ({\n cause: 'x402_balance' as const,\n message: 'Failed to get x402 balance',\n })\n );\n\n if (x402BalanceResult.isErr()) {\n log.debug('Balance comparison failed, defaulting to mpp');\n return 'mpp';\n }\n\n const x402Balance = x402BalanceResult.value;\n\n // Get MPP (Tempo) balance — need token address from the challenge\n let mppBalance = 0;\n const challengeResult = safeGetMppChallenge(surface, response);\n if (challengeResult.isOk()) {\n const currency = challengeResult.value.request.currency as\n | string\n | undefined;\n const decimals =\n (challengeResult.value.request.decimals as number | undefined) ?? 6;\n if (currency) {\n const tempoResult = await resultFromPromise(\n 'tempo',\n surface,\n getTempoBalance({\n address: account.address,\n tokenAddress: currency as Address,\n }),\n () => ({\n cause: 'tempo_balance' as const,\n message: 'Tempo balance check failed',\n })\n );\n if (tempoResult.isOk()) {\n mppBalance = Number(formatUnits(tempoResult.value.balance, decimals));\n }\n }\n }\n\n log.info(`Protocol selection — x402: $${x402Balance}, mpp: $${mppBalance}`);\n return x402Balance >= mppBalance ? 'x402' : 'mpp';\n}\n\nasync function handleX402Payment(\n surface: string,\n response: Response,\n clonedRequest: Request,\n client: x402HTTPClient,\n beforePayment: BeforePaymentHook | undefined,\n timeout: number | undefined,\n maxAmount: number\n) {\n const paymentRequiredResult = await safeGetPaymentRequired(\n surface,\n client,\n response\n );\n\n if (paymentRequiredResult.isErr()) {\n return paymentRequiredResult;\n }\n\n const paymentRequired = paymentRequiredResult.value;\n\n if (\n paymentRequired.x402Version === 1\n ) {\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: '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 = paymentRequired.accepts[0];\n if (accept) {\n const amount = tokenStringToNumber(accept.amount);\n if (amount > maxAmount) {\n return x402Err(surface, {\n cause: 'payment_already_attempted' 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\n // Call beforePayment hook (e.g. balance check) before signing\n if (beforePayment) {\n if (accept) {\n const amount = tokenStringToNumber(accept.amount);\n const hookResult = await resultFromPromise(\n 'x402',\n surface,\n beforePayment({\n protocol: 'x402',\n amount,\n currency: 'USDC',\n network: accept.network,\n }),\n e => ({\n cause: 'payment_already_attempted' as const,\n message:\n e instanceof Error ? e.message : 'Before-payment hook failed',\n })\n );\n if (hookResult.isErr()) {\n return x402Err(surface, hookResult.error);\n }\n }\n }\n\n const paymentPayloadResult = await safeCreatePaymentPayload(\n surface,\n client,\n paymentRequired\n );\n\n if (paymentPayloadResult.isErr()) {\n return paymentPayloadResult;\n }\n\n const paymentPayload = paymentPayloadResult.value;\n\n // Encode payment header\n const paymentHeaders = client.encodePaymentSignatureHeader(paymentPayload);\n\n // Check if this is already a retry to prevent infinite loops\n if (\n clonedRequest.headers.has('PAYMENT-SIGNATURE') ||\n clonedRequest.headers.has('X-PAYMENT')\n ) {\n return x402Err(surface, {\n cause: 'payment_already_attempted',\n message: 'Payment already attempted',\n });\n }\n\n // Add payment headers to cloned request\n for (const [key, value] of Object.entries(paymentHeaders)) {\n clonedRequest.headers.set(key, value);\n }\n clonedRequest.headers.set(\n 'Access-Control-Expose-Headers',\n 'PAYMENT-RESPONSE,X-PAYMENT-RESPONSE'\n );\n\n // Retry the request with payment\n return await safeFetch(surface, clonedRequest, timeout).andThen(\n paidResponse => {\n const settlementResult = safeGetPaymentSettlement(\n surface,\n client,\n paidResponse\n );\n\n return x402Ok<FetchWithPaymentResult>({\n response: paidResponse,\n paymentInfo: {\n protocol: 'x402',\n price: tokenStringToNumber(\n paymentPayload.accepted.amount\n ).toLocaleString('en-US', {\n style: 'currency',\n currency: 'USD',\n }),\n ...(settlementResult.isOk()\n ? {\n payment: {\n success: settlementResult.value.success,\n transactionHash: settlementResult.value.transaction,\n },\n }\n : {}),\n },\n });\n }\n );\n}\n\nasync function handleMppPayment(\n surface: string,\n response: Response,\n clonedRequest: Request,\n options: FetchWithPaymentOptions,\n maxAmount: number\n) {\n const { clients, beforePayment, timeout } = options;\n const mppxClient = clients.mpp;\n\n // Prevent retry loops\n if (clonedRequest.headers.has('Authorization')) {\n return mppErr(surface, {\n cause: 'mpp_payment_already_attempted',\n message: 'MPP payment already attempted',\n });\n }\n\n // Parse the challenge from the WWW-Authenticate header\n const challengeResult = safeGetMppChallenge(surface, response);\n\n if (challengeResult.isErr()) {\n return challengeResult;\n }\n\n const challenge = challengeResult.value;\n\n // Extract payment info from challenge request\n const amount = challenge.request.amount as string | undefined;\n const decimals = (challenge.request.decimals as number | undefined) ?? 6;\n const currency = challenge.request.currency as string | undefined;\n\n // Check amount against maxAmount before any payment logic\n if (amount) {\n const numericAmount = Number(formatUnits(BigInt(amount), decimals));\n if (numericAmount > maxAmount) {\n return mppErr(surface, {\n cause: 'mpp_payment_already_attempted' as const,\n message: `Endpoint requested $${numericAmount} 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\n // Call beforePayment hook (e.g. balance check)\n if (beforePayment && amount && currency) {\n const numericAmount = Number(formatUnits(BigInt(amount), decimals));\n const hookResult = await resultFromPromise(\n 'mpp',\n surface,\n beforePayment({\n protocol: 'mpp',\n amount: numericAmount,\n currency,\n network: `tempo:${challenge.method}`,\n }),\n e => ({\n cause: 'mpp_payment_already_attempted' as const,\n message: e instanceof Error ? e.message : 'Before-payment hook failed',\n })\n );\n if (hookResult.isErr()) {\n return mppErr(surface, hookResult.error);\n }\n }\n\n // Create credential (signs transaction on Tempo)\n const credentialResult = await safeCreateMppCredential(\n surface,\n mppxClient,\n response\n );\n\n if (credentialResult.isErr()) {\n return credentialResult;\n }\n\n const credential = credentialResult.value;\n\n // Set Authorization header on cloned request\n clonedRequest.headers.set('Authorization', credential);\n\n // Retry the fetch with the credential\n return await safeFetch(surface, clonedRequest, timeout).andThen(\n paidResponse => {\n // Parse the receipt for transaction hash\n const receiptResult = safeGetMppReceipt(surface, paidResponse);\n\n const priceDisplay = amount\n ? Number(formatUnits(BigInt(amount), decimals)).toLocaleString(\n 'en-US',\n {\n style: 'currency',\n currency: 'USD',\n }\n )\n : undefined;\n\n return mppOk<FetchWithPaymentResult>({\n response: paidResponse,\n paymentInfo: {\n protocol: 'mpp',\n ...(priceDisplay ? { price: priceDisplay } : {}),\n ...(receiptResult.isOk()\n ? {\n payment: {\n success: true,\n transactionHash: receiptResult.value.reference,\n },\n }\n : {}),\n },\n });\n }\n );\n}\n","import { formatUnits } from 'viem';\n\nexport const tokenStringToNumber = (amount: string, decimals = 6) => {\n return Number(formatUnits(BigInt(amount), decimals));\n};\n","import type { PaymentRequired } from '@x402/core/types';\nimport type { DiscoveryExtension } from '@x402/extensions/bazaar';\nimport type {\n CompleteSIWxInfo,\n SIWxExtensionInfo,\n SupportedChain,\n} from '@x402/extensions/sign-in-with-x';\n\nconst getBazaarExtension = (extensions: PaymentRequired['extensions']) => {\n const { bazaar } = extensions ?? {};\n\n if (!bazaar) {\n return undefined;\n }\n\n return bazaar as DiscoveryExtension;\n};\n\nexport const getInputSchema = (extensions: PaymentRequired['extensions']) =>\n getBazaarExtension(extensions)?.schema.properties.input;\n\nexport const getSiwxExtension = (\n extensions: PaymentRequired['extensions']\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 // Pick the first EVM chain from supportedChains, falling back to defaults\n const chain = siwx.supportedChains?.find(c =>\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","import { x402Client, x402HTTPClient } from '@x402/core/client';\nimport { encodeSIWxHeader } from '@x402/extensions/sign-in-with-x';\n\nimport type { PrivateKeyAccount } from 'viem';\n\nimport {\n DEFAULT_USER_FETCH_TIMEOUT,\n fetchOk,\n safeFetch,\n} from '@/shared/neverthrow/fetch';\nimport {\n safeCreateSIWxPayload,\n safeGetPaymentRequired,\n} from '@/shared/neverthrow/x402';\nimport { getSiwxExtension } from '@/server/lib/x402-extensions';\n\nexport type FetchWithAuthResult =\n | { outcome: 'response'; response: Response; authenticated: boolean }\n | { outcome: 'no_siwx_extension'; extensions: string[] };\n\nexport interface FetchWithAuthOptions {\n surface: string;\n account: PrivateKeyAccount;\n timeout?: number;\n}\n\n/**\n * Create a fetch function with automatic SIWX (Sign-In With X) authentication.\n *\n * 1. Makes initial request\n * 2. If 402, parses for SIWX extension\n * 3. Creates signed wallet proof\n * 4. Retries with SIGN-IN-WITH-X header\n *\n * Returns a discriminated result:\n * - `outcome: 'response'` — a Response (authenticated or not), consumer handles ok/error\n * - `outcome: 'no_siwx_extension'` — 402 without SIWX, consumer decides how to present\n */\nexport function createFetchWithAuth(options: FetchWithAuthOptions) {\n const { surface, account, timeout = DEFAULT_USER_FETCH_TIMEOUT } = options;\n\n return async (request: Request) => {\n const retryRequest = request.clone();\n const httpClient = new x402HTTPClient(new x402Client());\n\n const firstResult = await safeFetch(surface, request, timeout);\n\n if (firstResult.isErr()) return firstResult;\n\n const firstResponse = firstResult.value;\n\n if (firstResponse.status !== 402) {\n return fetchOk<FetchWithAuthResult>({\n outcome: 'response',\n response: firstResponse,\n authenticated: false,\n });\n }\n\n const paymentRequiredResult = await safeGetPaymentRequired(\n surface,\n httpClient,\n firstResponse\n );\n\n if (paymentRequiredResult.isErr()) return paymentRequiredResult;\n\n const paymentRequired = paymentRequiredResult.value;\n const siwxExtension = getSiwxExtension(paymentRequired.extensions);\n\n if (!siwxExtension) {\n return fetchOk<FetchWithAuthResult>({\n outcome: 'no_siwx_extension',\n extensions: Object.keys(paymentRequired.extensions ?? {}),\n });\n }\n\n const payloadResult = await safeCreateSIWxPayload(\n surface,\n siwxExtension,\n account\n );\n\n if (payloadResult.isErr()) return payloadResult;\n\n const siwxHeader = encodeSIWxHeader(payloadResult.value);\n\n retryRequest.headers.set('SIGN-IN-WITH-X', siwxHeader);\n\n return (await safeFetch(surface, retryRequest, timeout)).andThen(response =>\n fetchOk<FetchWithAuthResult>({\n outcome: 'response',\n response,\n authenticated: true,\n })\n );\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,OAAO;AAMP,IAAM,gBAAgB,EAAE,OAAO;AAAA,EACpC,KAAK,EAAE,OAAO,EAAE,SAAS,eAAe,GAAG;AAAA,EAC3C,QAAQ,EACL,KAAK,CAAC,OAAO,QAAQ,OAAO,UAAU,OAAO,CAAC,EAC9C,SAAS,EACT,SAAS,eAAe,MAAM;AAAA,EACjC,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,eAAe,IAAI;AAAA,EACzD,SAAS,EACN,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,EAC7B,SAAS,EACT,SAAS,eAAe,OAAO,EAC/B,QAA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,kBAAkB,UAAU;AAErD,YAAQ,MAAM,UAAU,SAAS,cAAc,OAAO,GAAG;AAAA,MAAQ,cAC/D,QAA6B;AAAA,QAC3B,SAAS;AAAA,QACT;AAAA,QACA,eAAe;AAAA,MACjB,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["errorType","z","z","formatUnits","response","formatUnits"]}
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-KAEAFW3A.js";
4
4
  import {
5
5
  DIST_TAG
6
- } from "./chunk-AFAWW7YZ.js";
6
+ } from "./chunk-F5TWCY6D.js";
7
7
  import {
8
8
  wait
9
9
  } from "./chunk-DZNSJ2BA.js";
@@ -596,4 +596,4 @@ export {
596
596
  tryAddServer,
597
597
  addServer
598
598
  };
599
- //# sourceMappingURL=chunk-BDGWC3Y4.js.map
599
+ //# sourceMappingURL=chunk-R64IV5GT.js.map
@@ -9,21 +9,21 @@ import {
9
9
  getSettings,
10
10
  requestSchema,
11
11
  setSettings
12
- } from "./chunk-W65V5DL2.js";
12
+ } from "./chunk-P6XPLUQA.js";
13
13
  import {
14
14
  ORIGIN_METADATA,
15
15
  PRIMARY_ORIGINS,
16
16
  addUserOrigin,
17
17
  loadUserOrigins,
18
18
  removeUserOrigin
19
- } from "./chunk-4ALGXM6F.js";
19
+ } from "./chunk-LSDMWRFT.js";
20
20
  import {
21
21
  TEMPO_RPC_URL,
22
22
  getOnboardingCta,
23
23
  getWalletInfo,
24
24
  submitErrorReport
25
- } from "./chunk-S5HW6SFM.js";
26
- import "./chunk-DKMBMJQA.js";
25
+ } from "./chunk-ECZS3TJG.js";
26
+ import "./chunk-36HB4WY2.js";
27
27
  import {
28
28
  checkEndpoint,
29
29
  discoverResources
@@ -31,11 +31,11 @@ import {
31
31
  import {
32
32
  getPlatformPath,
33
33
  tryAddServer
34
- } from "./chunk-BDGWC3Y4.js";
34
+ } from "./chunk-R64IV5GT.js";
35
35
  import "./chunk-KAEAFW3A.js";
36
36
  import {
37
37
  MCP_VERSION
38
- } from "./chunk-AFAWW7YZ.js";
38
+ } from "./chunk-F5TWCY6D.js";
39
39
  import "./chunk-DZNSJ2BA.js";
40
40
  import {
41
41
  DEFAULT_NETWORK,
@@ -1029,7 +1029,7 @@ async function serverCommand(flags) {
1029
1029
  "MCP server started. If you meant to explore the CLI, run: npx agentcash --help\n"
1030
1030
  );
1031
1031
  }
1032
- const { startServer } = await import("./server-P5FI6GYD.js");
1032
+ const { startServer } = await import("./server-NSKHFPDM.js");
1033
1033
  await startServer(flags);
1034
1034
  }
1035
1035
 
@@ -1743,4 +1743,4 @@ export {
1743
1743
  walletInfoCommand,
1744
1744
  walletRedeemCommand
1745
1745
  };
1746
- //# sourceMappingURL=commands-D4LB6MQN.js.map
1746
+ //# sourceMappingURL=commands-JDEJKVYM.js.map