@haven_ai/sdk 0.1.23-alpha.2 → 0.1.25-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.d.cts CHANGED
@@ -224,6 +224,21 @@ interface X402PaymentOption {
224
224
  asset: string;
225
225
  payTo: string;
226
226
  maxTimeoutSeconds: number;
227
+ /**
228
+ * Merchant-supplied scheme metadata. Two keys are load-bearing for Haven
229
+ * (#1453), both from MetaMask's erc7710 x402 shape:
230
+ *
231
+ * assetTransferMethod — 'erc7710' marks this entry as settleable by
232
+ * redeeming a delegation chain. Absent/other means
233
+ * the standard EIP-3009 authorization.
234
+ * facilitatorAddresses — who may redeem it, pinned into the settlement
235
+ * child's redeemer caveat (#1058).
236
+ *
237
+ * Left as an open record on purpose: the field is the merchant's, and
238
+ * narrowing it to Haven's two keys would silently drop everything else a
239
+ * merchant sends. Read it through `x402AssetTransferMethod` /
240
+ * `x402FacilitatorAddresses` rather than indexing it raw.
241
+ */
227
242
  extra?: Record<string, unknown>;
228
243
  }
229
244
  /** Receipt returned after a successful x402 payment. */
@@ -937,6 +952,8 @@ interface PaymentStatusResult {
937
952
  token: string;
938
953
  resourceUrl: string | null;
939
954
  merchantAddress: string | null;
955
+ /** Delegate EOA captured on the payment intent when it was created. */
956
+ payerAddress?: string | null;
940
957
  txHash: string | null;
941
958
  expiresAt: string;
942
959
  chainId: number;
@@ -976,6 +993,27 @@ interface PendingApproval extends PaymentStatusResult {
976
993
  requested?: string;
977
994
  remaining?: string | null;
978
995
  }
996
+ /**
997
+ * Result of an erc7710 direct settlement (#1454).
998
+ *
999
+ * Deliberately NOT an `X402Receipt`. A 3009 receipt describes a completed
1000
+ * two-leg payment — funding tx included — whereas here nothing has settled yet
1001
+ * when this returns: the merchant redeems the delegation chain when the caller
1002
+ * retries with the header. Reusing the receipt type would let a caller read
1003
+ * `txHash` as "paid" on a payment that has not moved a cent.
1004
+ */
1005
+ interface X402Erc7710Settlement {
1006
+ paymentId: string;
1007
+ /** Pass verbatim as the `X-PAYMENT` header on the merchant retry. */
1008
+ paymentHeader: string;
1009
+ /** The merchant address the child delegation is pinned to. */
1010
+ merchantPayTo: string;
1011
+ amountAtomic: string;
1012
+ asset: string;
1013
+ network: string;
1014
+ /** Facilitators the child is redeemable by, when the merchant advertised any. */
1015
+ facilitatorAddresses: string[] | null;
1016
+ }
979
1017
  /** @internal */
980
1018
  /** One payable service in Haven's curated merchant catalog. */
981
1019
  interface HavenCatalogEntry {
@@ -1560,6 +1598,76 @@ declare class HavenClient {
1560
1598
  */
1561
1599
  payX402Quote(quote: X402Quote, options?: X402AuthorizationOptions): Promise<Response>;
1562
1600
  private authorizeStandardX402;
1601
+ /**
1602
+ * Pay a merchant through **erc7710 direct settlement** (#1454, epic #1450).
1603
+ *
1604
+ * The whole point of this path is what it does NOT do. There is no funding
1605
+ * leg: the merchant redeems a delegation chain and pulls from the treasury
1606
+ * directly, so the delegate EOA never holds the money, no sweep can strand
1607
+ * it, and the #713 reconciliation class does not apply. It is also why this
1608
+ * method is SMALLER than the 3009 path — the backend assembles the merchant
1609
+ * `X-PAYMENT` header in `assembleSettlementPayload`, so the SDK builds no
1610
+ * header locally.
1611
+ *
1612
+ * authorize (payTo = the MERCHANT) → sign the child → settle → header
1613
+ *
1614
+ * The caller then retries the merchant with that header. **Nothing has
1615
+ * settled when this returns** — that is why it does not return an
1616
+ * `X402Receipt`.
1617
+ *
1618
+ * Requires a delegation-rail account. The backend enforces that
1619
+ * (`validateGenericSchemeRail`), and so does this method, before building a
1620
+ * request the backend would only reject: an error a client can explain is
1621
+ * worth more than a 400 it has to decode.
1622
+ *
1623
+ * **MCP callers must pass `options.resourceUrl`.** An in-band MCP 402
1624
+ * challenge frequently carries no `resource` object at all, so
1625
+ * `paymentRequired.resource?.url` is undefined and the backend answers
1626
+ * "Valid url is required". The QA scenario this path was ported from falls
1627
+ * back to the request URL for exactly that reason — the SDK cannot, because
1628
+ * it never saw the request. Pass it.
1629
+ */
1630
+ settleX402Erc7710(paymentRequired: X402PaymentRequired, options?: {
1631
+ resourceUrl?: string;
1632
+ }): Promise<X402Erc7710Settlement>;
1633
+ /**
1634
+ * The AUTHORIZE half of erc7710 settlement (#1456): select the scheme, build
1635
+ * the request, and return the child to be signed — without signing it.
1636
+ *
1637
+ * Split out because the hosted topology cannot use `settleX402Erc7710()`:
1638
+ * that method signs in-process with `delegateKey`, and hosted Haven does not
1639
+ * have one and must not. The hosted MCP server drives these two halves with
1640
+ * the LOCAL signer in between, so the key stays where it belongs and the
1641
+ * request shaping stays in one place rather than being reimplemented.
1642
+ */
1643
+ prepareX402Erc7710(paymentRequired: X402PaymentRequired, options?: {
1644
+ resourceUrl?: string;
1645
+ /**
1646
+ * The account's rail, when the caller has ALREADY read it from
1647
+ * `GET /machine-payments/agent` — passing it skips a duplicate fetch
1648
+ * (#1456: the hosted tool reads the agent for the delegate address
1649
+ * anyway, and #1348 pins that path to exactly one agent round-trip).
1650
+ *
1651
+ * This is an optimisation, not a trust boundary: omit it and the rail is
1652
+ * read here, and either way the backend independently refuses erc7710
1653
+ * from a non-delegation account (`validateGenericSchemeRail`). A caller
1654
+ * that asserted the wrong rail would build a request the backend rejects.
1655
+ */
1656
+ delegationRail?: boolean;
1657
+ }): Promise<{
1658
+ paymentId: string;
1659
+ signData: SignData;
1660
+ settlement: Omit<X402Erc7710Settlement, 'paymentHeader'>;
1661
+ }>;
1662
+ /**
1663
+ * The SETTLE half (#1456): exchange the signed child for the merchant header.
1664
+ *
1665
+ * The SDK builds no header on this path — the backend assembles the MetaMask
1666
+ * erc7710 payload in `assembleSettlementPayload`. Whoever produced the
1667
+ * signature (an in-process delegate key, or the local edge signer over the
1668
+ * hosted boundary) is irrelevant here.
1669
+ */
1670
+ submitX402Erc7710(paymentId: string, signature: string): Promise<string>;
1563
1671
  resumeAuthorizedX402(input: ResumeAuthorizedX402Input): Promise<X402Receipt>;
1564
1672
  resumeX402Payment(input: ResumeX402PaymentInput | X402ResumeState): Promise<Response>;
1565
1673
  /**
@@ -1650,8 +1758,18 @@ declare class HavenClient {
1650
1758
  * balance — otherwise it rejects with "Payment verification failed". The
1651
1759
  * SDK's local path already does this (see authorizeStandardX402); the hosted
1652
1760
  * split flow regressed when the 5→3 collapse removed the incidental
1653
- * inter-call latency that used to mask it. No-op when the funding tx hash or
1654
- * a chain RPC (chainRpcs[chainId]) is unavailable.
1761
+ * inter-call latency that used to mask it.
1762
+ *
1763
+ * **NOT a no-op when the funding tx hash is absent** (#1508). The WAIT is
1764
+ * skipped without a hash or a chain RPC, but the `GET /payments/:id` read
1765
+ * below runs UNCONDITIONALLY — it is how the fallback hash and the chainId
1766
+ * are obtained. That distinction is load-bearing: this method must never be
1767
+ * called on a scheme with no funding leg, because the read itself fails once
1768
+ * the intent reaches a status the backend maps to a non-2xx (`submitted` is a
1769
+ * 409), turning a settled payment into a reported error. The previous wording
1770
+ * here said "No-op when the funding tx hash ... is unavailable", and the
1771
+ * hosted erc7710 path was written against that promise — see
1772
+ * `deliverMerchantPayment`'s `noFundingLeg` option.
1655
1773
  */
1656
1774
  ensureFundingConfirmed(paymentId: string, fundingTxHash?: string): Promise<void>;
1657
1775
  completeX402MerchantCall(input: {
@@ -1660,6 +1778,16 @@ declare class HavenClient {
1660
1778
  paymentId: string;
1661
1779
  paymentHeader: string;
1662
1780
  mcpTransport?: X402McpTransport;
1781
+ /**
1782
+ * #1508: the payment settles with NO funding leg (erc7710). This method was
1783
+ * written for EIP-3009 and encodes that lifecycle in two places — the
1784
+ * readiness gate wants `confirmed`, and a Haven funding tx hash is
1785
+ * mandatory. Neither is reachable on a scheme where the MERCHANT redeems
1786
+ * the delegation chain: the intent sits at `submitted` by design, and there
1787
+ * is no Haven-submitted transaction at all. Set this to take the
1788
+ * no-funding-leg path through both.
1789
+ */
1790
+ noFundingLeg?: boolean;
1663
1791
  }): Promise<{
1664
1792
  status: number;
1665
1793
  ok: boolean;
@@ -1816,12 +1944,13 @@ declare function signHash(privateKey: string, hash: string): string;
1816
1944
  * verbatim and never reconstruct it (a second source of truth could drift
1817
1945
  * from the account's own rules).
1818
1946
  */
1819
- declare function signUserOpTypedDataForDelegation(privateKey: string, typedData: {
1947
+ interface Eip712TypedData {
1820
1948
  domain: Record<string, unknown>;
1821
1949
  types: Record<string, unknown>;
1822
1950
  primaryType: string;
1823
1951
  message: Record<string, unknown>;
1824
- }): Promise<string>;
1952
+ }
1953
+ declare function signUserOpTypedDataForDelegation(privateKey: string, typedData: Eip712TypedData): Promise<string>;
1825
1954
  /**
1826
1955
  * Derive the Ethereum address from a private key.
1827
1956
  */
@@ -1970,9 +2099,19 @@ type SharedToolKey = keyof typeof toolDescriptions;
1970
2099
  * this canonical string and asserts byte-for-byte equality, so the two copies
1971
2100
  * cannot drift.
1972
2101
  */
1973
- declare const HAVEN_SKILL_MD = "---\nname: haven-pay\ndescription: Pay for things from the user's Haven wallet within their agent rules. Use when the user asks to send, pay, tip, or transfer crypto \u2014 or when a request hits an HTTP 402 (x402) paywall.\n---\n\n# Haven: pay from a Haven wallet\n\nThis skill lets the agent make payments from the user's Haven wallet through\nthe Haven MCP tools. Every payment is checked against the agent's on-chain\nbudget before money moves; payments above the remaining budget wait for the\nuser's approval in Haven.\n\nHosted tools run in the `mcp__haven__` namespace. Local signing tools run in\nthe `mcp__haven-signer__` namespace and keep the delegate key on this machine.\nTool results carry the exact next step (`next_action`, `next_tool`,\n`next_arguments`) \u2014 follow those fields first; the prose below is fallback\nand orientation, not the source of truth.\n\n## When to use this skill\n\n- The user asks to send money, pay someone, tip, donate, or transfer tokens.\n- A request returns HTTP 402 (x402): use the Haven pay tools to settle it,\n then retry the original request.\n\n## Identity and budget\n\nDo not guess the wallet address, network, or budget.\n\nFor instant orientation at the start of a session, read the non-secret\n`agent.json` the connector wrote to your Haven credential directory (typically\n`~/.haven/agents/<agent-id>/agent.json` \u2014 if you don't know the agent id, list\n`~/.haven/agents/` to find the folder). It\nholds your agent id, Haven wallet address, network, and *configured* per-token\nbudget, and contains no keys \u2014 the fastest way to answer \"who am I and what may\nI spend\" with no round trip. If that file is absent (some setups don't write\nit), use the tools below instead.\n\nBefore any payment, confirm the *live remaining* budget with the tools \u2014\n`agent.json` shows the configured budget, not what is left after recent\nspending:\n\n- `mcp__haven__haven_get_agent` \u2014 the recommended first call: identity\n (wallet, network) plus a readiness signal (`ready` / `needs_approval` /\n `revoked`) and live remaining per-token allowance, in one shot.\n- `mcp__haven__haven_get_allowances` \u2014 detailed per-token breakdown\n (configured, spent, reset window) when you need more than the summary.\n\nBudgets reset on a period the user chose. If a payment exceeds the remaining\nbudget it is queued for the user to approve in the Haven dashboard \u2014 this is\nnormal, not an error.\n\n## Paying\n\n**Catalog purchases \u2014 the primary path for MCP merchants:**\n\n1. `mcp__haven__haven_discover_tools` to find a payable service and its\n `catalog_id`.\n2. `mcp__haven__haven_prepare_catalog_purchase` with `catalog_id` and a\n spending cap. A cap is REQUIRED on this tool and is best practice on every\n paid call below too \u2014 it caps what the LIVE merchant quote may charge,\n checked before any funding intent is created. Write it the way the user\n said it: `max_amount_human` is whole tokens, so \"no more than 1 USDC\" is\n `max_amount_human: \"1\"`. (`max_amount` is the atomic-unit form, where\n \"1\" means 0.000001 USDC \u2014 do not convert by hand, and never send both.)\n3. Then FOLLOW THE RESPONSE'S GUIDANCE FIELDS: `next_action`, `next_tool`,\n and `next_arguments` name the exact next call \u2014 act on those first; the\n prose in this section is fallback and debugging detail. If the catalog\n entry is missing or degraded, the response instead names\n `mcp__haven__haven_pay_mcp_tool` (merchant URL, tool name, arguments) as\n the manual fallback.\n\n**Signing:** `mcp__haven-signer__haven_sign_x402` with `payment_id` ONLY \u2014\nthe local signer fetches the exact signing bytes AND `payment_required`\nitself, so never relay `typed_data` or the 402 blob yourself. If the signer\nreports its fetched context carried no `payment_required` (older backend),\nre-call with `payment_required` added verbatim. Fallback for an older signer\nor backend: re-run the quote/prepare tool with the SAME `idempotency_key`\nplus `include_signing_payload=true`, then pass `payload_hash`,\n`x402_expected` (the nested `x402.expected` object), and\n`typed_data`/`typed_data_b64` through unchanged.\n\n**Settle:** `mcp__haven__haven_settle_mcp_tool` with `payment_id`,\n`signature`, and `payment_header` ONLY \u2014 Haven rehydrates the merchant call\ncontext (`merchant_url`, `tool_name`, `arguments`, `mcp_transport`)\nserver-side from `payment_id`. Pass those four fields explicitly only as a\nversion-skew fallback when Haven has no stored context for the id \u2014 both or\nnone together, never just one. If the settle result carries `settled: false`,\nfunding is queued for the user's approval \u2014 tell them and check status later,\ndo not re-pay.\n\nStep-by-step alternative (also key-safe; for an older signer or backend, or\nwhen you already have a merchant URL and tool name instead of a\n`catalog_id`): `mcp__haven__haven_pay_mcp_tool` then\n`mcp__haven-signer__haven_sign` \u2192 `mcp__haven__haven_submit` \u2192\n`mcp__haven-signer__haven_x402_sign_header` \u2192\n`mcp__haven__haven_complete_mcp_tool`. Pass `payment_required`,\n`arguments`, and `mcp_transport` verbatim from the quote/prepare result.\nThe returned `expires_at` is the signing window; if a tool returns\n`PAYMENT_WINDOW_EXPIRED`, re-run the same quote/prepare tool with the same\n`idempotency_key`. Do not call the merchant yourself \u2014 Haven completes the\nmerchant leg for you.\n\n**Direct transfer / non-MCP paywall:** `mcp__haven__haven_pay` with\nrecipient, amount, and token for a plain transfer. For an arbitrary,\nnon-MCP x402 paywall: `mcp__haven__haven_quote_x402` to get a quote, then\n`mcp__haven__haven_pay_x402_quote` \u2014 follow the result's guidance fields\nfirst, sign in the local Haven signer, and retry the original request only\nwhen the result says `retry_original_x402_request`.\n\n**Catalog tool arguments:** when `haven_discover_tools` returns\n`tool_arguments`, pass that object unchanged as the pay tool's\n`arguments` field (for example\n`tool_arguments: { \"tier\": \"50gb\" }` -> `arguments: { \"tier\": \"50gb\" }`).\n\n**Prices:** show the user the live price from the pay-tool result, never a\ncatalog price. `haven_discover_tools` prices are indicative\n(`price_is_indicative`) and can be stale. The pay-tool result's `amount` /\n`amount_atomic` is the amount Haven authorizes for the call \u2014 a ceiling the\nmerchant settles at or below \u2014 so present it as the most the user will pay.\n\n**Status:** `mcp__haven__haven_get_payment_status` with a `payment_id` to\ncheck on queued or in-flight payments. Do not poll in a tight loop.\n\n## Approval semantics\n\n- A result with `pending_approval` means the payment exceeded the remaining\n budget and is waiting for the user in Haven. Tell the user, then check\n status later.\n- `safe_to_continue: false` on a guidance block is the same signal in\n machine-readable form: stop and involve the user before calling anything\n else for this payment.\n- Never ask the user for private keys. Signing happens only in the local Haven\n signer; the hosted Haven tools never receive the signing key. If a tool\n reports a missing or invalid credential, tell the user to re-run the Haven\n setup command.\n\n## Failure handling\n\nHaven tool failures are shaped like `{ success: false, code, message, ... }`\nor older `{ error, status, details? }` responses. Branch on `code` when\npresent and surface `message` or `error` verbatim. Common cases:\n\n- `pending_approval`: queued for the user's approval (see above).\n- `insufficient_funds`: the Haven wallet doesn't hold enough of that token.\n Suggest the user add funds in the Haven dashboard.\n- `PRICE_EXCEEDS_MAX`: the live merchant price exceeded your cap. No funds\n moved; ask the user before retrying with a higher one.\n- `AMBIGUOUS_MAX_AMOUNT`: you sent both `max_amount` and\n `max_amount_human`. Nothing was contacted or spent \u2014 re-send with exactly\n one (`max_amount_human` for a cap the user stated in tokens).\n- `MAX_AMOUNT_UNCONVERTIBLE`: `max_amount_human` does not fit this quote's\n asset \u2014 unknown decimals, or more decimal places than the asset supports.\n Round the cap, or send an exact atomic `max_amount`.\n- `PAYMENT_WINDOW_EXPIRED`: re-run the quote/prepare tool with the same\n `idempotency_key`, then sign the fresh payload.\n- `MERCHANT_REJECTED_AFTER_FUNDING`: the merchant refused the paid retry.\n Stop-and-sweep \u2014 stop retrying the merchant and use\n `mcp__haven__haven_sweep_delegate` to recover stranded delegate funds.\n- `MERCHANT_UNRESPONSIVE_AFTER_FUNDING`: funding confirmed on-chain, but the\n merchant never answered the paid retry. This is NOT proof of rejection \u2014 the\n merchant may still settle late. Verify-then-sweep, never a blind sweep:\n check `mcp__haven__haven_get_payment_status`, retry\n `mcp__haven__haven_complete_mcp_tool` ONCE, and only sweep with\n `mcp__haven__haven_sweep_delegate` if no settlement appears.\n- Budget exceeded: tell the user how much remains (from\n `mcp__haven__haven_get_allowances`) and that they can raise the budget in\n Haven.\n\n## Reporting after a purchase\n\nA settled `mcp__haven__haven_settle_mcp_tool` response carries\n`agent_summary.purchase_summary` and the remaining post-purchase allowance\nin `allowance` \u2014 report the product, Haven-derived payment/transaction\nfields, and what is left from those fields directly. `result` is optional\nraw merchant evidence; never use it to decide whether the purchase was paid.\nDo not call `haven_get_agent` or `haven_get_allowances` again just to\nreport a purchase you already made.\n\n## Revoke\n\nIf this agent's credential may have leaked, tell the user to pause or revoke\nthe agent in the Haven dashboard under Agents. New requests stop immediately\nfor that credential.\n";
2102
+ declare const HAVEN_SKILL_MD = "---\nname: haven-pay\ndescription: Pay for things from the user's Haven wallet within their agent rules. Use when the user asks to send, pay, tip, or transfer crypto \u2014 or when a request hits an HTTP 402 (x402) paywall.\n---\n\n# Haven: pay from a Haven wallet\n\nThis skill lets the agent make payments from the user's Haven wallet through\nthe Haven MCP tools. Every payment is checked against the agent's on-chain\nbudget before money moves; payments above the remaining budget wait for the\nuser's approval in Haven.\n\nHosted tools run in the `mcp__haven__` namespace. Local signing tools run in\nthe `mcp__haven-signer__` namespace and keep the delegate key on this machine.\nTool results carry the exact next step (`next_action`, `next_tool`,\n`next_arguments`) \u2014 follow those fields first; the prose below is fallback\nand orientation, not the source of truth.\n\n## When to use this skill\n\n- The user asks to send money, pay someone, tip, donate, or transfer tokens.\n- A request returns HTTP 402 (x402): use the Haven pay tools to settle it,\n then retry the original request.\n\n## Identity and budget\n\nDo not guess the wallet address, network, or budget.\n\nFor instant orientation at the start of a session, read the non-secret\n`agent.json` the connector wrote to your Haven credential directory (typically\n`~/.haven/agents/<agent-id>/agent.json` \u2014 if you don't know the agent id, list\n`~/.haven/agents/` to find the folder). It\nholds your agent id, Haven wallet address, network, and *configured* per-token\nbudget, and contains no keys \u2014 the fastest way to answer \"who am I and what may\nI spend\" with no round trip. If that file is absent (some setups don't write\nit), use the tools below instead.\n\nBefore any payment, confirm the *live remaining* budget with the tools \u2014\n`agent.json` shows the configured budget, not what is left after recent\nspending:\n\n- `mcp__haven__haven_get_agent` \u2014 the recommended first call: identity\n (wallet, network) plus a readiness signal (`ready` / `needs_approval` /\n `revoked`) and live remaining per-token allowance, in one shot.\n- `mcp__haven__haven_get_allowances` \u2014 detailed per-token breakdown\n (configured, spent, reset window) when you need more than the summary.\n\nBudgets reset on a period the user chose. If a payment exceeds the remaining\nbudget it is queued for the user to approve in the Haven dashboard \u2014 this is\nnormal, not an error.\n\n## Paying\n\n**Catalog purchases \u2014 the primary path for MCP merchants:**\n\n1. `mcp__haven__haven_discover_tools` to find a payable service and its\n `catalog_id`.\n2. If the user needs the live price before authorizing a cap, call\n `mcp__haven__haven_quote_catalog_purchase` with `catalog_id`. It is\n read-only and informational only: it never reserves a price or creates a\n payment. Tell the user its `amount` / `amount_atomic`, then choose a cap.\n3. `mcp__haven__haven_prepare_catalog_purchase` with `catalog_id` and a\n spending cap. A cap is REQUIRED on this tool and is best practice on every\n paid call below too \u2014 it caps what the LIVE merchant quote may charge,\n checked before any funding intent is created. Write it the way the user\n said it: `max_amount_human` is whole tokens, so \"no more than 1 USDC\" is\n `max_amount_human: \"1\"`. (`max_amount` is the atomic-unit form, where\n \"1\" means 0.000001 USDC \u2014 do not convert by hand, and never send both.)\n4. Then FOLLOW THE RESPONSE'S GUIDANCE FIELDS: `next_action`, `next_tool`,\n and `next_arguments` name the exact next call \u2014 act on those first; the\n prose in this section is fallback and debugging detail. If the catalog\n entry is missing or degraded, the response instead names\n `mcp__haven__haven_pay_mcp_tool` (merchant URL, tool name, arguments) as\n the manual fallback.\n\n**Signing:** `mcp__haven-signer__haven_sign_x402` with `payment_id` ONLY \u2014\nthe local signer fetches the exact signing bytes AND `payment_required`\nitself, so never relay `typed_data` or the 402 blob yourself. If the signer\nreports its fetched context carried no `payment_required` (older backend),\nre-call with `payment_required` added verbatim. Fallback for an older signer\nor backend: re-run the quote/prepare tool with the SAME `idempotency_key`\nplus `include_signing_payload=true`, then pass `payload_hash`,\n`x402_expected` (the nested `x402.expected` object), and\n`typed_data`/`typed_data_b64` through unchanged.\n\n**Settle:** `mcp__haven__haven_settle_mcp_tool` with `payment_id`,\n`signature`, and `payment_header` ONLY \u2014 Haven rehydrates the merchant call\ncontext (`merchant_url`, `tool_name`, `arguments`, `mcp_transport`)\nserver-side from `payment_id`. Pass those four fields explicitly only as a\nversion-skew fallback when Haven has no stored context for the id \u2014 both or\nnone together, never just one. If the settle result carries `settled: false`,\nfunding is queued for the user's approval \u2014 tell them and check status later,\ndo not re-pay.\n\nStep-by-step alternative (also key-safe; for an older signer or backend, or\nwhen you already have a merchant URL and tool name instead of a\n`catalog_id`): if the user needs the live price before choosing a cap, first\ncall `mcp__haven__haven_quote_mcp_tool` with that merchant URL, tool name,\nand arguments. It is informational only; then call\n`mcp__haven__haven_pay_mcp_tool` with the same inputs and the explicit cap.\nThe paid call always obtains a fresh quote before it creates any intent. Then\ncontinue `mcp__haven__haven_pay_mcp_tool` \u2192\n`mcp__haven-signer__haven_sign` \u2192 `mcp__haven__haven_submit` \u2192\n`mcp__haven-signer__haven_x402_sign_header` \u2192\n`mcp__haven__haven_complete_mcp_tool`. Pass `payment_required`,\n`arguments`, and `mcp_transport` verbatim from the quote/prepare result.\nThe returned `expires_at` is the signing window; if a tool returns\n`PAYMENT_WINDOW_EXPIRED`, re-run the same quote/prepare tool with the same\n`idempotency_key`. Do not call the merchant yourself \u2014 Haven completes the\nmerchant leg for you.\n\n**Direct transfer / non-MCP paywall:** `mcp__haven__haven_pay` with\nrecipient, amount, and token for a plain transfer. For an arbitrary,\nnon-MCP x402 paywall: `mcp__haven__haven_quote_x402` to get a quote, then\n`mcp__haven__haven_pay_x402_quote` \u2014 follow the result's guidance fields\nfirst, sign in the local Haven signer, and retry the original request only\nwhen the result says `retry_original_x402_request`.\n\n**Catalog tool arguments:** when `haven_discover_tools` returns\n`tool_arguments`, pass that object unchanged as the pay tool's\n`arguments` field (for example\n`tool_arguments: { \"tier\": \"50gb\" }` -> `arguments: { \"tier\": \"50gb\" }`).\n\n**Prices:** show the user the live price from a read-only quote or the pay-tool\nresult, never a catalog price. `haven_discover_tools` prices are indicative\n(`price_is_indicative`) and can be stale. A read-only quote is informational\nonly and does not reserve a price; the later paid call re-quotes and enforces\nthe cap. The pay-tool result's `amount` / `amount_atomic` is the amount\nHaven authorizes for that call \u2014 a ceiling the merchant settles at or below \u2014\nso present it as the most the user will pay.\n\n**Status:** `mcp__haven__haven_get_payment_status` with a `payment_id` to\ncheck on queued or in-flight payments. Do not poll in a tight loop.\n\n## Approval semantics\n\n- A result with `pending_approval` means the payment exceeded the remaining\n budget and is waiting for the user in Haven. Tell the user, then check\n status later.\n- `safe_to_continue: false` on a guidance block is the same signal in\n machine-readable form: stop and involve the user before calling anything\n else for this payment.\n- Never ask the user for private keys. Signing happens only in the local Haven\n signer; the hosted Haven tools never receive the signing key. If a tool\n reports a missing or invalid credential, tell the user to re-run the Haven\n setup command.\n\n## Failure handling\n\nHaven tool failures are shaped like `{ success: false, code, message, ... }`\nor older `{ error, status, details? }` responses. Branch on `code` when\npresent and surface `message` or `error` verbatim. Common cases:\n\n- `pending_approval`: queued for the user's approval (see above).\n- `insufficient_funds`: the Haven wallet doesn't hold enough of that token.\n Suggest the user add funds in the Haven dashboard.\n- `PRICE_EXCEEDS_MAX`: the live merchant price exceeded your cap. No funds\n moved; ask the user before retrying with a higher one.\n- `AMBIGUOUS_MAX_AMOUNT`: you sent both `max_amount` and\n `max_amount_human`. Nothing was contacted or spent \u2014 re-send with exactly\n one (`max_amount_human` for a cap the user stated in tokens).\n- `MAX_AMOUNT_UNCONVERTIBLE`: `max_amount_human` does not fit this quote's\n asset \u2014 unknown decimals, or more decimal places than the asset supports.\n Round the cap, or send an exact atomic `max_amount`.\n- `PAYMENT_WINDOW_EXPIRED`: re-run the quote/prepare tool with the same\n `idempotency_key`, then sign the fresh payload.\n- `MERCHANT_REJECTED_AFTER_FUNDING`: the merchant refused the paid retry.\n Stop-and-sweep \u2014 stop retrying the merchant and use\n `mcp__haven__haven_sweep_delegate` to recover stranded delegate funds.\n- `MERCHANT_UNRESPONSIVE_AFTER_FUNDING`: funding confirmed on-chain, but the\n merchant never answered the paid retry. This is NOT proof of rejection \u2014 the\n merchant may still settle late. Verify-then-sweep, never a blind sweep:\n check `mcp__haven__haven_get_payment_status`, retry\n `mcp__haven__haven_complete_mcp_tool` ONCE, and only sweep with\n `mcp__haven__haven_sweep_delegate` if no settlement appears.\n- Budget exceeded: tell the user how much remains (from\n `mcp__haven__haven_get_allowances`) and that they can raise the budget in\n Haven.\n\n## Reporting after a purchase\n\nA settled `mcp__haven__haven_settle_mcp_tool` response carries\n`agent_summary.purchase_summary` and the remaining post-purchase allowance\nin `allowance` \u2014 report the product, Haven-derived payment/transaction\nfields, and what is left from those fields directly. `result` is optional\nraw merchant evidence; never use it to decide whether the purchase was paid.\nDo not call `haven_get_agent` or `haven_get_allowances` again just to\nreport a purchase you already made.\n\n## Revoke\n\nIf this agent's credential may have leaked, tell the user to pause or revoke\nthe agent in the Haven dashboard under Agents. New requests stop immediately\nfor that credential.\n";
1974
2103
  /** Directory name for the installed skill folder. */
1975
2104
  declare const SKILL_FOLDER_NAME = "haven-pay";
2105
+ /**
2106
+ * The skill BODY — HAVEN_SKILL_MD with the YAML front-matter stripped.
2107
+ *
2108
+ * For runtimes whose instruction mechanism is a plain guidance file rather
2109
+ * than a skills folder (Codex's global AGENTS.md, #1332), the front-matter is
2110
+ * skill-registry metadata with no meaning and would render as a stray table.
2111
+ * Derived mechanically from the canonical string above, never maintained by
2112
+ * hand — the substance cannot fork per runtime.
2113
+ */
2114
+ declare const HAVEN_SKILL_BODY_MD: string;
1976
2115
 
1977
2116
  /**
1978
2117
  * The Node.js floor Haven's published packages support (#1161).
@@ -2055,6 +2194,24 @@ declare function unsupportedNodeVersionMessage(options: UnsupportedNodeVersionMe
2055
2194
  * (see client.ts) since they need API access and signing.
2056
2195
  */
2057
2196
 
2197
+ /**
2198
+ * Persisted, agent-scoped facts used to preflight a signed standard x402
2199
+ * payment header. This is an integrity comparison only: it never rebuilds,
2200
+ * modifies, persists, or submits the supplied authorization.
2201
+ */
2202
+ interface X402PaymentHeaderContext {
2203
+ merchantTo: string;
2204
+ amountAtomic: string;
2205
+ asset: string;
2206
+ network: string;
2207
+ resourceUrl: string;
2208
+ payer: string;
2209
+ chainId: number;
2210
+ }
2211
+ /** A deliberately value-free refusal for untrusted payment-header input. */
2212
+ declare class X402PaymentHeaderValidationError extends Error {
2213
+ constructor();
2214
+ }
2058
2215
  /**
2059
2216
  * Upper bound on the MERCHANT-requested part of the EIP-3009 authorization
2060
2217
  * window (#715, epic #713). The x402 library sets
@@ -2085,6 +2242,7 @@ declare const X402_MAX_AUTHORIZATION_WINDOW_SECONDS = 600;
2085
2242
  * clamp discipline.
2086
2243
  */
2087
2244
  declare const X402_SETTLEMENT_FORWARD_MARGIN_SECONDS = 300;
2245
+ declare function normalizePaymentRequired(value: unknown): X402PaymentRequired | null;
2088
2246
  /**
2089
2247
  * Parse an HTTP 402 response into x402 PaymentRequired data.
2090
2248
  *
@@ -2111,12 +2269,84 @@ declare function parsePaymentRequiredResponse(response: Response): Promise<X402P
2111
2269
  * 3. null — no compatible option
2112
2270
  */
2113
2271
  declare function selectPaymentOption(accepts: X402PaymentOption[]): X402PaymentOption | null;
2272
+ /** The `extra.assetTransferMethod` value that marks an erc7710-settleable entry. */
2273
+ declare const ERC7710_ASSET_TRANSFER_METHOD = "erc7710";
2274
+ /**
2275
+ * Read `extra.assetTransferMethod` defensively. `extra` is the merchant's own
2276
+ * object, so it is untrusted shape: anything that is not the exact string is
2277
+ * treated as "not erc7710" rather than coerced.
2278
+ */
2279
+ declare function x402AssetTransferMethod(option: X402PaymentOption): string | null;
2280
+ /** True when the merchant advertises this entry as erc7710-settleable. */
2281
+ declare function isErc7710Option(option: X402PaymentOption): boolean;
2282
+ /**
2283
+ * The facilitator addresses a merchant advertises for an erc7710 entry, for
2284
+ * the #1058 redeemer pin — or `null` when it pins nothing.
2285
+ *
2286
+ * **An EMPTY array is `null`, not `[]`.** The backend rejects an empty
2287
+ * `redeemers` list with a 400 (`routes/x402.ts`), and the QA scenario already
2288
+ * treats empty as absent. Returning `[]` here would hand callers a value that
2289
+ * means "pin to nobody" — which is not a narrower pin, it is an unbuildable
2290
+ * delegation.
2291
+ *
2292
+ * Malformed entries are DROPPED rather than failing the whole option, and that
2293
+ * asymmetry is deliberate. A pin narrowed by a merchant's typo means the
2294
+ * facilitator that actually tries to redeem is not on the list, so redemption
2295
+ * reverts — and erc7710 has no funding leg, so nothing moved and nothing is
2296
+ * stranded. Refusing the option outright would instead deny a payment the
2297
+ * remaining valid facilitators could have settled. Losing the payment is the
2298
+ * worse outcome, precisely because the failure this issue closes (#1453) is the
2299
+ * one where funds move BEFORE the rejection.
2300
+ */
2301
+ declare function x402FacilitatorAddresses(option: X402PaymentOption): string[] | null;
2114
2302
  /**
2115
2303
  * Select an option that can be paid with the official x402 EIP-3009 exact
2116
2304
  * scheme. Haven's older tx-hash proof path can describe more networks; the
2117
2305
  * merchant-verified path currently needs Base USDC.
2306
+ *
2307
+ * **Skips erc7710-tagged entries (#1453).** It used to return the first
2308
+ * positional match and never look at `extra.assetTransferMethod`, so a merchant
2309
+ * that listed its erc7710 entry first made a Haven client echo that option
2310
+ * while signing a standard EIP-3009 authorization. The merchant rejects the
2311
+ * mismatch cleanly — but on the legacy two-leg the Safe→delegate funding
2312
+ * transfer has already executed, so the visible result is a stranded delegate
2313
+ * balance for the sweep to reclaim. Only our own demo merchant's ordering was
2314
+ * holding that shut, and that pin binds our merchant, not the ones we do not
2315
+ * control.
2118
2316
  */
2119
2317
  declare function selectStandardPaymentOption(accepts: X402PaymentOption[]): X402PaymentOption | null;
2318
+ /**
2319
+ * Select the erc7710-settleable option, if the merchant advertises one.
2320
+ */
2321
+ declare function selectErc7710PaymentOption(accepts: X402PaymentOption[]): X402PaymentOption | null;
2322
+ /** What a settlement-scheme decision resolved to. */
2323
+ interface X402SchemeSelection {
2324
+ scheme: 'erc7710' | 'eip3009';
2325
+ option: X402PaymentOption;
2326
+ /** Redeemer pin for the settlement child; only ever set on erc7710. */
2327
+ facilitatorAddresses: string[] | null;
2328
+ }
2329
+ /**
2330
+ * THE preference rule, in one place (#1450 owner decision, #1453).
2331
+ *
2332
+ * Prefer erc7710 whenever the account is on the delegation rail and the
2333
+ * merchant advertises `extra.assetTransferMethod: "erc7710"`; fall back to
2334
+ * the EIP-3009 bridge otherwise.
2335
+ *
2336
+ * Both halves of that condition are required, and the rail half is the
2337
+ * caller's to supply — the SDK cannot see which rail an account is on from a
2338
+ * 402 response alone. A legacy AllowanceModule account passing
2339
+ * `delegationRail: true` would select a scheme its account cannot settle; the
2340
+ * backend refuses that at authorize (`validateGenericSchemeRail`), which is
2341
+ * where a rail mismatch SHOULD fail, on-chain-adjacent rather than in a client
2342
+ * that could be lying to itself.
2343
+ *
2344
+ * Returns `null` when neither scheme has a payable entry — the caller decides
2345
+ * whether that is an error or a reason to look elsewhere.
2346
+ */
2347
+ declare function selectX402SettlementScheme(accepts: X402PaymentOption[], opts: {
2348
+ delegationRail: boolean;
2349
+ }): X402SchemeSelection | null;
2120
2350
  declare function x402AuthorizationAmount(option: X402PaymentOption): string;
2121
2351
  /**
2122
2352
  * Canonical Haven-authenticated x402 expected context, recomputed byte-for-byte
@@ -2136,6 +2366,15 @@ declare function x402AuthorizationAmount(option: X402PaymentOption): string;
2136
2366
  */
2137
2367
  declare function buildX402ExpectedMessage(context: X402ExpectedContext): string;
2138
2368
  declare function toStandardPaymentRequirements(paymentRequired: X402PaymentRequired, option: X402PaymentOption): PaymentRequirements;
2369
+ /**
2370
+ * Strictly validate an edge-signed EIP-3009 X-PAYMENT header against the
2371
+ * persisted x402 intent context before a hosted relay can submit funding.
2372
+ *
2373
+ * The merchant/facilitator remains the final protocol verifier. This closes a
2374
+ * separate hosted-relay integrity gap: malformed or context-mismatched input
2375
+ * must never cause Haven to relay the funding signature first.
2376
+ */
2377
+ declare function validateStandardX402PaymentHeader(paymentHeader: string, context: X402PaymentHeaderContext): Promise<void>;
2139
2378
  /**
2140
2379
  * Encode a payment receipt as a base64 PAYMENT-SIGNATURE header value.
2141
2380
  *
@@ -2230,4 +2469,4 @@ declare function discoverMerchantMcpUrl(inputUrl: string): Promise<string | null
2230
2469
  /** Trailing-slash/percent-case echoes compare equal; unparseable never does. */
2231
2470
  declare function sameUrl(a: string, b: string): boolean;
2232
2471
 
2233
- export { AGENT_PAYMENT_FAILURE_CODE_VALUES, AGENT_PAYMENT_NEXT_ACTION_VALUES, AGENT_PAYMENT_PHASE_VALUES, AGENT_PAYMENT_RAIL_VALUES, type AgentNextStep, type AgentPaymentEnumSchema, AgentPaymentFailureCode, AgentPaymentFailureCodeDescriptions, AgentPaymentFailureCodeSchema, AgentPaymentNextAction, AgentPaymentNextActionDescriptions, AgentPaymentNextActionSchema, AgentPaymentPhase, AgentPaymentPhaseDescriptions, AgentPaymentPhaseSchema, AgentPaymentRail, AgentPaymentRailDescriptions, AgentPaymentRailSchema, type AgentPaymentSummary, type AgentPaymentWarning, AgentPaymentWarningCode, type AgentPurchaseSummary, type ClaudeTool, DISCOVERY_MAX_BYTES, HAVEN_MINIMUM_NODE_VERSION, HAVEN_SKILL_MD, type HavenAgent, type HavenAgentAllowanceSummary, type HavenAgentReadiness, type HavenAgentSummary, type HavenAllowance, type HavenAllowanceSummary, HavenApiError, type HavenCatalogEntry, HavenClient, type HavenClientConfig, HavenError, type HavenPaymentReceipt, HavenPaymentStateError, HavenSigningError, HavenTimeoutError, HavenUnsupportedSignerVersionError, MERCHANT_DISCOVERY_PATHS, type MachinePaymentRail, MerchantTimeoutError, type OpenAITool, type PaymentFee, type PaymentIntent, type PaymentNextAction, type PaymentPhase, type PaymentReceipt, type PaymentRequest, type PaymentResult, type PaymentResumeState, type PaymentStatus, type PaymentStatusResult, type PendingApproval, type PostPurchaseAllowanceSummary, RECEIPT_VERSION, type ReceiptVerification, type ResumeAuthorizedX402Input, type ResumeX402PaymentInput, SIGNER_UPDATE_FALLBACK, SKILL_FOLDER_NAME, SWEEP_BASE_CHAIN_ID, SWEEP_BASE_SEPOLIA_CHAIN_ID, SWEEP_BASE_SEPOLIA_USDC_ADDRESS, SWEEP_BASE_USDC_ADDRESS, type SharedToolKey, type SignData, SignerRefusalCode, type SweepAuthorization, type SweepEip712Domain, type SweepEntry, type SweepExpectedAuth, type SweepPreparation, type SweepPrepareResponse, type SweepResult, type SweepSubmitResponse, type SweepSubmitResult, type SweepTypedData, TRANSFER_WITH_AUTHORIZATION_TYPES, type ToolDescription, type UnsupportedNodeVersionMessageOptions, type X402AuthorizationOptions, type X402ExpectedAuth, type X402ExpectedContext, type X402Intent, type X402McpCallContext, type X402McpTransport, type X402MerchantCallContext, type X402PaymentOption, type X402PaymentRequired, type X402Quote, type X402Receipt, type X402RequestSnapshot, type X402ResumeState, X402UnexpectedStatusError, X402_MAX_AUTHORIZATION_WINDOW_SECONDS, X402_SETTLEMENT_FORWARD_MARGIN_SECONDS, addressFromKey, buildSweepAuthorizationMessage, buildSweepTypedData, buildX402ExpectedMessage, compareNodeVersions, composeDescription, decodeBase64Json, decodeBase64Utf8, discoverMerchantMcpUrl, encodeBase64Json, encodeBase64Utf8, encodePaymentProof, havenTools, isSupportedNodeVersion, isSweepableChain, parsePaymentRequired, parsePaymentRequiredResponse, resolveTokenFromAddress, sameUrl, selectPaymentOption, selectStandardPaymentOption, signHash, signUserOpTypedDataForDelegation, sweepUsdcAddress, sweepUsdcDomain, toStandardPaymentRequirements, toolDescriptions, unsupportedNodeVersionMessage, verifyPaymentReceipt, verifySignature, x402AuthorizationAmount };
2472
+ export { AGENT_PAYMENT_FAILURE_CODE_VALUES, AGENT_PAYMENT_NEXT_ACTION_VALUES, AGENT_PAYMENT_PHASE_VALUES, AGENT_PAYMENT_RAIL_VALUES, type AgentNextStep, type AgentPaymentEnumSchema, AgentPaymentFailureCode, AgentPaymentFailureCodeDescriptions, AgentPaymentFailureCodeSchema, AgentPaymentNextAction, AgentPaymentNextActionDescriptions, AgentPaymentNextActionSchema, AgentPaymentPhase, AgentPaymentPhaseDescriptions, AgentPaymentPhaseSchema, AgentPaymentRail, AgentPaymentRailDescriptions, AgentPaymentRailSchema, type AgentPaymentSummary, type AgentPaymentWarning, AgentPaymentWarningCode, type AgentPurchaseSummary, type ClaudeTool, DISCOVERY_MAX_BYTES, ERC7710_ASSET_TRANSFER_METHOD, HAVEN_MINIMUM_NODE_VERSION, HAVEN_SKILL_BODY_MD, HAVEN_SKILL_MD, type HavenAgent, type HavenAgentAllowanceSummary, type HavenAgentReadiness, type HavenAgentSummary, type HavenAllowance, type HavenAllowanceSummary, HavenApiError, type HavenCatalogEntry, HavenClient, type HavenClientConfig, HavenError, type HavenPaymentReceipt, HavenPaymentStateError, HavenSigningError, HavenTimeoutError, HavenUnsupportedSignerVersionError, MERCHANT_DISCOVERY_PATHS, type MachinePaymentRail, MerchantTimeoutError, type OpenAITool, type PaymentFee, type PaymentIntent, type PaymentNextAction, type PaymentPhase, type PaymentReceipt, type PaymentRequest, type PaymentResult, type PaymentResumeState, type PaymentStatus, type PaymentStatusResult, type PendingApproval, type PostPurchaseAllowanceSummary, RECEIPT_VERSION, type ReceiptVerification, type ResumeAuthorizedX402Input, type ResumeX402PaymentInput, SIGNER_UPDATE_FALLBACK, SKILL_FOLDER_NAME, SWEEP_BASE_CHAIN_ID, SWEEP_BASE_SEPOLIA_CHAIN_ID, SWEEP_BASE_SEPOLIA_USDC_ADDRESS, SWEEP_BASE_USDC_ADDRESS, type SharedToolKey, type SignData, SignerRefusalCode, type SweepAuthorization, type SweepEip712Domain, type SweepEntry, type SweepExpectedAuth, type SweepPreparation, type SweepPrepareResponse, type SweepResult, type SweepSubmitResponse, type SweepSubmitResult, type SweepTypedData, TRANSFER_WITH_AUTHORIZATION_TYPES, type ToolDescription, type UnsupportedNodeVersionMessageOptions, type X402AuthorizationOptions, type X402Erc7710Settlement, type X402ExpectedAuth, type X402ExpectedContext, type X402Intent, type X402McpCallContext, type X402McpTransport, type X402MerchantCallContext, type X402PaymentHeaderContext, X402PaymentHeaderValidationError, type X402PaymentOption, type X402PaymentRequired, type X402Quote, type X402Receipt, type X402RequestSnapshot, type X402ResumeState, type X402SchemeSelection, 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 };