@haven_ai/sdk 0.1.32-alpha.0 → 0.1.34-alpha.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.
package/dist/index.js CHANGED
@@ -615,6 +615,7 @@ function normalizePaymentRequired(value) {
615
615
  const resourceUrl = candidate.resource?.url ?? first.resource;
616
616
  if (!resourceUrl) return null;
617
617
  const resource = {
618
+ ...candidate.resource && typeof candidate.resource === "object" ? candidate.resource : {},
618
619
  url: resourceUrl,
619
620
  description: candidate.resource?.description ?? first.description,
620
621
  mimeType: candidate.resource?.mimeType ?? first.mimeType
@@ -665,6 +666,41 @@ var NETWORK_TOKENS = {
665
666
  "eip155:84532": BASE_SEPOLIA_TOKENS,
666
667
  "base-sepolia": BASE_SEPOLIA_TOKENS
667
668
  };
669
+ var X402_PAYMENT_HEADER_NAME = "PAYMENT-SIGNATURE";
670
+ var X402_LEGACY_PAYMENT_HEADER_NAME = "X-PAYMENT";
671
+ var X402_PAYMENT_REQUIRED_HEADER_NAME = "PAYMENT-REQUIRED";
672
+ var X402_PAYMENT_RESPONSE_HEADER_NAME = "PAYMENT-RESPONSE";
673
+ var X402_PAYMENT_HEADER_NAMES_SENT = `${X402_PAYMENT_HEADER_NAME}, ${X402_LEGACY_PAYMENT_HEADER_NAME}`;
674
+ var X402_PAYMENT_HEADER_NAMES = [
675
+ X402_PAYMENT_HEADER_NAME,
676
+ X402_LEGACY_PAYMENT_HEADER_NAME
677
+ ];
678
+ function x402PaymentHeaderNamesFor(paymentHeader) {
679
+ const both = [X402_PAYMENT_HEADER_NAME, X402_LEGACY_PAYMENT_HEADER_NAME];
680
+ let decoded;
681
+ try {
682
+ decoded = decodeBase64Json(paymentHeader);
683
+ } catch {
684
+ return both;
685
+ }
686
+ const accepted = decoded?.accepted;
687
+ if (!accepted || typeof accepted !== "object" || Array.isArray(accepted)) return both;
688
+ return isErc7710Option(accepted) ? [X402_PAYMENT_HEADER_NAME] : both;
689
+ }
690
+ function x402PaymentHeaderNamesSent(paymentHeader) {
691
+ return x402PaymentHeaderNamesFor(paymentHeader).join(", ");
692
+ }
693
+ function x402V2PaymentEnvelope(paymentRequired, accepted, payload) {
694
+ const resource = paymentRequired.resource;
695
+ const extensions = paymentRequired.extensions;
696
+ return {
697
+ x402Version: paymentRequired.x402Version,
698
+ ...resource && typeof resource === "object" && !Array.isArray(resource) ? { resource } : {},
699
+ accepted,
700
+ payload,
701
+ ...extensions && typeof extensions === "object" && !Array.isArray(extensions) ? { extensions } : {}
702
+ };
703
+ }
668
704
  function parsePaymentRequired(response) {
669
705
  const v2Header = response.headers.get("PAYMENT-REQUIRED");
670
706
  if (v2Header) {
@@ -844,7 +880,15 @@ async function validateStandardX402PaymentHeader(paymentHeader, context) {
844
880
  throw new Error("context");
845
881
  }
846
882
  } else {
847
- if (!hasOnlyKeys(decoded, ["x402Version", "accepted", "payload"])) throw new Error("shape");
883
+ if (!hasOnlyKeys(decoded, ["x402Version", "accepted", "payload"], ["resource", "extensions"])) {
884
+ throw new Error("shape");
885
+ }
886
+ if ("resource" in decoded && (!decoded.resource || typeof decoded.resource !== "object" || Array.isArray(decoded.resource))) {
887
+ throw new Error("shape");
888
+ }
889
+ if ("extensions" in decoded && (!decoded.extensions || typeof decoded.extensions !== "object" || Array.isArray(decoded.extensions))) {
890
+ throw new Error("shape");
891
+ }
848
892
  const accepted = selectStandardPaymentOption([decoded.accepted]);
849
893
  if (!accepted || !matchesHeaderContext(accepted, context)) throw new Error("context");
850
894
  }
@@ -896,8 +940,8 @@ async function validateStandardX402PaymentHeader(paymentHeader, context) {
896
940
  throw new X402PaymentHeaderValidationError();
897
941
  }
898
942
  }
899
- function hasOnlyKeys(value, allowed) {
900
- return Object.keys(value).every((key) => allowed.includes(key)) && allowed.every((key) => key in value);
943
+ function hasOnlyKeys(value, required, optional = []) {
944
+ return Object.keys(value).every((key) => required.includes(key) || optional.includes(key)) && required.every((key) => key in value);
901
945
  }
902
946
  function sameAddress2(left, right) {
903
947
  return left.toLowerCase() === right.toLowerCase();
@@ -1155,7 +1199,7 @@ function nextActionForStatus(status) {
1155
1199
  if (status === "submitted") return AgentPaymentNextAction.CheckStatusLater;
1156
1200
  if (status === "confirmed") return AgentPaymentNextAction.None;
1157
1201
  if (status === "pending" || status === "pending_approval") return AgentPaymentNextAction.StopAndTellUser;
1158
- if (status === "approved") return AgentPaymentNextAction.WaitForUserToCompletePayment;
1202
+ if (status === "approved") return AgentPaymentNextAction.StopAndTellUser;
1159
1203
  if (status === "proposed") return AgentPaymentNextAction.StopAndTellUser;
1160
1204
  if (status === "executed") return AgentPaymentNextAction.StopAndTellUser;
1161
1205
  if (status === "rejected") return AgentPaymentNextAction.StopAndTellUser;
@@ -1167,6 +1211,9 @@ function messageForState(label, status, paymentId, nextAction) {
1167
1211
  if (status === "pending" || status === "pending_approval") {
1168
1212
  return `${label} is not payable: it is outside the agent's on-chain budget and no approval is pending (payment_id: ${paymentId}). Ask the user to grant or raise the budget in Haven.`;
1169
1213
  }
1214
+ if (status === "approved") {
1215
+ return `This payment carries a retired status ("approved") that no live Haven rail produces (payment_id: ${paymentId}). Nothing is waiting to be completed \u2014 tell the user to review this payment in Haven.`;
1216
+ }
1170
1217
  if (status === "executed") {
1171
1218
  return `This payment carries a retired status ("executed") that no live Haven rail produces (payment_id: ${paymentId}). Do not retry it \u2014 tell the user to review this payment in Haven.`;
1172
1219
  }
@@ -1384,10 +1431,37 @@ var McpMerchantTransport = class {
1384
1431
  hasBazaarExtension(response) {
1385
1432
  return responseHasBazaarExtension(response);
1386
1433
  }
1387
- /** Deliver an already-signed x402 header without changing the caller body. */
1434
+ /**
1435
+ * Deliver an already-signed x402 header without changing the caller body.
1436
+ *
1437
+ * #2289: x402 v2 reads `PAYMENT-SIGNATURE`; v1 reads `X-PAYMENT`. Sending
1438
+ * only the legacy name meant a strict v2 merchant never saw the header —
1439
+ * indistinguishable, from the merchant's side, from sending no header at
1440
+ * all, while on the EIP-3009 bridge the funding leg had already moved the
1441
+ * money.
1442
+ *
1443
+ * #2341: WHICH names go on is per-payload, not always both — see
1444
+ * `x402PaymentHeaderNamesFor`. Both for EIP-3009; `PAYMENT-SIGNATURE` alone
1445
+ * for erc7710, whose header carries a whole delegation chain and answered
1446
+ * HTTP 431 when duplicated. The decision is made here rather than by the
1447
+ * caller so every path inherits it, and it is read from the payload rather
1448
+ * than passed in, because a flag a caller supplies is a flag a caller can
1449
+ * get wrong.
1450
+ *
1451
+ * Always `set`, never `append`, so a stale header on the caller's `init` is
1452
+ * replaced rather than added to — a merchant that reads the first of two
1453
+ * values would otherwise verify a superseded authorization. The name NOT
1454
+ * being sent is deleted for the same reason: on erc7710 a stale `X-PAYMENT`
1455
+ * left in place would be a superseded authorization we chose not to
1456
+ * overwrite, which is worse than the duplicate this change removes.
1457
+ */
1388
1458
  async deliverPayment(url, init, paymentHeader) {
1389
1459
  const headers = new Headers(init?.headers);
1390
- headers.set("X-PAYMENT", paymentHeader);
1460
+ const send = x402PaymentHeaderNamesFor(paymentHeader);
1461
+ for (const name of X402_PAYMENT_HEADER_NAMES) {
1462
+ if (send.includes(name)) headers.set(name, paymentHeader);
1463
+ else headers.delete(name);
1464
+ }
1391
1465
  return this.fetch(url, { ...init, headers });
1392
1466
  }
1393
1467
  async notifyInitialized(url, init, sessionId, wallet) {
@@ -2072,11 +2146,7 @@ var X402FundingLeg = class {
2072
2146
  );
2073
2147
  if (paymentRequired.x402Version < 2) return header;
2074
2148
  const payment = decodeBase64Json(header);
2075
- return encodeBase64Json({
2076
- x402Version: paymentRequired.x402Version,
2077
- accepted: option,
2078
- payload: payment.payload
2079
- });
2149
+ return encodeBase64Json(x402V2PaymentEnvelope(paymentRequired, option, payment.payload));
2080
2150
  }
2081
2151
  // ── Receipt mapping ──────────────────────────────────────────────
2082
2152
  receiptFromAuthorization(paymentRequired, option, paymentHeader, raw, execResult) {
@@ -2233,10 +2303,11 @@ var X402Erc7710 = class {
2233
2303
  * settled when this returns** — that is why it does not return an
2234
2304
  * `X402Receipt`.
2235
2305
  *
2236
- * Requires a delegation-rail account. The backend enforces that
2237
- * (`validateGenericSchemeRail`), and so does this method, before building a
2238
- * request the backend would only reject: an error a client can explain is
2239
- * worth more than a 400 it has to decode.
2306
+ * Requires a delegation-rail account. The backend enforces that at the
2307
+ * rail seam — a non-delegation account gets the #1986 retired-rail 410 from
2308
+ * `POST /x402/authorize` whatever scheme it asks for (#2245) — and so does
2309
+ * this method, before building a request the backend would only reject: an
2310
+ * error a client can explain is worth more than a refusal it has to decode.
2240
2311
  *
2241
2312
  * **MCP callers must pass `options.resourceUrl`.** An in-band MCP 402
2242
2313
  * challenge frequently carries no `resource` object at all, so
@@ -2286,6 +2357,16 @@ var X402Erc7710 = class {
2286
2357
  const amountAtomic = x402AuthorizationAmount(option);
2287
2358
  const raw = await this.post("/x402", {
2288
2359
  url: options.resourceUrl ?? paymentRequired.resource?.url,
2360
+ // #2373: the full 402 challenge, persisted verbatim by the backend
2361
+ // (#1355) so the settle handoff can echo its resource/extensions into
2362
+ // the X-PAYMENT envelope (#2361). This scheme decomposes the challenge
2363
+ // into the fields below for AUTHORITY; the stored copy exists for the
2364
+ // echo, which cannot be reconstructed from the decomposition — omitting
2365
+ // it is how every erc7710 payment failed a merchant that enforces the
2366
+ // spec's extensions-echo MUST. Same ≤64KB guard and omission behaviour
2367
+ // as the 3009 path (client.ts): an oversized challenge omits the field
2368
+ // rather than failing the payment, and the settle echo then omits too.
2369
+ ...new TextEncoder().encode(JSON.stringify(paymentRequired)).length <= 65536 ? { paymentRequired } : {},
2289
2370
  // payTo = the MERCHANT is what selects direct settlement server-side.
2290
2371
  // The explicit settlementScheme must AGREE with that shape (#1360) —
2291
2372
  // disagreement is a 400 by design, so that a stale delegate address
@@ -2530,7 +2611,7 @@ var MerchantCompletion = class {
2530
2611
  merchantStatus: retryResponse.status,
2531
2612
  challengePayload: paymentRequired,
2532
2613
  selectedPayment: receipt.accepted,
2533
- paymentProofHeaderName: "X-PAYMENT",
2614
+ paymentProofHeaderName: x402PaymentHeaderNamesSent(receipt.paymentHeader),
2534
2615
  paymentProofHeader: receipt.paymentHeader,
2535
2616
  protocolReceiptHeaderName: "PAYMENT-RESPONSE",
2536
2617
  protocolReceiptHeader: retryResponse.headers.get("PAYMENT-RESPONSE") ?? void 0
@@ -2640,6 +2721,109 @@ var MerchantCompletion = class {
2640
2721
  } catch {
2641
2722
  }
2642
2723
  }
2724
+ /**
2725
+ * #2292: record what a merchant said to a retry **Haven did not make**.
2726
+ *
2727
+ * On the plain-HTTP x402 path Haven tells the agent to call the merchant
2728
+ * itself — that is the keyless design, not an oversight — so the two writes
2729
+ * above were reachable only from `completeX402MerchantCall`, where Haven IS
2730
+ * the caller. A manual retry had nowhere to put its outcome, which left
2731
+ * `intentStateFor`'s merchant-rejected branch dead on the one flow Haven
2732
+ * prescribes and made the 15-minute grace window the only route to
2733
+ * `funded_but_unsettled`.
2734
+ *
2735
+ * Three properties distinguish this from `recordRetryRejected` /
2736
+ * `reportEvidence`, and each is deliberate:
2737
+ *
2738
+ * 1. **It does not swallow.** Those two are bookkeeping hung off a call
2739
+ * whose outcome is already decided, so an exception there would turn a
2740
+ * completed payment into a reported failure. Here the report IS the
2741
+ * caller's request; silently dropping it would recreate the exact
2742
+ * unobservability #2292 exists to remove.
2743
+ * 2. **The anchor is server-side.** `txHash` and `resourceUrl` come from
2744
+ * the payment's own Haven record, never from the reporter — so a report
2745
+ * cannot be pointed at a different transaction or a different resource,
2746
+ * and it can never CONFIRM an intent (an erc7710 intent has no Haven
2747
+ * tx hash and is refused here rather than completed from a supplied one,
2748
+ * which is #2092's verified seam and stays its own path).
2749
+ * 3. **It is evidence, never authority.** Haven does not and must not check
2750
+ * the claim: verifying it would mean calling the merchant, which is the
2751
+ * property this whole path exists to preserve. What bounds a false
2752
+ * report is scope — the backend routes resolve the payment
2753
+ * `WHERE agent_id = $`, so a caller can only ever describe its own
2754
+ * payment — plus the fact that nothing financial keys off the claim:
2755
+ * the sweep is balance-driven, the intent's status/amount/recipient are
2756
+ * untouched, and a false `accepted` runs the server's own on-chain
2757
+ * residue check, which re-flags stranded funds independently.
2758
+ */
2759
+ async reportMerchantOutcome(input) {
2760
+ if (!Number.isInteger(input.merchantStatus) || input.merchantStatus < 100 || input.merchantStatus > 599) {
2761
+ throw new HavenApiError(
2762
+ `merchant_status must be an integer HTTP status from 100 to 599 (received ${input.merchantStatus}).`,
2763
+ 400,
2764
+ void 0,
2765
+ input.paymentId
2766
+ );
2767
+ }
2768
+ const looksAccepted = input.merchantStatus >= 200 && input.merchantStatus < 300;
2769
+ if (looksAccepted !== (input.outcome === "accepted")) {
2770
+ throw new HavenApiError(
2771
+ `outcome "${input.outcome}" contradicts merchant_status ${input.merchantStatus}: report "accepted" only for a 2xx and "rejected" only for a non-2xx.`,
2772
+ 400,
2773
+ void 0,
2774
+ input.paymentId
2775
+ );
2776
+ }
2777
+ const status = await this.getPaymentStatus(input.paymentId);
2778
+ if (status.rail !== "x402") {
2779
+ throw new HavenPaymentStateError(
2780
+ `Payment ${status.paymentId} is ${status.rail}, not x402 \u2014 there is no merchant retry to report.`,
2781
+ 409,
2782
+ status
2783
+ );
2784
+ }
2785
+ if (status.status !== "confirmed" || !status.txHash) {
2786
+ throw new HavenPaymentStateError(
2787
+ `Payment ${status.paymentId} has no confirmed Haven funding transaction to anchor a merchant report to (status ${status.status}). ${status.message}`,
2788
+ paymentStateStatusCode(status.status, 409),
2789
+ status
2790
+ );
2791
+ }
2792
+ const resourceUrl = status.resourceUrl ?? status.x402?.resourceUrl ?? null;
2793
+ if (!resourceUrl) {
2794
+ throw new HavenApiError(
2795
+ `Payment ${status.paymentId} has no recorded resource URL, so a merchant report cannot be stored.`,
2796
+ 409,
2797
+ status,
2798
+ status.paymentId
2799
+ );
2800
+ }
2801
+ const txHash = status.txHash;
2802
+ if (input.outcome === "rejected") {
2803
+ await this.post("/machine-payments/reconciliation-events", {
2804
+ paymentId: status.paymentId,
2805
+ rail: "x402",
2806
+ eventType: "merchant_retry_rejected_after_payment",
2807
+ txHash,
2808
+ reason: `Agent-reported: merchant returned HTTP ${input.merchantStatus} to a manual retry after Haven payment confirmation`,
2809
+ details: {
2810
+ resource_url: resourceUrl,
2811
+ retry_status: input.merchantStatus,
2812
+ retry_body: input.merchantBody?.slice(0, MERCHANT_BODY_SNIPPET_LIMIT) || null,
2813
+ reported_by: "agent_manual_retry"
2814
+ }
2815
+ });
2816
+ return { paymentId: status.paymentId, outcome: "rejected", txHash, resourceUrl, recorded: "reconciliation_event" };
2817
+ }
2818
+ await this.post("/machine-payments/evidence", {
2819
+ paymentId: status.paymentId,
2820
+ rail: "x402",
2821
+ txHash,
2822
+ resourceUrl,
2823
+ merchantStatus: input.merchantStatus
2824
+ });
2825
+ return { paymentId: status.paymentId, outcome: "accepted", txHash, resourceUrl, recorded: "evidence" };
2826
+ }
2643
2827
  async reportEvidence(input) {
2644
2828
  const body = {
2645
2829
  paymentId: input.paymentId,
@@ -3526,7 +3710,7 @@ var HavenClient = class {
3526
3710
  * Deliver an already-signed x402 payment header to the merchant and return
3527
3711
  * the merchant's response. Used by the hosted MCP server to complete the
3528
3712
  * merchant leg of an MCP tool payment after the edge signer has built the
3529
- * `X-PAYMENT` header.
3713
+ * merchant payment header.
3530
3714
  *
3531
3715
  * Custody note: this never needs the delegate key. It relays a signed,
3532
3716
  * amount/merchant/nonce-bound EIP-3009 authorization the edge signer already
@@ -3536,13 +3720,14 @@ var HavenClient = class {
3536
3720
  * says the merchant was Bazaar-discoverable, runs a fresh `initialize`
3537
3721
  * handshake (the quote-time session is gone once funding confirms; the x402
3538
3722
  * challenge is stateless w.r.t. the MCP session, so a fresh session is
3539
- * accepted), threads the session + wallet headers, sets `X-PAYMENT`, and
3723
+ * accepted), threads the session + wallet headers, sets the x402 payment
3724
+ * header under the names that scheme requires (#2341), and
3540
3725
  * collapses an SSE JSON-RPC response to its `result`.
3541
3726
  */
3542
3727
  /**
3543
3728
  * Wait for a payment's Safe→delegate funding tx to reach ≥1 on-chain
3544
3729
  * confirmation. The hosted x402 completion path MUST call this after funding
3545
- * and before delivering the X-PAYMENT header, so the merchant's
3730
+ * and before delivering the merchant payment header, so the merchant's
3546
3731
  * balanceOf(delegate) / transferWithAuthorization verification sees the funded
3547
3732
  * balance — otherwise it rejects with "Payment verification failed". The
3548
3733
  * SDK's local path already does this (see `X402FundingLeg.authorize`); the hosted
@@ -3617,7 +3802,7 @@ var HavenClient = class {
3617
3802
  txHash: evidenceTxHash,
3618
3803
  resourceUrl: evidenceContext.resourceUrl,
3619
3804
  merchantStatus: surfaced.status,
3620
- paymentProofHeaderName: "X-PAYMENT",
3805
+ paymentProofHeaderName: x402PaymentHeaderNamesSent(input.paymentHeader),
3621
3806
  paymentProofHeader: input.paymentHeader,
3622
3807
  protocolReceiptHeaderName: protocolReceiptHeader ? "PAYMENT-RESPONSE" : void 0,
3623
3808
  protocolReceiptHeader
@@ -3632,6 +3817,18 @@ var HavenClient = class {
3632
3817
  settlementTxHash: settlement.settlementTxHash ?? void 0
3633
3818
  };
3634
3819
  }
3820
+ /**
3821
+ * #2292: report the outcome of a merchant retry the AGENT performed.
3822
+ *
3823
+ * The hosted `haven_complete_mcp_tool` / `completeX402MerchantCall` path is
3824
+ * for merchants Haven calls itself. On the plain-HTTP x402 path Haven never
3825
+ * talks to the merchant, so the outcome of that retry had no way back —
3826
+ * see `MerchantCompletion.reportMerchantOutcome` for what is verified about
3827
+ * a caller-asserted report and what deliberately is not.
3828
+ */
3829
+ async reportX402MerchantOutcome(input) {
3830
+ return await this.merchantCompletion.reportMerchantOutcome(input);
3831
+ }
3635
3832
  /**
3636
3833
  * GET /x402/:id/merchant-call-context — the settle-leg twin of #1263's
3637
3834
  * sign-context fetch (#1307). Re-serves the stored merchant MCP-tool call
@@ -3793,12 +3990,12 @@ var toolDescriptions = {
3793
3990
  payX402OneShot: {
3794
3991
  summary: "Fetch an x402 paid HTTP resource in a single call. Handles the full probe -> pay -> retry round trip and returns the merchant response.",
3795
3992
  selectionGuidance: "Prefer this over the quote+pay split when the agent just wants the paid resource and does not need to inspect the price first. If you already have a quote from haven_quote_x402, use haven_pay_x402_quote instead. Do not use for read-only allowance, budget, spend-limit, remaining-amount, reset-period, or what-can-I-spend questions; use the allowance lookup tool instead.",
3796
- behavior: "Calls the URL, parses any HTTP 402 x402 challenge, signs the payment locally, then retries the original request with the X-PAYMENT header and returns the merchant response. Settlement is either direct account-to-merchant with no funding leg, or a bridge that first redeems the agent's budget delegation to fund the delegate wallet for an EIP-3009 authorization. A payment outside the on-chain budget is declined before any money moves; nothing is queued for a human to approve later. If the resource returns a non-402 status, returns it unchanged without contacting Haven.",
3993
+ behavior: "Calls the URL, parses any HTTP 402 x402 challenge, signs the payment locally, then retries the original request with the signed payment header (sent under PAYMENT-SIGNATURE, plus the legacy X-PAYMENT on the EIP-3009 path only) and returns the merchant response. Settlement is either direct account-to-merchant with no funding leg, or a bridge that first redeems the agent's budget delegation to fund the delegate wallet for an EIP-3009 authorization. A payment outside the on-chain budget is declined before any money moves; nothing is queued for a human to approve later. If the resource returns a non-402 status, returns it unchanged without contacting Haven.",
3797
3994
  nextActionGuidance: "Preserve the returned resume_state or paymentId \u2014 either identifies this payment if you need to ask about it later. This tool performs the merchant retry itself, so do not wait on a signal while the call is in flight. If the process crashes after this call and a later haven_get_payment_status reports nextAction=retry_original_x402_request, Haven's funding leg confirmed but no merchant response was ever recorded \u2014 call the resume tool with the preserved resume_state or payment_id instead of paying again. If the response carries phase=insufficient_funds and nextAction=fund_safe_or_raise_allowance, the payment cannot be retried until the account is funded or the agent budget raised \u2014 stop and tell the user the shortfall reported on the response."
3798
3995
  },
3799
3996
  resumeX402: {
3800
3997
  summary: "Resume an x402 payment whose Haven-side authorization already succeeded but whose merchant retry did not complete.",
3801
- behavior: "Accepts either resume_state or payment_id, validates the original x402 details against the authorized Haven funding, and retries the merchant request with the X-PAYMENT header. No new Haven payment is created.",
3998
+ behavior: "Accepts either resume_state or payment_id, validates the original x402 details against the authorized Haven funding, and retries the merchant request with the signed payment header (sent under PAYMENT-SIGNATURE, plus the legacy X-PAYMENT on the EIP-3009 path only). No new Haven payment is created.",
3802
3999
  nextActionGuidance: "Only call this after haven_get_payment_status reports nextAction=retry_original_x402_request \u2014 that means Haven's funding leg confirmed but no merchant response was ever recorded, most often because the process crashed between funding and the merchant retry. Any other nextAction reports a conflict instead of retrying, so do not call this speculatively. Do not start a new merchant session and do not pay again \u2014 that would pay twice for one resource."
3803
4000
  },
3804
4001
  // #1328: quoteMpp / payMpp / resumeMpp (the mpp_demo challenge/quote/resume
@@ -3984,7 +4181,7 @@ var resumeX402Schema = {
3984
4181
  var MAKE_PAYMENT_DESCRIPTION = "Request and sign a payment from the user-controlled account within its on-chain budget. For read-only allowance, budget, spend-limit, remaining-amount, or reset-period questions, use get_allowances instead of making a payment. Haven authenticates the agent and relays the signed transaction that redeems the agent budget delegation; it does not hold keys or control funds. Gnosis Chain tokens: EURe, USDC.e, xDAI. Base tokens: USDC, ETH.";
3985
4182
  var GET_STATUS_DESCRIPTION = toolDescriptions.getPaymentStatus.summary + " Accepts payment intent IDs. Returns the current status, phase, next_action, transaction hash if available, and payment details.";
3986
4183
  var GET_ALLOWANCES_DESCRIPTION = composeDescription(toolDescriptions.getAllowances);
3987
- var AUTHORIZE_X402_DESCRIPTION = composeDescription(toolDescriptions.payX402) + " In this SDK tool set, the allowance lookup tool is get_allowances. When a paid API returns x402 payment requirements, use this tool to sign with the agent-owned delegate key; funding, when the scheme needs it, is redeemed from the agent budget delegation and is bounded by it. Haven relays signed transactions only; the agent key authorizes payment and on-chain limits enforce spend. A payment outside the on-chain budget is declined before any money moves \u2014 report the decline and ask the user to raise the budget in Haven; do not loop retries and do not wait for an approval, because none is queued. Preserve the original merchant/MCP session and x402 details. Use the returned payment_header as the X-PAYMENT header on the retry request when doing a manual HTTP retry.";
4184
+ var AUTHORIZE_X402_DESCRIPTION = composeDescription(toolDescriptions.payX402) + " In this SDK tool set, the allowance lookup tool is get_allowances. When a paid API returns x402 payment requirements, use this tool to sign with the agent-owned delegate key; funding, when the scheme needs it, is redeemed from the agent budget delegation and is bounded by it. Haven relays signed transactions only; the agent key authorizes payment and on-chain limits enforce spend. A payment outside the on-chain budget is declined before any money moves \u2014 report the decline and ask the user to raise the budget in Haven; do not loop retries and do not wait for an approval, because none is queued. Preserve the original merchant/MCP session and x402 details. On a manual HTTP retry always set PAYMENT-SIGNATURE (x402 v2) to the returned payment_header; a strict v2 merchant reads only that name. Also set X-PAYMENT (v1) on the EIP-3009 funding path for legacy merchants, but NEVER on erc7710 \u2014 that header carries a delegation chain and duplicating it is refused with HTTP 431.";
3988
4185
  var RESUME_X402_DESCRIPTION = toolDescriptions.resumeX402.summary + " Only call this after get_payment_status reports nextAction=retry_original_x402_request \u2014 that means Haven's funding leg confirmed but no merchant response was ever recorded (typically a crash between funding and the merchant retry). Any other nextAction reports a conflict instead of retrying \u2014 do not call this speculatively, and do not pay again.";
3989
4186
  var SWEEP_DELEGATE_DESCRIPTION = composeDescription(toolDescriptions.sweep_delegate);
3990
4187
  var sweepDelegateSchema = {
@@ -4196,8 +4393,14 @@ The paid call always obtains a fresh quote before it creates any intent. Then
4196
4393
  continue \`mcp__haven__haven_pay_mcp_tool\` \u2192
4197
4394
  \`mcp__haven-signer__haven_sign\` \u2192 \`mcp__haven__haven_submit\` \u2192
4198
4395
  \`mcp__haven-signer__haven_x402_sign_header\` \u2192
4199
- \`mcp__haven__haven_complete_mcp_tool\`. Pass \`payment_required\`,
4200
- \`arguments\`, and \`mcp_transport\` verbatim from the quote/prepare result.
4396
+ \`mcp__haven__haven_complete_mcp_tool\`. Call that last step with
4397
+ \`payment_id\` and the signer's \`payment_header\` ONLY. It does not take
4398
+ \`payment_required\`: Haven rehydrates the merchant call context
4399
+ (\`merchant_url\`, \`tool_name\`, \`arguments\`, \`mcp_transport\`) and the
4400
+ 402 server-side from \`payment_id\`, exactly as at settle. Pass that context
4401
+ explicitly only as a version-skew fallback when Haven has no stored context
4402
+ for the id \u2014 \`merchant_url\` and \`tool_name\` both or none together, never
4403
+ just one.
4201
4404
  The returned \`expires_at\` is the signing window; if a tool returns
4202
4405
  \`PAYMENT_WINDOW_EXPIRED\`, re-run the same quote/prepare tool with the same
4203
4406
  \`idempotency_key\`. Do not call the merchant yourself \u2014 Haven completes the
@@ -4207,8 +4410,20 @@ merchant leg for you.
4207
4410
  recipient, amount, and token for a plain transfer. For an arbitrary,
4208
4411
  non-MCP x402 paywall: \`mcp__haven__haven_quote_x402\` to get a quote, then
4209
4412
  \`mcp__haven__haven_pay_x402_quote\` \u2014 follow the result's guidance fields
4210
- first and sign in the local Haven signer. The pay tool performs the merchant
4211
- retry itself, so do not wait on a signal while it runs. If the process
4413
+ first and sign in the local Haven signer. On THIS path Haven does not talk to
4414
+ the merchant: \`mcp__haven-signer__haven_sign_x402\` returns both
4415
+ \`signature\` and \`payment_header\`; relay \`signature\` with
4416
+ \`mcp__haven__haven_submit\`, then retry the paywalled URL yourself with
4417
+ \`payment_header\`. Do not pass that call's \`x402_binding\` to
4418
+ \`mcp__haven-signer__haven_x402_sign_header\` \u2014 the one-shot already spent it
4419
+ building the header, so the call can only refuse. Then tell Haven what the
4420
+ merchant answered: \`mcp__haven__haven_report_x402_outcome\` with the
4421
+ \`payment_id\`, \`outcome\` (\`"accepted"\` for a 2xx, else \`"rejected"\`)
4422
+ and the \`merchant_status\` you got. Because Haven never contacted that
4423
+ merchant, this is the only way it can learn the purchase failed \u2014 without it a
4424
+ failed purchase reads as complete for fifteen minutes. (The SDK's own
4425
+ \`haven_pay_x402\` tool does perform the merchant retry itself; that tool is
4426
+ not part of the hosted MCP surface.) If the process
4212
4427
  crashes after payment, a later \`mcp__haven__haven_get_payment_status\` call
4213
4428
  may report \`nextAction: 'retry_original_x402_request'\` \u2014 only then call
4214
4429
  \`mcp__haven__haven_resume_x402_payment\` with the preserved resume state or
@@ -4223,9 +4438,11 @@ payment id, instead of paying again.
4223
4438
  result, never a catalog price. \`haven_discover_tools\` prices are indicative
4224
4439
  (\`price_is_indicative\`) and can be stale. A read-only quote is informational
4225
4440
  only and does not reserve a price; the later paid call re-quotes and enforces
4226
- the cap. The pay-tool result's \`amount\` / \`amount_atomic\` is the amount
4227
- Haven authorizes for that call \u2014 a ceiling the merchant settles at or below \u2014
4228
- so present it as the most the user will pay.
4441
+ the cap. The pay-tool result's \`amount\` / \`amount_atomic\` is the merchant's
4442
+ own quoted price for that call \u2014 a ceiling the merchant settles at or below \u2014
4443
+ so present it as the most the user will pay. It is a price, not an approval:
4444
+ the payment goes through only if it also fits the cap you set and the on-chain
4445
+ budget the user signed, which is enforced on-chain rather than by Haven.
4229
4446
 
4230
4447
  **Status:** \`mcp__haven__haven_get_payment_status\` with a \`payment_id\` to
4231
4448
  check on in-flight payments. Do not poll in a tight loop.
@@ -4376,6 +4593,6 @@ function sameUrl(a, b) {
4376
4593
  }
4377
4594
  }
4378
4595
 
4379
- export { AGENT_PAYMENT_FAILURE_CODE_VALUES, AGENT_PAYMENT_NEXT_ACTION_VALUES, AGENT_PAYMENT_PHASE_VALUES, AGENT_PAYMENT_RAIL_VALUES, AgentPaymentFailureCode, AgentPaymentFailureCodeDescriptions, AgentPaymentFailureCodeSchema, AgentPaymentNextAction, AgentPaymentNextActionDescriptions, AgentPaymentNextActionSchema, AgentPaymentPhase, AgentPaymentPhaseDescriptions, AgentPaymentPhaseSchema, AgentPaymentRail, AgentPaymentRailDescriptions, AgentPaymentRailSchema, AgentPaymentWarningCode, DEFAULT_CONFIRMATION_TIMEOUT_MS, DISCOVERY_MAX_BYTES, ERC7710_ASSET_TRANSFER_METHOD, HAVEN_MINIMUM_NODE_VERSION, HAVEN_SKILL_BODY_MD, HAVEN_SKILL_MD, HavenApiError, HavenClient, HavenError, HavenPaymentStateError, HavenSigningError, HavenTimeoutError, HavenUnsupportedSignerVersionError, MERCHANT_DISCOVERY_PATHS, MerchantTimeoutError, RECEIPT_VERSION, SIGNER_UPDATE_FALLBACK, SKILL_FOLDER_NAME, SWEEP_BASE_CHAIN_ID, SWEEP_BASE_SEPOLIA_CHAIN_ID, SWEEP_BASE_SEPOLIA_USDC_ADDRESS, SWEEP_BASE_USDC_ADDRESS, SignerRefusalCode, TRANSFER_WITH_AUTHORIZATION_TYPES, X402AlreadySettledError, X402PaymentHeaderValidationError, X402UnexpectedStatusError, X402_MAX_AUTHORIZATION_WINDOW_SECONDS, X402_SETTLEMENT_FORWARD_MARGIN_SECONDS, addressFromKey, buildSweepAuthorizationMessage, buildSweepTypedData, buildX402ExpectedMessage, compareNodeVersions, composeDescription, decodeBase64Json, decodeBase64Utf8, discoverMerchantMcpUrl, encodeBase64Json, encodeBase64Utf8, encodePaymentProof, havenTools, isErc7710Option, isSupportedNodeVersion, isSweepableChain, normalizePaymentRequired, parsePaymentRequired, parsePaymentRequiredResponse, resolveTokenFromAddress, sameUrl, selectErc7710PaymentOption, selectPaymentOption, selectStandardPaymentOption, selectX402SettlementScheme, signHash, signUserOpTypedDataForDelegation, sweepUsdcAddress, sweepUsdcDomain, toStandardPaymentRequirements, toolDescriptions, unsupportedNodeVersionMessage, validateStandardX402PaymentHeader, verifyPaymentReceipt, verifySignature, x402AssetTransferMethod, x402AuthorizationAmount, x402FacilitatorAddresses };
4596
+ export { AGENT_PAYMENT_FAILURE_CODE_VALUES, AGENT_PAYMENT_NEXT_ACTION_VALUES, AGENT_PAYMENT_PHASE_VALUES, AGENT_PAYMENT_RAIL_VALUES, AgentPaymentFailureCode, AgentPaymentFailureCodeDescriptions, AgentPaymentFailureCodeSchema, AgentPaymentNextAction, AgentPaymentNextActionDescriptions, AgentPaymentNextActionSchema, AgentPaymentPhase, AgentPaymentPhaseDescriptions, AgentPaymentPhaseSchema, AgentPaymentRail, AgentPaymentRailDescriptions, AgentPaymentRailSchema, AgentPaymentWarningCode, DEFAULT_CONFIRMATION_TIMEOUT_MS, DISCOVERY_MAX_BYTES, ERC7710_ASSET_TRANSFER_METHOD, HAVEN_MINIMUM_NODE_VERSION, HAVEN_SKILL_BODY_MD, HAVEN_SKILL_MD, HavenApiError, HavenClient, HavenError, HavenPaymentStateError, HavenSigningError, HavenTimeoutError, HavenUnsupportedSignerVersionError, MERCHANT_DISCOVERY_PATHS, MerchantTimeoutError, RECEIPT_VERSION, SIGNER_UPDATE_FALLBACK, SKILL_FOLDER_NAME, SWEEP_BASE_CHAIN_ID, SWEEP_BASE_SEPOLIA_CHAIN_ID, SWEEP_BASE_SEPOLIA_USDC_ADDRESS, SWEEP_BASE_USDC_ADDRESS, SignerRefusalCode, TRANSFER_WITH_AUTHORIZATION_TYPES, X402AlreadySettledError, X402PaymentHeaderValidationError, X402UnexpectedStatusError, X402_LEGACY_PAYMENT_HEADER_NAME, X402_MAX_AUTHORIZATION_WINDOW_SECONDS, X402_PAYMENT_HEADER_NAME, X402_PAYMENT_HEADER_NAMES_SENT, X402_PAYMENT_REQUIRED_HEADER_NAME, X402_PAYMENT_RESPONSE_HEADER_NAME, X402_SETTLEMENT_FORWARD_MARGIN_SECONDS, addressFromKey, buildSweepAuthorizationMessage, buildSweepTypedData, buildX402ExpectedMessage, compareNodeVersions, composeDescription, decodeBase64Json, decodeBase64Utf8, discoverMerchantMcpUrl, encodeBase64Json, encodeBase64Utf8, encodePaymentProof, havenTools, isErc7710Option, isSupportedNodeVersion, isSweepableChain, normalizePaymentRequired, parsePaymentRequired, parsePaymentRequiredResponse, resolveTokenFromAddress, sameUrl, selectErc7710PaymentOption, selectPaymentOption, selectStandardPaymentOption, selectX402SettlementScheme, signHash, signUserOpTypedDataForDelegation, sweepUsdcAddress, sweepUsdcDomain, toStandardPaymentRequirements, toolDescriptions, unsupportedNodeVersionMessage, validateStandardX402PaymentHeader, verifyPaymentReceipt, verifySignature, x402AssetTransferMethod, x402AuthorizationAmount, x402FacilitatorAddresses, x402V2PaymentEnvelope };
4380
4597
  //# sourceMappingURL=index.js.map
4381
4598
  //# sourceMappingURL=index.js.map