@aifinpay/mcp 2.0.0-rc.5 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +161 -69
  3. package/bin/aifinpay-mcp.js +115 -67
  4. package/dist/api.d.ts +2 -0
  5. package/dist/api.d.ts.map +1 -0
  6. package/dist/api.js +6 -0
  7. package/dist/api.js.map +1 -0
  8. package/dist/config.d.ts +17 -2
  9. package/dist/config.d.ts.map +1 -1
  10. package/dist/config.js +66 -11
  11. package/dist/config.js.map +1 -1
  12. package/dist/identity.d.ts +9 -0
  13. package/dist/identity.d.ts.map +1 -0
  14. package/dist/identity.js +81 -0
  15. package/dist/identity.js.map +1 -0
  16. package/dist/index.d.ts +3 -6
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +3 -6
  19. package/dist/index.js.map +1 -1
  20. package/dist/payment-state.d.ts +35 -0
  21. package/dist/payment-state.d.ts.map +1 -0
  22. package/dist/payment-state.js +127 -0
  23. package/dist/payment-state.js.map +1 -0
  24. package/dist/safe-fetch.d.ts.map +1 -1
  25. package/dist/safe-fetch.js +73 -19
  26. package/dist/safe-fetch.js.map +1 -1
  27. package/dist/server.d.ts +5 -15
  28. package/dist/server.d.ts.map +1 -1
  29. package/dist/server.js +127 -38
  30. package/dist/server.js.map +1 -1
  31. package/dist/tools/agent-address.d.ts.map +1 -1
  32. package/dist/tools/agent-address.js +5 -4
  33. package/dist/tools/agent-address.js.map +1 -1
  34. package/dist/tools/agent-history.d.ts +58 -0
  35. package/dist/tools/agent-history.d.ts.map +1 -0
  36. package/dist/tools/agent-history.js +141 -0
  37. package/dist/tools/agent-history.js.map +1 -0
  38. package/dist/tools/agent-quota.d.ts.map +1 -1
  39. package/dist/tools/agent-quota.js +3 -1
  40. package/dist/tools/agent-quota.js.map +1 -1
  41. package/dist/tools/{agent-quote.d.ts → dev-payment-quote.d.ts} +10 -12
  42. package/dist/tools/dev-payment-quote.d.ts.map +1 -0
  43. package/dist/tools/dev-payment-quote.js +80 -0
  44. package/dist/tools/dev-payment-quote.js.map +1 -0
  45. package/dist/tools/payable-fetch.d.ts +3 -29
  46. package/dist/tools/payable-fetch.d.ts.map +1 -1
  47. package/dist/tools/payable-fetch.js +231 -109
  48. package/dist/tools/payable-fetch.js.map +1 -1
  49. package/dist/tools/production-control.d.ts +104 -0
  50. package/dist/tools/production-control.d.ts.map +1 -1
  51. package/dist/tools/production-control.js +177 -14
  52. package/dist/tools/production-control.js.map +1 -1
  53. package/dist/tools/supported-chains.d.ts +38 -0
  54. package/dist/tools/supported-chains.d.ts.map +1 -0
  55. package/dist/tools/supported-chains.js +132 -0
  56. package/dist/tools/supported-chains.js.map +1 -0
  57. package/package.json +30 -7
  58. package/skills/SKILL.md +332 -0
  59. package/smithery.yaml +137 -0
  60. package/dist/directory.d.ts +0 -55
  61. package/dist/directory.d.ts.map +0 -1
  62. package/dist/directory.js +0 -56
  63. package/dist/directory.js.map +0 -1
  64. package/dist/tools/agent-call.d.ts +0 -68
  65. package/dist/tools/agent-call.d.ts.map +0 -1
  66. package/dist/tools/agent-call.js +0 -129
  67. package/dist/tools/agent-call.js.map +0 -1
  68. package/dist/tools/agent-claim-self.d.ts +0 -66
  69. package/dist/tools/agent-claim-self.d.ts.map +0 -1
  70. package/dist/tools/agent-claim-self.js +0 -299
  71. package/dist/tools/agent-claim-self.js.map +0 -1
  72. package/dist/tools/agent-quote.d.ts.map +0 -1
  73. package/dist/tools/agent-quote.js +0 -81
  74. package/dist/tools/agent-quote.js.map +0 -1
  75. package/dist/tools/pay-with-split.d.ts +0 -93
  76. package/dist/tools/pay-with-split.d.ts.map +0 -1
  77. package/dist/tools/pay-with-split.js +0 -138
  78. package/dist/tools/pay-with-split.js.map +0 -1
@@ -0,0 +1,80 @@
1
+ export function devPaymentQuoteTool() {
2
+ return {
3
+ name: "dev_payment_quote",
4
+ description: "Inspect the dev paid-content challenge and quote a prepaid batch on Amoy. Checks the requested contract version against the deployed quote. Never signs or broadcasts; a version mismatch is an error, not permission to relabel a contract.",
5
+ inputSchema: {
6
+ type: "object",
7
+ additionalProperties: false,
8
+ properties: {
9
+ contract_version: { type: "string", enum: ["1.2", "1.4"] },
10
+ units: { type: "integer", minimum: 1, default: 1000 },
11
+ },
12
+ required: ["contract_version"],
13
+ },
14
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
15
+ };
16
+ }
17
+ export async function runDevPaymentQuote(ctx, args) {
18
+ const fail = (text) => ({ isError: true, content: [{ type: "text", text }] });
19
+ const version = args.contract_version, units = args.units ?? 1000;
20
+ if (version !== "1.2" && version !== "1.4")
21
+ return fail("Choose contract_version 1.2 or 1.4");
22
+ if (!Number.isSafeInteger(units) || Number(units) < 1)
23
+ return fail("units must be a positive integer");
24
+ if (!ctx.config.devMode || !ctx.config.baseUrl)
25
+ return fail("Configure AIFINPAY_MODE=dev and AIFINPAY_BASE_URL explicitly");
26
+ try {
27
+ const base = ctx.config.baseUrl.replace(/\/+$/, "");
28
+ if (["aifinpay.io", "api.aifinpay.io", "gateway.aifinpay.io"].includes(new URL(base).hostname)) {
29
+ return fail("Dev quotes require a separate dev backend URL");
30
+ }
31
+ const fetchImpl = ctx.agent.inner.fetchImpl;
32
+ const resource = "/v1/dev/paid/data";
33
+ const response = await fetchImpl(`${base}${resource}`);
34
+ if (response.status !== 402)
35
+ return fail(`Dev paid route must return 402; received HTTP ${response.status}`);
36
+ const challenge = (await response.json());
37
+ if (!challenge?.merchant_id || !challenge.accepted_chains?.includes("amoy"))
38
+ return fail("Dev route has no configured Amoy settlement");
39
+ const quoted = await fetchImpl(`${base}/v1/quote`, {
40
+ method: "POST",
41
+ headers: { "content-type": "application/json" },
42
+ body: JSON.stringify({
43
+ merchant_id: challenge.merchant_id,
44
+ resource,
45
+ scope: "exact",
46
+ tier: "standard",
47
+ units,
48
+ payer: ctx.agent.evmAddress,
49
+ }),
50
+ });
51
+ if (!quoted.ok)
52
+ return fail(`Dev quote failed: HTTP ${quoted.status}`);
53
+ const quote = (await quoted.json());
54
+ if (quote.network_mode !== "test" ||
55
+ quote.merchant_id !== challenge.merchant_id ||
56
+ quote.resource !== resource ||
57
+ quote.accepted_chains?.length !== 1 ||
58
+ quote.accepted_chains[0] !== "amoy") {
59
+ return fail("Quote is not bound to this test merchant/resource on Amoy");
60
+ }
61
+ if (quote.settlement_call?.splitter_version !== version)
62
+ return fail(`Requested ${version}; backend advertises ${quote.settlement_call?.splitter_version ?? "no verified version"}. Configure the corresponding dev deployment first.`);
63
+ return {
64
+ content: [
65
+ {
66
+ type: "text",
67
+ text: JSON.stringify({
68
+ quote,
69
+ signing_available: false,
70
+ next_step: "Use a separately verified Amoy executor for this exact deployment; current MCP does not broadcast payments. Keep the quote and transaction reference for receipt recovery.",
71
+ }, null, 2),
72
+ },
73
+ ],
74
+ };
75
+ }
76
+ catch {
77
+ return fail("Dev backend unavailable or returned an invalid response");
78
+ }
79
+ }
80
+ //# sourceMappingURL=dev-payment-quote.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-payment-quote.js","sourceRoot":"","sources":["../../src/tools/dev-payment-quote.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,mBAAmB;IACjC,OAAO;QACL,IAAI,EAAE,mBAAmB;QACzB,WAAW,EACT,8OAA8O;QAChP,WAAW,EAAE;YACX,IAAI,EAAE,QAAQ;YACd,oBAAoB,EAAE,KAAK;YAC3B,UAAU,EAAE;gBACV,gBAAgB,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,EAAE;gBAC1D,KAAK,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE;aACtD;YACD,QAAQ,EAAE,CAAC,kBAAkB,CAAC;SAC/B;QACD,WAAW,EAAE,EAAE,YAAY,EAAE,KAAK,EAAE,eAAe,E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CAAC;QAC3E,CAAC;QACD,IAAI,KAAK,CAAC,eAAe,EAAE,gBAAgB,KAAK,OAAO;YACrD,OAAO,IAAI,CACT,aAAa,OAAO,wBAAwB,KAAK,CAAC,eAAe,EAAE,gBAAgB,IAAI,qBAAqB,qDAAqD,CAClK,CAAC;QACJ,OAAO;YACL,OAAO,EAAE;gBACP;oBACE,IAAI,EAAE,MAAM;oBACZ,IAAI,EAAE,IAAI,CAAC,SAAS,CAClB;wBACE,KAAK;wBACL,iBAAiB,EAAE,KAAK;wBACxB,SAAS,EACP,4KAA4K;qBAC/K,EACD,IAAI,EACJ,CAAC,CACF;iBACF;aACF;SACF,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC,yDAAyD,CAAC,CAAC;IACzE,CAAC;AACH,CAAC"}
@@ -9,49 +9,23 @@ export declare function payableFetchTool(): {
9
9
  type: string;
10
10
  description: string;
11
11
  };
12
- method: {
13
- type: string;
14
- enum: string[];
15
- default: string;
16
- };
17
- body: {
18
- type: string;
19
- description: string;
20
- };
21
- headers: {
22
- type: string;
23
- additionalProperties: {
24
- type: string;
25
- };
26
- description: string;
27
- };
28
12
  max_amount_usd: {
29
13
  type: string;
30
- description: string;
31
- };
32
- facilitator: {
33
- type: string;
14
+ exclusiveMinimum: number;
34
15
  description: string;
35
16
  };
36
17
  };
37
18
  required: string[];
19
+ additionalProperties: boolean;
38
20
  };
39
21
  annotations: {
40
22
  readOnlyHint: boolean;
41
23
  openWorldHint: boolean;
42
24
  destructiveHint: boolean;
43
25
  };
44
- outputSchema: {
45
- type: string;
46
- };
47
26
  };
27
+ /** Never expose bearer receipts, raw signed transactions, or exception response bodies. */
48
28
  export declare function runPayableFetch(ctx: ToolContext, args: Record<string, unknown>): Promise<{
49
- isError: boolean;
50
- content: {
51
- type: string;
52
- text: string;
53
- }[];
54
- } | {
55
29
  content: {
56
30
  type: string;
57
31
  text: string;
@@ -1 +1 @@
1
- {"version":3,"file":"payable-fetch.d.ts","sourceRoot":"","sources":["../../src/tools/payable-fetch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,wBAAgB,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAsD/B;AAED,wBAAsB,eAAe,CACnC,GAAG,EAAE,WAAW,EAChB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;;;;;;;;;;;GA8F9B"}
1
+ {"version":3,"file":"payable-fetch.d.ts","sourceRoot":"","sources":["../../src/tools/payable-fetch.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAIhD,wBAAgB,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;EAoB/B;AAED,2FAA2F;AAC3F,wBAAsB,eAAe,CAAC,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;;;;;GA+NpF"}
@@ -1,135 +1,257 @@
1
+ import { Aifp1SettlementUnsupportedError, parseGatewayUrl } from "@aifinpay/agent";
2
+ import { validatePaymentConfig } from "../config.js";
3
+ import { PaymentStateError } from "../payment-state.js";
1
4
  export function payableFetchTool() {
2
5
  return {
3
6
  name: "payable_fetch",
4
- description: "USE THIS TOOL to fetch any URL that may require payment (HTTP 402). " +
5
- "DO NOT use WebFetch for URLs that might be paid endpoints — WebFetch " +
6
- "cannot sign x402 payment headers and will only see the 402 challenge " +
7
- "without being able to settle it. " +
8
- "Natural-language triggers: 'fetch <paid URL>', 'pay for <url>', " +
9
- "'try this URL — it might be paid', 'pay the 402 and get the response'. " +
10
- "The agent automatically detects the protocol — the AIFP-1 gateway " +
11
- "(gateway.aifinpay.io) or an x402 facilitator (AiFinPay or Coinbase " +
12
- "x402) — pays from the agent's wallet, retries, and returns the response " +
13
- "status, headers, and body. For known " +
14
- "AiFinPay-registered providers (exa, io-net, venice, ...), prefer " +
15
- "`agent_call` instead — it's higher-level and resolves the bridge URL " +
16
- "from the registry.",
7
+ description: "Fetch a GET resource from an owner-approved AiFinPay merchant. Buys a prepaid batch through verified native Polygon v1.4 within owner limits, then reuses its receipt. Pending payments are recovered without sending another transaction. Other payment protocols are unsupported.",
17
8
  inputSchema: {
18
9
  type: "object",
19
10
  properties: {
20
- url: { type: "string", description: "Target URL (https)." },
21
- method: {
22
- type: "string",
23
- enum: ["GET", "POST", "PUT", "PATCH", "DELETE"],
24
- default: "GET",
25
- },
26
- body: {
27
- type: "string",
28
- description: "Request body (string). Set Content-Type via headers if non-JSON.",
29
- },
30
- headers: {
31
- type: "object",
32
- additionalProperties: { type: "string" },
33
- description: "Extra request headers.",
34
- },
11
+ url: { type: "string", description: "HTTPS resource on an owner-configured exact gateway origin." },
35
12
  max_amount_usd: {
36
13
  type: "number",
37
- description: "Refuse to pay if the facilitator wants more than this. " +
38
- "Defaults to AIFINPAY_MAX_USD env or no cap.",
39
- },
40
- facilitator: {
41
- type: "string",
42
- description: "Force a facilitator: 'aifinpay' | 'coinbase-x402'. Default 'auto'.",
14
+ exclusiveMinimum: 0,
15
+ description: "Optional tighter per-payment USD limit; cannot increase the owner's cap.",
43
16
  },
44
17
  },
45
18
  required: ["url"],
19
+ additionalProperties: false,
46
20
  },
47
- // Auto-pays a 402 challenge for an arbitrary URL → write + open-world + irreversible.
48
21
  annotations: { readOnlyHint: false, openWorldHint: true, destructiveHint: true },
49
- outputSchema: { type: "object" },
50
22
  };
51
23
  }
24
+ /** Never expose bearer receipts, raw signed transactions, or exception response bodies. */
52
25
  export async function runPayableFetch(ctx, args) {
53
- const url = String(args.url ?? "");
54
- if (!url)
55
- return errorResult("missing required arg: url");
56
- const method = String(args.method ?? "GET").toUpperCase();
57
- const body = args.body ? String(args.body) : undefined;
58
- const headers = typeof args.headers === "object" && args.headers !== null
59
- ? args.headers
60
- : undefined;
61
- const maxAmountUsd = typeof args.max_amount_usd === "number"
62
- ? args.max_amount_usd
63
- : ctx.config.maxAmountUsd;
64
- const forcedFacilitator = typeof args.facilitator === "string" ? args.facilitator : undefined;
26
+ let state;
65
27
  try {
66
- // Two payment protocols answer a 402 here, and this tool used to speak only
67
- // one of them.
68
- //
69
- // AIFP-1 gateway (gateway.aifinpay.io/{slug}/…): quote → settle on-chain →
70
- // receipt → retry. Lives on the unified agent as fetchPaid().
71
- // x402 facilitators (AiFinPay / Coinbase): the X-PAYMENT header flow, on
72
- // the wrapped Solana-side agent as inner.pay().
73
- //
74
- // Before this, payable_fetch called inner.pay() only, so an MCP agent
75
- // pointed at a gateway URL got stuck on the 402 it could not read — the
76
- // single most common paid surface we run (AIFINP-118 neighbour).
77
- //
78
- // Routing, safe by construction: fetchPaid() is documented to return a
79
- // non-AIFP-1 402 UNTOUCHED and cost nothing, so trying it first can pay an
80
- // AIFP-1 URL but can never mis-pay an x402 one. Anything it hands back still
81
- // 402 falls through to the x402 path. A caller who forces a facilitator has
82
- // stated x402 intent, so skip AIFP-1 entirely for them.
83
- let resp = null;
84
- if (!forcedFacilitator) {
85
- resp = await ctx.agent.fetchPaid(url, { method, body, headers });
86
- if (resp === null) {
87
- // Budget cap hit with on_limit_exceeded="skip" — do NOT then try to pay
88
- // the same call via x402; that would defeat the cap the caller set.
89
- return errorResult("payment skipped: the per-call or daily budget cap was reached " +
90
- "(on_limit_exceeded is set to skip).");
28
+ let maxGasWei;
29
+ try {
30
+ maxGasWei = validatePaymentConfig(ctx.config);
31
+ }
32
+ catch (error) {
33
+ return errorResult(error.message);
34
+ }
35
+ const store = ctx.paymentState;
36
+ if (!store || store.address !== ctx.agent.evmAddress.toLowerCase())
37
+ return errorResult("A persistent matching wallet is required for payments.");
38
+ if (Object.keys(args).some((k) => !["url", "max_amount_usd"].includes(k)))
39
+ return errorResult("Only url and max_amount_usd are supported; no facilitator fallback.");
40
+ if (typeof args.url !== "string")
41
+ return errorResult("url must be an HTTPS resource URL.");
42
+ const url = new URL(args.url);
43
+ if (url.protocol !== "https:" ||
44
+ url.username ||
45
+ url.password ||
46
+ url.hash ||
47
+ !ctx.config.gatewayOrigins.includes(url.origin))
48
+ return errorResult("The URL must use an owner-approved exact HTTPS origin without credentials or fragment.");
49
+ if (args.max_amount_usd !== undefined &&
50
+ (typeof args.max_amount_usd !== "number" || !Number.isFinite(args.max_amount_usd) || args.max_amount_usd <= 0))
51
+ return errorResult("max_amount_usd must be a positive finite amount.");
52
+ const maximum = Math.min(ctx.config.maxAmountUsd, typeof args.max_amount_usd === "number" ? args.max_amount_usd : Infinity);
53
+ const parsed = parseGatewayUrl(url.href, ctx.config.gatewayOrigins, ctx.config.gatewayPathMode);
54
+ return await store.exclusive(async () => {
55
+ state = store.read();
56
+ for (const entry of ctx.agent.aifp1Receipts.list())
57
+ ctx.agent.aifp1Receipts.evict(entry);
58
+ for (const entry of state.receipts)
59
+ ctx.agent.aifp1Receipts.put(entry);
60
+ if (state.pending) {
61
+ const pending = state.pending;
62
+ // Always recover the existing operation first, even if the caller asks
63
+ // for another resource. This method cannot broadcast a transaction.
64
+ const configuredApi = (ctx.config.baseUrl ?? "https://api.aifinpay.io").replace(/\/+$/, "");
65
+ const call = pending.recovery.quote.settlement_call;
66
+ if (pending.recovery.apiBaseUrl.replace(/\/+$/, "") !== configuredApi ||
67
+ (pending.recovery.paymentIssuer ?? configuredApi).replace(/\/+$/, "") !== configuredApi ||
68
+ pending.recovery.quote.payer?.toLowerCase() !== ctx.agent.evmAddress.toLowerCase() ||
69
+ call?.chain !== "polygon" ||
70
+ call.splitter_version !== "1.4" ||
71
+ pending.recovery.asset !== "POL") {
72
+ throw new Error("Pending payment does not match configured wallet/API/native Polygon route");
73
+ }
74
+ const paid = await ctx.agent.recoverPaidPayment(pending.recovery, { paymentIssuer: configuredApi });
75
+ const receipt = {
76
+ site: pending.site,
77
+ merchantId: paid.merchant_id,
78
+ receiptId: paid.receipt_id,
79
+ jwt: paid.receipt,
80
+ scope: paid.scope,
81
+ resource: paid.resource,
82
+ unitQuota: paid.unit_quota,
83
+ remaining: paid.unit_quota,
84
+ expiresAt: Date.parse(paid.expires_at),
85
+ amountUsd: pending.amountUsd,
86
+ };
87
+ if (!Number.isFinite(receipt.expiresAt))
88
+ throw new Error("Invalid recovered receipt expiry");
89
+ ctx.agent.aifp1Receipts.put(receipt);
90
+ state.receipts = ctx.agent.aifp1Receipts.list();
91
+ delete state.pending;
92
+ store.save(state);
91
93
  }
92
- if (resp.status === 402) {
93
- // Not an AIFP-1 gateway 402 — fetchPaid passed it through. Try x402.
94
- resp = null;
94
+ const spent = store.spent24h(state);
95
+ const priorReceiptIds = new Set(state.receipts.map((entry) => entry.receiptId));
96
+ let price;
97
+ try {
98
+ const response = await ctx.agent.fetchPaid(url.href, { method: "GET", redirect: "manual" }, {
99
+ apiBaseUrl: ctx.config.baseUrl,
100
+ paymentIssuer: ctx.config.baseUrl ?? "https://api.aifinpay.io",
101
+ gatewayOrigins: ctx.config.gatewayOrigins,
102
+ resourcePathMode: ctx.config.gatewayPathMode,
103
+ scope: "exact",
104
+ maxAmountUsd: Math.min(maximum, Math.max(0, ctx.config.dailyAmountUsd - spent)),
105
+ nativeUsdPrice: async () => {
106
+ // Independent public price origin, never the quote API's rate.
107
+ const response = await ctx.agent.inner.fetchImpl("https://api.coinbase.com/v2/prices/POL-USD/spot", {
108
+ signal: AbortSignal.timeout(10_000),
109
+ redirect: "manual",
110
+ });
111
+ if (!response.ok)
112
+ throw new Error("Independent native price unavailable");
113
+ const priceBody = await boundedBody(response, 16 * 1024);
114
+ if (priceBody.truncated)
115
+ throw new Error("Independent price response exceeds limit");
116
+ const data = JSON.parse(priceBody.body);
117
+ const usd = Number(data.data?.amount);
118
+ if (data.data?.base !== "POL" || data.data?.currency !== "USD" || !Number.isFinite(usd) || usd <= 0)
119
+ throw new Error("Invalid independent native price");
120
+ price = { usd, observedAtMs: Date.now() };
121
+ return price;
122
+ },
123
+ v14: {
124
+ maxGasWei,
125
+ onPrepared: async (prepared) => {
126
+ if (state.pending)
127
+ throw new Error("A payment is already pending");
128
+ if (!price || Date.now() - price.observedAtMs > 60_000)
129
+ throw new Error("Independent price expired before preparation");
130
+ const native = prepared.quote.native_settlement;
131
+ const usd = Math.max(Number(prepared.quote.amount), (Number(BigInt(native.total_wei)) / 1e18) * price.usd);
132
+ if (!Number.isFinite(usd) ||
133
+ usd <= 0 ||
134
+ usd > maximum ||
135
+ store.spent24h(state) + usd > ctx.config.dailyAmountUsd)
136
+ throw new Error("Owner spending limit reached");
137
+ const site = ctx.config.gatewayPathMode === "direct"
138
+ ? `direct:${JSON.stringify([url.origin, prepared.quote.merchant_id])}`
139
+ : parsed.site;
140
+ state.pending = {
141
+ recovery: {
142
+ apiBaseUrl: prepared.apiBaseUrl,
143
+ quote: prepared.quote,
144
+ txRef: prepared.txRef,
145
+ asset: prepared.asset,
146
+ paymentIssuer: prepared.paymentIssuer,
147
+ },
148
+ serializedTransaction: prepared.serializedTransaction,
149
+ site,
150
+ amountUsd: usd,
151
+ };
152
+ state.spend.push({ at: Date.now(), usd, tx: prepared.txRef });
153
+ // Atomic fsync completes BEFORE the SDK is allowed to broadcast.
154
+ store.save(state);
155
+ },
156
+ },
157
+ });
158
+ if (response === null)
159
+ return errorResult("Payment skipped: owner budget reached.");
160
+ const redact = (value) => {
161
+ for (const entry of ctx.agent.aifp1Receipts.list()) {
162
+ if (entry.jwt)
163
+ value = value.replaceAll(entry.jwt, "[redacted receipt]");
164
+ }
165
+ return value.replace(/\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g, "[redacted token]");
166
+ };
167
+ const headers = {};
168
+ for (const name of ["content-type", "aifp-quota-remaining", "aifp-quota-total"]) {
169
+ const value = response.headers.get(name);
170
+ if (value !== null)
171
+ headers[name] = redact(value);
172
+ }
173
+ const bounded = await boundedBody(response);
174
+ const body = redact(bounded.body);
175
+ const truncated = bounded.truncated;
176
+ return {
177
+ content: [
178
+ {
179
+ type: "text",
180
+ text: JSON.stringify({
181
+ status: response.status,
182
+ ok: response.ok,
183
+ headers,
184
+ body,
185
+ truncated,
186
+ receipts: ctx.agent.getReceiptCacheSummary(),
187
+ }),
188
+ },
189
+ ],
190
+ };
95
191
  }
192
+ finally {
193
+ // Receipt caching precedes content retry in the SDK. Retain it even
194
+ // when that content request fails; never discard already bought access.
195
+ state.receipts = ctx.agent.aifp1Receipts.list();
196
+ if (state.pending &&
197
+ state.receipts.some((entry) => !priorReceiptIds.has(entry.receiptId) &&
198
+ entry.site === state.pending.site &&
199
+ entry.merchantId === state.pending.recovery.quote.merchant_id)) {
200
+ delete state.pending;
201
+ }
202
+ store.save(state);
203
+ }
204
+ });
205
+ }
206
+ catch (error) {
207
+ if (error instanceof PaymentStateError)
208
+ return errorResult(error.message);
209
+ if (!state?.pending && error instanceof Aifp1SettlementUnsupportedError) {
210
+ return errorResult("The merchant must offer a signed native Polygon v1.4 quote. Its current settlement route is unsupported; no legacy or alternate-protocol payment was attempted.");
96
211
  }
97
- if (resp === null) {
98
- resp = await ctx.agent.inner.pay(url, {
99
- method,
100
- body,
101
- headers,
102
- options: { maxAmountUsd, facilitator: forcedFacilitator },
103
- });
212
+ if (!state?.pending && error instanceof Error && error.name === "V14SettlementError") {
213
+ const code = error.code;
214
+ const messages = {
215
+ V14_INSUFFICIENT_BALANCE: "The wallet needs enough POL for the quoted purchase plus the owner-capped gas fee.",
216
+ V14_GAS_BUDGET_EXCEEDED: "Estimated gas exceeds AIFINPAY_MAX_GAS_POL. The owner can review the limit; the agent cannot raise it.",
217
+ V14_PAUSED: "The approved payment deployment is paused. No payment was sent.",
218
+ V14_EXPIRED: "The signed quote expired before submission. Request a fresh quote.",
219
+ V14_EXPIRING: "The signed quote expires too soon to submit safely. Request a fresh quote.",
220
+ V14_STALE_NONCE: "The signed quote uses a stale wallet nonce. Request a fresh quote.",
221
+ };
222
+ return errorResult(messages[code ?? ""] ??
223
+ "Payment verification refused this deployment, signer or quote. The merchant must offer a verified native Polygon v1.4 route; no fallback was attempted.");
224
+ }
225
+ return errorResult(state?.pending
226
+ ? `Payment pending (${state.pending.recovery.txRef}). Its private recovery journal is retained. Retry to recover the receipt; no replacement payment will be submitted. If submission never occurred or reverted, the owner must reconcile the journal.`
227
+ : "Payment request failed before completion. Check owner configuration, wallet, supported route, network and spending limits. No fallback payment was attempted.");
228
+ }
229
+ }
230
+ async function boundedBody(response, limit = 64 * 1024) {
231
+ if (!response.body)
232
+ return { body: "", truncated: false };
233
+ const reader = response.body.getReader();
234
+ const chunks = [];
235
+ let size = 0;
236
+ try {
237
+ while (true) {
238
+ const { done, value } = await reader.read();
239
+ if (done)
240
+ return { body: Buffer.concat(chunks).toString("utf8"), truncated: false };
241
+ const room = limit - size;
242
+ chunks.push(value.subarray(0, room));
243
+ size += Math.min(room, value.length);
244
+ if (value.length > room || size === limit) {
245
+ await reader.cancel();
246
+ return { body: Buffer.concat(chunks).toString("utf8"), truncated: true };
247
+ }
104
248
  }
105
- const respHeaders = {};
106
- resp.headers.forEach((v, k) => (respHeaders[k] = v));
107
- const text = await resp.text();
108
- return {
109
- content: [
110
- {
111
- type: "text",
112
- text: JSON.stringify({
113
- status: resp.status,
114
- ok: resp.ok,
115
- headers: respHeaders,
116
- body: text,
117
- }, null, 2),
118
- },
119
- ],
120
- };
121
249
  }
122
- catch (e) {
123
- const err = e;
124
- return errorResult(`${err.constructor.name}: ${err.message}`, `Tip: ensure agent ${ctx.agent.solanaAddress} has a funded Seat PDA, ` +
125
- `or use the unified \`agent_call\` tool (Polygon settlement). ` +
126
- `Docs: https://aifinpay.io/docs`);
250
+ finally {
251
+ reader.releaseLock();
127
252
  }
128
253
  }
129
- function errorResult(...lines) {
130
- return {
131
- isError: true,
132
- content: lines.map((line) => ({ type: "text", text: line })),
133
- };
254
+ function errorResult(message) {
255
+ return { isError: true, content: [{ type: "text", text: message }] };
134
256
  }
135
257
  //# sourceMappingURL=payable-fetch.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"payable-fetch.js","sourceRoot":"","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