@haven_ai/sdk 0.1.23-alpha.2 → 0.1.24-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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts","../src/signer.ts","../src/receipt.ts","../src/base64.ts","../src/x402.ts","../src/provider.ts","../src/client.ts","../src/tool-descriptions.ts","../src/tools.ts","../src/skill-content.ts","../src/node-version.ts","../src/sweep.ts","../src/merchant-discovery.ts"],"names":["ethers","signHash","createHash","hashTypedData","AsyncLocalStorage","receipt","privateKeyToAccount","exact","sameAddress","stableStringify"],"mappings":";;;;;;;;;;;;AAktBO,IAAM,iBAAA,GAAoB;AAAA;AAAA,EAE/B,sBAAA,EAAwB,0BAAA;AAAA;AAAA,EAExB,gBAAA,EAAkB,mBAAA;AAAA;AAAA,EAElB,gBAAA,EAAkB,mBAAA;AAAA;AAAA,EAElB,oBAAA,EAAsB,wBAAA;AAAA;AAAA,EAEtB,qBAAA,EAAuB,yBAAA;AAAA;AAAA,EAEvB,6BAAA,EAA+B,kCAAA;AAAA;AAAA,EAE/B,WAAA,EAAa,cAAA;AAAA;AAAA,EAEb,QAAA,EAAU,UAAA;AAAA;AAAA,EAEV,OAAA,EAAS,SAAA;AAAA;AAAA,EAET,MAAA,EAAQ,QAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQR,iBAAA,EAAmB,oBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOnB,kBAAA,EAAoB;AACtB;AAIO,IAAM,sBAAA,GAAyB;AAAA;AAAA,EAEpC,oBAAA,EAAsB,yBAAA;AAAA;AAAA,EAEtB,gBAAA,EAAkB,oBAAA;AAAA;AAAA,EAElB,IAAA,EAAM,MAAA;AAAA;AAAA,EAEN,mBAAA,EAAqB,wBAAA;AAAA;AAAA,EAErB,4BAAA,EAA8B,mCAAA;AAAA;AAAA,EAE9B,wBAAA,EAA0B,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AE,CAAA;AAAA,EACtG,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF","file":"index.cjs","sourcesContent":["// ── Client Configuration ─────────────────────────────────────────\n\nexport interface HavenClientConfig {\n /** Haven API key (sk_agent_xxx) */\n apiKey: string\n\n /** Agent's delegate EOA private key. If provided, the SDK handles signing automatically. */\n delegateKey?: string\n\n /** Haven API base URL (default: http://localhost:3001) */\n baseUrl?: string\n\n /** Optional wallet identity to send as the x402-wallet header. */\n x402Wallet?: string\n\n /** Timeout in ms for individual HTTP requests (default: 30000) */\n requestTimeout?: number\n /** Timeout (ms) for MERCHANT-facing requests — x402/MPP probes, MCP\n * handshakes, paid retries. Separate from requestTimeout (Haven API):\n * merchants may settle on-chain synchronously, so the default is\n * deliberately generous. #1300. */\n merchantTimeout?: number\n\n /** Timeout in ms when polling for tx confirmation (default: 90000) */\n confirmationTimeout?: number\n\n /** Polling interval in ms when waiting for confirmation (default: 3000) */\n pollingInterval?: number\n\n /**\n * Extra headers to attach to every request to the Haven API.\n *\n * Used by the MCP server to tag requests with `X-Haven-MCP-Tool: <name>`\n * so the backend can record an audit-log entry per tool invocation. Has\n * no effect on outbound merchant requests (x402 / MPP) — those are\n * standard HTTP and never carry Haven-internal headers.\n */\n defaultHeaders?: Record<string, string>\n\n /**\n * JSON-RPC RPC URLs keyed by EIP-155 chain ID.\n *\n * When provided for a chain, the SDK waits for ≥1 on-chain confirmation of\n * the AllowanceModule funding tx before retrying the merchant. This prevents\n * the race where the merchant's `balanceOf(delegate)` call runs before the\n * funding block has propagated to the merchant's RPC node.\n *\n * Without this option the SDK proceeds as soon as Haven's backend confirms\n * submission (backward-compatible default). Set it to a reliable RPC\n * endpoint (e.g. Alchemy / Infura) for production usage.\n *\n * @example { 8453: 'https://mainnet.base.org' }\n */\n chainRpcs?: Record<number, string>\n}\n\n// ── Payment Types ────────────────────────────────────────────────\n\nexport interface PaymentRequest {\n /** Token symbol: \"EURe\", \"USDC.e\", or \"xDAI\" */\n token: string\n\n /** Amount as a decimal string, e.g. \"5.00\" */\n amount: string\n\n /** Recipient Ethereum address (0x...) */\n to: string\n\n /**\n * Optional dedupe key (#1207): a retried request with the same key returns\n * the FIRST request's result instead of minting a second transfer or a\n * second approval. Same contract as /machine-payments/send. Max 128 chars.\n */\n idempotencyKey?: string\n}\n\nexport interface SignData {\n /** The hash to sign (keccak256, 0x-prefixed) */\n hash: string\n\n /**\n * Delegation rail: 'eip712_userop' (funding redemption) or\n * 'eip712_delegation' (erc7710 settlement child). Absent = legacy\n * AllowanceModule (raw ECDSA over `hash`). The session rail's\n * 'eip191_userop' is retired (#834).\n *\n * When present, `hash` is NOT what gets signed — `typed_data` is (#1138).\n */\n signature_scheme?: 'eip712_userop' | 'eip712_delegation'\n\n /**\n * EIP-712 payload the account validates, signed VERBATIM (#829). Present\n * whenever `signature_scheme` is — never reconstruct it from `components`.\n */\n typed_data?: {\n domain: Record<string, unknown>\n types: Record<string, unknown>\n primaryType: string\n message: Record<string, unknown>\n }\n\n /** Breakdown of values that were hashed — useful for debugging */\n components: {\n safe: string\n token: string\n to: string\n amount: string\n payment_token: string\n payment: string\n nonce: number\n }\n\n /** Human-readable signing instructions */\n instructions: string\n}\n\nexport interface PaymentIntent {\n /** Unique payment ID */\n paymentId: string\n\n /** Current status */\n status: 'pending_signature'\n\n /** ISO 8601 expiry timestamp */\n expiresAt: string\n\n /** Data needed to sign the payment */\n signData: SignData\n}\n\nexport type PaymentStatus =\n | 'pending_signature'\n | 'submitted'\n | 'confirmed'\n | 'pending_approval'\n | 'approved'\n | 'proposed'\n | 'executed'\n | 'rejected'\n | 'expired'\n | 'failed'\n\nexport interface PaymentResult {\n /** Unique payment ID */\n paymentId: string\n\n /** Final status */\n status: PaymentStatus\n\n /** Token that was sent */\n token: string\n\n /** Amount that was sent (human-readable) */\n amount: string\n\n /** Recipient address */\n to: string\n\n /** On-chain transaction hash (present when confirmed) */\n txHash: string | null\n\n /** Error message (present when failed) */\n errorMessage: string | null\n\n /** Block explorer URL for the transaction (chain-dependent) */\n explorerUrl: string | null\n\n /** ISO 8601 timestamps */\n createdAt: string\n signedAt: string | null\n submittedAt: string | null\n confirmedAt: string | null\n expiresAt: string\n\n /**\n * Platform fee surfaced on the result so it's never silently collected. Dark\n * today (`amount` \"0\", `applied` false); always present so it's visible the\n * moment fees go live.\n */\n fee?: PaymentFee | null\n}\n\n/** The Haven platform fee applied to a payment (#386). */\nexport interface PaymentFee {\n /** Human-readable fee amount (\"0\" while the fee module is dark). */\n amount: string\n /** Token the fee is denominated in. */\n token: string\n /** Fee as basis points of gross (0 while dark). */\n basisPoints: number\n /** True when a non-zero fee was actually applied. */\n applied: boolean\n}\n\n// ── x402 Types ──────────────────────────────────────────────────\n\n/** Payment requirements from an HTTP 402 response (x402 protocol). */\nexport interface X402PaymentRequired {\n x402Version: number\n resource: {\n url: string\n description?: string\n mimeType?: string\n }\n accepts: X402PaymentOption[]\n error?: string\n extensions?: Record<string, unknown>\n}\n\n/** A single payment option from x402 PaymentRequired. */\nexport interface X402PaymentOption {\n scheme: string // \"exact\"\n network: string // CAIP-2 chain ID or x402 network, e.g. \"eip155:8453\" or \"base\"\n amount: string // Atomic units\n maxAmountRequired?: string // Atomic units (official x402 field)\n resource?: string\n description?: string\n mimeType?: string\n asset: string // Token contract address\n payTo: string // Recipient address\n maxTimeoutSeconds: number\n extra?: Record<string, unknown>\n}\n\n/** Receipt returned after a successful x402 payment. */\nexport interface X402Receipt {\n success: boolean\n paymentId: string\n txHash: string\n token: string\n amount: string\n to: string\n resourceUrl: string\n explorerUrl: string\n accepted?: X402PaymentOption\n paymentHeader?: string\n merchantTo?: string | null\n payer?: string\n chainId?: number\n haven?: {\n paymentId: string\n fundingTxHash: string\n fundingExplorerUrl: string\n }\n merchant?: {\n payTo: string | null\n settlementTxHash?: string | null\n settlementExplorerUrl?: string | null\n }\n x402?: {\n amount: string\n token: string\n network: string\n asset: string\n resource: string\n }\n}\n\nexport interface X402AuthorizationOptions {\n /** Stable caller-supplied key for this user intent. Prevents duplicate approvals across fresh 402 quotes. */\n idempotencyKey?: string\n /**\n * #1307: the merchant MCP-tool call context this quote was made against\n * (merchant_url, tool_name, arguments, mcp_transport). Persisted on the\n * intent so `getX402MerchantCallContext` can rehydrate it by payment_id at\n * settle/complete time instead of the caller re-threading it. Optional —\n * omit for a non-MCP-tool x402 merchant (plain HTTP resource).\n */\n mcpCallContext?: X402McpCallContext\n /**\n * #1348: the agent's delegate address, when the caller already resolved it\n * from `getAgent()` in this same flow — skips `createX402Intent`'s internal\n * agent fetch (one full round trip on every guided purchase). Staleness\n * caveat (#1358 review): the backend derives the funding shape by comparing\n * `payTo` to the CURRENT delegate address, so a value made stale by a\n * delegate rotation mid-flow is not always a clean failure — a pinned-budget\n * agent gets a 403, but an open-budget delegation agent would route to the\n * settlement shape with the stale address. The window is one tool call\n * (previously sub-millisecond, now the merchant-quote duration), never\n * externally suppliable; server-truth hardening is tracked in #1360. Only\n * pass an address fetched in THIS flow; omit to keep the self-contained\n * fetch.\n */\n delegateAddress?: string\n}\n\n/**\n * Keyless x402 construct result.\n *\n * Returned by `createX402Intent` — the non-custodial half of an x402 payment.\n * It carries the unsigned funding hash (`signData.hash`, Safe → delegate EOA)\n * plus everything the *edge* needs to build and sign the EIP-3009 merchant\n * header itself. The construct path never signs; both delegate signatures\n * (funding hash + merchant header) happen on the machine that holds the key.\n */\nexport interface X402Intent {\n /** Haven payment id for the funding transfer. */\n paymentId: string\n /** Stable key used to create or refresh this x402 funding intent. */\n idempotencyKey: string\n status: 'pending_signature'\n /** ISO 8601 expiry of the funding intent, if returned. */\n expiresAt?: string\n /** The unsigned funding hash to sign with the delegate key (Safe → delegate EOA). */\n signData: SignData\n /** The selected x402 option — the edge needs this to build the EIP-3009 header. */\n accepted: X402PaymentOption\n /** Resource URL the 402 came from. */\n resourceUrl: string\n /** Merchant payTo address (the final recipient of the EIP-3009 transfer). */\n merchantTo: string\n /** Atomic amount the edge signer must authorize in the merchant header. */\n amountAtomic: string\n /** Token contract the merchant header must pay. */\n asset: string\n /** x402 network the merchant header must use. */\n network: string\n /** Haven-authenticated binding over the x402 expected context. */\n expectedAuth: X402ExpectedAuth\n /**\n * EIP-712 digest of `signData.typed_data`, present on the delegation rail\n * (#1138). The edge signer needs it to reconstruct the v2 expected-context\n * message that Haven signed.\n */\n expectedTypedDataHash?: string\n /** Delegate EOA the funding transfer tops up (the x402 payer). */\n fundingTo: string\n}\n\nexport interface X402ExpectedContext {\n paymentId: string\n payloadHash: string\n resourceUrl: string\n merchantTo: string\n amount: string\n asset: string\n network: string\n /** Optional ISO expiry for the funding/quote window. When present, it is bound into the Haven-authenticated context. */\n expiresAt?: string\n /**\n * EIP-712 digest of the typed data the account actually validates\n * (delegation rail, #1138). Present ⇒ the context is **version 2** and the\n * signer must sign that typed data, never `payloadHash`.\n *\n * On the delegation rail `payloadHash` is the bare ERC-4337 UserOp hash,\n * which is NOT what the account validates — binding it alone would leave the\n * edge signer unable to verify the payload it is being asked to sign. Binding\n * this digest makes Haven's declaration cover the real payload.\n */\n typedDataHash?: string\n}\n\nexport interface X402ExpectedAuth {\n /**\n * 1 = hash-only (legacy rail). 2 = carries `typedDataHash` (delegation rail,\n * #1138).\n *\n * Deliberately `number`, not a literal union (#1143). This is an **inbound**\n * value: a signer parses a context Haven produced, and a signer older than the\n * backend will legitimately receive a version it does not know. A closed union\n * makes that state unrepresentable, which pushed the rejection down to the\n * schema boundary and produced a raw validation error naming neither the cause\n * nor the fix. The supported set lives in the signer\n * (`SUPPORTED_X402_EXPECTED_VERSIONS`), which fails closed on anything outside\n * it with an actionable message.\n */\n version: number\n message: string\n signature: string\n signer: string\n}\n\n/** Serializable HTTP request state for retrying the same x402 merchant request. */\nexport interface X402RequestSnapshot {\n url: string\n method: string\n headers: [string, string][]\n body?: string\n}\n\nexport interface X402McpTransport {\n handshakeRequired: boolean\n source: 'path' | 'bazaar'\n}\n\n/**\n * #1307: the merchant MCP-tool call an x402 quote was made against — carried\n * through `createX402Intent`'s options so Haven can persist it for the\n * settle-leg rehydration handoff (`getX402MerchantCallContext`). Convenience\n * metadata for retrying the merchant's OWN JSON-RPC call, never payment\n * authority.\n */\nexport interface X402McpCallContext {\n merchantUrl: string\n toolName: string\n arguments?: Record<string, unknown>\n mcpTransport?: X402McpTransport\n}\n\n/**\n * Response shape of `getX402MerchantCallContext` — the stored merchant call\n * context for a payment_id, rehydrated instead of re-threaded (#1307).\n */\nexport interface X402MerchantCallContext {\n paymentId: string\n merchantUrl: string\n toolName: string\n arguments: Record<string, unknown>\n mcpTransport?: X402McpTransport\n}\n\n/** @internal */\nexport interface RawX402MerchantCallContext {\n payment_id: string\n merchant_url: string\n tool_name: string\n arguments?: Record<string, unknown>\n mcp_transport?: { handshake_required: boolean; source: 'path' | 'bazaar' }\n error?: string\n error_code?: string\n status?: string\n}\n\n/** Quote parsed from an HTTP 402 response without creating a Haven payment. */\nexport interface X402Quote {\n rail: 'x402'\n idempotencyKey: string\n paymentRequired: X402PaymentRequired\n accepted: X402PaymentOption\n request: X402RequestSnapshot\n mcpTransport?: X402McpTransport\n resourceUrl: string\n description: string | null\n mimeType: string | null\n amountAtomic: string\n amount: string\n token: string\n /**\n * #1351: decimals for `asset` on `network`, resolved from the SAME\n * address→token binding that produced `token` — the quote's own authority on\n * how many atomic units one human unit is. `null` when the merchant's asset\n * is not a token Haven recognises on that network, in which case `token` is\n * an unverified fallback label and NO human→atomic conversion is safe.\n * Consumers converting a human-denominated figure (a user-intent spending\n * cap) MUST fail closed on `null` rather than assume 6.\n */\n decimals: number | null\n asset: string\n network: string\n chainId: number | null\n merchantAddress: string\n maxTimeoutSeconds: number\n}\n\n/** State bundle an agent can persist while waiting for manual x402 approval. */\nexport interface X402ResumeState {\n rail: 'x402'\n paymentId: string\n idempotencyKey: string\n paymentRequired: X402PaymentRequired\n accepted: X402PaymentOption\n url: string\n request?: X402RequestSnapshot\n resourceUrl: string\n description: string | null\n amountAtomic: string\n amount: string\n token: string\n asset: string\n network: string\n chainId: number | null\n merchantAddress: string\n}\n\n// #1328: MppAuthorizationOptions / MppQuote / MppResumeState / ResumeAuthorizedMppInput\n// / ResumeMppPaymentInput / MachinePaymentChallenge / MachinePaymentReceipt were\n// the wire types for the retired mpp_demo challenge/quote/resume client surface\n// (`quoteMpp` / `payMppChallenge` / `resumeMppPayment` / `authorizeMachinePayment`,\n// all removed from client.ts). `MachinePaymentRail` stays — it is still the read-path\n// vocabulary for historical payment/evidence/status rows (mpp_demo, mpp_crypto,\n// stripe_deposit, spt all remain valid values there).\n\nexport type PaymentResumeState = X402ResumeState\n\nexport interface ResumeAuthorizedX402Input extends X402AuthorizationOptions {\n /** Payment or approval request ID returned by authorizeX402 / haven.fetch. */\n paymentId: string\n\n /** Original or freshly parsed x402 requirements for the merchant retry. */\n paymentRequired: X402PaymentRequired\n}\n\nexport interface ResumeX402PaymentInput extends X402AuthorizationOptions {\n /** Payment or approval request ID returned by authorizeX402 / haven.fetch. */\n paymentId: string\n\n /** Original paid URL. If paymentRequired is omitted, Haven will call it once to re-read the 402 challenge. */\n url: string\n\n /** Original fetch options. Reused for the 402 probe and final merchant retry. */\n init?: RequestInit\n\n /** Serializable original request captured by quoteX402() / pending approval errors. */\n request?: X402RequestSnapshot\n\n /** Original or freshly parsed x402 requirements. Supplying this avoids an extra merchant 402 probe. */\n paymentRequired?: X402PaymentRequired\n}\n\n// ── Machine Payment Types ───────────────────────────────────────\n//\n// The wire-shape TYPES for the retired mpp_demo challenge/quote/resume\n// client surface (MachinePaymentChallenge, MachinePaymentReceipt,\n// MppAuthorizationOptions, ResumeAuthorizedMppInput, ResumeMppPaymentInput)\n// were removed with it (#1328). MachinePaymentRail stays: it is still the\n// read-path vocabulary on historical payment/evidence/status responses.\n\nexport type MachinePaymentRail =\n | 'x402'\n | 'mpp_demo'\n | 'mpp_crypto'\n | 'stripe_deposit'\n | 'spt'\n\nexport interface HavenAgent {\n id: string\n name: string\n status: string\n safeAddress: string\n delegateAddress: string\n chainId: number\n /**\n * Which on-chain policy primitive gates this agent's spend (#1306): the\n * legacy Safe AllowanceModule (import-only accounts) or the delegation\n * rail's active budget delegations (#1090). Read-only reporting — the\n * on-chain state is the actual gate either way, this only says which\n * mechanism a caller should read/derive from.\n */\n executionRail: 'legacy' | 'delegation'\n}\n\nexport interface HavenAllowance {\n id: string\n tokenAddress: string\n tokenSymbol: string\n configuredAmount: string\n resetPeriodMin: number\n onchain: {\n amount: string\n spent: string\n remaining: string\n effectiveSpent: string\n resetTimeMin: number\n lastResetMin: number\n nonce: number\n isResetPending: boolean\n /**\n * Delegation rail only (#1319, provenance for #1145's fallback): true\n * when `remaining` came from a live on-chain enforcer read, false when\n * the read failed and `remaining` is the fallback full configured\n * budget. Undefined on the legacy AllowanceModule rail, which has no\n * fallback concept. Reporting only — the on-chain policy remains the\n * actual spend gate either way.\n */\n remainingIsFromChain?: boolean\n }\n}\n\nexport interface HavenAllowanceSummary {\n agentId: string\n safeAddress: string\n delegateAddress: string\n chainId: number\n allowances: HavenAllowance[]\n}\n\n/**\n * Post-purchase allowance/budget summary attached to a settled x402 payment\n * (#1310). Read-only reporting — the on-chain policy remains the actual\n * spend gate either way, this only says what is left after the purchase.\n *\n * Deliberately the SAME rail-labeled field spelling as #1306's\n * catalog-purchase preflight `allowance` block (never a new spelling),\n * minus the preflight-only `sufficient` field: post-purchase reporting\n * answers \"what is left\", not \"was this purchase covered\". Read through the\n * exact same source as {@link HavenAllowanceSummary} / `haven_get_allowances`\n * (`GET /machine-payments/allowances`; delegation-rail values are the #1090\n * `deriveDelegationBudgets`-backed enforcer read, never `agent_allowances`),\n * so this can never disagree with `haven_get_allowances` for the same\n * fixture.\n */\nexport interface PostPurchaseAllowanceSummary {\n /** Which on-chain policy primitive gates this agent's spend (#1306 labeling). */\n rail: 'legacy' | 'delegation'\n /** Remaining atomic units, read through the same source as {@link HavenAllowance.onchain.remaining}. */\n remaining_atomic: string\n /** Human-readable remaining, e.g. \"4.96 USDC\". Omitted when the token's decimals are unknown. */\n remaining_display?: string\n token_symbol?: string\n token_address?: string\n /** Minutes — mirrors {@link HavenAllowance.resetPeriodMin} / the delegation's period. */\n reset_period?: number\n source: 'allowance_module' | 'active_delegations'\n}\n\n/**\n * Affirmative spend-readiness for the authenticated agent, derived from the raw\n * agent status plus the remaining spend authority the backend reports per rail\n * (the on-chain AllowanceModule on the legacy rail; the active budget\n * delegation on the delegation rail — #1135):\n * - `ready` — active and at least one token has remaining spend authority.\n * - `needs_approval`— active but no remaining spend authority to auto-spend.\n * The over-budget outcome differs by rail: on the legacy\n * AllowanceModule rail the payment is queued for the wallet\n * owner to approve in Haven; on the delegation rail there is\n * NO approval queue — an over-budget redemption reverts\n * on-chain, so the owner must grant or raise the budget in\n * Haven before the agent can pay.\n * - `revoked` — the agent's status is not `active`; nothing auto-executes.\n *\n * Note: a hard-paused/disabled credential is rejected by the API before this\n * call returns, so it surfaces as an API error rather than `revoked`. `revoked`\n * is reached when the request authenticates but the agent status is non-active.\n *\n * Wallet token balance is intentionally NOT folded in here: the on-chain\n * remaining allowance is the gate Haven enforces, and insufficient wallet\n * funding surfaces at pay time as INSUFFICIENT_FUNDS.\n */\nexport type HavenAgentReadiness = 'ready' | 'needs_approval' | 'revoked'\n\n/** Compact, agent-facing per-token spend authority for the bootstrap summary. */\nexport interface HavenAgentAllowanceSummary {\n tokenSymbol: string\n /** Live on-chain remaining allowance in atomic units. */\n remainingAtomic: string\n /** Human-readable remaining, e.g. \"4.96 USDC\". */\n remainingDisplay: string\n /** Configured allowance amount (atomic) the owner granted. */\n configuredAmount: string\n resetPeriodMin: number\n isResetPending: boolean\n}\n\n/**\n * One-shot \"am I ready?\" bootstrap: identity + live spend authority + a\n * readiness signal, so an agent can answer \"who am I and can I pay right now\"\n * from a single call at session start. Superset of {@link HavenAgent}.\n */\nexport interface HavenAgentSummary extends HavenAgent {\n readiness: HavenAgentReadiness\n allowances: HavenAgentAllowanceSummary[]\n}\n\nexport interface HavenPaymentReceipt {\n id: string\n paymentId: string\n paymentIntentId?: string | null\n approvalRequestId?: string | null\n rail: string\n proofStatus: string\n txHash: string\n chainId: number\n resourceUrl: string\n merchantAddress: string | null\n payerAddress: string\n settlementAddress: string\n tokenSymbol: string\n tokenAddress: string\n amountRaw: string\n amount: string\n challengeId: string | null\n idempotencyKey: string | null\n challengePayload?: Record<string, unknown> | null\n selectedPayment?: Record<string, unknown> | null\n paymentProofHeaderName: string | null\n protocolReceiptHeaderName: string | null\n protocolReceiptPayload?: Record<string, unknown> | null\n merchantStatus: number | null\n confirmedAt: string | null\n createdAt: string\n updatedAt: string\n}\n\n// ── Delegate Sweep Types ─────────────────────────────────────────\n\n/** One transferred asset in a delegate sweep. */\nexport interface SweepEntry {\n /** 'USDC' or 'ETH' */\n asset: string\n /** Human-readable amount swept (e.g. \"0.12\") */\n amount: string\n /** Atomic amount swept */\n amountAtomic: string\n /** Transaction hash of the sweep transfer */\n txHash: string\n /** Block explorer URL for the tx */\n explorerUrl: string\n}\n\n/** Result of a `sweepDelegate()` call. */\nexport interface SweepResult {\n /** Address funds were swept FROM */\n fromAddress: string\n /** Address funds were swept TO (always the originating Safe) */\n toAddress: string\n /** Chain the sweep occurred on */\n chainId: number\n /** One entry per transferred asset. Empty when nothing was stranded. */\n transfers: SweepEntry[]\n}\n\n// ── Agent Payment State Types ────────────────────────────────────\n\nexport type PaymentStateKind = 'payment_intent' | 'approval_request'\n\nexport interface AgentPaymentEnumSchema {\n type: 'string'\n enum: readonly string[]\n description: string\n 'x-enumDescriptions': Record<string, string>\n}\n\nexport const AgentPaymentPhase = {\n /** The agent must sign and submit the prepared payment before Haven can relay it. */\n AgentSignatureRequired: 'agent_signature_required',\n /** Haven has received the signed payment and the agent should poll for confirmation. */\n PaymentSubmitted: 'payment_submitted',\n /** The direct payment is confirmed; the agent does not need to do more for this payment id. */\n PaymentConfirmed: 'payment_confirmed',\n /** The payment needs wallet owner approval in Haven before it can continue. */\n UserApprovalRequired: 'user_approval_required',\n /** The wallet owner approved the request and still needs to complete the funding payment. */\n UserExecutionRequired: 'user_execution_required',\n /** The funding payment was proposed and is waiting for the remaining account approvals. */\n WaitingForAdditionalApprovals: 'waiting_for_additional_approvals',\n /** The Haven funding leg was sent; the agent can continue the merchant/protocol leg. */\n FundingSent: 'funding_sent',\n /** The wallet owner rejected the request; the agent should stop and tell the user. */\n Rejected: 'rejected',\n /** The payment or approval request expired before completion. */\n Expired: 'expired',\n /** Haven could not complete the payment; the agent should stop and surface the failure. */\n Failed: 'failed',\n /**\n * Pre-flight check determined the delegate's existing balance plus the\n * remaining on-chain allowance cannot cover the requested amount, so no\n * payment intent was created. Distinct from `UserApprovalRequired`: there\n * is no approval that would fix this — the originating Safe needs more\n * funds or the agent's per-token allowance needs to be raised first.\n */\n InsufficientFunds: 'insufficient_funds',\n /**\n * Haven's funding leg (Safe → delegate) confirmed on-chain, but the\n * merchant rejected the x402 retry. The delegate wallet may hold stranded\n * USDC that was never settled to the merchant. The agent should stop, tell\n * the user, and wait for the sweep flow to reclaim the funds.\n */\n FundedButUnsettled: 'funded_but_unsettled',\n} as const\n\nexport type AgentPaymentPhase = (typeof AgentPaymentPhase)[keyof typeof AgentPaymentPhase]\n\nexport const AgentPaymentNextAction = {\n /** Sign with the delegate key and submit the payment to Haven. */\n SignAndSubmitPayment: 'sign_and_submit_payment',\n /** Poll getPaymentStatus later using this payment id. */\n CheckStatusLater: 'check_status_later',\n /** No further agent action is required for this payment id. */\n None: 'none',\n /** Wait for the wallet owner to approve or reject the request in Haven. */\n WaitForUserApproval: 'wait_for_user_approval',\n /** Wait for the wallet owner to finish sending the approved funding payment. */\n WaitForUserToCompletePayment: 'wait_for_user_to_complete_payment',\n /** Resume this payment id and retry the original x402 request with the merchant payment header. */\n RetryOriginalX402Request: 'retry_original_x402_request',\n /** Stop retrying this payment and tell the user what happened. */\n StopAndTellUser: 'stop_and_tell_user',\n /** Ask again only if the user still wants the payment after expiry. */\n RequestAgainIfUserStillWantsIt: 'request_again_if_user_still_wants_it',\n /** #1307: retry the SAME tool call, supplying the explicit context fields the server could not rehydrate. */\n RetryWithExplicitContext: 'retry_with_explicit_context',\n /**\n * The x402 funding/quote window expired. Re-quote the same logical merchant\n * operation with the same idempotency key to stay double-charge-safe.\n */\n PaymentWindowExpired: 'payment_window_expired',\n /**\n * Stop and tell the user that the originating Safe needs to be funded or\n * the agent's per-token allowance needs to be raised before the payment\n * can succeed. A user approval will not fix this state on its own.\n */\n FundSafeOrRaiseAllowance: 'fund_safe_or_raise_allowance',\n /**\n * The delegate wallet may hold funds that were sent from the Safe but never\n * settled to the merchant. The wallet owner should initiate a sweep to\n * return those funds to the originating Safe.\n */\n SweepStrandedFunds: 'sweep_stranded_funds',\n} as const\n\nexport type AgentPaymentNextAction = (typeof AgentPaymentNextAction)[keyof typeof AgentPaymentNextAction]\n\nexport const AgentPaymentFailureCode = {\n /** A merchant-authoritative x402 price exceeds the caller's pre-funding max_amount cap. */\n PriceExceedsMax: 'PRICE_EXCEEDS_MAX',\n /** The x402 funding/quote window expired before the signer or hosted settle step could finish. */\n PaymentWindowExpired: 'PAYMENT_WINDOW_EXPIRED',\n /** The Haven funding leg succeeded, but the merchant rejected the paid retry. */\n MerchantRejectedAfterFunding: 'MERCHANT_REJECTED_AFTER_FUNDING',\n /** #1300 review: funding is on-chain but the merchant never ANSWERED the\n * paid retry within the timeout. NOT proof of rejection — the merchant\n * holds a valid EIP-3009 authorization and may still settle late, so the\n * guidance is verify-then-sweep, never blind sweep. */\n MerchantUnresponsiveAfterFunding: 'MERCHANT_UNRESPONSIVE_AFTER_FUNDING',\n /**\n * #1307: the caller omitted merchant_url/tool_name (asking Haven to\n * rehydrate the stored MCP merchant-call context by payment_id), but no\n * usable context was stored for this intent — either it was never an\n * MCP-tool quote, or the stored context is incomplete. The fallback is\n * mechanical: re-send merchant_url, tool_name, arguments, and\n * mcp_transport explicitly (the version-skew path).\n */\n MerchantCallContextUnavailable: 'MERCHANT_CALL_CONTEXT_UNAVAILABLE',\n /**\n * #1351: the caller supplied BOTH the atomic `max_amount` and the\n * human-denominated `max_amount_human` cap for one purchase. Haven refuses\n * to guess which the user meant — the two differ by a factor of 10^decimals,\n * so picking wrong is exactly the silent-overspend this cap exists to\n * prevent. Rejected before any merchant probe, funding intent, or signature.\n */\n AmbiguousMaxAmount: 'AMBIGUOUS_MAX_AMOUNT',\n /**\n * #1351: a human-denominated cap was supplied, but it cannot be converted to\n * atomic units against THIS quote — either the quote's asset has no known\n * decimals on its network, or the cap carries more fraction digits than the\n * asset can represent (truncating it would silently change the user's cap).\n * The fallback is the exact atomic `max_amount`.\n */\n MaxAmountUnconvertible: 'MAX_AMOUNT_UNCONVERTIBLE',\n} as const\n\nexport type AgentPaymentFailureCode = (typeof AgentPaymentFailureCode)[keyof typeof AgentPaymentFailureCode]\n\n/**\n * Stable rail identifier carried on Haven agent payment responses and resume\n * state.\n *\n * Two layers of vocabulary share this enum because both reach the wire:\n *\n * - **Categorical rails** identify the rail family and are used as the\n * `PaymentResumeState` discriminator: `direct`, `x402` (`mpp` remains a\n * valid categorical VALUE on historical status reads, but #1328 retired\n * the `MppResumeState` variant that used to carry it — the mpp_demo\n * client resume flow no longer exists).\n * - **Granular rails** identify the specific protocol the backend persists\n * and returns on response bodies: `mpp_demo`, `mpp_crypto`,\n * `stripe_deposit`, `spt`. `x402` doubles as both categorical and\n * granular.\n *\n * Consumers reading the top-level `rail` field on a payment status response\n * should treat any `mpp*` value as the MPP family — this still applies to\n * historical `mpp_demo` rows, which remain readable.\n */\nexport const AgentPaymentRail = {\n /** Standard Haven payment from the user's Safe through an approved delegate allowance. */\n Direct: 'direct',\n /** x402 HTTP 402 payment flow with a Haven funding leg and merchant retry leg. */\n X402: 'x402',\n /** Machine Payment Protocol family — categorical value used as a resume-state discriminator. */\n Mpp: 'mpp',\n /** Haven internal MPP demo rail. Not for production traffic. */\n MppDemo: 'mpp_demo',\n /** Crypto-settled MPP rail. */\n MppCrypto: 'mpp_crypto',\n /** Stripe-deposit-backed MPP rail. */\n StripeDeposit: 'stripe_deposit',\n /** Stripe Payment Token MPP rail. */\n Spt: 'spt',\n} as const\n\nexport type AgentPaymentRail = (typeof AgentPaymentRail)[keyof typeof AgentPaymentRail]\n\nexport type PaymentPhase = AgentPaymentPhase\n\nexport type PaymentNextAction = AgentPaymentNextAction\n\nexport const AGENT_PAYMENT_PHASE_VALUES = Object.values(AgentPaymentPhase)\n\nexport const AGENT_PAYMENT_NEXT_ACTION_VALUES = Object.values(AgentPaymentNextAction)\n\nexport const AGENT_PAYMENT_FAILURE_CODE_VALUES = Object.values(AgentPaymentFailureCode)\n\nexport const AGENT_PAYMENT_RAIL_VALUES = Object.values(AgentPaymentRail)\n\nexport const AgentPaymentPhaseDescriptions: Record<AgentPaymentPhase, string> = {\n [AgentPaymentPhase.AgentSignatureRequired]: 'The agent must sign and submit the prepared payment before Haven can relay it.',\n [AgentPaymentPhase.PaymentSubmitted]: 'Haven has received the signed payment and the agent should poll for confirmation.',\n [AgentPaymentPhase.PaymentConfirmed]: 'The direct payment is confirmed; the agent does not need to do more for this payment id.',\n [AgentPaymentPhase.UserApprovalRequired]: 'The payment needs wallet owner approval in Haven before it can continue.',\n [AgentPaymentPhase.UserExecutionRequired]: 'The wallet owner approved the request and still needs to complete the funding payment.',\n [AgentPaymentPhase.WaitingForAdditionalApprovals]: 'The funding payment was proposed and is waiting for the remaining account approvals.',\n [AgentPaymentPhase.FundingSent]: 'The Haven funding leg was sent; the agent can continue the merchant/protocol leg.',\n [AgentPaymentPhase.Rejected]: 'The wallet owner rejected the request; the agent should stop and tell the user.',\n [AgentPaymentPhase.Expired]: 'The payment or approval request expired before completion.',\n [AgentPaymentPhase.Failed]: 'Haven could not complete the payment; the agent should stop and surface the failure.',\n [AgentPaymentPhase.InsufficientFunds]:\n 'Pre-flight check determined the delegate balance plus the remaining on-chain allowance cannot cover the requested amount, so no payment was created. The originating Safe must be funded or the agent allowance raised before retrying.',\n [AgentPaymentPhase.FundedButUnsettled]:\n \"Haven's funding leg confirmed on-chain but the merchant rejected the x402 retry. The delegate wallet may hold stranded funds. The agent should stop and wait for the wallet owner to sweep the stranded funds back to the Safe.\",\n}\n\nexport const AgentPaymentNextActionDescriptions: Record<AgentPaymentNextAction, string> = {\n [AgentPaymentNextAction.SignAndSubmitPayment]: 'Sign with the delegate key and submit the payment to Haven.',\n [AgentPaymentNextAction.CheckStatusLater]: 'Poll getPaymentStatus later using this payment id.',\n [AgentPaymentNextAction.None]: 'No further agent action is required for this payment id.',\n [AgentPaymentNextAction.WaitForUserApproval]: 'Wait for the wallet owner to approve or reject the request in Haven.',\n [AgentPaymentNextAction.WaitForUserToCompletePayment]: 'Wait for the wallet owner to finish sending the approved funding payment.',\n [AgentPaymentNextAction.RetryOriginalX402Request]: 'Resume this payment id and retry the original x402 request with the merchant payment header.',\n [AgentPaymentNextAction.StopAndTellUser]: 'Stop retrying this payment and tell the user what happened.',\n [AgentPaymentNextAction.RequestAgainIfUserStillWantsIt]: 'Ask again only if the user still wants the payment after expiry.',\n [AgentPaymentNextAction.PaymentWindowExpired]:\n 'The x402 funding/quote window expired. Re-quote with the same idempotency key before asking the signer to build a merchant payment header again.',\n [AgentPaymentNextAction.FundSafeOrRaiseAllowance]:\n 'Stop and tell the user that the originating Safe needs to be funded or the agent allowance raised before the payment can succeed.',\n [AgentPaymentNextAction.RetryWithExplicitContext]:\n 'Retry the same tool call, this time passing merchant_url, tool_name, arguments, and mcp_transport explicitly — the server had no stored context to rehydrate for this payment id.',\n [AgentPaymentNextAction.SweepStrandedFunds]:\n 'Tell the user that funds may be stranded in the delegate wallet and prompt them to initiate a sweep in Haven to return them to the originating Safe.',\n}\n\nexport const AgentPaymentFailureCodeDescriptions: Record<AgentPaymentFailureCode, string> = {\n [AgentPaymentFailureCode.PriceExceedsMax]:\n \"The merchant-authoritative x402 amount exceeds the caller's max_amount cap. No funding transfer was created; ask the user before retrying with a larger cap.\",\n [AgentPaymentFailureCode.PaymentWindowExpired]:\n 'The x402 funding/quote window expired before the signer or hosted settle step could finish. Re-quote via haven_pay_mcp_tool with the same idempotency key to avoid duplicate funding.',\n [AgentPaymentFailureCode.MerchantRejectedAfterFunding]:\n 'The Haven funding leg succeeded, but the merchant rejected the paid retry. Stop retrying the merchant and reconcile stranded delegate funds with haven_sweep_delegate.',\n [AgentPaymentFailureCode.MerchantUnresponsiveAfterFunding]:\n 'The Haven funding leg succeeded, but the merchant did not answer the paid retry before the timeout. The merchant may still settle late — check haven_get_payment_status (and retry haven_complete_mcp_tool once) BEFORE sweeping; sweep only if no settlement appears.',\n [AgentPaymentFailureCode.MerchantCallContextUnavailable]:\n 'merchant_url/tool_name were omitted and no stored merchant call context is available for this payment_id. Re-send merchant_url, tool_name, arguments, and mcp_transport explicitly.',\n [AgentPaymentFailureCode.AmbiguousMaxAmount]:\n 'Both max_amount (atomic units) and max_amount_human (whole tokens) were supplied for one purchase. Nothing was contacted and nothing was spent. Re-send with exactly ONE: max_amount_human for a cap the user stated in tokens, max_amount for an exact atomic figure.',\n [AgentPaymentFailureCode.MaxAmountUnconvertible]:\n \"max_amount_human could not be converted to atomic units against this quote's asset — either its decimals are unknown to Haven or the cap has more decimal places than the asset supports. Nothing was spent. Round the cap, or re-send it as an exact atomic max_amount.\",\n}\n\n/**\n * #1308: machine-readable warning codes carried in the `warnings` array on\n * x402 MCP tool responses. Warnings are ADVISORY — they never replace a\n * refusal, and existing failure codes stay authoritative for errors. The\n * legacy `cap_warning` string field is kept for compatibility; the structured\n * entry carries the same message under MISSING_MAX_AMOUNT.\n */\nexport const AgentPaymentWarningCode = {\n /** No max_amount cap was supplied — the live quoted price was accepted as-is. */\n MissingMaxAmount: 'MISSING_MAX_AMOUNT',\n /** The signing window closes soon; sign promptly or re-quote with the same idempotency key. */\n QuoteExpiresSoon: 'QUOTE_EXPIRES_SOON',\n /** The merchant URL was resolved via discovery — pass the RESOLVED url forward. */\n MerchantUrlDiscovered: 'MERCHANT_URL_DISCOVERED',\n /**\n * #1306: the catalog's last-verified price_atomic differs from the LIVE\n * merchant quote for a guided catalog purchase. The catalog price is only\n * ever indicative; the live quote in the same response is authoritative.\n */\n CatalogPriceDiffers: 'CATALOG_PRICE_DIFFERS',\n /**\n * #1306: the rail-aware allowance/budget pre-check could not be read (RPC\n * failure, etc). `sufficient` is reported as null rather than a fabricated\n * true/false — the on-chain policy remains the actual gate either way.\n */\n AllowanceCheckUnavailable: 'ALLOWANCE_CHECK_UNAVAILABLE',\n /**\n * #1319: the delegation-rail read itself SUCCEEDED, but the remaining\n * figure it returned is the #1145 fallback (the full configured budget)\n * rather than a live ERC20PeriodTransferEnforcer read — `sufficient` is a\n * real true/false, just computed from an optimistic number. Distinct from\n * {@link AgentPaymentWarningCode.AllowanceCheckUnavailable}, which fires\n * when the read failed outright and `sufficient` degrades to null. The\n * on-chain policy re-checks at redemption either way; this only says the\n * guidance shown here may be optimistic.\n */\n AllowanceReadOptimistic: 'ALLOWANCE_READ_OPTIMISTIC',\n} as const\n\nexport type AgentPaymentWarningCode =\n (typeof AgentPaymentWarningCode)[keyof typeof AgentPaymentWarningCode]\n\nexport interface AgentPaymentWarning {\n code: AgentPaymentWarningCode\n message: string\n}\n\n/**\n * #1308: the structured next-step contract on x402 MCP tool responses. It\n * EXTENDS the existing taxonomy — `next_action` values come from\n * AgentPaymentNextAction, never a parallel vocabulary. `next_arguments`\n * carries the small, literally-usable arguments; bulky pass-through fields\n * (payment_required) are named in `reason` and taken from the SAME response.\n */\nexport interface AgentNextStep {\n next_action: AgentPaymentNextAction\n /** Fully-qualified tool name for the next call, when one exists. */\n next_tool?: string\n /** Small literal arguments for next_tool. Bulky fields are referenced by reason. */\n next_arguments?: Record<string, unknown>\n /** False when the agent should stop and involve the user before continuing. */\n safe_to_continue: boolean\n reason: string\n}\n\n/**\n * #1349: compact, Haven-generated reporting evidence for a completed x402\n * merchant purchase. `status`, money fields, merchant endpoint/address, and\n * funding transaction come from Haven payment state; `product` and\n * `invoice_id` are optional merchant-supplied display metadata. The raw\n * merchant result remains separate evidence and MUST NOT be used to infer\n * settlement status.\n */\nexport interface AgentPurchaseSummary {\n /** Set only after Haven has completed the funding and merchant-settlement flow. */\n status: 'settled'\n product: string | null\n amount: string | null\n amount_atomic: string | null\n asset: string | null\n network: string | null\n merchant: {\n address: string | null\n resource_url: string | null\n }\n /** Merchant-supplied identifier, or null when the merchant did not supply one. */\n invoice_id: string | null\n funding_tx_hash: string | null\n /** Optional merchant receipt reference parsed from PAYMENT-RESPONSE; not Haven settlement proof. */\n settlement_tx_hash: string | null\n /** Same read-only allowance block returned at the top level, or null when unavailable. */\n allowance: PostPurchaseAllowanceSummary | null\n}\n\n/** #1308: compact reporting summary — what the agent tells the user. */\nexport interface AgentPaymentSummary {\n payment_id: string\n status: string\n amount?: string\n amount_atomic?: string\n token?: string\n network?: string\n expires_at?: string\n product?: string\n /**\n * Default reporting contract for a successful `haven_settle_mcp_tool` call.\n * The merchant's raw `result` remains available separately as advanced\n * evidence; do not parse it to determine whether a payment settled.\n */\n purchase_summary?: AgentPurchaseSummary\n}\n\nexport const AgentPaymentRailDescriptions: Record<AgentPaymentRail, string> = {\n [AgentPaymentRail.Direct]: 'Standard Haven payment from the user-controlled Safe through an approved delegate allowance.',\n [AgentPaymentRail.X402]: 'x402 HTTP 402 payment flow with a Haven funding leg and merchant retry leg.',\n [AgentPaymentRail.Mpp]: 'Categorical MPP rail value used as a resume-state discriminator. Response bodies carry a granular mpp_* value instead.',\n [AgentPaymentRail.MppDemo]: 'Haven internal MPP demo rail. Not for production traffic.',\n [AgentPaymentRail.MppCrypto]: 'Crypto-settled MPP rail.',\n [AgentPaymentRail.StripeDeposit]: 'Stripe-deposit-backed MPP rail.',\n [AgentPaymentRail.Spt]: 'Stripe Payment Token MPP rail.',\n}\n\nexport const AgentPaymentPhaseSchema: AgentPaymentEnumSchema = {\n type: 'string',\n enum: AGENT_PAYMENT_PHASE_VALUES,\n description: 'Stable Haven agent payment state phase.',\n 'x-enumDescriptions': AgentPaymentPhaseDescriptions,\n}\n\nexport const AgentPaymentNextActionSchema: AgentPaymentEnumSchema = {\n type: 'string',\n enum: AGENT_PAYMENT_NEXT_ACTION_VALUES,\n description: 'Stable next action an agent should take for a Haven payment state.',\n 'x-enumDescriptions': AgentPaymentNextActionDescriptions,\n}\n\nexport const AgentPaymentFailureCodeSchema: AgentPaymentEnumSchema = {\n type: 'string',\n enum: AGENT_PAYMENT_FAILURE_CODE_VALUES,\n description: 'Stable machine-readable failure codes for Haven agent payment recovery paths.',\n 'x-enumDescriptions': AgentPaymentFailureCodeDescriptions,\n}\n\nexport const AgentPaymentRailSchema: AgentPaymentEnumSchema = {\n type: 'string',\n enum: AGENT_PAYMENT_RAIL_VALUES,\n description: 'Stable rail identifier for Haven agent payment states.',\n 'x-enumDescriptions': AgentPaymentRailDescriptions,\n}\n\nexport interface PaymentStatusResult {\n paymentId: string\n kind: PaymentStateKind\n rail: string\n status: PaymentStatus | string\n phase: PaymentPhase\n nextAction: PaymentNextAction\n amount: string\n token: string\n resourceUrl: string | null\n merchantAddress: string | null\n txHash: string | null\n expiresAt: string\n chainId: number\n message: string\n /** Platform fee surfaced so it's never silently collected (#386). */\n fee?: PaymentFee | null\n amountAtomic?: string | null\n asset?: string | null\n network?: string | null\n description?: string | null\n idempotencyKey?: string | null\n x402?: {\n amountAtomic: string | null\n asset: string | null\n network: string | null\n resourceUrl: string | null\n merchantAddress: string | null\n description: string | null\n idempotencyKey: string | null\n }\n mpp?: {\n amountAtomic: string | null\n asset: string | null\n network: string | null\n resourceUrl: string | null\n merchantAddress: string | null\n description: string | null\n idempotencyKey: string | null\n challengeId: string | null\n }\n}\n\nexport interface PendingApproval extends PaymentStatusResult {\n kind: 'approval_request'\n status: 'pending_approval' | 'pending' | string\n phase: typeof AgentPaymentPhase.UserApprovalRequired\n nextAction: typeof AgentPaymentNextAction.WaitForUserApproval\n requested?: string\n remaining?: string | null\n}\n\n\n/** @internal */\nexport interface RawX402AuthorizeResponse {\n success?: boolean\n payment_id: string\n kind?: string\n rail?: string\n status: string\n phase?: string\n next_action?: string\n message?: string\n remaining?: string | null\n requested?: string\n tx_hash?: string\n chain_id?: number\n safe_address?: string\n payer?: string\n token?: string\n amount?: string\n amount_atomic?: string | null\n asset?: string | null\n network?: string | null\n description?: string | null\n idempotency_key?: string | null\n to?: string\n merchant_to?: string | null\n merchant_address?: string | null\n x402_expected_auth?: X402ExpectedAuth\n resource_url?: string\n explorer_url?: string\n x402?: RawX402StateContext\n mpp?: RawMppStateContext\n challenge_id?: string\n expires_at?: string\n sign_data?: SignData\n error?: string\n}\n\n// ── API Response Shapes (raw, snake_case from server) ────────────\n\n/** @internal */\nexport interface RawCreateResponse {\n payment_id: string\n kind?: string\n status: string\n phase?: string\n next_action?: string\n message?: string\n remaining?: string | null\n requested?: string\n expires_at: string\n sign_data: {\n hash: string\n /** 'eip712_userop' = delegation rail; absent = legacy AllowanceModule (raw ECDSA). The session rail's 'eip191_userop' is retired (#834). */\n signature_scheme?: 'eip712_userop'\n components: {\n safe: string\n token: string\n to: string\n amount: string\n payment_token: string\n payment: string\n nonce: number\n }\n instructions: string\n }\n error?: string\n supported?: string[]\n}\n\n/** @internal */\nexport interface RawSignResponse {\n payment_id: string\n kind?: string\n status: string\n phase?: string\n next_action?: string\n message?: string\n remaining?: string | null\n requested?: string\n tx_hash?: string\n token?: string\n amount?: string\n amount_atomic?: string | null\n asset?: string | null\n network?: string | null\n description?: string | null\n idempotency_key?: string | null\n to?: string\n merchant_to?: string | null\n merchant_address?: string | null\n resource_url?: string\n rail?: string\n x402?: RawX402StateContext\n mpp?: RawMppStateContext\n challenge_id?: string\n explorer_url?: string\n chain_id?: number\n expires_at?: string\n error?: string\n details?: string\n}\n\n/** @internal */\nexport interface RawStatusResponse {\n payment_id: string\n status: string\n token: string\n amount: string\n to: string\n tx_hash: string | null\n explorer_url?: string | null\n chain_id?: number\n fee?: { amount: string; token: string; basis_points: number; applied: boolean } | null\n error_message: string | null\n created_at: string\n signed_at: string | null\n submitted_at: string | null\n confirmed_at: string | null\n expires_at: string\n}\n\n/** @internal */\nexport interface RawPaymentStatusResult {\n payment_id: string\n kind: PaymentStateKind\n rail: string\n status: string\n phase: PaymentPhase\n next_action: PaymentNextAction\n amount: string\n token: string\n resource_url: string | null\n merchant_address: string | null\n tx_hash: string | null\n expires_at: string\n chain_id: number\n message: string\n fee?: { amount: string; token: string; basis_points: number; applied: boolean } | null\n amount_atomic?: string | null\n asset?: string | null\n network?: string | null\n description?: string | null\n idempotency_key?: string | null\n x402?: RawX402StateContext\n mpp?: RawMppStateContext\n}\n\n/** @internal */\nexport interface RawHavenAgent {\n id: string\n name: string\n status: string\n safe_address: string\n delegate_address: string\n chain_id: number\n execution_rail: string\n}\n\n/** @internal */\nexport interface RawHavenAllowance {\n id: string\n token_address: string\n token_symbol: string\n configured_amount: string\n reset_period_min: number\n onchain: {\n amount: string\n spent: string\n remaining: string\n effective_spent: string\n reset_time_min: number\n last_reset_min: number\n nonce: number\n is_reset_pending: boolean\n /** #1319 — see {@link HavenAllowance.onchain.remainingIsFromChain}. */\n remaining_is_from_chain?: boolean\n }\n}\n\n/** @internal */\nexport interface RawHavenAllowanceSummary {\n agent_id: string\n safe_address: string\n delegate_address: string\n chain_id: number\n allowances: RawHavenAllowance[]\n}\n\n/** @internal */\nexport interface RawHavenPaymentReceipt {\n id: string\n payment_id: string\n payment_intent_id?: string | null\n approval_request_id?: string | null\n rail: string\n proof_status: string\n tx_hash: string\n chain_id: number\n resource_url: string\n merchant_address: string | null\n payer_address: string\n settlement_address: string\n token_symbol: string\n token_address: string\n amount_raw: string\n amount_human: string\n challenge_id: string | null\n idempotency_key: string | null\n challenge_payload?: Record<string, unknown> | null\n selected_payment?: Record<string, unknown> | null\n payment_proof_header_name: string | null\n protocol_receipt_header_name: string | null\n protocol_receipt_payload?: Record<string, unknown> | null\n merchant_status: number | null\n confirmed_at: string | null\n created_at: string\n updated_at: string\n}\n\n/** @internal */\n/** One payable service in Haven's curated merchant catalog. */\nexport interface HavenCatalogEntry {\n id: string\n name: string\n description: string\n category: string\n resourceUrl: string\n rail: 'x402' | 'mpp'\n protocol: 'http' | 'mcp'\n toolName: string | null\n toolArguments: Record<string, unknown> | null\n priceDisplay: string | null\n priceAtomic: string | null\n asset: string | null\n network: string | null\n status: 'active' | 'degraded' | 'delisted'\n verifiedAt: string | null\n}\n\n/** @internal */\nexport interface RawCatalogEntry {\n id: string\n name: string\n description: string\n category: string\n resource_url: string\n rail: 'x402' | 'mpp'\n protocol: 'http' | 'mcp'\n tool_name: string | null\n tool_arguments: Record<string, unknown> | null\n price_display: string | null\n price_atomic: string | null\n asset: string | null\n network: string | null\n status: 'active' | 'degraded' | 'delisted'\n verified_at: string | null\n}\n\nexport interface RawHavenPaymentReceiptsResponse {\n receipts: RawHavenPaymentReceipt[]\n}\n\n/** @internal */\nexport interface RawX402StateContext {\n amount_atomic?: string | null\n asset?: string | null\n network?: string | null\n resource_url?: string | null\n merchant_address?: string | null\n description?: string | null\n idempotency_key?: string | null\n}\n\n/** @internal */\nexport interface RawMppStateContext {\n amount_atomic?: string | null\n asset?: string | null\n network?: string | null\n resource_url?: string | null\n merchant_address?: string | null\n description?: string | null\n idempotency_key?: string | null\n challenge_id?: string | null\n}\n\n// ── Error Types ──────────────────────────────────────────────────\n\nexport class HavenError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly statusCode?: number,\n public readonly paymentId?: string,\n ) {\n super(message)\n this.name = 'HavenError'\n }\n}\n\nexport class HavenApiError extends HavenError {\n constructor(\n message: string,\n statusCode: number,\n public readonly body?: unknown,\n paymentId?: string,\n ) {\n super(message, 'API_ERROR', statusCode, paymentId)\n this.name = 'HavenApiError'\n }\n}\n\n/**\n * #1300: quoteX402 hit a URL that answered something other than 402 — the\n * typed form of \"this is not the x402 endpoint\". Exists so consumers (the\n * hosted MCP's #1271 discovery trigger) can key on a class instead of\n * message text.\n */\n/**\n * #1300: a merchant-facing fetch hit the client-side merchantTimeout. Typed\n * so consumers can distinguish \"merchant never answered\" from a real HTTP\n * error response — the funded-retry path routes this to verify-then-sweep\n * guidance instead of a bare 504.\n */\nexport class MerchantTimeoutError extends HavenApiError {\n readonly merchantErrorCode = 'merchant_timeout' as const\n constructor(message: string) {\n super(message, 504)\n this.name = 'MerchantTimeoutError'\n }\n}\n\nexport class X402UnexpectedStatusError extends HavenApiError {\n readonly x402ErrorCode = 'unexpected_non_402_status' as const\n constructor(message: string, statusCode: number) {\n super(message, statusCode)\n this.name = 'X402UnexpectedStatusError'\n }\n}\n\nexport class HavenPaymentStateError extends HavenApiError {\n resumeState?: X402ResumeState\n\n constructor(\n message: string,\n statusCode: number,\n public readonly state: PaymentStatusResult,\n body?: unknown,\n ) {\n super(message, statusCode, body, state.paymentId)\n this.name = 'HavenPaymentStateError'\n }\n\n get status(): string {\n return this.state.status\n }\n\n get phase(): PaymentPhase {\n return this.state.phase\n }\n\n get nextAction(): PaymentNextAction {\n return this.state.nextAction\n }\n}\n\nexport class HavenSigningError extends HavenError {\n constructor(message: string) {\n super(message, 'SIGNING_ERROR')\n this.name = 'HavenSigningError'\n }\n}\n\n/**\n * Refusal codes the local signer returns when it does not recognise the\n * VERSION of a Haven-signed binding it was asked to sign (#1309). Distinct\n * from `AgentPaymentFailureCode`: these describe a **signer capability**\n * problem (this install cannot evaluate what Haven sent), not a payment-domain\n * outcome, and they never reach the backend's REST/OpenAPI surface — only the\n * local signer's own MCP tool responses (`haven_sign` / `haven_sign_x402` /\n * `haven_sign_sweep_delegate`). That is also why this pair does not go through\n * the `AgentPaymentFailureCode` four-gate (sdk → backend mirror → spec →\n * api-types): there is no backend mirror to keep in sync with.\n */\nexport const SignerRefusalCode = {\n /** `SUPPORTED_X402_EXPECTED_VERSIONS` in `@haven_ai/signer` does not include the received version. */\n UnsupportedExpectedContextVersion: 'UNSUPPORTED_EXPECTED_CONTEXT_VERSION',\n /** `SUPPORTED_SWEEP_BINDING_VERSIONS` in `@haven_ai/signer` does not include the received version. */\n UnsupportedSweepBindingVersion: 'UNSUPPORTED_SWEEP_BINDING_VERSION',\n} as const\n\nexport type SignerRefusalCode = (typeof SignerRefusalCode)[keyof typeof SignerRefusalCode]\n\n/**\n * Canonical recovery guidance for a stale local signer (#1309) — the ONE\n * string both the signer's structured refusal (`fallback` field, carried by\n * `HavenUnsupportedSignerVersionError`) and the hosted quote's advisory\n * `signer_compatibility.fallback` (#1155) render, so an agent that meets\n * either surface is told the identical fix. A second hand-maintained copy of\n * this sentence is exactly how the two surfaces could start disagreeing about\n * what to do.\n */\nexport const SIGNER_UPDATE_FALLBACK =\n 'Update @haven_ai/signer by rerunning `npx @haven_ai/connect@alpha`, which reinstalls the ' +\n 'pinned MCP runtime, then retry the same signing call. Nothing was signed or spent — the ' +\n 'quote or payment this version came from is unaffected and does not need to be re-quoted.'\n\n/**\n * Thrown by the local signer when a Haven-signed binding (x402 expected\n * context or sweep authorization) carries a version outside what this signer\n * install enforces (#1143, structured as #1309). Machine-readable: `code`,\n * `supportedVersions`, and `receivedVersion` are DERIVED from the signer's own\n * `SUPPORTED_X402_EXPECTED_VERSIONS` / `SUPPORTED_SWEEP_BINDING_VERSIONS`\n * constants at the throw site, never a second literal — see\n * `assertSupportedBindingVersion` in `@haven_ai/signer`.\n *\n * This narrows HOW the refusal is reported. It does not weaken it: nothing is\n * signed either way, and the version stays inside the Haven-signed binding\n * message (callers must not \"fix\" a mismatch by rewriting it).\n */\nexport class HavenUnsupportedSignerVersionError extends HavenError {\n constructor(\n message: string,\n code: SignerRefusalCode,\n public readonly supportedVersions: readonly number[],\n public readonly receivedVersion: number,\n public readonly fallback: string,\n ) {\n super(message, code)\n this.name = 'HavenUnsupportedSignerVersionError'\n }\n}\n\nexport class HavenTimeoutError extends HavenError {\n constructor(paymentId: string) {\n super(\n `Timed out waiting for payment ${paymentId} to confirm`,\n 'TIMEOUT',\n undefined,\n paymentId,\n )\n this.name = 'HavenTimeoutError'\n }\n}\n","import { ethers } from 'ethers'\nimport { HavenSigningError } from './types.js'\n\n/**\n * Sign a hash using raw ECDSA (no Ethereum message prefix).\n *\n * This matches what Safe's AllowanceModule `checkSignature` expects —\n * a direct ecrecover over the hash, NOT the \"\\x19Ethereum Signed Message\" variant.\n *\n * Uses ethers.SigningKey.sign() instead of wallet.signMessage() to avoid the prefix.\n */\nexport function signHash(privateKey: string, hash: string): string {\n try {\n const signingKey = new ethers.SigningKey(privateKey)\n const sig = signingKey.sign(hash)\n return sig.serialized // 0x + r(32) + s(32) + v(1)\n } catch (err) {\n throw new HavenSigningError(\n `Failed to sign hash: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/**\n * Sign a delegation-rail payment (#829).\n *\n * The delegate SMART ACCOUNT validates an EIP-712 signature over the packed\n * UserOperation — signing the bare 4337 hash would be rejected on-chain. The\n * backend sends the exact typed data in `sign_data.typed_data`; we sign it\n * verbatim and never reconstruct it (a second source of truth could drift\n * from the account's own rules).\n */\nexport async function signUserOpTypedDataForDelegation(\n privateKey: string,\n typedData: {\n domain: Record<string, unknown>\n types: Record<string, unknown>\n primaryType: string\n message: Record<string, unknown>\n },\n): Promise<string> {\n try {\n const wallet = new ethers.Wallet(privateKey)\n // ethers derives EIP712Domain itself and rejects it in `types`.\n const types = { ...typedData.types }\n delete (types as Record<string, unknown>).EIP712Domain\n return await wallet.signTypedData(\n typedData.domain as never,\n types as never,\n typedData.message as never,\n )\n } catch (err) {\n throw new HavenSigningError(\n `Failed to sign delegation UserOperation: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/**\n * Derive the Ethereum address from a private key.\n */\nexport function addressFromKey(privateKey: string): string {\n try {\n return new ethers.Wallet(privateKey).address\n } catch (err) {\n throw new HavenSigningError(\n `Invalid private key: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/**\n * Verify that a signature over a hash recovers to the expected address.\n */\nexport function verifySignature(hash: string, signature: string, expectedAddress: string): boolean {\n try {\n const recovered = ethers.recoverAddress(hash, signature)\n return recovered.toLowerCase() === expectedAddress.toLowerCase()\n } catch {\n return false\n }\n}\n","import { ethers } from 'ethers'\n\n/**\n * Verifiable payment receipts.\n *\n * A self-contained proof bundle for a settled Haven payment that anyone can\n * verify **independently of Haven**. The anchor is the agent delegate's\n * signature over the on-chain transfer hash: recover the signer and confirm it\n * is the agent's delegate, and you have cryptographic proof the agent authorised\n * exactly this transfer — no need to trust Haven's backend. The on-chain\n * `txHash` is the settlement source of truth (verify on any explorer).\n *\n * This lives in the SDK so agents and users can verify receipts client-side\n * with zero Haven trust.\n */\nexport const RECEIPT_VERSION = 'haven-receipt-1'\n\nexport interface PaymentReceipt {\n version: typeof RECEIPT_VERSION\n paymentId: string\n payment: {\n token: string\n tokenAddress: string\n amount: string\n amountSek: string | null\n recipient: string\n safe: string\n chainId: number\n settledAt: string | null\n resourceUrl: string | null\n }\n /** The agent's cryptographic authorisation — what makes the receipt verifiable. */\n authorization: {\n delegate: string\n signHash: string\n signature: string | null\n }\n onChain: {\n txHash: string | null\n chainId: number\n }\n}\n\nexport type ReceiptVerification =\n | { verified: true; recoveredSigner: string }\n | {\n verified: false\n reason: 'missing_signature' | 'bad_signature' | 'signer_mismatch'\n recoveredSigner?: string\n }\n\n/** Default ECDSA recovery (raw ecrecover over the hash, no message prefix). */\nfunction defaultRecover(hash: string, signature: string): string {\n return ethers.recoverAddress(hash, signature)\n}\n\n/**\n * Verify a receipt independently: recover the signer from the authorisation and\n * confirm it is the agent's delegate. Pure — `recover` is injectable but\n * defaults to standard ECDSA recovery, so this runs anywhere (no Haven backend).\n */\nexport function verifyPaymentReceipt(\n receipt: PaymentReceipt,\n recover: (hash: string, signature: string) => string = defaultRecover,\n): ReceiptVerification {\n const { delegate, signHash, signature } = receipt.authorization\n if (!signature) return { verified: false, reason: 'missing_signature' }\n\n let recovered: string\n try {\n recovered = recover(signHash, signature)\n } catch {\n return { verified: false, reason: 'bad_signature' }\n }\n\n if (recovered.toLowerCase() !== delegate.toLowerCase()) {\n return { verified: false, reason: 'signer_mismatch', recoveredSigner: recovered }\n }\n return { verified: true, recoveredSigner: recovered }\n}\n","/**\n * Runtime-agnostic base64 helpers — the single source of truth for the wire\n * encoding shared by the SDK and the edge signer (#325).\n *\n * Why this module exists: the SDK used `atob`/`btoa` (Web globals) while the\n * signer used `Buffer` (Node-only). Both worked because both currently run in\n * Node ≥ 16, but the duplication was a latent wire-incompatibility — and the\n * signer is headed for non-Node runtimes (browsers, Cloudflare Workers) where\n * `Buffer` does not exist (#314).\n *\n * Encoding contract:\n * - Output is ALWAYS standard base64 (`+`, `/`, padded). The x402 protocol's\n * reference implementation validates headers against\n * `/^[A-Za-z0-9+/]*={0,2}$/` — URL-safe output would be rejected.\n * - Decoding is tolerant: URL-safe input (`-`, `_`, unpadded) is normalized\n * before decoding, since third-party merchants are not guaranteed to be as\n * strict as the reference implementation.\n * - UTF-8 throughout. Naive `btoa(JSON.stringify(...))` throws on any\n * non-Latin-1 character (e.g. a merchant description with an emoji or\n * non-ASCII name); these helpers route through TextEncoder/TextDecoder on\n * the Web path so multibyte characters round-trip identically on both\n * runtimes.\n */\n\n/** Normalize URL-safe alphabet and missing padding to standard base64. */\nfunction normalizeBase64(value: string): string {\n const standard = value.replace(/-/g, '+').replace(/_/g, '/')\n const remainder = standard.length % 4\n return remainder === 0 ? standard : standard + '='.repeat(4 - remainder)\n}\n\n/** Encode a UTF-8 string as standard base64. */\nexport function encodeBase64Utf8(value: string): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(value, 'utf8').toString('base64')\n }\n const bytes = new TextEncoder().encode(value)\n let binary = ''\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i])\n }\n return btoa(binary)\n}\n\n/** Decode standard or URL-safe base64 to a UTF-8 string. */\nexport function decodeBase64Utf8(value: string): string {\n const normalized = normalizeBase64(value)\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(normalized, 'base64').toString('utf8')\n }\n const binary = atob(normalized)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i)\n }\n return new TextDecoder().decode(bytes)\n}\n\n/** Encode a JSON-serializable value as a standard-base64 string. */\nexport function encodeBase64Json(value: unknown): string {\n return encodeBase64Utf8(JSON.stringify(value))\n}\n\n/**\n * Decode a base64 JSON payload.\n *\n * Pass a `label` to get a wrapped error message instead of the raw\n * JSON/base64 error — call sites parsing untrusted merchant headers use this\n * to produce actionable failures.\n */\nexport function decodeBase64Json<T>(value: string, label?: string): T {\n try {\n return JSON.parse(decodeBase64Utf8(value)) as T\n } catch (err) {\n if (label) throw new Error(`Failed to decode ${label}`)\n throw err\n }\n}\n","/**\n * x402 protocol support for the Haven SDK.\n *\n * Provides:\n * - parsePaymentRequired() — extract payment requirements from a 402 response\n * - parsePaymentRequiredResponse() — async parser with JSON body fallback\n * - encodePaymentProof() — encode a receipt as a PAYMENT-SIGNATURE header\n *\n * The main authorizeX402() and fetchWithPayment() are methods on HavenClient\n * (see client.ts) since they need API access and signing.\n */\n\nimport { createHash } from 'node:crypto'\nimport type { X402ExpectedContext, X402PaymentRequired, X402PaymentOption } from './types.js'\nimport type { PaymentRequirements } from 'x402/types'\nimport { decodeBase64Json, encodeBase64Json } from './base64.js'\n\nconst BASE_USDC_ADDRESS = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913'\nconst BASE_SEPOLIA_USDC_ADDRESS = '0x036cbd53842c5426634e7929541ec2318f3dcf7e'\n/** USDC addresses the standard EIP-3009 exact scheme can pay (Base mainnet + Base Sepolia). */\nconst STANDARD_X402_USDC_ADDRESSES = new Set([BASE_USDC_ADDRESS, BASE_SEPOLIA_USDC_ADDRESS])\nconst X402_IDEMPOTENCY_BUCKET_MS = 300_000\nconst DECIMAL_ATOMIC_AMOUNT_RE = /^[0-9]+$/\n\nfunction isPositiveDecimalAtomicAmount(value: string): boolean {\n return DECIMAL_ATOMIC_AMOUNT_RE.test(value) && BigInt(value) > 0n\n}\n\nfunction optionAuthorizationAmount(option: X402PaymentOption): string {\n return option.maxAmountRequired ?? option.amount\n}\n\n/**\n * Upper bound on the MERCHANT-requested part of the EIP-3009 authorization\n * window (#715, epic #713). The x402 library sets\n * `validBefore = now + maxTimeoutSeconds` straight from the MERCHANT's 402\n * challenge — without a cap, a malicious or sloppy merchant can request a\n * year-long window and a leaked signed authorization stays spendable that\n * whole time. 600 s is generous for any facilitator settle (typical is\n * 30–60 s); we CLAMP rather than reject so payments keep flowing while\n * exposure stays bounded. `validBefore` is a deadline, not a demand —\n * settling earlier is always valid.\n */\nexport const X402_MAX_AUTHORIZATION_WINDOW_SECONDS = 600\n\n/**\n * Forward margin ADDED on top of the (clamped) merchant timeout when the\n * authorization is actually signed (#1256). The x402 verify rule requires\n * `validBefore ≥ now + maxTimeoutSeconds` AT THE FACILITATOR — but the\n * upstream library computes `validBefore = now + maxTimeoutSeconds` at\n * SIGNING time, leaving zero forward margin. Haven's flow guarantees elapsed\n * time between the two (the funding UserOp confirms before the merchant\n * retry, ~1 min plus latency), so every purchase against a merchant whose\n * `maxTimeoutSeconds` exceeded that latency failed structurally — measured\n * live on Base mainnet: Anchor requires 300 s, and 226 s remained at verify.\n *\n * 300 s covers funding + retry latency with room to spare. The #715 exposure\n * ceiling becomes clamped-timeout + margin ≤ 900 s total forward — a\n * deliberate widening from 600 s, recorded on #1256: an authorization that\n * cannot pass verify protects no one, and 900 s is still bounded by the same\n * clamp discipline.\n */\nexport const X402_SETTLEMENT_FORWARD_MARGIN_SECONDS = 300\n\nfunction clampAuthorizationWindow(seconds: number | undefined): number {\n const requested = typeof seconds === 'number' && Number.isFinite(seconds) ? seconds : 30\n return Math.min(Math.max(Math.floor(requested), 1), X402_MAX_AUTHORIZATION_WINDOW_SECONDS)\n}\n\nfunction normalizePaymentOption(value: unknown): X402PaymentOption | null {\n const candidate = value as Partial<X402PaymentOption> | null\n if (\n !candidate ||\n typeof candidate !== 'object' ||\n typeof candidate.scheme !== 'string' ||\n typeof candidate.network !== 'string' ||\n typeof candidate.asset !== 'string' ||\n typeof candidate.payTo !== 'string'\n ) {\n return null\n }\n\n const amount =\n typeof candidate.amount === 'string'\n ? candidate.amount\n : typeof candidate.maxAmountRequired === 'string'\n ? candidate.maxAmountRequired\n : null\n\n if (!amount) return null\n if (!isPositiveDecimalAtomicAmount(amount)) return null\n if (\n candidate.maxAmountRequired !== undefined &&\n (\n typeof candidate.maxAmountRequired !== 'string' ||\n !isPositiveDecimalAtomicAmount(candidate.maxAmountRequired)\n )\n ) {\n return null\n }\n\n return {\n scheme: candidate.scheme,\n network: candidate.network,\n amount,\n maxAmountRequired: candidate.maxAmountRequired,\n resource: candidate.resource,\n description: candidate.description,\n mimeType: candidate.mimeType,\n asset: candidate.asset,\n payTo: candidate.payTo,\n maxTimeoutSeconds: clampAuthorizationWindow(candidate.maxTimeoutSeconds),\n extra: candidate.extra,\n }\n}\n\nfunction normalizePaymentRequired(value: unknown): X402PaymentRequired | null {\n const candidate = value as Partial<X402PaymentRequired> | null\n if (\n !candidate ||\n typeof candidate !== 'object' ||\n typeof candidate.x402Version !== 'number' ||\n !Array.isArray(candidate.accepts)\n ) {\n return null\n }\n\n const accepts = candidate.accepts\n .map((option) => normalizePaymentOption(option))\n .filter((option): option is X402PaymentOption => !!option)\n\n if (accepts.length === 0) return null\n\n const first = accepts[0]\n const resourceUrl = candidate.resource?.url ?? first.resource\n if (!resourceUrl) return null\n\n const resource = {\n url: resourceUrl,\n description: candidate.resource?.description ?? first.description,\n mimeType: candidate.resource?.mimeType ?? first.mimeType,\n }\n\n return {\n x402Version: candidate.x402Version,\n resource,\n accepts,\n error: candidate.error,\n ...(candidate.extensions && typeof candidate.extensions === 'object'\n ? { extensions: candidate.extensions as Record<string, unknown> }\n : {}),\n }\n}\n\n// ── Supported networks ───────────────────────────────────────────\n\n/** Network identifiers that Haven can recognise in x402 payment requests. */\nexport const SUPPORTED_X402_NETWORKS: Record<string, string> = {\n 'eip155:100': 'Gnosis Chain',\n 'eip155:8453': 'Base',\n 'base': 'Base',\n 'eip155:84532': 'Base Sepolia',\n 'base-sepolia': 'Base Sepolia',\n}\n\n/** Networks supported by the official x402 EIP-3009 exact scheme. */\nconst STANDARD_X402_NETWORKS: Record<string, PaymentRequirements['network']> = {\n 'eip155:8453': 'base',\n 'base': 'base',\n 'eip155:84532': 'base-sepolia',\n 'base-sepolia': 'base-sepolia',\n}\n\n// ── Token address maps ────────────────────────────────────────────\n\n/** Known tokens on Gnosis Chain (chainId 100). */\nconst GNOSIS_TOKENS: Record<string, { symbol: string; decimals: number }> = {\n '0x0000000000000000000000000000000000000000': { symbol: 'xDAI', decimals: 18 },\n '0xcb444e90d8198415266c6a2724b7900fb12fc56e': { symbol: 'EURe', decimals: 18 },\n '0x2a22f9c3b484c3629090feed35f17ff8f88f76f0': { symbol: 'USDC.e', decimals: 6 },\n}\n\n/** Known tokens on Base (chainId 8453). */\nconst BASE_TOKENS: Record<string, { symbol: string; decimals: number }> = {\n '0x0000000000000000000000000000000000000000': { symbol: 'ETH', decimals: 18 },\n '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913': { symbol: 'USDC', decimals: 6 },\n}\n\n/** Known tokens on Base Sepolia (chainId 84532) — testnet. */\nconst BASE_SEPOLIA_TOKENS: Record<string, { symbol: string; decimals: number }> = {\n '0x0000000000000000000000000000000000000000': { symbol: 'ETH', decimals: 18 },\n '0x036cbd53842c5426634e7929541ec2318f3dcf7e': { symbol: 'USDC', decimals: 6 },\n}\n\n/** All known tokens across all supported chains (for display / resolution). */\nconst ALL_TOKENS: Record<string, { symbol: string; decimals: number }> = {\n ...GNOSIS_TOKENS,\n ...BASE_TOKENS,\n ...BASE_SEPOLIA_TOKENS,\n}\n\n/** Maps CAIP-2 network ID → token address map. */\nconst NETWORK_TOKENS: Record<string, Record<string, { symbol: string; decimals: number }>> = {\n 'eip155:100': GNOSIS_TOKENS,\n 'eip155:8453': BASE_TOKENS,\n 'base': BASE_TOKENS,\n 'eip155:84532': BASE_SEPOLIA_TOKENS,\n 'base-sepolia': BASE_SEPOLIA_TOKENS,\n}\n\n// ── Parser ───────────────────────────────────────────────────────\n\n/**\n * Parse an HTTP 402 response into x402 PaymentRequired data.\n *\n * Supports:\n * - v2: PAYMENT-REQUIRED header (base64 JSON)\n * - v1 fallback: X-PAYMENT header or response body\n */\nexport function parsePaymentRequired(response: Response): X402PaymentRequired {\n // v2: PAYMENT-REQUIRED header\n const v2Header = response.headers.get('PAYMENT-REQUIRED')\n if (v2Header) {\n const parsed = normalizePaymentRequired(\n decodeBase64Json<unknown>(v2Header, 'PAYMENT-REQUIRED header'),\n )\n if (parsed) return parsed\n }\n\n // v1: X-PAYMENT header\n const v1Header = response.headers.get('X-PAYMENT')\n if (v1Header) {\n const parsed = normalizePaymentRequired(\n decodeBase64Json<unknown>(v1Header, 'X-PAYMENT header'),\n )\n if (parsed) return parsed\n }\n\n throw new Error(\n 'No x402 payment headers found in 402 response. ' +\n 'Expected PAYMENT-REQUIRED (v2) or X-PAYMENT (v1) header.',\n )\n}\n\n/**\n * Parse an HTTP 402 response into x402 PaymentRequired data.\n *\n * Soundside and other Bazaar-style MCP endpoints return the PaymentRequired\n * object in the JSON body, while older Haven demos and many x402 examples use\n * base64 headers. This keeps the synchronous header parser intact and adds the\n * body fallback needed for those endpoints.\n */\nexport async function parsePaymentRequiredResponse(\n response: Response,\n): Promise<X402PaymentRequired> {\n try {\n return parsePaymentRequired(response)\n } catch (headerErr) {\n try {\n const body = await response.clone().json()\n const parsed = normalizePaymentRequired(body)\n if (parsed) return parsed\n } catch {\n // Fall through to the original, more specific header error below.\n }\n\n throw headerErr\n }\n}\n\n/**\n * Select the best payment option from the x402 accepts array.\n *\n * Preference order:\n * 1. Option on a Haven-supported network with a known token\n * 2. Any option on a Haven-supported network\n * 3. null — no compatible option\n */\nexport function selectPaymentOption(\n accepts: X402PaymentOption[],\n): X402PaymentOption | null {\n if (!accepts || accepts.length === 0) return null\n\n // First pass: find a supported network with a known token\n for (const opt of accepts) {\n if (opt.network in SUPPORTED_X402_NETWORKS) {\n const networkTokens = NETWORK_TOKENS[opt.network]\n if (\n networkTokens?.[opt.asset.toLowerCase()] &&\n isPositiveDecimalAtomicAmount(optionAuthorizationAmount(opt))\n ) {\n return opt\n }\n }\n }\n\n // Second pass: any supported network\n for (const opt of accepts) {\n if (\n opt.network in SUPPORTED_X402_NETWORKS &&\n isPositiveDecimalAtomicAmount(optionAuthorizationAmount(opt))\n ) {\n return opt\n }\n }\n\n // No compatible option found\n return null\n}\n\n/**\n * Select an option that can be paid with the official x402 EIP-3009 exact\n * scheme. Haven's older tx-hash proof path can describe more networks; the\n * merchant-verified path currently needs Base USDC.\n */\nexport function selectStandardPaymentOption(\n accepts: X402PaymentOption[],\n): X402PaymentOption | null {\n if (!accepts || accepts.length === 0) return null\n\n for (const opt of accepts) {\n if (\n opt.scheme === 'exact' &&\n opt.network in STANDARD_X402_NETWORKS &&\n STANDARD_X402_USDC_ADDRESSES.has(opt.asset.toLowerCase()) &&\n isPositiveDecimalAtomicAmount(optionAuthorizationAmount(opt))\n ) {\n return opt\n }\n }\n\n return null\n}\n\nexport function x402AuthorizationAmount(option: X402PaymentOption): string {\n const amount = optionAuthorizationAmount(option)\n if (!isPositiveDecimalAtomicAmount(amount)) {\n throw new Error('Invalid x402 amount: must be a positive decimal atomic amount')\n }\n return amount\n}\n\n/**\n * Canonical Haven-authenticated x402 expected context, recomputed byte-for-byte\n * by the edge signer before it signs anything.\n *\n * **Two versions, and the version is derived — never passed in (#1138).**\n * `typedDataHash` present ⇒ v2, absent ⇒ v1. A v1 message is byte-identical to\n * what shipped before, so existing signers keep verifying legacy-rail bindings\n * unchanged.\n *\n * The version lives in both the header line and the payload so neither can be\n * reinterpreted as the other: a v2 context cannot be replayed as a v1 one that\n * drops the typed-data commitment, and a v1 context cannot be presented as v2.\n * That downgrade is exactly the attack the digest exists to stop — see\n * `assertExpectedBinding` in `@haven_ai/signer`, which refuses to raw-sign a\n * hash under a v2 binding and refuses to sign typed data without one.\n */\nexport function buildX402ExpectedMessage(context: X402ExpectedContext): string {\n const version = context.typedDataHash ? 2 : 1\n const payload: Record<string, unknown> = {\n version,\n kind: 'haven.x402.expected',\n paymentId: context.paymentId,\n payloadHash: context.payloadHash.toLowerCase(),\n resourceUrl: context.resourceUrl,\n merchantTo: context.merchantTo.toLowerCase(),\n amount: context.amount,\n asset: context.asset.toLowerCase(),\n network: context.network,\n }\n if (context.expiresAt) {\n payload.expiresAt = context.expiresAt\n }\n if (context.typedDataHash) {\n payload.typedDataHash = context.typedDataHash.toLowerCase()\n }\n return `Haven x402 expected context v${version}\\n${stableStringify(payload)}`\n}\n\nexport function toStandardPaymentRequirements(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n): PaymentRequirements {\n const network = STANDARD_X402_NETWORKS[option.network]\n if (!network) {\n throw new Error(`x402 exact payments are not supported on ${option.network}`)\n }\n\n if (option.scheme !== 'exact') {\n throw new Error(`Unsupported x402 scheme: ${option.scheme}`)\n }\n\n return {\n scheme: 'exact',\n network,\n maxAmountRequired: x402AuthorizationAmount(option),\n resource: option.resource ?? paymentRequired.resource.url,\n description:\n option.description ??\n paymentRequired.resource.description ??\n 'Haven x402 payment',\n mimeType:\n option.mimeType ??\n paymentRequired.resource.mimeType ??\n 'application/octet-stream',\n payTo: option.payTo,\n asset: option.asset,\n // Second enforcement point (#715): the parse path clamps too, but this is\n // the last stop before the x402 library turns the timeout into\n // `validBefore` — options constructed without parsing are bounded here.\n // The forward margin (#1256) is added ONLY here, at signing: the parse\n // path keeps recording the merchant's advertised timeout unchanged, and\n // the library's `validBefore = now + this value` then carries enough\n // slack to satisfy the facilitator's `validBefore ≥ now + maxTimeout`\n // verify rule after our funding leg confirms.\n maxTimeoutSeconds:\n clampAuthorizationWindow(option.maxTimeoutSeconds) +\n X402_SETTLEMENT_FORWARD_MARGIN_SECONDS,\n extra: option.extra,\n }\n}\n\nexport function buildX402IdempotencyKey(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n now = Date.now(),\n): string {\n const bucket = Math.floor(now / X402_IDEMPOTENCY_BUCKET_MS)\n const material = [\n paymentRequired.resource.url,\n paymentRequired.resource.description ?? '',\n option.payTo.toLowerCase(),\n option.asset.toLowerCase(),\n x402AuthorizationAmount(option),\n option.network,\n bucket,\n ].join('|')\n\n return `x402:${createHash('sha256').update(material).digest('hex').slice(0, 16)}`\n}\n\n/**\n * Encode a payment receipt as a base64 PAYMENT-SIGNATURE header value.\n *\n * This follows the x402 v2 protocol — the server's facilitator will\n * verify the on-chain transaction referenced by tx_hash.\n */\nexport function encodePaymentProof(receipt: {\n txHash: string\n paymentId: string\n token: string\n amount: string\n to: string\n resourceUrl?: string\n accepted?: X402PaymentOption\n payer?: string\n chainId?: number\n}): string {\n const payload = {\n x402Version: 2,\n resource: receipt.resourceUrl ? { url: receipt.resourceUrl } : undefined,\n accepted: receipt.accepted,\n payload: {\n type: 'haven_tx_hash',\n txHash: receipt.txHash,\n paymentId: receipt.paymentId,\n settledVia: 'haven',\n payer: receipt.payer,\n chainId: receipt.chainId,\n },\n }\n return encodeBase64Json(payload)\n}\n\n/**\n * Resolve a token symbol from a contract address.\n *\n * Checks all supported chains. For chain-specific resolution,\n * pass the optional `network` CAIP-2 string (e.g. \"eip155:100\").\n */\nexport function resolveTokenFromAddress(\n address: string,\n network?: string,\n): { symbol: string; decimals: number } | null {\n const lower = address.toLowerCase()\n\n if (network && network in NETWORK_TOKENS) {\n return NETWORK_TOKENS[network][lower] ?? null\n }\n\n return ALL_TOKENS[lower] ?? null\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') {\n const primitive = JSON.stringify(value)\n return primitive === undefined ? 'undefined' : primitive\n }\n // Match JSON.stringify's Date handling: serialize to the ISO string, not the\n // empty object the generic-object branch would produce (Object.keys(date) is\n // []). The backend builds the x402 expected-context message from a Postgres\n // TIMESTAMPTZ (a Date at runtime), so without this the signed message carried\n // \"expiresAt\":{} while the edge signer recomputed \"expiresAt\":\"<ISO>\" — a\n // mismatch that broke x402 signature verification once expires_at entered the\n // signed context.\n if (value instanceof Date) return JSON.stringify(value.toISOString())\n if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(',')}]`\n const object = value as Record<string, unknown>\n return `{${Object.keys(object)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${stableStringify(object[key])}`)\n .join(',')}}`\n}\n","import { ethers } from 'ethers'\n\nexport function createJsonRpcProvider(url: string): ethers.JsonRpcProvider {\n return new ethers.JsonRpcProvider(url)\n}\n\nexport function createWallet(privateKey: string, provider: ethers.JsonRpcProvider): ethers.Wallet {\n return new ethers.Wallet(privateKey, provider)\n}\n\nexport function createErc20Contract(\n address: string,\n abi: readonly string[],\n signer: ethers.Signer,\n): ethers.Contract {\n return new ethers.Contract(address, abi as string[], signer)\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { exact } from 'x402/schemes'\nimport { hashTypedData } from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport { signHash, signUserOpTypedDataForDelegation, addressFromKey, verifySignature } from './signer.js'\nimport { verifyPaymentReceipt, type PaymentReceipt, type ReceiptVerification } from './receipt.js'\nimport type {\n HavenClientConfig,\n PaymentRequest,\n PaymentIntent,\n PaymentResult,\n PaymentStatus,\n PaymentPhase,\n PaymentNextAction,\n PaymentStatusResult,\n PaymentResumeState,\n SignData,\n SweepResult,\n X402AuthorizationOptions,\n RawCreateResponse,\n RawSignResponse,\n RawStatusResponse,\n RawPaymentStatusResult,\n X402PaymentRequired,\n X402PaymentOption,\n X402Intent,\n X402McpTransport,\n X402MerchantCallContext,\n RawX402MerchantCallContext,\n X402Quote,\n X402Receipt,\n X402RequestSnapshot,\n X402ResumeState,\n ResumeAuthorizedX402Input,\n ResumeX402PaymentInput,\n RawX402AuthorizeResponse,\n HavenAgent,\n HavenAgentSummary,\n HavenAgentAllowanceSummary,\n HavenAgentReadiness,\n HavenAllowanceSummary,\n PostPurchaseAllowanceSummary,\n HavenPaymentReceipt,\n RawHavenAgent,\n RawHavenAllowanceSummary,\n RawHavenPaymentReceiptsResponse,\n RawHavenPaymentReceipt,\n HavenCatalogEntry,\n RawCatalogEntry,\n AgentPaymentWarning,\n} from './types.js'\nimport {\n AgentPaymentNextAction,\n AgentPaymentPhase,\n AgentPaymentRail,\n AgentPaymentWarningCode,\n HavenApiError,\n HavenPaymentStateError,\n MerchantTimeoutError,\n X402UnexpectedStatusError,\n HavenSigningError,\n HavenTimeoutError,\n} from './types.js'\nimport {\n buildX402IdempotencyKey,\n parsePaymentRequiredResponse,\n resolveTokenFromAddress,\n selectStandardPaymentOption,\n toStandardPaymentRequirements,\n x402AuthorizationAmount,\n} from './x402.js'\nimport type {\n SweepAuthorization,\n SweepPrepareResponse,\n SweepSubmitResponse,\n} from './sweep.js'\nimport { createJsonRpcProvider, createWallet, createErc20Contract } from './provider.js'\nimport { decodeBase64Json, encodeBase64Json } from './base64.js'\n\nconst DEFAULT_BASE_URL = 'http://localhost:3001'\n\nconst CHAIN_EXPLORER_TX: Record<number, string> = {\n 100: 'https://gnosisscan.io/tx',\n 8453: 'https://basescan.org/tx',\n}\n\n// Canonical USDC contract address per chain — the single source the sweep flow\n// resolves against. Base (8453) is the only chain Haven sweeps today; the x402\n// path keeps its own lowercase copy for header comparison (see x402.ts\n// BASE_TOKENS). Add a chain here to make its USDC sweepable.\nconst CHAIN_USDC: Record<number, string> = {\n 8453: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n 84532: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',\n}\n\nfunction buildExplorerUrl(chainId: number | undefined, txHash: string): string {\n const base = CHAIN_EXPLORER_TX[chainId ?? 8453] ?? CHAIN_EXPLORER_TX[8453]\n return `${base}/${txHash}`\n}\n\nfunction explorerUrlOrEmpty(chainId: number | undefined, txHash: string | null | undefined): string {\n return txHash ? buildExplorerUrl(chainId, txHash) : ''\n}\n\nconst DEFAULT_REQUEST_TIMEOUT = 30_000\n// #1300: merchant-facing default, CALIBRATED against this repo's own\n// tolerances (post-merge review finding): the demo merchant advertises\n// maxTimeoutSeconds: 300 in every PaymentRequired, and its synchronous\n// settlement wait inherits viem's 180 s waitForTransactionReceipt default —\n// so a shorter client bound would abort settlements the protocol contract\n// itself calls normal. 300 s keeps the hang bounded without racing the\n// merchant's own window. Override per client via config.merchantTimeout.\nconst DEFAULT_MERCHANT_TIMEOUT = 300_000\n// The best-effort MCP initialized-notification does not deserve the\n// settlement budget — its result is discarded either way.\nconst NOTIFY_TIMEOUT = 10_000\nconst DEFAULT_CONFIRMATION_TIMEOUT = 90_000\nconst DEFAULT_POLLING_INTERVAL = 3_000\n\nfunction formatAtomicAmount(atomic: bigint, decimals: number): string {\n // Defensive: negative atomics can't occur today (remaining is floored at 0n)\n // but would otherwise produce corrupt output like \"0.000...-5\".\n if (atomic < 0n) return '0.0'\n const s = atomic.toString().padStart(decimals + 1, '0')\n const intPart = s.slice(0, s.length - decimals) || '0'\n const fracPart = s.slice(s.length - decimals).replace(/0+$/, '') || '0'\n return `${intPart}.${fracPart}`\n}\n\n/** Parse an atomic-amount string, defaulting to 0n on malformed input. */\nfunction safeBigInt(value: string): bigint {\n try {\n return BigInt(value)\n } catch {\n return 0n\n }\n}\n\n/**\n * Derive the agent's spend-readiness from its raw status and per-token remaining\n * allowance. See {@link HavenAgentReadiness} for the contract.\n */\nfunction deriveReadiness(\n status: string,\n allowances: ReadonlyArray<{ remainingAtomic: string }>,\n): HavenAgentReadiness {\n if (status !== 'active') return 'revoked'\n const hasSpendable = allowances.some((a) => safeBigInt(a.remainingAtomic) > 0n)\n return hasSpendable ? 'ready' : 'needs_approval'\n}\n\n// ── MCP-over-x402 transport (issue #315) ──────────────────────────\n// MCP merchants (Soundside, the Coinbase reference) speak the Streamable\n// HTTP transport: an `initialize` handshake hands back an `mcp-session-id`\n// that must ride on every subsequent request, and responses arrive as SSE.\nconst MCP_PROTOCOL_VERSION = '2025-06-18'\nconst MCP_ACCEPT = 'application/json, text/event-stream'\nconst MCP_CLIENT_INFO = { name: 'haven-sdk', version: '1' }\n\n/** Cap the merchant body persisted to the reconciliation event (the full body is kept on the thrown error). */\nconst MERCHANT_BODY_SNIPPET_LIMIT = 1000\n\n/** A failed merchant retry response, captured verbatim for debugging and surfaced on the structured error. */\ninterface CapturedMerchantResponse {\n merchant_status: number\n merchant_status_text: string\n merchant_headers: Record<string, string>\n merchant_body: string\n}\n\nconst PAYMENT_STATE_STATUS_CODES: Record<string, number> = {\n pending: 202,\n pending_approval: 202,\n approved: 202,\n proposed: 202,\n executed: 200,\n pending_signature: 409,\n submitted: 409,\n expired: 410,\n failed: 502,\n rejected: 409,\n}\n\nfunction chainIdFromNetwork(network: string | undefined): number | undefined {\n if (network === 'base') return 8453\n if (!network?.startsWith('eip155:')) return undefined\n const chainId = Number(network.slice('eip155:'.length))\n return Number.isFinite(chainId) ? chainId : undefined\n}\n\nfunction chainIdOrNull(network: string | undefined): number | null {\n return chainIdFromNetwork(network) ?? null\n}\n\nfunction phaseForStatus(status: string): PaymentPhase | null {\n if (status === 'pending_signature') return AgentPaymentPhase.AgentSignatureRequired\n if (status === 'submitted') return AgentPaymentPhase.PaymentSubmitted\n if (status === 'confirmed') return AgentPaymentPhase.PaymentConfirmed\n if (status === 'pending' || status === 'pending_approval') return AgentPaymentPhase.UserApprovalRequired\n if (status === 'approved') return AgentPaymentPhase.UserExecutionRequired\n if (status === 'proposed') return AgentPaymentPhase.WaitingForAdditionalApprovals\n if (status === 'executed') return AgentPaymentPhase.FundingSent\n if (status === 'rejected') return AgentPaymentPhase.Rejected\n if (status === 'expired') return AgentPaymentPhase.Expired\n if (status === 'failed') return AgentPaymentPhase.Failed\n return null\n}\n\nfunction nextActionForStatus(status: string): PaymentNextAction | null {\n if (status === 'pending_signature') return AgentPaymentNextAction.SignAndSubmitPayment\n if (status === 'submitted') return AgentPaymentNextAction.CheckStatusLater\n if (status === 'confirmed') return AgentPaymentNextAction.None\n if (status === 'pending' || status === 'pending_approval') return AgentPaymentNextAction.WaitForUserApproval\n if (status === 'approved') return AgentPaymentNextAction.WaitForUserToCompletePayment\n if (status === 'proposed') return AgentPaymentNextAction.WaitForUserApproval\n if (status === 'executed') return AgentPaymentNextAction.RetryOriginalX402Request\n if (status === 'rejected') return AgentPaymentNextAction.StopAndTellUser\n if (status === 'expired') return AgentPaymentNextAction.RequestAgainIfUserStillWantsIt\n if (status === 'failed') return AgentPaymentNextAction.StopAndTellUser\n return null\n}\n\nfunction messageForState(\n label: string,\n status: string,\n paymentId: string,\n nextAction: PaymentNextAction,\n): string {\n if (status === 'pending' || status === 'pending_approval') {\n return `${label} is above the remaining agent budget and is waiting for user approval in Haven (payment_id: ${paymentId}).`\n }\n if (status === 'executed') {\n return 'The user completed the funding payment. Retry the original x402 request.'\n }\n if (status === 'rejected') {\n return `The user rejected this payment request (payment_id: ${paymentId}).`\n }\n if (status === 'expired') {\n return `This payment request expired (payment_id: ${paymentId}).`\n }\n return `${label} is ${status}; next_action=${nextAction} (payment_id: ${paymentId}).`\n}\n\nfunction sameAddress(a: string | null | undefined, b: string | null | undefined): boolean {\n return Boolean(a && b && a.toLowerCase() === b.toLowerCase())\n}\n\nfunction decimalFromUsdcAtomic(value: string): string {\n const amount = BigInt(value)\n const whole = amount / 1_000_000n\n const fraction = (amount % 1_000_000n).toString().padStart(6, '0').replace(/0+$/, '')\n return fraction ? `${whole}.${fraction}` : whole.toString()\n}\n\nfunction normalizeDecimal(value: string): string {\n if (!value.includes('.')) return value.replace(/^0+(?=\\d)/, '') || '0'\n const [whole, fraction = ''] = value.split('.')\n const normalizedWhole = whole.replace(/^0+(?=\\d)/, '') || '0'\n const normalizedFraction = fraction.replace(/0+$/, '')\n return normalizedFraction ? `${normalizedWhole}.${normalizedFraction}` : normalizedWhole\n}\n\nfunction parseMerchantSettlement(header: string | null): {\n settlementTxHash?: string | null\n} {\n if (!header) return {}\n const parsed = parseProtocolReceiptHeader(header)\n const tx =\n typeof parsed?.transaction === 'string'\n ? parsed.transaction\n : typeof parsed?.txHash === 'string'\n ? parsed.txHash\n : typeof parsed?.tx_hash === 'string'\n ? parsed.tx_hash\n : null\n return { settlementTxHash: tx }\n}\n\n/**\n * MCP-over-HTTP merchants expose their endpoint at a path ending in `/mcp`\n * (Soundside, the Coinbase reference — the convention). That path is the\n * primary auto-handshake signal. Trailing slashes and query/hash suffixes\n * are tolerated so `/mcp/`, `/mcp?x=1`, and `/foo/mcp` all match.\n */\nfunction isMcpUrl(url: string): boolean {\n try {\n return new URL(url).pathname.replace(/\\/+$/, '').endsWith('/mcp')\n } catch {\n return /\\/mcp(?:[/?#]|$)/.test(url)\n }\n}\n\n/**\n * Coinbase Bazaar's published-discovery extension. Its presence in a 402 body\n * marks an MCP-discoverable resource even when the URL doesn't end in `/mcp`,\n * so it is the second auto-handshake signal.\n */\nasync function responseHasBazaarExtension(response: Response): Promise<boolean> {\n try {\n const body = (await response.clone().json()) as { extensions?: { bazaar?: unknown } } | null\n return body?.extensions?.bazaar != null\n } catch {\n return false\n }\n}\n\n/**\n * Parse the `data:` frames of an MCP Streamable-HTTP SSE stream into the\n * JSON-RPC messages they carry. Multiple `data:` lines before a blank line are\n * concatenated into one payload per the SSE spec; non-JSON frames (keep-alives)\n * are skipped.\n */\nfunction parseSseJsonRpcMessages(text: string): Array<Record<string, unknown>> {\n const messages: Array<Record<string, unknown>> = []\n let dataLines: string[] = []\n\n const flush = (): void => {\n if (dataLines.length === 0) return\n try {\n messages.push(JSON.parse(dataLines.join('\\n')) as Record<string, unknown>)\n } catch {\n // Ignore keep-alives and non-JSON data frames.\n }\n dataLines = []\n }\n\n for (const line of text.split(/\\r?\\n/)) {\n if (line === '') {\n flush()\n continue\n }\n if (line.startsWith('data:')) {\n dataLines.push(line.slice(5).replace(/^ /, ''))\n }\n }\n flush()\n\n return messages\n}\n\n/** Pick the JSON-RPC response (result/error) from a set of SSE messages. */\nfunction selectJsonRpcResult(\n messages: Array<Record<string, unknown>>,\n): Record<string, unknown> | undefined {\n return messages.find((m) => 'result' in m || 'error' in m) ?? messages[messages.length - 1]\n}\n\n/**\n * Digest of a delegation-rail signing payload, or `undefined` when there is\n * none (#1138).\n *\n * Guarded because a payload that cannot be hashed is not a recoverable\n * condition to paper over: the edge signer derives this same digest before\n * signing, so an unhashable payload can never be signed by anyone. Surfacing it\n * as a named Haven error beats letting a raw viem type error escape from the\n * middle of intent construction.\n */\nfunction x402TypedDataDigest(typedData: unknown): string | undefined {\n if (!typedData || typeof typedData !== 'object') return undefined\n try {\n return hashTypedData(typedData as Parameters<typeof hashTypedData>[0])\n } catch (err) {\n throw new HavenSigningError(\n 'The x402 funding intent carried a sign_data.typed_data that is not a valid EIP-712 ' +\n 'payload (needs domain, types, primaryType, message), so its digest cannot be derived ' +\n 'and no signer could accept it. ' +\n `Underlying error: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/** Shared by {@link HavenClient.discoverTools} and {@link HavenClient.getCatalogEntry} (#1306). */\nfunction mapCatalogEntry(entry: RawCatalogEntry): HavenCatalogEntry {\n return {\n id: entry.id,\n name: entry.name,\n description: entry.description,\n category: entry.category,\n resourceUrl: entry.resource_url,\n rail: entry.rail,\n protocol: entry.protocol,\n toolName: entry.tool_name,\n toolArguments: entry.tool_arguments ?? null,\n priceDisplay: entry.price_display,\n priceAtomic: entry.price_atomic,\n asset: entry.asset,\n network: entry.network,\n status: entry.status,\n verifiedAt: entry.verified_at,\n }\n}\n\nexport class HavenClient {\n private readonly apiKey: string\n private readonly delegateKey: string | undefined\n private readonly baseUrl: string\n private readonly x402Wallet: string | undefined\n private readonly requestTimeout: number\n private readonly merchantTimeout: number\n private readonly confirmationTimeout: number\n private readonly pollingInterval: number\n private readonly chainRpcs: Record<number, string>\n private readonly inFlightX402 = new Map<string, Promise<X402Receipt>>()\n private readonly x402ReceiptCache = new Map<string, { expiresAt: number; receipt: X402Receipt }>()\n /**\n * Setup-time headers configured via `HavenClientConfig.defaultHeaders`.\n * Read-only after construction — use `withRequestContext` for per-call\n * scoping so concurrent requests don't race on shared mutable state.\n */\n private readonly defaultHeaders: Record<string, string>\n /**\n * Async-local store for per-request context (currently: extra headers).\n * Each `withRequestContext` invocation produces an isolated store, so\n * overlapping async work — like two MCP tool dispatches in flight at\n * the same time — see their own headers without stepping on each other.\n */\n private readonly requestContext = new AsyncLocalStorage<{ headers: Record<string, string> }>()\n\n /** Monotonic JSON-RPC id source for the MCP `initialize` handshake. */\n private mcpRequestId = 0\n\n /** Delegate address derived from the private key (if provided) */\n readonly delegateAddress: string | undefined\n\n constructor(config: HavenClientConfig) {\n this.apiKey = config.apiKey\n this.delegateKey = config.delegateKey\n this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '')\n this.x402Wallet = config.x402Wallet\n this.requestTimeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT\n this.merchantTimeout = config.merchantTimeout ?? DEFAULT_MERCHANT_TIMEOUT\n this.confirmationTimeout = config.confirmationTimeout ?? DEFAULT_CONFIRMATION_TIMEOUT\n this.pollingInterval = config.pollingInterval ?? DEFAULT_POLLING_INTERVAL\n this.chainRpcs = config.chainRpcs ?? {}\n this.defaultHeaders = { ...(config.defaultHeaders ?? {}) }\n\n if (this.delegateKey) {\n this.delegateAddress = addressFromKey(this.delegateKey)\n }\n }\n\n /**\n * Run `fn` with extra Haven-API headers scoped to the async work it\n * performs. Used by the MCP server to tag every Haven API request that\n * a single tool dispatch makes with `X-Haven-MCP-Tool: <name>` so the\n * backend can write an audit-log row attributing the call.\n *\n * The headers are held in an `AsyncLocalStorage` so overlapping\n * dispatches do not leak headers into each other's requests. The store\n * inherits across `await` boundaries, so any Haven API call made while\n * `fn` is awaiting will pick up the right headers.\n *\n * Has no effect on outbound merchant requests (x402 / MPP) — those\n * never go through the internal `request<T>` path that reads the\n * context.\n */\n withRequestContext<T>(headers: Record<string, string>, fn: () => Promise<T>): Promise<T> {\n return this.requestContext.run({ headers: { ...headers } }, fn)\n }\n\n // ── High-Level API ───────────────────────────────────────────────\n\n /**\n * Send a payment in one call.\n *\n * Creates the intent, signs the hash, submits the signature,\n * and polls until confirmed (or throws on failure/timeout).\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async pay(request: PaymentRequest): Promise<PaymentResult> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'Cannot use pay() without a delegateKey. Use createIntent() + submitSignature() for manual signing.',\n )\n }\n\n // Step 1: Create intent\n const intent = await this.createIntent(request)\n\n // Step 2: Sign\n const signature = this.sign(intent.signData.hash)\n\n // Step 3: Submit\n await this.submitSignature(intent.paymentId, signature)\n\n // Step 4: Wait for confirmation\n return this.waitForConfirmation(intent.paymentId)\n }\n\n // ── Step-by-Step API ─────────────────────────────────────────────\n\n /**\n * Step 1: Create a payment intent.\n *\n * Returns the intent with the hash to sign.\n */\n async createIntent(request: PaymentRequest): Promise<PaymentIntent> {\n const raw = await this.post<RawCreateResponse>('/payments', {\n token: request.token,\n amount: request.amount,\n to: request.to,\n ...(request.idempotencyKey ? { idempotency_key: request.idempotencyKey } : {}),\n })\n\n // Haven returns HTTP 202 with this status when the requested amount\n // exceeds the on-chain allowance. The payment is parked for the owner\n // to approve in the dashboard — there's nothing to sign yet, so the SDK\n // surfaces it as an explicit error rather than returning a malformed\n // intent with no signData.\n if (raw.status === 'pending_approval') {\n this.throwPaymentStateError('Payment', raw)\n }\n\n return {\n paymentId: raw.payment_id,\n status: 'pending_signature',\n expiresAt: raw.expires_at,\n signData: raw.sign_data,\n }\n }\n\n /**\n * Keyless x402 construct.\n *\n * The non-custodial half of an x402 payment: posts the funding request to\n * `/x402` and returns the unsigned funding hash plus the data the caller\n * needs to build and sign the EIP-3009 merchant header itself. Crucially it\n * does **not** sign — neither the funding hash nor the merchant header — so\n * it works without a `delegateKey`. Both delegate signatures happen on the\n * machine that holds the key (the edge); the hosted MCP server relays only.\n *\n * Use this from the hosted, keyless server. The all-in-one `authorizeX402`\n * remains for local clients that hold the key.\n *\n * Throws (via the shared payment-state path) when the amount exceeds the\n * on-chain allowance — there is nothing to sign until the user approves.\n */\n async createX402Intent(\n paymentRequired: X402PaymentRequired,\n options: X402AuthorizationOptions = {},\n ): Promise<X402Intent> {\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n if (!option) {\n throw new HavenApiError(\n 'No compatible payment option found in x402 requirements. ' +\n 'Haven supports standard x402 exact payments on Base USDC.',\n 400,\n )\n }\n\n // The funding transfer tops up the agent's delegate EOA. With no local key\n // we resolve that address from the authenticated agent record rather than\n // deriving it from a private key. #1348: a caller that already fetched the\n // agent in this flow passes delegateAddress and skips the duplicate fetch.\n const fundingTo = options.delegateAddress ?? (await this.getAgent()).delegateAddress\n if (!fundingTo) {\n throw new HavenApiError('Authenticated agent has no delegate address registered.', 502)\n }\n\n const idempotencyKey = options.idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option)\n const raw = await this.post<RawX402AuthorizeResponse>('/x402', {\n url: paymentRequired.resource.url,\n payTo: fundingTo,\n merchantPayTo: option.payTo,\n // #1360: this path ALWAYS means the EIP-3009 funding leg (payTo is the\n // agent's own delegate EOA). Saying so explicitly turns a stale/rotated\n // delegate address into the backend's LOUD shape-mismatch 400 instead\n // of a silent reroute to the erc7710 settlement branch (the #1358\n // review's open-budget misroute). Legacy-rail backends ignore the field.\n settlementScheme: 'eip3009',\n amount: x402AuthorizationAmount(option),\n asset: option.asset,\n network: option.network,\n description: paymentRequired.resource.description,\n idempotencyKey,\n // #1307: persisted so the settle leg can rehydrate it by payment_id.\n ...(options.mcpCallContext ? { mcpCallContext: options.mcpCallContext } : {}),\n // #1355: persisted so the SIGN leg can rehydrate it by payment_id — the\n // local signer's context fetch then carries the 402 PaymentRequired and\n // the agent passes only payment_id. Bounded: the backend rejects >64KB,\n // so an oversized blob is omitted here (signer falls back to the\n // caller-supplied copy) rather than failing the intent.\n ...(new TextEncoder().encode(JSON.stringify(paymentRequired)).length <= 65536\n ? { paymentRequired }\n : {}),\n })\n\n // Anything other than a signable funding intent (pending_approval,\n // expired, already-executed, error) is surfaced through the shared path.\n if (raw.status !== 'pending_signature') {\n this.throwPaymentStateError('x402 payment', raw)\n }\n if (!raw.sign_data?.hash) {\n throw new HavenApiError('No sign_hash returned from x402/authorize', 500, raw)\n }\n // #946/#1138: a delegation-rail funding intent signs the ACCOUNT's EIP-712\n // typed data, not the bare hash. This path is keyless by construction, so\n // it does not sign either one — it passes the payload through to whoever\n // holds the key (the local signer the connector installs). What it MUST\n // refuse is a scheme it cannot describe faithfully: handing a caller a\n // `hash` for a typed-data intent invites a raw ECDSA signature the account\n // rejects at the bundler, after the intent is claimed.\n if (raw.sign_data.signature_scheme !== undefined && !raw.sign_data.typed_data) {\n throw new HavenSigningError(\n `This account's x402 funding intent declares signature scheme ` +\n `'${raw.sign_data.signature_scheme}' but carried no typed_data to sign. ` +\n 'Refusing to fall back to the bare hash — the account would reject that signature ' +\n 'on-chain. This is a backend contract violation; report it rather than working around it.',\n )\n }\n if (!raw.x402_expected_auth) {\n throw new HavenApiError('No x402 expected-context binding returned from x402/authorize', 500, raw)\n }\n\n return {\n paymentId: raw.payment_id,\n idempotencyKey,\n status: 'pending_signature',\n expiresAt: raw.expires_at,\n signData: raw.sign_data,\n accepted: option,\n resourceUrl: paymentRequired.resource.url,\n merchantTo: raw.merchant_to ?? option.payTo,\n amountAtomic: x402AuthorizationAmount(option),\n asset: option.asset,\n network: option.network,\n expectedAuth: raw.x402_expected_auth,\n // #1138: the digest the delegation-rail expected context commits to.\n // Re-derived locally, exactly like every other context field the edge\n // signer is handed (amount, merchantTo, …) — none of them are trusted\n // because they arrived, they are trusted because the reconstructed\n // message has to match Haven's signature over it. A typed_data altered in\n // transit therefore fails message equality and is refused, and the signer\n // re-derives this digest a second time from the payload it actually signs.\n expectedTypedDataHash: x402TypedDataDigest(raw.sign_data.typed_data),\n fundingTo,\n }\n }\n\n /**\n * Step 2: Sign a hash with the delegate key.\n *\n * Returns the 65-byte signature (0x-prefixed).\n * Requires `delegateKey` to be set in the client config.\n */\n sign(hash: string): string {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'Cannot sign without a delegateKey. Pass the private key in HavenClient config, or sign externally.',\n )\n }\n\n const signature = signHash(this.delegateKey, hash)\n\n // Verify the signature locally before submitting\n if (!verifySignature(hash, signature, this.delegateAddress!)) {\n throw new HavenSigningError(\n 'Local signature verification failed — recovered address does not match delegate key.',\n )\n }\n\n return signature\n }\n\n /**\n * Sign a payment's `sign_data` with the correct scheme for its rail.\n *\n * Dispatching on the server-provided scheme means a caller never has to\n * know which rail an account is on; an unknown scheme is a hard error,\n * never a guessed signature. The session rail's 'eip191_userop' is retired\n * (#834) — the backend refuses those intents with HTTP 410 before any\n * sign_data reaches a client, so encountering it here is a hard error too.\n */\n private async signForData(signData: {\n hash: string\n signature_scheme?: string\n typed_data?: unknown\n }): Promise<string> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'Cannot sign without a delegateKey. Pass the private key in HavenClient config, or sign externally.',\n )\n }\n const scheme = signData.signature_scheme\n if (scheme === 'eip191_userop') {\n throw new HavenSigningError(\n \"The session rail is retired — 'eip191_userop' intents can no longer be signed. Re-onboard the account on the delegation rail.\",\n )\n }\n if (scheme === 'eip712_userop') {\n if (!signData.typed_data) {\n throw new HavenSigningError(\n 'sign_data.signature_scheme is eip712_userop but typed_data is missing — refusing to sign the bare hash (the account would reject it).',\n )\n }\n return signUserOpTypedDataForDelegation(this.delegateKey, signData.typed_data as never)\n }\n if (scheme === undefined) {\n return signHash(this.delegateKey, signData.hash) // legacy AllowanceModule rail\n }\n throw new HavenSigningError(\n `Unknown sign_data.signature_scheme '${scheme}' — refusing to guess a signing scheme. Update @haven_ai/sdk.`,\n )\n }\n\n /**\n * Step 3: Submit a signature to execute the payment.\n *\n * The signature can come from `client.sign()` or from external signing.\n */\n async submitSignature(\n paymentId: string,\n signature: string,\n ): Promise<{ status: string; txHash?: string }> {\n const raw = await this.post<RawSignResponse>(\n `/payments/${paymentId}/sign`,\n { signature },\n )\n\n return {\n status: raw.status,\n txHash: raw.tx_hash,\n }\n }\n\n /**\n * Get the current status of a payment.\n */\n async getPayment(paymentId: string): Promise<PaymentResult> {\n const raw = await this.get<RawStatusResponse>(`/payments/${paymentId}`)\n return this.mapPaymentResult(raw)\n }\n\n /**\n * Get agent-actionable status for a payment intent or approval request.\n *\n * Use this for IDs returned by agent tools and machine-payment/x402 flows.\n * `getPayment()` remains available for payment-intent-only integrations.\n */\n async getPaymentStatus(paymentId: string): Promise<PaymentStatusResult> {\n const raw = await this.get<RawPaymentStatusResult>(`/machine-payments/${paymentId}/status`)\n return this.mapPaymentStatusResult(raw)\n }\n\n /**\n * Get the agent identity tied to this API key.\n */\n async getAgent(): Promise<HavenAgent> {\n // #1348: coalesce CONCURRENT reads into one HTTP GET — the guided\n // purchase flow legitimately wants the agent in two overlapping places\n // (the caller's preflight and the quote leg's x402-wallet resolution).\n // This is in-flight dedupe only, never a cache: the promise is cleared\n // the moment it settles, so sequential calls stay fresh reads and a\n // delegate rotation is picked up exactly as before.\n if (this.agentInFlight) return this.agentInFlight\n const request = this.fetchAgent()\n this.agentInFlight = request\n request.finally(() => {\n this.agentInFlight = null\n }).catch(() => {})\n return request\n }\n\n private agentInFlight: Promise<HavenAgent> | null = null\n\n private async fetchAgent(): Promise<HavenAgent> {\n const raw = await this.get<RawHavenAgent>('/machine-payments/agent')\n return {\n id: raw.id,\n name: raw.name,\n status: raw.status,\n safeAddress: raw.safe_address,\n delegateAddress: raw.delegate_address,\n chainId: raw.chain_id,\n // Defensive normalization, not trust: the backend contract is exactly\n // 'legacy' | 'delegation' (#1306), but an older/mismatched backend\n // during a rollout window should degrade to the wider legacy bucket\n // rather than propagate an unrecognized string.\n executionRail: raw.execution_rail === 'delegation' ? 'delegation' : 'legacy',\n }\n }\n\n /**\n * One-shot \"am I ready?\" bootstrap: identity + live spend authority + a\n * readiness signal, in a single call. Folds {@link getAgent} and\n * {@link getAllowances} together and derives a {@link HavenAgentReadiness}\n * so an agent can answer \"who am I and can I pay right now\" at session start\n * without two round trips and manual assembly.\n */\n async getAgentSummary(): Promise<HavenAgentSummary> {\n const [agent, allowanceSummary] = await Promise.all([\n this.getAgent(),\n this.getAllowances(),\n ])\n\n const allowances: HavenAgentAllowanceSummary[] = allowanceSummary.allowances.map((a) => {\n // Only format a human amount when we KNOW the token's decimals. Guessing a\n // default (e.g. 6) for an unregistered token would misformat an 18-decimal\n // balance by 12 orders of magnitude and mislead the agent about what it can\n // spend — so for unknown tokens we surface the exact atomic value, flagged.\n const token = resolveTokenFromAddress(a.tokenAddress)\n const remainingDisplay = token\n ? `${formatAtomicAmount(safeBigInt(a.onchain.remaining), token.decimals)} ${a.tokenSymbol}`\n : `${a.onchain.remaining} ${a.tokenSymbol} (atomic; unknown decimals)`\n return {\n tokenSymbol: a.tokenSymbol,\n remainingAtomic: a.onchain.remaining,\n remainingDisplay,\n configuredAmount: a.configuredAmount,\n resetPeriodMin: a.resetPeriodMin,\n isResetPending: a.onchain.isResetPending,\n }\n })\n\n return { ...agent, readiness: deriveReadiness(agent.status, allowances), allowances }\n }\n\n /**\n * Sweep stranded USDC and ETH from the delegate EOA back to the originating Safe.\n *\n * The delegate key held by this client signs and submits the transfer transactions\n * directly — Haven's backend never handles the key or constructs signed txs\n * (CASP/MiCA Red Line #2). Funds always go to the Safe linked to this agent.\n *\n * Requires `chainRpcs` to be set for the agent's chain in `HavenClientConfig`.\n */\n async sweepDelegate(): Promise<SweepResult> {\n if (!this.delegateKey) {\n throw new HavenSigningError('delegateKey is required for sweepDelegate.')\n }\n\n const agent = await this.getAgent()\n const { safeAddress, delegateAddress, chainId } = agent\n\n if (!delegateAddress) {\n throw new HavenApiError('Agent has no delegate address.', 422)\n }\n\n const rpcUrl = this.chainRpcs[chainId]\n if (!rpcUrl) {\n throw new HavenApiError(\n `chainRpcs[${chainId}] must be configured to sweep the delegate wallet.`,\n 422,\n )\n }\n\n const provider = createJsonRpcProvider(rpcUrl)\n const wallet = createWallet(this.delegateKey, provider)\n\n const ERC20_TRANSFER_ABI = ['function balanceOf(address) view returns (uint256)', 'function transfer(address to, uint256 amount) returns (bool)'] as const\n\n const transfers: SweepResult['transfers'] = []\n\n // ── 1. Sweep ERC-20 USDC ────────────────────────────────────────\n const usdcAddress = CHAIN_USDC[chainId]\n if (usdcAddress) {\n const usdcContract = createErc20Contract(usdcAddress, ERC20_TRANSFER_ABI, wallet)\n const usdcBalance: bigint = await usdcContract.balanceOf(delegateAddress)\n if (usdcBalance > 0n) {\n const tx = await usdcContract.transfer(safeAddress, usdcBalance)\n const receipt = await (tx as { wait: (n: number) => Promise<{ hash: string } | null> }).wait(1)\n const txHash: string = (receipt as { hash: string } | null)?.hash ?? (tx as { hash: string }).hash\n transfers.push({\n asset: 'USDC',\n amount: formatAtomicAmount(usdcBalance, 6),\n amountAtomic: usdcBalance.toString(),\n txHash,\n explorerUrl: buildExplorerUrl(chainId, txHash),\n })\n }\n }\n\n // ── 2. Sweep native ETH ─────────────────────────────────────────\n const ethBalance = await provider.getBalance(delegateAddress)\n if (ethBalance > 0n) {\n // Reserve gas for the native transfer. An EIP-1559 (type-2) tx is billed up\n // to maxFeePerGas, not gasPrice, so reserve against that — with a buffer for\n // base-fee drift between estimation and inclusion — or the send reverts with\n // \"insufficient funds for intrinsic transaction cost\".\n const fee = await provider.getFeeData()\n const effectiveGasPrice = fee.maxFeePerGas ?? fee.gasPrice ?? 1_000_000n\n const gasLimit = 21_000n\n const gasCost = effectiveGasPrice * gasLimit * 2n\n const ethToSend = ethBalance > gasCost ? ethBalance - gasCost : 0n\n if (ethToSend > 0n) {\n const tx = await wallet.sendTransaction({ to: safeAddress, value: ethToSend })\n const receipt = await tx.wait(1)\n const txHash: string = receipt?.hash ?? tx.hash\n transfers.push({\n asset: 'ETH',\n amount: formatAtomicAmount(ethToSend, 18),\n amountAtomic: ethToSend.toString(),\n txHash,\n explorerUrl: buildExplorerUrl(chainId, txHash),\n })\n }\n }\n\n return {\n fromAddress: delegateAddress,\n toAddress: safeAddress,\n chainId,\n transfers,\n }\n }\n\n /**\n * Hosted (keyless) split-signer sweep — step 1 of 2.\n *\n * Asks the backend to build a gasless EIP-3009 sweep authorization for the\n * delegate's stranded USDC. Returns `nothing_stranded` when the delegate is\n * empty, otherwise an `authorization` + Haven `expected_auth` to hand to the\n * edge signer's `haven_sign_sweep_delegate`. No key is required on this client.\n */\n async prepareSweep(): Promise<SweepPrepareResponse> {\n return this.post<SweepPrepareResponse>('/machine-payments/sweep/prepare', {})\n }\n\n /**\n * Hosted (keyless) split-signer sweep — step 2 of 2.\n *\n * Relays the delegate-signed authorization. The Haven relayer submits the\n * on-chain `transferWithAuthorization` and pays gas; this client never holds\n * the key.\n */\n async submitSweep(\n authorization: SweepAuthorization,\n signature: string,\n ): Promise<SweepSubmitResponse> {\n return this.post<SweepSubmitResponse>('/machine-payments/sweep/submit', {\n authorization,\n signature,\n })\n }\n\n /**\n * Get configured and on-chain allowances for the authenticated agent.\n */\n async getAllowances(): Promise<HavenAllowanceSummary> {\n const raw = await this.get<RawHavenAllowanceSummary>('/machine-payments/allowances')\n return {\n agentId: raw.agent_id,\n safeAddress: raw.safe_address,\n delegateAddress: raw.delegate_address,\n chainId: raw.chain_id,\n allowances: raw.allowances.map((allowance) => ({\n id: allowance.id,\n tokenAddress: allowance.token_address,\n tokenSymbol: allowance.token_symbol,\n configuredAmount: allowance.configured_amount,\n resetPeriodMin: allowance.reset_period_min,\n onchain: {\n amount: allowance.onchain.amount,\n spent: allowance.onchain.spent,\n remaining: allowance.onchain.remaining,\n effectiveSpent: allowance.onchain.effective_spent,\n resetTimeMin: allowance.onchain.reset_time_min,\n lastResetMin: allowance.onchain.last_reset_min,\n nonce: allowance.onchain.nonce,\n isResetPending: allowance.onchain.is_reset_pending,\n remainingIsFromChain: allowance.onchain.remaining_is_from_chain,\n },\n })),\n }\n }\n\n /**\n * Post-purchase allowance/budget summary for a settled payment (#1310).\n *\n * Reuses the EXACT rail-aware read path {@link getAllowances} / #1306's\n * catalog-purchase preflight `allowance` block use — `GET\n * /machine-payments/allowances`, with delegation-rail values coming from\n * the #1090 `deriveDelegationBudgets`-backed enforcer read, never\n * `agent_allowances` — so this can never disagree with\n * {@link getAllowances} for the same fixture. The settled token is\n * resolved from {@link getPaymentStatus} so callers pass only\n * `paymentId`, never a second haven_get_agent-style round trip.\n *\n * NEVER throws: any failed read (status lookup, agent lookup, or the\n * allowance/budget lookup itself) degrades to `{ allowance: null,\n * warnings: [ALLOWANCE_CHECK_UNAVAILABLE] }` rather than converting a\n * successful settlement into a failure — the on-chain policy remains the\n * actual spend gate regardless of whether this report can be produced.\n *\n * Freshness caveat (#1319): the delegation rail's on-chain enforcer read\n * can silently fall back to the optimistic full period budget without\n * throwing when the RPC read itself fails (#1145's fund-safe design,\n * unchanged here). {@link getAllowances}'s `onchain.remainingIsFromChain`\n * now carries that provenance on the wire, and the #1306 catalog-purchase\n * preflight (`haven_prepare_catalog_purchase`) surfaces it as a warning —\n * this summary does not (yet). `remaining_atomic` here reflects the last\n * successful chain read, not a guaranteed-live one, and callers should not\n * phrase it as guaranteed-fresh.\n */\n async getPostPurchaseAllowanceSummary(\n paymentId: string,\n ): Promise<{\n allowance: PostPurchaseAllowanceSummary | null\n warnings: AgentPaymentWarning[]\n /** Same authenticated payment-state read used to resolve the settled token. */\n payment: PaymentStatusResult | null\n }> {\n const unavailable = (detail: string): {\n allowance: null\n warnings: AgentPaymentWarning[]\n payment: null\n } => ({\n payment: null,\n allowance: null,\n warnings: [\n {\n code: AgentPaymentWarningCode.AllowanceCheckUnavailable,\n message:\n `Could not read the post-purchase allowance/budget for payment ${paymentId} (${detail}). ` +\n 'The payment itself succeeded — the on-chain policy remains the actual spend gate; this ' +\n 'only affects the remaining-budget figure reported here.',\n },\n ],\n })\n // #1320 review: all three reads in ONE parallel leg. Keep a successfully\n // read payment state even when a best-effort allowance read fails: it is\n // authoritative reporting data in its own right.\n const [statusResult, agentResult, allowanceResult] = await Promise.allSettled([\n this.getPaymentStatus(paymentId),\n this.getAgent(),\n this.getAllowances(),\n ])\n if (statusResult.status === 'rejected') {\n return unavailable(statusResult.reason instanceof Error ? statusResult.reason.message : String(statusResult.reason))\n }\n const status = statusResult.value\n if (agentResult.status === 'rejected') {\n return { ...unavailable(agentResult.reason instanceof Error ? agentResult.reason.message : String(agentResult.reason)), payment: status }\n }\n if (allowanceResult.status === 'rejected') {\n return { ...unavailable(allowanceResult.reason instanceof Error ? allowanceResult.reason.message : String(allowanceResult.reason)), payment: status }\n }\n try {\n const tokenAddress = status.asset ?? status.x402?.asset ?? null\n if (!tokenAddress) {\n return { ...unavailable('the settled payment does not carry a resolvable token address'), payment: status }\n }\n const rail = agentResult.value.executionRail\n const source = rail === 'delegation' ? 'active_delegations' : 'allowance_module'\n const match = allowanceResult.value.allowances.find(\n (a) => a.tokenAddress.toLowerCase() === tokenAddress.toLowerCase(),\n )\n if (!match) {\n // #1320 review: a missing row is UNKNOWN, not zero — an unexpected\n // address, rail mismatch, or read race must not report a confident\n // \"$0 remaining\" to the user.\n return { ...unavailable('no allowance/budget row matches the settled token'), payment: status }\n }\n // Same \"only format when decimals are known\" discipline as\n // getAgentSummary() above — an unregistered token surfaces the exact\n // atomic value rather than a misformatted guess.\n const token = resolveTokenFromAddress(match.tokenAddress)\n const remainingDisplay = token\n ? `${formatAtomicAmount(safeBigInt(match.onchain.remaining), token.decimals)} ${match.tokenSymbol}`\n : undefined\n return {\n payment: status,\n allowance: {\n rail,\n remaining_atomic: match.onchain.remaining,\n ...(remainingDisplay ? { remaining_display: remainingDisplay } : {}),\n token_symbol: match.tokenSymbol,\n token_address: match.tokenAddress,\n reset_period: match.resetPeriodMin,\n source,\n },\n warnings: [],\n }\n } catch (err) {\n return unavailable(err instanceof Error ? err.message : String(err))\n }\n }\n\n /**\n * `haven_get_payment_status` convenience: fetch status and, for a\n * genuinely SETTLED x402 payment, attach the same post-purchase\n * allowance/budget summary a settle response carries.\n *\n * #1310/#1311 parity: this is the ONE home for logic that was duplicated\n * verbatim in `packages/mcp-server/src/tools.ts` and `packages/mcp/src/tools.ts`\n * (both hosted and local `haven_get_payment_status` handlers) — extracted\n * here because both packages already depend on `@haven_ai/sdk` and call\n * methods on a `HavenClient` instance, so this needed no new dependency\n * edge. `funded_but_unsettled` is deliberately excluded: that phase means\n * the merchant did NOT accept the retry. Every other phase/rail returns\n * the status untouched.\n */\n async getPaymentStatusWithPostPurchaseAllowance(paymentId: string): Promise<\n PaymentStatusResult & {\n allowance?: PostPurchaseAllowanceSummary | null\n warnings?: AgentPaymentWarning[]\n }\n > {\n const status = await this.getPaymentStatus(paymentId)\n if (status.rail === AgentPaymentRail.X402 && status.phase === AgentPaymentPhase.PaymentConfirmed) {\n const { allowance, warnings } = await this.getPostPurchaseAllowanceSummary(paymentId)\n return { ...status, allowance, ...(warnings.length > 0 ? { warnings } : {}) }\n }\n return status\n }\n\n /**\n * Discover payable services from Haven's curated merchant catalog.\n *\n * Read-only: returns catalog entries (price, rail, protocol) so an agent\n * can choose a service and pay it with the regular payment tools in the\n * same session. Never creates payments or signatures.\n */\n async discoverTools(\n options: { category?: string; search?: string; rail?: 'x402' | 'mpp' } = {},\n ): Promise<HavenCatalogEntry[]> {\n const params = new URLSearchParams()\n if (options.category) params.set('category', options.category)\n if (options.search !== undefined) params.set('search', options.search)\n if (options.rail) params.set('rail', options.rail)\n const query = params.size > 0 ? `?${params.toString()}` : ''\n const raw = await this.get<{ entries: RawCatalogEntry[] }>(`/catalog${query}`)\n return raw.entries.map(mapCatalogEntry)\n }\n\n /**\n * Fetch one curated catalog entry by id (#1306).\n *\n * Chain-scoped for free by the backend's SQL when the client is\n * agent-authenticated (#1299): an unknown id and an id curated for a\n * DIFFERENT chain than this agent's both 404 identically — this method does\n * not (and must not) re-filter by chain in JS. Read-only, like\n * {@link discoverTools}.\n */\n async getCatalogEntry(id: string): Promise<HavenCatalogEntry> {\n const raw = await this.get<RawCatalogEntry>(`/catalog/${encodeURIComponent(id)}`)\n return mapCatalogEntry(raw)\n }\n\n /**\n * List recent machine-payment receipts/evidence for bookkeeping.\n */\n async listReceipts(options: { limit?: number } = {}): Promise<HavenPaymentReceipt[]> {\n const query = options.limit ? `?limit=${encodeURIComponent(String(options.limit))}` : ''\n const raw = await this.get<RawHavenPaymentReceiptsResponse>(`/machine-payments/receipts${query}`)\n return raw.receipts.map((receipt) => this.mapPaymentReceipt(receipt))\n }\n\n /**\n * Fetch the verifiable receipt bundle for a settled payment and verify it\n * locally. The server's own verification is ignored — the receipt is verified\n * here (independently of Haven) by recovering the signer from the\n * authorisation, so the result is trustworthy even if the backend lied.\n */\n async getReceipt(\n paymentId: string,\n ): Promise<{ receipt: PaymentReceipt; verification: ReceiptVerification }> {\n const { receipt } = await this.get<{ receipt: PaymentReceipt }>(\n `/payments/${paymentId}/receipt`,\n )\n return { receipt, verification: verifyPaymentReceipt(receipt) }\n }\n\n /**\n * Rehydrate the x402 resume-state bundle for a payment id (#1328: the MPP\n * resume-state variant retired along with the rest of the mpp_demo surface).\n *\n * The server returns stored protocol context only. The client still signs the\n * merchant proof locally when resumeX402Payment() runs.\n */\n async getResumeState(paymentId: string): Promise<PaymentResumeState> {\n return this.get<PaymentResumeState>(`/payments/${paymentId}/resume_state`)\n }\n\n /**\n * Poll until a payment reaches a terminal status (confirmed, failed, expired).\n */\n async waitForConfirmation(paymentId: string): Promise<PaymentResult> {\n const deadline = Date.now() + this.confirmationTimeout\n\n while (Date.now() < deadline) {\n const result = await this.getPayment(paymentId)\n\n if (result.status === 'confirmed' || result.status === 'failed' || result.status === 'expired') {\n return result\n }\n\n await sleep(this.pollingInterval)\n }\n\n throw new HavenTimeoutError(paymentId)\n }\n\n // ── x402 Protocol Support ────────────────────────────────────────\n\n /**\n * Authorize an x402 payment.\n *\n * Takes the parsed PaymentRequired from a 402 response, selects a compatible\n * option, funds the delegate wallet through Haven, and returns the standard\n * x402 header that the merchant can verify and settle.\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async authorizeX402(\n paymentRequired: X402PaymentRequired,\n options: X402AuthorizationOptions = {},\n ): Promise<X402Receipt> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'delegateKey is required for x402 payments. Pass it in the HavenClient config.',\n )\n }\n if (!this.delegateAddress) {\n throw new HavenSigningError('delegateAddress could not be derived from delegateKey.')\n }\n\n // 1. Select best payment option\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n if (!option) {\n throw new HavenApiError(\n 'No compatible payment option found in x402 requirements. ' +\n 'Haven supports standard x402 exact payments on Base USDC.',\n 400,\n )\n }\n\n const idempotencyKey = options.idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option)\n const cached = this.x402ReceiptCache.get(idempotencyKey)\n if (cached && cached.expiresAt > Date.now()) return cached.receipt\n\n const inFlight = this.inFlightX402.get(idempotencyKey)\n if (inFlight) return inFlight\n\n const promise = this.authorizeStandardX402(paymentRequired, option, idempotencyKey)\n this.inFlightX402.set(idempotencyKey, promise)\n\n try {\n return await promise\n } catch (err) {\n this.attachResumeState(err, {\n rail: 'x402',\n paymentRequired,\n accepted: option,\n idempotencyKey,\n })\n throw err\n } finally {\n this.inFlightX402.delete(idempotencyKey)\n }\n }\n\n /**\n * Probe a paid endpoint and return its x402 quote without creating a Haven\n * payment or approval request.\n */\n async quoteX402(\n url: string,\n init?: RequestInit,\n options: X402AuthorizationOptions = {},\n ): Promise<X402Quote> {\n const initialInit = this.withX402Wallet(init, this.x402PayerAddress())\n const request = this.snapshotX402Request(url, initialInit)\n const response = await this.merchantFetch(url, initialInit)\n\n if (response.status !== 402) {\n // #1300: typed, so consumers key on the class instead of message text.\n throw new X402UnexpectedStatusError(\n `Expected an x402 quote response with HTTP 402, got HTTP ${response.status}.`,\n response.status || 400,\n )\n }\n\n if (response.headers.get('MACHINE-PAYMENT-CHALLENGE')) {\n throw new HavenApiError('quoteX402 only supports standard x402 Payment Required responses.', 400)\n }\n\n const paymentRequired = await parsePaymentRequiredResponse(response)\n const mcpTransport = await this.detectX402McpTransport(url, paymentRequired, response)\n return this.buildX402Quote(paymentRequired, request, options.idempotencyKey, mcpTransport)\n }\n\n /**\n * Probe an MCP tool for its x402 quote without creating a payment.\n *\n * Unlike the generic {@link quoteX402} helper, this completes the\n * Streamable-HTTP MCP lifecycle before sending the unpaid `tools/call`.\n * Hosted MCP uses this path while remaining keyless: it resolves only the\n * agent's public delegate address for `x402-wallet`; signing remains local.\n * It refuses before the quote when the merchant does not establish a session;\n * callers that need a plain x402 endpoint must use {@link quoteX402}.\n */\n async quoteMcpX402(\n url: string,\n init?: RequestInit,\n options: X402AuthorizationOptions = {},\n ): Promise<X402Quote> {\n const wallet = await this.resolveX402WalletForMerchantCall()\n const sessionId = await this.mcpInitialize(url, init, wallet)\n if (!sessionId) {\n throw new HavenApiError(\n 'The merchant did not establish an MCP session before the x402 quote. No payment was created.',\n 502,\n { mcpSessionNotEstablished: true },\n )\n }\n\n let requestInit = this.withX402Wallet(init, wallet)\n requestInit = this.withMcpHeaders(requestInit, sessionId)\n\n const quote = await this.quoteX402(url, requestInit, options)\n // This dedicated helper established an MCP session even when the endpoint\n // uses a custom path and does not advertise Bazaar metadata. Preserve that\n // fact for the later, fresh session used by the paid retry.\n return {\n ...quote,\n mcpTransport: quote.mcpTransport ?? { handshakeRequired: true, source: 'path' },\n }\n }\n\n /**\n * Pay a previously inspected x402 quote and retry the exact captured request.\n */\n async payX402Quote(\n quote: X402Quote,\n options: X402AuthorizationOptions = {},\n ): Promise<Response> {\n const idempotencyKey = options.idempotencyKey ?? quote.idempotencyKey\n\n try {\n const receipt = await this.authorizeX402(quote.paymentRequired, { idempotencyKey })\n return this.retryX402Request(\n quote.request.url,\n this.requestInitFromSnapshot(quote.request),\n quote.paymentRequired,\n receipt,\n )\n } catch (err) {\n this.attachResumeState(err, {\n rail: 'x402',\n paymentRequired: quote.paymentRequired,\n accepted: quote.accepted,\n idempotencyKey,\n request: quote.request,\n })\n throw err\n }\n }\n\n private async authorizeStandardX402(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n idempotencyKey: string,\n ): Promise<X402Receipt> {\n // 2. Standard x402 settles from an EOA, so the SDK uses the agent-owned\n // delegate EOA for the merchant-facing EIP-3009 authorization. Haven does\n // not control this EOA or its private key.\n //\n // The only automated funding path is a separate Safe AllowanceModule\n // transfer signed by the agent key and constrained by the user's on-chain\n // allowance. Haven's backend relays that signed top-up; it is not the source\n // of payment authority.\n // Sign before funding so retries reuse one EIP-3009 nonce. If funding fails,\n // the unused authorization simply expires via validBefore.\n const paymentHeader = await this.createStandardX402Header(paymentRequired, option)\n const raw = await this.post<RawX402AuthorizeResponse>('/x402', {\n url: paymentRequired.resource.url,\n payTo: this.delegateAddress,\n merchantPayTo: option.payTo,\n amount: x402AuthorizationAmount(option),\n asset: option.asset,\n network: option.network,\n description: paymentRequired.resource.description,\n idempotencyKey,\n // #1360: same explicit funding-leg declaration as createX402Intent —\n // this local-key path derives payTo from the key (never stale), but the\n // declaration keeps both writers of the 3009 shape loud-by-default.\n settlementScheme: 'eip3009',\n })\n\n // If the backend already executed (shouldn't happen without sig), return\n if (raw.success && raw.tx_hash) {\n const receipt = this.mapX402ReceiptFromAuthorization(paymentRequired, option, paymentHeader, raw)\n this.cacheX402Receipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n const state = this.paymentStateFromRaw('x402 payment', raw)\n if (state?.nextAction === AgentPaymentNextAction.RetryOriginalX402Request) {\n const receipt = this.mapX402ReceiptFromStatus(paymentRequired, option, paymentHeader, state)\n this.cacheX402Receipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n this.throwIfNonSignableAuthorizationState('x402 payment', raw)\n\n // 3. Sign the hash\n if (!raw.sign_data?.hash) {\n throw new HavenApiError('No sign_hash returned from x402/authorize', 500, raw)\n }\n const sig = await this.signForData(raw.sign_data)\n\n // 4. Submit signature (reuse existing payments/:id/sign endpoint)\n const execResult = await this.post<RawSignResponse>(\n `/payments/${raw.payment_id}/sign`,\n { signature: sig },\n )\n\n if (execResult.status !== 'confirmed') {\n this.throwPaymentStateError('x402 payment', execResult)\n }\n\n // Wait for ≥1 on-chain confirmation before retrying the merchant so the\n // merchant's balanceOf(delegate) check sees the funded balance.\n await this.waitForFundingTx(\n execResult.tx_hash,\n execResult.chain_id ?? chainIdFromNetwork(option.network),\n )\n\n const receipt = this.mapX402ReceiptFromAuthorization(paymentRequired, option, paymentHeader, raw, execResult)\n this.cacheX402Receipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n async resumeAuthorizedX402(input: ResumeAuthorizedX402Input): Promise<X402Receipt> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'delegateKey is required for x402 payments. Pass it in the HavenClient config.',\n )\n }\n if (!this.delegateAddress) {\n throw new HavenSigningError('delegateAddress could not be derived from delegateKey.')\n }\n\n const option = selectStandardPaymentOption(input.paymentRequired.accepts)\n if (!option) {\n throw new HavenApiError(\n 'No compatible payment option found in x402 requirements. ' +\n 'Haven supports standard x402 exact payments on Base USDC.',\n 400,\n )\n }\n\n const idempotencyKey = input.idempotencyKey ?? buildX402IdempotencyKey(input.paymentRequired, option)\n const cached = this.x402ReceiptCache.get(idempotencyKey)\n if (cached && cached.expiresAt > Date.now()) return cached.receipt\n\n const status = await this.getPaymentStatus(input.paymentId)\n this.assertCanResumeX402(status, input.paymentRequired, option)\n\n const paymentHeader = await this.createStandardX402Header(input.paymentRequired, option)\n const receipt = this.mapX402ReceiptFromStatus(input.paymentRequired, option, paymentHeader, status)\n this.cacheX402Receipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n async resumeX402Payment(input: ResumeX402PaymentInput | X402ResumeState): Promise<Response> {\n const inputInit = 'init' in input ? input.init : undefined\n const initialInit = this.withX402Wallet(\n inputInit ?? (input.request ? this.requestInitFromSnapshot(input.request) : undefined),\n this.x402PayerAddress(),\n )\n let paymentRequired = input.paymentRequired\n const url = input.url ?? input.request?.url\n\n if (!paymentRequired) {\n if (!url) {\n throw new HavenApiError('x402 resume requires the original URL or a captured request snapshot.', 400)\n }\n const response = await this.merchantFetch(url, initialInit)\n if (response.status !== 402) {\n throw new HavenApiError('Expected the original x402 request to return HTTP 402 before resuming.', 400)\n }\n paymentRequired = await parsePaymentRequiredResponse(response)\n }\n\n const receipt = await this.resumeAuthorizedX402({\n paymentId: input.paymentId,\n paymentRequired,\n idempotencyKey: input.idempotencyKey,\n })\n\n return this.retryX402Request(url ?? paymentRequired.resource.url, initialInit, paymentRequired, receipt)\n }\n\n /**\n * Fetch wrapper that automatically handles HTTP 402 responses.\n *\n * Works like the standard `fetch()` but intercepts 402 responses,\n * pays via x402 through Haven, and retries the request.\n *\n * ```ts\n * const response = await haven.fetch('https://paid-api.com/data')\n * const data = await response.json()\n * ```\n *\n * **MCP-over-x402 auto-handshake (issue #315):** when the endpoint is\n * MCP-shaped — the URL path ends in `/mcp`, or the 402 body carries a\n * Coinbase Bazaar `extensions.bazaar` block — the SDK runs the MCP\n * `initialize` handshake, threads the resulting `mcp-session-id`,\n * `Accept: application/json, text/event-stream`, and `x402-wallet` headers\n * through every request, and collapses SSE responses to the JSON-RPC\n * `result`. The caller just passes `(url, { body })` and never sees the\n * protocol plumbing. A non-MCP server (handshake error / no session id)\n * falls back to standard x402 behaviour.\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async fetch(\n url: string,\n init?: RequestInit,\n options: X402AuthorizationOptions = {},\n ): Promise<Response> {\n // Signal A: a `/mcp` path is the MCP-over-HTTP convention, so handshake\n // up front — before the probe — so the session id rides on the probe and\n // the retry alike. A non-MCP server yields `undefined` and we fall back.\n let mcpSessionId: string | undefined\n if (isMcpUrl(url)) {\n mcpSessionId = await this.mcpInitialize(url, init)\n }\n\n let requestInit = this.withX402Wallet(init, this.x402PayerAddress())\n if (mcpSessionId) requestInit = this.withMcpHeaders(requestInit, mcpSessionId)\n\n // 1. Make the original request\n const response = await this.merchantFetch(url, requestInit)\n\n // 2. Not a 402 — return as-is (collapsing SSE for MCP sessions)\n if (response.status !== 402) {\n return mcpSessionId ? this.surfaceMcpResult(response) : response\n }\n\n // #1328: the legacy MACHINE-PAYMENT-CHALLENGE / mpp_demo auto-handling is\n // retired — a 402 that isn't standard x402 (including a stray\n // MACHINE-PAYMENT-CHALLENGE header from a pre-retirement caller) is\n // returned to the agent unmodified rather than auto-paid.\n\n // 3. Parse x402 payment requirements\n let paymentRequired: X402PaymentRequired\n try {\n paymentRequired = await parsePaymentRequiredResponse(response)\n } catch {\n // Not a standard x402 402 response — return it unchanged.\n return response\n }\n\n // Signal B: a Bazaar `extensions.bazaar` block marks an MCP-discoverable\n // resource even without the `/mcp` convention. Handshake now (if we\n // haven't already) so the paid retry carries the session id.\n if (!mcpSessionId && (await responseHasBazaarExtension(response))) {\n mcpSessionId = await this.mcpInitialize(url, init)\n if (mcpSessionId) requestInit = this.withMcpHeaders(requestInit, mcpSessionId)\n }\n\n // 4. Pay through Haven\n const request = this.snapshotX402Request(url, requestInit)\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n const idempotencyKey = options.idempotencyKey ?? (option ? buildX402IdempotencyKey(paymentRequired, option) : undefined)\n let receipt: X402Receipt\n try {\n receipt = await this.authorizeX402(paymentRequired, options)\n } catch (err) {\n if (option && idempotencyKey) {\n this.attachResumeState(err, {\n rail: 'x402',\n paymentRequired,\n accepted: option,\n idempotencyKey,\n request,\n })\n }\n throw err\n }\n const retryResponse = await this.retryX402Request(url, requestInit, paymentRequired, receipt)\n return mcpSessionId ? this.surfaceMcpResult(retryResponse) : retryResponse\n }\n\n // ── MCP-over-x402 transport helpers (issue #315) ─────────────────\n\n /**\n * Run the MCP `initialize` handshake against a Streamable-HTTP endpoint and\n * return the `mcp-session-id` the server assigns.\n *\n * Returns `undefined` whenever the endpoint is not actually an MCP server —\n * a transport/HTTP error, a missing session id, or a JSON-RPC error in the\n * handshake response — so the caller can fall back to plain x402.\n */\n private async mcpInitialize(\n url: string,\n init?: RequestInit,\n wallet = this.x402PayerAddress(),\n ): Promise<string | undefined> {\n try {\n const headers = new Headers(init?.headers)\n headers.set('Content-Type', 'application/json')\n headers.set('Accept', MCP_ACCEPT)\n if (wallet && !headers.has('x402-wallet')) headers.set('x402-wallet', wallet)\n\n const response = await this.merchantFetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: ++this.mcpRequestId,\n method: 'initialize',\n params: {\n protocolVersion: MCP_PROTOCOL_VERSION,\n capabilities: {},\n clientInfo: MCP_CLIENT_INFO,\n },\n }),\n })\n\n if (!response.ok) return undefined\n\n const sessionId = response.headers.get('mcp-session-id')\n if (!sessionId) return undefined\n\n // A JSON-RPC error means the server spoke MCP but rejected the\n // handshake — treat it as non-MCP and fall back to standard x402.\n const message = await this.readMcpMessage(response)\n if (message && 'error' in message) return undefined\n\n // Per the MCP lifecycle, the client confirms initialization with a\n // `notifications/initialized` notification. Servers that gate tool\n // calls on it would otherwise reject every subsequent request.\n await this.mcpNotifyInitialized(url, init, sessionId, wallet)\n\n return sessionId\n } catch {\n return undefined\n }\n }\n\n /**\n * Send the MCP `notifications/initialized` notification that completes the\n * lifecycle handshake. Best-effort: the session is already established, so a\n * failed notification must not abort the payment.\n */\n private async mcpNotifyInitialized(\n url: string,\n init: RequestInit | undefined,\n sessionId: string,\n wallet = this.x402PayerAddress(),\n ): Promise<void> {\n try {\n const headers = new Headers(init?.headers)\n headers.set('Content-Type', 'application/json')\n headers.set('Accept', MCP_ACCEPT)\n headers.set('mcp-session-id', sessionId)\n if (wallet && !headers.has('x402-wallet')) headers.set('x402-wallet', wallet)\n\n // #1300 review: best-effort notification, discarded either way — do not\n // give it the settlement-sized budget.\n await this.merchantFetch(\n url,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }),\n },\n NOTIFY_TIMEOUT,\n )\n } catch {\n // Best-effort — see doc comment.\n }\n }\n\n /** Read a single JSON-RPC message from an MCP response (JSON or SSE body). */\n private async readMcpMessage(response: Response): Promise<Record<string, unknown> | undefined> {\n let text: string\n try {\n text = await response.clone().text()\n } catch {\n return undefined\n }\n\n if ((response.headers.get('content-type') ?? '').includes('text/event-stream')) {\n return selectJsonRpcResult(parseSseJsonRpcMessages(text))\n }\n\n try {\n return JSON.parse(text) as Record<string, unknown>\n } catch {\n return undefined\n }\n }\n\n /** Add the MCP transport headers (session id + SSE Accept) to a request. */\n private withMcpHeaders(init: RequestInit | undefined, sessionId: string): RequestInit {\n const headers = new Headers(init?.headers)\n headers.set('mcp-session-id', sessionId)\n headers.set('Accept', MCP_ACCEPT)\n return { ...init, headers }\n }\n\n /**\n * Collapse an MCP SSE response into a plain JSON response carrying the\n * JSON-RPC `result`, so callers of `fetch()` never see raw SSE framing.\n * Non-SSE responses pass through untouched.\n */\n private async surfaceMcpResult(response: Response): Promise<Response> {\n if (!(response.headers.get('content-type') ?? '').includes('text/event-stream')) {\n return response\n }\n\n let text: string\n try {\n text = await response.clone().text()\n } catch {\n return response\n }\n\n const message = selectJsonRpcResult(parseSseJsonRpcMessages(text))\n if (!message) return response\n\n const body = 'result' in message ? message.result : message\n const headers = new Headers(response.headers)\n headers.set('content-type', 'application/json')\n headers.delete('content-length')\n // Don't leak the transport session id back to the caller — the whole\n // point of the auto-handshake is that the agent never sees MCP plumbing.\n headers.delete('mcp-session-id')\n\n return new Response(JSON.stringify(body), {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n }\n\n private async retryX402Request(\n url: string,\n initialInit: RequestInit | undefined,\n paymentRequired: X402PaymentRequired,\n receipt: X402Receipt,\n ): Promise<Response> {\n if (!receipt.accepted) {\n throw new HavenApiError('No accepted x402 option was recorded for payment retry', 500)\n }\n if (!receipt.paymentHeader) {\n throw new HavenApiError('No x402 payment header was returned for payment retry', 500)\n }\n\n // 5. Retry with a merchant-verifiable x402 EIP-3009 payment header.\n const retryHeaders = new Headers(initialInit?.headers)\n retryHeaders.set('X-PAYMENT', receipt.paymentHeader)\n\n const retryResponse = await this.merchantFetch(url, {\n ...initialInit,\n headers: retryHeaders,\n })\n\n if (!retryResponse.ok) {\n const merchant = await captureMerchantResponse(retryResponse)\n await this.recordMerchantRetryRejected({\n rail: 'x402',\n paymentId: receipt.paymentId,\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n merchant,\n details: {\n merchant_to: receipt.merchantTo,\n delegate_to: receipt.to,\n },\n })\n\n throw new HavenApiError(\n 'x402 retry failed after Haven funded the delegate wallet; reconciliation may be required.',\n merchant.merchant_status,\n {\n marker: 'x402_retry_rejected_after_funding',\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n resource_url: receipt.resourceUrl,\n merchant_to: receipt.merchantTo,\n delegate_to: receipt.to,\n ...merchant,\n },\n )\n }\n\n const merchantSettlement = parseMerchantSettlement(retryResponse.headers.get('PAYMENT-RESPONSE'))\n if (receipt.merchant && merchantSettlement.settlementTxHash) {\n receipt.merchant.settlementTxHash = merchantSettlement.settlementTxHash\n receipt.merchant.settlementExplorerUrl = buildExplorerUrl(\n receipt.chainId,\n merchantSettlement.settlementTxHash,\n )\n }\n\n await this.reportMachinePaymentEvidence({\n paymentId: receipt.paymentId,\n rail: 'x402',\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n merchantStatus: retryResponse.status,\n challengePayload: paymentRequired as unknown as Record<string, unknown>,\n selectedPayment: receipt.accepted as unknown as Record<string, unknown>,\n paymentProofHeaderName: 'X-PAYMENT',\n paymentProofHeader: receipt.paymentHeader,\n protocolReceiptHeaderName: 'PAYMENT-RESPONSE',\n protocolReceiptHeader: retryResponse.headers.get('PAYMENT-RESPONSE') ?? undefined,\n })\n\n await this.reportMerchantReceipt(receipt.paymentId, retryResponse)\n\n return retryResponse\n }\n\n /**\n * #956: capture the merchant's OWN receipt when the paid response carries\n * one, and report it to Haven so the reporting feed can attach it next to\n * the Haven-generated payment evidence (#498). Two supported signals on the\n * paid response:\n *\n * x-receipt-json: base64-encoded JSON receipt document (inline)\n * x-receipt-url: https URL to the receipt document (reference)\n *\n * Strictly best-effort: absence is the normal case, and no failure here may\n * ever affect the completed payment — the response is already paid for.\n */\n private async reportMerchantReceipt(paymentId: string, response: Response): Promise<void> {\n try {\n const inlineB64 = response.headers.get('x-receipt-json')\n const url = response.headers.get('x-receipt-url')\n if (!inlineB64 && !url) return\n\n let body: Record<string, unknown> | null = null\n if (inlineB64) {\n // Mirror the backend's 64KB decoded cap exactly (base64 inflates 4/3)\n // — don't ship what the server will reject.\n if (inlineB64.length > Math.ceil((64 * 1024 * 4) / 3)) return\n const decoded = JSON.parse(Buffer.from(inlineB64, 'base64').toString('utf8')) as unknown\n if (decoded && typeof decoded === 'object') body = { json: decoded }\n } else if (url && url.startsWith('https://') && url.length <= 2048) {\n body = { url }\n }\n if (!body) return\n\n await this.post(`/machine-payments/${paymentId}/merchant-receipt`, body)\n } catch {\n // Best-effort by contract — a malformed header or a capture-endpoint\n // hiccup never surfaces to the caller of a successful payment.\n }\n }\n\n /**\n * Deliver an already-signed x402 payment header to the merchant and return\n * the merchant's response. Used by the hosted MCP server to complete the\n * merchant leg of an MCP tool payment after the edge signer has built the\n * `X-PAYMENT` header.\n *\n * Custody note: this never needs the delegate key. It relays a signed,\n * amount/merchant/nonce-bound EIP-3009 authorization the edge signer already\n * produced — the hosted server cannot mint or reuse signing authority.\n *\n * When the URL is MCP-shaped (`/mcp` path) or the quote-time transport context\n * says the merchant was Bazaar-discoverable, runs a fresh `initialize`\n * handshake (the quote-time session is gone once funding confirms; the x402\n * challenge is stateless w.r.t. the MCP session, so a fresh session is\n * accepted), threads the session + wallet headers, sets `X-PAYMENT`, and\n * collapses an SSE JSON-RPC response to its `result`.\n */\n /**\n * Wait for a payment's Safe→delegate funding tx to reach ≥1 on-chain\n * confirmation. The hosted x402 completion path MUST call this after funding\n * and before delivering the X-PAYMENT header, so the merchant's\n * balanceOf(delegate) / transferWithAuthorization verification sees the funded\n * balance — otherwise it rejects with \"Payment verification failed\". The\n * SDK's local path already does this (see authorizeStandardX402); the hosted\n * split flow regressed when the 5→3 collapse removed the incidental\n * inter-call latency that used to mask it. No-op when the funding tx hash or\n * a chain RPC (chainRpcs[chainId]) is unavailable.\n */\n async ensureFundingConfirmed(paymentId: string, fundingTxHash?: string): Promise<void> {\n const status = await this.getPaymentStatus(paymentId)\n await this.waitForFundingTx(fundingTxHash ?? status.txHash ?? undefined, status.chainId)\n }\n\n async completeX402MerchantCall(input: {\n url: string\n init?: RequestInit\n paymentId: string\n paymentHeader: string\n mcpTransport?: X402McpTransport\n }): Promise<{ status: number; ok: boolean; body: unknown; settlementTxHash?: string }> {\n const evidenceContext = await this.resolveX402MerchantCompletionContext({\n paymentId: input.paymentId,\n url: input.url,\n })\n const shouldHandshakeMcp =\n isMcpUrl(input.url) ||\n input.mcpTransport?.handshakeRequired === true\n const x402Wallet = shouldHandshakeMcp ? await this.resolveX402WalletForMerchantCall() : this.x402PayerAddress()\n let mcpSessionId: string | undefined\n if (shouldHandshakeMcp) {\n mcpSessionId = await this.mcpInitialize(input.url, input.init, x402Wallet)\n }\n\n let requestInit: RequestInit = this.withX402Wallet(input.init, x402Wallet) ?? {}\n if (mcpSessionId) requestInit = this.withMcpHeaders(requestInit, mcpSessionId)\n const headers = new Headers(requestInit.headers)\n headers.set('X-PAYMENT', input.paymentHeader)\n requestInit = { ...requestInit, headers }\n\n const response = await this.merchantFetch(input.url, requestInit)\n const surfaced = mcpSessionId ? await this.surfaceMcpResult(response) : response\n const protocolReceiptHeader = surfaced.headers.get('PAYMENT-RESPONSE') ?? undefined\n const settlement = parseMerchantSettlement(protocolReceiptHeader ?? null)\n\n const text = await surfaced.text()\n let body: unknown\n try {\n body = text ? JSON.parse(text) : null\n } catch {\n body = text\n }\n\n if (!surfaced.ok) {\n await this.recordMerchantRetryRejected({\n rail: 'x402',\n paymentId: evidenceContext.paymentId,\n txHash: evidenceContext.txHash,\n resourceUrl: evidenceContext.resourceUrl,\n merchant: {\n merchant_status: surfaced.status,\n merchant_status_text: surfaced.statusText,\n merchant_headers: Object.fromEntries(surfaced.headers.entries()),\n merchant_body: text,\n },\n details: {\n merchant_to: evidenceContext.merchantAddress,\n },\n })\n } else {\n await this.reportMachinePaymentEvidence({\n paymentId: evidenceContext.paymentId,\n rail: 'x402',\n txHash: evidenceContext.txHash,\n resourceUrl: evidenceContext.resourceUrl,\n merchantStatus: surfaced.status,\n paymentProofHeaderName: 'X-PAYMENT',\n paymentProofHeader: input.paymentHeader,\n protocolReceiptHeaderName: protocolReceiptHeader ? 'PAYMENT-RESPONSE' : undefined,\n protocolReceiptHeader,\n })\n // #956: the hosted-MCP completion path is a successful paid retry too —\n // capture the merchant's receipt exactly like the local flow does.\n await this.reportMerchantReceipt(evidenceContext.paymentId, surfaced)\n }\n\n return {\n status: surfaced.status,\n ok: surfaced.ok,\n body,\n settlementTxHash: settlement.settlementTxHash ?? undefined,\n }\n }\n\n /**\n * GET /x402/:id/merchant-call-context — the settle-leg twin of #1263's\n * sign-context fetch (#1307). Re-serves the stored merchant MCP-tool call\n * context (merchant_url, tool_name, arguments, mcp_transport) recorded at\n * quote time, so `haven_settle_mcp_tool` / `haven_complete_mcp_tool` can\n * omit those fields and let Haven rehydrate them by payment_id instead of\n * the caller re-threading them. Throws `HavenApiError` (404 unknown/foreign\n * payment_id, 409 no stored context, 410 expired) — the caller decides the\n * fallback (re-send the full context explicitly).\n */\n async getX402MerchantCallContext(paymentId: string): Promise<X402MerchantCallContext> {\n const raw = await this.get<RawX402MerchantCallContext>(\n `/x402/${paymentId}/merchant-call-context`,\n )\n return {\n paymentId: raw.payment_id,\n merchantUrl: raw.merchant_url,\n toolName: raw.tool_name,\n arguments: raw.arguments ?? {},\n ...(raw.mcp_transport\n ? {\n mcpTransport: {\n handshakeRequired: raw.mcp_transport.handshake_required,\n source: raw.mcp_transport.source,\n },\n }\n : {}),\n }\n }\n\n private async resolveX402MerchantCompletionContext(input: {\n paymentId: string\n url: string\n }): Promise<{\n paymentId: string\n txHash: string\n resourceUrl: string\n merchantAddress: string | null\n }> {\n const status = await this.getPaymentStatus(input.paymentId)\n\n if (status.rail !== 'x402') {\n throw new HavenPaymentStateError(\n `Payment ${status.paymentId} is ${status.rail}, not x402.`,\n 409,\n status,\n )\n }\n\n const readyForMerchantCompletion =\n status.nextAction === AgentPaymentNextAction.RetryOriginalX402Request ||\n (\n status.kind === 'payment_intent' &&\n status.status === 'confirmed' &&\n status.phase === AgentPaymentPhase.PaymentConfirmed &&\n status.nextAction === AgentPaymentNextAction.None\n )\n\n if (!readyForMerchantCompletion) {\n throw new HavenPaymentStateError(status.message, PAYMENT_STATE_STATUS_CODES[status.status] ?? 409, status)\n }\n\n if (!status.txHash) {\n throw new HavenApiError(\n `x402 payment ${status.paymentId} is ready for merchant completion but has no Haven transaction hash.`,\n 502,\n status,\n status.paymentId,\n )\n }\n\n const approvedResourceUrl = status.resourceUrl ?? status.x402?.resourceUrl ?? null\n if (approvedResourceUrl && approvedResourceUrl !== input.url) {\n throw new HavenApiError(\n 'x402 merchant completion does not match the approved resource URL.',\n 409,\n { status, url: input.url },\n status.paymentId,\n )\n }\n\n return {\n paymentId: status.paymentId,\n txHash: status.txHash,\n resourceUrl: approvedResourceUrl ?? input.url,\n merchantAddress: status.merchantAddress ?? status.x402?.merchantAddress ?? null,\n }\n }\n\n private async resolveX402WalletForMerchantCall(): Promise<string | undefined> {\n const localWallet = this.x402PayerAddress()\n if (localWallet) return localWallet\n\n try {\n const agent = await this.getAgent()\n return agent.delegateAddress ?? undefined\n } catch {\n return undefined\n }\n }\n\n // #1328: authorizeMachinePayment / authorizeMppDemoPayment / resumeAuthorizedMpp\n // / resumeMppPayment / fetchWithMachinePayment / retryMppRequest (the\n // MACHINE-PAYMENT-CHALLENGE / mpp_demo client surface) are retired — the\n // backend's POST /machine-payments/authorize refuses unconditionally now,\n // and MACHINE-PAYMENT-CHALLENGE was never produced by any other Haven\n // surface. Use the x402 flow (authorizeX402 / fetch / quoteX402 / payX402Quote)\n // for agent-to-merchant payments.\n\n private assertCanResumeX402(\n status: PaymentStatusResult,\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n ): void {\n if (status.rail !== 'x402') {\n throw new HavenPaymentStateError(\n `Payment ${status.paymentId} is ${status.rail}, not x402.`,\n 409,\n status,\n )\n }\n\n if (status.nextAction !== AgentPaymentNextAction.RetryOriginalX402Request) {\n throw new HavenPaymentStateError(status.message, PAYMENT_STATE_STATUS_CODES[status.status] ?? 409, status)\n }\n\n if (!status.txHash) {\n throw new HavenApiError(\n `x402 payment ${status.paymentId} is ready to retry but has no Haven transaction hash.`,\n 502,\n status,\n status.paymentId,\n )\n }\n\n if (status.resourceUrl && status.resourceUrl !== paymentRequired.resource.url) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved resource URL.',\n 409,\n { status, paymentRequired },\n status.paymentId,\n )\n }\n\n if (status.merchantAddress && !sameAddress(status.merchantAddress, option.payTo)) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved merchant.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n\n const optionChainId = chainIdFromNetwork(option.network)\n if (status.chainId && optionChainId && status.chainId !== optionChainId) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved network.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n\n if (status.token && status.token !== 'USDC') {\n throw new HavenApiError(\n 'x402 resume request does not match the approved token.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n\n const approvedAmount = status.amount ? normalizeDecimal(status.amount) : ''\n const requestedAmount = normalizeDecimal(decimalFromUsdcAtomic(x402AuthorizationAmount(option)))\n if (approvedAmount && approvedAmount !== requestedAmount) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved amount.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n }\n\n\n private mapX402ReceiptFromAuthorization(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n paymentHeader: string,\n raw: RawX402AuthorizeResponse,\n execResult?: RawSignResponse,\n ): X402Receipt {\n const txHash = execResult?.tx_hash ?? raw.tx_hash ?? ''\n const chainId = execResult?.chain_id ?? raw.chain_id ?? chainIdFromNetwork(option.network)\n const token = execResult?.token ?? raw.token ?? 'USDC'\n const amount = execResult?.amount ?? raw.amount ?? decimalFromUsdcAtomic(x402AuthorizationAmount(option))\n const to = execResult?.to ?? raw.to ?? this.delegateAddress ?? ''\n const explorerUrl = execResult?.explorer_url ?? raw.explorer_url ?? explorerUrlOrEmpty(chainId, txHash)\n const merchantTo = execResult?.merchant_to ?? raw.merchant_to ?? option.payTo\n const payer = raw.payer ?? raw.safe_address ?? raw.sign_data?.components.safe\n\n return this.buildX402Receipt({\n paymentId: raw.payment_id,\n txHash,\n token,\n amount,\n to,\n resourceUrl: paymentRequired.resource.url,\n explorerUrl,\n accepted: option,\n paymentHeader,\n merchantTo,\n payer,\n chainId,\n })\n }\n\n private mapX402ReceiptFromStatus(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n paymentHeader: string,\n status: PaymentStatusResult,\n ): X402Receipt {\n if (!status.txHash) {\n throw new HavenApiError(\n `x402 payment ${status.paymentId} is ready to retry but has no Haven transaction hash.`,\n 502,\n status,\n status.paymentId,\n )\n }\n\n return this.buildX402Receipt({\n paymentId: status.paymentId,\n txHash: status.txHash,\n token: status.token || 'USDC',\n amount: status.amount || decimalFromUsdcAtomic(x402AuthorizationAmount(option)),\n to: this.delegateAddress ?? '',\n resourceUrl: paymentRequired.resource.url,\n explorerUrl: explorerUrlOrEmpty(status.chainId, status.txHash),\n accepted: option,\n paymentHeader,\n merchantTo: status.merchantAddress ?? option.payTo,\n payer: this.x402Wallet,\n chainId: status.chainId || chainIdFromNetwork(option.network),\n })\n }\n\n private buildX402Receipt(input: {\n paymentId: string\n txHash: string\n token: string\n amount: string\n to: string\n resourceUrl: string\n explorerUrl: string\n accepted: X402PaymentOption\n paymentHeader: string\n merchantTo?: string | null\n payer?: string\n chainId?: number\n }): X402Receipt {\n const fundingExplorerUrl = input.explorerUrl || explorerUrlOrEmpty(input.chainId, input.txHash)\n\n return {\n success: true,\n paymentId: input.paymentId,\n txHash: input.txHash,\n token: input.token,\n amount: input.amount,\n to: input.to,\n resourceUrl: input.resourceUrl,\n explorerUrl: input.explorerUrl,\n accepted: input.accepted,\n paymentHeader: input.paymentHeader,\n merchantTo: input.merchantTo ?? input.accepted.payTo,\n payer: input.payer,\n chainId: input.chainId,\n haven: {\n paymentId: input.paymentId,\n fundingTxHash: input.txHash,\n fundingExplorerUrl,\n },\n merchant: {\n payTo: input.merchantTo ?? input.accepted.payTo,\n },\n x402: {\n amount: x402AuthorizationAmount(input.accepted),\n token: input.token,\n network: input.accepted.network,\n asset: input.accepted.asset,\n resource: input.accepted.resource ?? input.resourceUrl,\n },\n }\n }\n\n private async createStandardX402Header(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n ): Promise<string> {\n if (!this.delegateKey) {\n throw new HavenSigningError('delegateKey is required to sign x402 payment headers.')\n }\n\n const account = privateKeyToAccount(this.delegateKey as `0x${string}`)\n const requirements = toStandardPaymentRequirements(paymentRequired, option)\n\n const header = await exact.evm.createPaymentHeader(\n account,\n paymentRequired.x402Version,\n requirements,\n )\n if (paymentRequired.x402Version < 2) return header\n\n const payment = decodeBase64Json<{ payload: unknown }>(header)\n return encodeBase64Json({\n x402Version: paymentRequired.x402Version,\n accepted: option,\n payload: payment.payload,\n })\n }\n\n private cacheX402Receipt(\n idempotencyKey: string,\n paymentHeader: string,\n receipt: X402Receipt,\n ): void {\n const expiresAt = getPaymentHeaderValidBefore(paymentHeader)\n if (expiresAt > Date.now()) {\n this.x402ReceiptCache.set(idempotencyKey, { expiresAt, receipt })\n }\n }\n\n private async recordMerchantRetryRejected(input: {\n rail: string\n paymentId: string\n txHash: string\n resourceUrl: string\n merchant: CapturedMerchantResponse\n details?: Record<string, unknown>\n }): Promise<void> {\n try {\n await this.post('/machine-payments/reconciliation-events', {\n paymentId: input.paymentId,\n rail: input.rail,\n eventType: 'merchant_retry_rejected_after_payment',\n txHash: input.txHash,\n reason: `Merchant returned HTTP ${input.merchant.merchant_status} after Haven payment confirmation`,\n details: {\n resource_url: input.resourceUrl,\n retry_status: input.merchant.merchant_status,\n retry_body: input.merchant.merchant_body.slice(0, MERCHANT_BODY_SNIPPET_LIMIT) || null,\n ...input.details,\n },\n })\n } catch {\n // Best-effort durability: preserve the original retry failure for callers.\n }\n }\n\n private async reportMachinePaymentEvidence(input: {\n paymentId: string\n rail: string\n txHash: string\n resourceUrl: string\n merchantStatus: number\n challengePayload?: Record<string, unknown>\n selectedPayment?: Record<string, unknown>\n paymentProofHeaderName?: string\n paymentProofHeader?: string\n protocolReceiptHeaderName?: string\n protocolReceiptHeader?: string\n }): Promise<void> {\n try {\n await this.post('/machine-payments/evidence', {\n paymentId: input.paymentId,\n rail: input.rail,\n txHash: input.txHash,\n resourceUrl: input.resourceUrl,\n merchantStatus: input.merchantStatus,\n challengePayload: input.challengePayload,\n selectedPayment: input.selectedPayment,\n paymentProofHeaderName: input.paymentProofHeaderName,\n paymentProofHeader: input.paymentProofHeader,\n protocolReceiptHeaderName: input.protocolReceiptHeaderName,\n protocolReceiptHeader: input.protocolReceiptHeader,\n protocolReceiptPayload: input.protocolReceiptHeader\n ? parseProtocolReceiptHeader(input.protocolReceiptHeader)\n : undefined,\n })\n } catch {\n // Evidence reporting is best-effort. The paid resource response remains\n // the caller-visible result when merchant retry succeeded.\n }\n }\n\n /**\n * Wait for a funding tx to be mined with ≥1 confirmation before the\n * merchant retry, eliminating the race where the merchant's\n * `balanceOf(delegate)` runs before the funding block propagates.\n *\n * Skipped when `chainRpcs` does not include the chain; in that case Haven's\n * backend has already confirmed on-chain submission and callers accept the\n * small propagation window as a trade-off for not configuring an RPC URL.\n */\n private async waitForFundingTx(\n txHash: string | undefined,\n chainId: number | undefined,\n timeoutMs = 30_000,\n ): Promise<void> {\n if (!txHash || !chainId) return\n const rpcUrl = this.chainRpcs[chainId]\n if (!rpcUrl) return\n const provider = createJsonRpcProvider(rpcUrl)\n const onChainReceipt = await provider.waitForTransaction(txHash, 1, timeoutMs)\n if (!onChainReceipt || onChainReceipt.status !== 1) {\n throw new HavenApiError(\n 'Funding tx did not confirm on-chain within the timeout window.',\n 500,\n { txHash, chainId },\n )\n }\n }\n\n private throwIfNonSignableAuthorizationState(\n label: string,\n raw: RawX402AuthorizeResponse,\n ): void {\n if (raw.status === 'pending_signature') return\n this.throwPaymentStateError(label, raw)\n }\n\n private throwPaymentStateError(\n label: string,\n raw: RawX402AuthorizeResponse | RawSignResponse,\n ): never {\n const statusCode = PAYMENT_STATE_STATUS_CODES[raw.status] ?? 502\n const state = this.paymentStateFromRaw(label, raw)\n\n if (state) {\n throw new HavenPaymentStateError(state.message, statusCode, state, raw)\n }\n\n if (raw.status === 'pending_approval') {\n throw new HavenApiError(\n `${label} exceeds the on-chain allowance and was queued for owner approval (payment_id: ${raw.payment_id}).`,\n statusCode,\n raw,\n )\n }\n\n if (raw.status === 'expired') {\n throw new HavenApiError(\n `${label} expired before it could be completed (payment_id: ${raw.payment_id}).`,\n statusCode,\n raw,\n )\n }\n\n const paymentId = raw.payment_id ? ` (payment_id: ${raw.payment_id})` : ''\n const message = raw.error ?? `${label} ${raw.status}${paymentId}`\n throw new HavenApiError(message, statusCode, raw)\n }\n\n private paymentStateFromRaw(\n label: string,\n raw: RawX402AuthorizeResponse | RawSignResponse,\n ): PaymentStatusResult | null {\n if (!raw.payment_id || !raw.status) return null\n\n const phase = (raw.phase as PaymentPhase | undefined) ?? phaseForStatus(raw.status)\n const nextAction = (raw.next_action as PaymentNextAction | undefined) ?? nextActionForStatus(raw.status)\n if (!phase || !nextAction) return null\n\n const amount = raw.amount ?? raw.requested ?? ''\n const token = raw.token ?? ''\n const message =\n raw.message ??\n raw.error ??\n messageForState(label, raw.status, raw.payment_id, nextAction)\n\n return {\n paymentId: raw.payment_id,\n kind: raw.kind === 'payment_intent' ? 'payment_intent' : 'approval_request',\n rail: raw.rail ?? 'direct',\n status: raw.status === 'pending' ? 'pending_approval' : raw.status,\n phase,\n nextAction,\n amount,\n token,\n resourceUrl: raw.resource_url ?? null,\n merchantAddress: raw.merchant_address ?? raw.merchant_to ?? null,\n txHash: raw.tx_hash ?? null,\n expiresAt: raw.expires_at ?? '',\n chainId: raw.chain_id ?? 0,\n message,\n amountAtomic: raw.amount_atomic ?? raw.x402?.amount_atomic ?? raw.mpp?.amount_atomic ?? null,\n asset: raw.asset ?? raw.x402?.asset ?? raw.mpp?.asset ?? null,\n network: raw.network ?? raw.x402?.network ?? raw.mpp?.network ?? null,\n description: raw.description ?? raw.x402?.description ?? raw.mpp?.description ?? null,\n idempotencyKey: raw.idempotency_key ?? raw.x402?.idempotency_key ?? raw.mpp?.idempotency_key ?? null,\n x402: raw.x402\n ? {\n amountAtomic: raw.x402.amount_atomic ?? raw.amount_atomic ?? null,\n asset: raw.x402.asset ?? raw.asset ?? null,\n network: raw.x402.network ?? raw.network ?? null,\n resourceUrl: raw.x402.resource_url ?? raw.resource_url ?? null,\n merchantAddress: raw.x402.merchant_address ?? raw.merchant_address ?? raw.merchant_to ?? null,\n description: raw.x402.description ?? raw.description ?? null,\n idempotencyKey: raw.x402.idempotency_key ?? raw.idempotency_key ?? null,\n }\n : undefined,\n mpp: raw.mpp\n ? {\n amountAtomic: raw.mpp.amount_atomic ?? raw.amount_atomic ?? null,\n asset: raw.mpp.asset ?? raw.asset ?? null,\n network: raw.mpp.network ?? raw.network ?? null,\n resourceUrl: raw.mpp.resource_url ?? raw.resource_url ?? null,\n merchantAddress: raw.mpp.merchant_address ?? raw.merchant_address ?? raw.merchant_to ?? null,\n description: raw.mpp.description ?? raw.description ?? null,\n idempotencyKey: raw.mpp.idempotency_key ?? raw.idempotency_key ?? null,\n challengeId: raw.mpp.challenge_id ?? raw.challenge_id ?? null,\n }\n : undefined,\n }\n }\n\n private x402PayerAddress(): string | undefined {\n return this.delegateAddress ?? this.x402Wallet\n }\n\n private snapshotX402Request(url: string, init?: RequestInit): X402RequestSnapshot {\n return {\n url,\n method: init?.method ?? 'GET',\n headers: Array.from(new Headers(init?.headers).entries()),\n body: this.snapshotRequestBody(init?.body),\n }\n }\n\n private snapshotRequestBody(body: BodyInit | null | undefined): string | undefined {\n if (body == null) return undefined\n if (typeof body === 'string') return body\n if (body instanceof URLSearchParams) return body.toString()\n\n throw new HavenApiError(\n 'Quote helpers can only capture resumable request bodies that are strings or URLSearchParams. ' +\n 'For streams, blobs, or binary bodies, preserve the original request yourself and call the matching resume method with fresh init.',\n 400,\n )\n }\n\n private requestInitFromSnapshot(request: X402RequestSnapshot): RequestInit {\n return {\n method: request.method,\n headers: request.headers,\n body: request.body,\n }\n }\n\n private withX402Wallet(init?: RequestInit, wallet = this.x402PayerAddress()): RequestInit | undefined {\n if (!wallet) return init\n\n const headers = new Headers(init?.headers)\n if (!headers.has('x402-wallet')) {\n headers.set('x402-wallet', wallet)\n }\n\n return {\n ...init,\n headers,\n }\n }\n\n private buildX402Quote(\n paymentRequired: X402PaymentRequired,\n request: X402RequestSnapshot,\n idempotencyKey?: string,\n mcpTransport?: X402McpTransport,\n ): X402Quote {\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n if (!option) {\n throw new HavenApiError(\n 'No compatible payment option found in x402 requirements. ' +\n 'Haven supports standard x402 exact payments on Base USDC.',\n 400,\n )\n }\n\n const token = resolveTokenFromAddress(option.asset, option.network)\n return {\n rail: 'x402',\n idempotencyKey: idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option),\n paymentRequired,\n accepted: option,\n request,\n ...(mcpTransport ? { mcpTransport } : {}),\n resourceUrl: paymentRequired.resource.url,\n description: paymentRequired.resource.description ?? option.description ?? null,\n mimeType: paymentRequired.resource.mimeType ?? option.mimeType ?? null,\n amountAtomic: x402AuthorizationAmount(option),\n amount: decimalFromUsdcAtomic(x402AuthorizationAmount(option)),\n token: token?.symbol ?? 'USDC',\n // #1351: null when the asset is unrecognised on this network — the\n // `token` fallback above is a LABEL, not evidence of 6 decimals, and a\n // human-denominated cap must fail closed rather than convert against a\n // guess. Same resolution as `token`, so the two never disagree.\n decimals: token?.decimals ?? null,\n asset: option.asset,\n network: option.network,\n chainId: chainIdOrNull(option.network),\n merchantAddress: option.payTo,\n maxTimeoutSeconds: option.maxTimeoutSeconds,\n }\n }\n\n private async detectX402McpTransport(\n url: string,\n paymentRequired: X402PaymentRequired,\n response: Response,\n ): Promise<X402McpTransport | undefined> {\n if (isMcpUrl(url)) {\n return { handshakeRequired: true, source: 'path' }\n }\n if (paymentRequired.extensions?.bazaar != null) {\n return { handshakeRequired: true, source: 'bazaar' }\n }\n if (await responseHasBazaarExtension(response)) {\n return { handshakeRequired: true, source: 'bazaar' }\n }\n return undefined\n }\n\n private buildX402ResumeState(input: {\n paymentId: string\n paymentRequired: X402PaymentRequired\n accepted: X402PaymentOption\n idempotencyKey: string\n request?: X402RequestSnapshot\n }): X402ResumeState {\n const token = resolveTokenFromAddress(input.accepted.asset, input.accepted.network)\n return {\n rail: 'x402',\n paymentId: input.paymentId,\n idempotencyKey: input.idempotencyKey,\n paymentRequired: input.paymentRequired,\n accepted: input.accepted,\n url: input.request?.url ?? input.paymentRequired.resource.url,\n request: input.request,\n resourceUrl: input.paymentRequired.resource.url,\n description: input.paymentRequired.resource.description ?? input.accepted.description ?? null,\n amountAtomic: x402AuthorizationAmount(input.accepted),\n amount: decimalFromUsdcAtomic(x402AuthorizationAmount(input.accepted)),\n token: token?.symbol ?? 'USDC',\n asset: input.accepted.asset,\n network: input.accepted.network,\n chainId: chainIdOrNull(input.accepted.network),\n merchantAddress: input.accepted.payTo,\n }\n }\n\n // #1328: attachResumeState's 'mpp' branch (buildMppQuote / buildMppResumeState\n // / attachMppResumeState) is retired along with the rest of the MPP-demo\n // client surface — every remaining caller passes rail: 'x402' only, so this\n // is now a direct alias for attachX402ResumeState rather than a dispatcher.\n private attachResumeState(\n err: unknown,\n input: {\n rail: 'x402'\n paymentRequired: X402PaymentRequired\n accepted: X402PaymentOption\n idempotencyKey: string\n request?: X402RequestSnapshot\n },\n ): void {\n this.attachX402ResumeState(\n err,\n input.paymentRequired,\n input.accepted,\n input.idempotencyKey,\n input.request,\n )\n }\n\n private attachX402ResumeState(\n err: unknown,\n paymentRequired: X402PaymentRequired,\n accepted: X402PaymentOption,\n idempotencyKey: string,\n request?: X402RequestSnapshot,\n ): void {\n if (!(err instanceof HavenPaymentStateError)) return\n if (err.state.rail !== 'x402') return\n\n err.resumeState = this.buildX402ResumeState({\n paymentId: err.state.paymentId,\n paymentRequired,\n accepted,\n idempotencyKey,\n request,\n })\n }\n\n // ── Tool Execution (for agent frameworks) ────────────────────────\n\n /**\n * Execute a tool call by name and input.\n *\n * Designed to plug directly into agent tool-call handlers:\n *\n * ```ts\n * if (block.type === 'tool_use') {\n * const result = await haven.executeTool(block.name, block.input)\n * // send result back to the model\n * }\n * ```\n */\n async executeTool(\n toolName: string,\n input: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n if (toolName === 'make_payment') {\n const { token, amount, to } = input as {\n token: string\n amount: string\n to: string\n }\n\n try {\n const result = await this.pay({ token, amount, to })\n return {\n success: result.status === 'confirmed',\n payment_id: result.paymentId,\n status: result.status,\n tx_hash: result.txHash,\n token: result.token,\n amount: result.amount,\n to: result.to,\n explorer_url: result.explorerUrl,\n error: result.errorMessage,\n }\n } catch (err) {\n return this.toolError(err)\n }\n }\n\n if (toolName === 'authorize_x402_payment') {\n const { url, payTo, amount, asset, network, description, idempotencyKey } = input as {\n url: string\n payTo: string\n amount: string\n asset: string\n network: string\n description?: string\n idempotencyKey?: string\n }\n\n try {\n const receipt = await this.authorizeX402(\n this.toolX402PaymentRequired({ url, payTo, amount, asset, network, description }),\n { idempotencyKey },\n )\n return this.x402ToolReceipt(receipt)\n } catch (err) {\n return this.toolError(err)\n }\n }\n\n if (toolName === 'resume_x402_payment') {\n const { payment_id, url, payTo, amount, asset, network, description, idempotencyKey } = input as {\n payment_id: string\n url: string\n payTo: string\n amount: string\n asset: string\n network: string\n description?: string\n idempotencyKey?: string\n }\n\n try {\n const receipt = await this.resumeAuthorizedX402({\n paymentId: payment_id,\n paymentRequired: this.toolX402PaymentRequired({ url, payTo, amount, asset, network, description }),\n idempotencyKey,\n })\n return this.x402ToolReceipt(receipt)\n } catch (err) {\n return this.toolError(err)\n }\n }\n\n // #1328: the 'authorize_machine_payment' tool (mpp_demo only) is retired\n // along with the rest of the SDK's MPP-demo client surface — an unknown\n // toolName falls through to the Error below, same as any other retired name.\n\n if (toolName === 'get_payment_status') {\n const { payment_id } = input as { payment_id: string }\n const result = await this.getPaymentStatus(payment_id)\n return {\n payment_id: result.paymentId,\n kind: result.kind,\n rail: result.rail,\n status: result.status,\n phase: result.phase,\n next_action: result.nextAction,\n tx_hash: result.txHash,\n token: result.token,\n amount: result.amount,\n resource_url: result.resourceUrl,\n merchant_address: result.merchantAddress,\n amount_atomic: result.amountAtomic,\n asset: result.asset,\n network: result.network,\n description: result.description,\n idempotency_key: result.idempotencyKey,\n x402: result.x402,\n mpp: result.mpp,\n expires_at: result.expiresAt,\n chain_id: result.chainId,\n message: result.message,\n }\n }\n\n if (toolName === 'get_allowances') {\n return { ...await this.getAllowances() }\n }\n\n throw new Error(`Unknown tool: ${toolName}`)\n }\n\n private toolX402PaymentRequired(input: {\n url: string\n payTo: string\n amount: string\n asset: string\n network: string\n description?: string\n }): X402PaymentRequired {\n return {\n x402Version: 2,\n resource: { url: input.url, description: input.description },\n accepts: [\n {\n scheme: 'exact',\n network: input.network,\n amount: input.amount,\n asset: input.asset,\n payTo: input.payTo,\n maxTimeoutSeconds: 30,\n },\n ],\n }\n }\n\n private x402ToolReceipt(receipt: X402Receipt): Record<string, unknown> {\n return {\n success: true,\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n token: receipt.token,\n amount: receipt.amount,\n to: receipt.to,\n resource_url: receipt.resourceUrl,\n explorer_url: receipt.explorerUrl,\n payment_header: receipt.paymentHeader,\n merchant_to: receipt.merchantTo,\n payer: receipt.payer,\n chain_id: receipt.chainId,\n haven: receipt.haven,\n merchant: receipt.merchant,\n x402: receipt.x402,\n }\n }\n\n private toolError(err: unknown): Record<string, unknown> {\n if (err instanceof HavenPaymentStateError) {\n return {\n success: false,\n payment_id: err.state.paymentId,\n kind: err.state.kind,\n rail: err.state.rail,\n status: err.state.status,\n phase: err.state.phase,\n next_action: err.state.nextAction,\n tx_hash: err.state.txHash,\n token: err.state.token,\n amount: err.state.amount,\n resource_url: err.state.resourceUrl,\n merchant_address: err.state.merchantAddress,\n amount_atomic: err.state.amountAtomic,\n asset: err.state.asset,\n network: err.state.network,\n description: err.state.description,\n idempotency_key: err.state.idempotencyKey,\n x402: err.state.x402\n ? {\n amount_atomic: err.state.x402.amountAtomic,\n asset: err.state.x402.asset,\n network: err.state.x402.network,\n resource_url: err.state.x402.resourceUrl,\n merchant_address: err.state.x402.merchantAddress,\n description: err.state.x402.description,\n idempotency_key: err.state.x402.idempotencyKey,\n }\n : undefined,\n mpp: err.state.mpp\n ? {\n amount_atomic: err.state.mpp.amountAtomic,\n asset: err.state.mpp.asset,\n network: err.state.mpp.network,\n resource_url: err.state.mpp.resourceUrl,\n merchant_address: err.state.mpp.merchantAddress,\n description: err.state.mpp.description,\n idempotency_key: err.state.mpp.idempotencyKey,\n challenge_id: err.state.mpp.challengeId,\n }\n : undefined,\n resume_state: err.resumeState,\n expires_at: err.state.expiresAt,\n chain_id: err.state.chainId,\n message: err.state.message,\n error: err.message,\n }\n }\n\n if (err instanceof HavenApiError) {\n return {\n success: false,\n status_code: err.statusCode,\n error: err.message,\n body: err.body,\n }\n }\n\n return {\n success: false,\n error: err instanceof Error ? err.message : String(err),\n }\n }\n\n // ── HTTP Helpers ─────────────────────────────────────────────────\n\n private async post<T>(path: string, body: Record<string, unknown>): Promise<T> {\n return this.request<T>('POST', path, body)\n }\n\n private async get<T>(path: string): Promise<T> {\n return this.request<T>('GET', path)\n }\n\n /**\n * #1300: every MERCHANT-facing fetch goes through here. Haven API calls\n * have always been bounded (request() below); the merchant probes/retries\n * called globalThis.fetch bare, so a slow-loris merchant could hold a tool\n * call open forever. A caller-supplied signal still applies (combined via\n * AbortSignal.any); a timeout abort surfaces as a clear HavenApiError 504\n * naming the URL rather than a bare AbortError.\n */\n private async merchantFetch(\n url: string,\n init: RequestInit = {},\n timeoutMs = this.merchantTimeout,\n ): Promise<Response> {\n const timeoutSignal = AbortSignal.timeout(timeoutMs)\n const signal = init.signal ? AbortSignal.any([init.signal, timeoutSignal]) : timeoutSignal\n try {\n return await globalThis.fetch(url, { ...init, signal })\n } catch (err) {\n if (timeoutSignal.aborted) {\n throw new MerchantTimeoutError(`Merchant request timed out after ${timeoutMs}ms: ${url}`)\n }\n throw err\n }\n }\n\n private async request<T>(\n method: 'GET' | 'POST',\n path: string,\n body?: Record<string, unknown>,\n ): Promise<T> {\n const url = `${this.baseUrl}${path}`\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), this.requestTimeout)\n\n try {\n const contextHeaders = this.requestContext.getStore()?.headers ?? {}\n const res = await fetch(url, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n ...this.defaultHeaders,\n ...contextHeaders,\n },\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n })\n\n const data = await res.json()\n\n if (!res.ok) {\n const record = data as Record<string, unknown>\n const errorText = typeof record.error === 'string' ? record.error : undefined\n // agentAuth's structured refusals (#1130: agent_pending_approval,\n // agent_paused) carry their guidance as `detail` (singular) — without\n // this fallback the operator sees a bare error code and none of the\n // actionable text.\n const rawDetails = record.details ?? record.detail\n const detailsText =\n typeof rawDetails === 'string'\n ? rawDetails\n : rawDetails != null\n ? JSON.stringify(rawDetails)\n : undefined\n // Surface the backend's `details` alongside the generic `error` —\n // otherwise messages like \"On-chain execution failed\" mask the actual\n // revert reason (#684). The full body is still attached for callers.\n const message =\n errorText && detailsText\n ? `${errorText}: ${detailsText}`\n : errorText ?? detailsText ?? `API request failed`\n throw new HavenApiError(message, res.status, data)\n }\n\n return data as T\n } catch (err) {\n if (err instanceof HavenApiError) throw err\n if (err instanceof Error && err.name === 'AbortError') {\n throw new HavenApiError(`Request to ${path} timed out`, 408)\n }\n throw new HavenApiError(\n `Request to ${path} failed: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n )\n } finally {\n clearTimeout(timeout)\n }\n }\n\n // ── Mapping Helpers ──────────────────────────────────────────────\n\n private mapPaymentResult(raw: RawStatusResponse): PaymentResult {\n return {\n paymentId: raw.payment_id,\n status: raw.status as PaymentStatus,\n token: raw.token,\n amount: raw.amount,\n to: raw.to,\n txHash: raw.tx_hash,\n errorMessage: raw.error_message,\n explorerUrl: raw.explorer_url ?? (raw.tx_hash ? buildExplorerUrl(raw.chain_id, raw.tx_hash) : null),\n fee: raw.fee\n ? {\n amount: raw.fee.amount,\n token: raw.fee.token,\n basisPoints: raw.fee.basis_points,\n applied: raw.fee.applied,\n }\n : null,\n createdAt: raw.created_at,\n signedAt: raw.signed_at,\n submittedAt: raw.submitted_at,\n confirmedAt: raw.confirmed_at,\n expiresAt: raw.expires_at,\n }\n }\n\n private mapPaymentStatusResult(raw: RawPaymentStatusResult): PaymentStatusResult {\n return {\n paymentId: raw.payment_id,\n kind: raw.kind,\n rail: raw.rail,\n status: raw.status,\n phase: raw.phase,\n nextAction: raw.next_action,\n amount: raw.amount,\n token: raw.token,\n resourceUrl: raw.resource_url,\n merchantAddress: raw.merchant_address,\n txHash: raw.tx_hash,\n expiresAt: raw.expires_at,\n chainId: raw.chain_id,\n message: raw.message,\n fee: raw.fee\n ? {\n amount: raw.fee.amount,\n token: raw.fee.token,\n basisPoints: raw.fee.basis_points,\n applied: raw.fee.applied,\n }\n : null,\n amountAtomic: raw.amount_atomic ?? raw.x402?.amount_atomic ?? null,\n asset: raw.asset ?? raw.x402?.asset ?? null,\n network: raw.network ?? raw.x402?.network ?? null,\n description: raw.description ?? raw.x402?.description ?? null,\n idempotencyKey: raw.idempotency_key ?? raw.x402?.idempotency_key ?? null,\n x402: raw.x402\n ? {\n amountAtomic: raw.x402.amount_atomic ?? raw.amount_atomic ?? null,\n asset: raw.x402.asset ?? raw.asset ?? null,\n network: raw.x402.network ?? raw.network ?? null,\n resourceUrl: raw.x402.resource_url ?? raw.resource_url,\n merchantAddress: raw.x402.merchant_address ?? raw.merchant_address,\n description: raw.x402.description ?? raw.description ?? null,\n idempotencyKey: raw.x402.idempotency_key ?? raw.idempotency_key ?? null,\n }\n : undefined,\n }\n }\n\n private mapPaymentReceipt(raw: RawHavenPaymentReceipt): HavenPaymentReceipt {\n const receipt: HavenPaymentReceipt = {\n id: raw.id,\n paymentId: raw.payment_id,\n rail: raw.rail,\n proofStatus: raw.proof_status,\n txHash: raw.tx_hash,\n chainId: raw.chain_id,\n resourceUrl: raw.resource_url,\n merchantAddress: raw.merchant_address,\n payerAddress: raw.payer_address,\n settlementAddress: raw.settlement_address,\n tokenSymbol: raw.token_symbol,\n tokenAddress: raw.token_address,\n amountRaw: raw.amount_raw,\n amount: raw.amount_human,\n challengeId: raw.challenge_id,\n idempotencyKey: raw.idempotency_key,\n challengePayload: raw.challenge_payload,\n selectedPayment: raw.selected_payment,\n paymentProofHeaderName: raw.payment_proof_header_name,\n protocolReceiptHeaderName: raw.protocol_receipt_header_name,\n protocolReceiptPayload: raw.protocol_receipt_payload,\n merchantStatus: raw.merchant_status,\n confirmedAt: raw.confirmed_at,\n createdAt: raw.created_at,\n updatedAt: raw.updated_at,\n }\n\n if ('payment_intent_id' in raw) {\n receipt.paymentIntentId = raw.payment_intent_id ?? null\n }\n if ('approval_request_id' in raw) {\n receipt.approvalRequestId = raw.approval_request_id ?? null\n }\n\n return receipt\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction getPaymentHeaderValidBefore(paymentHeader: string): number {\n try {\n const payment = decodeBase64Json<{ payload?: { authorization?: { validBefore?: string } } }>(\n paymentHeader,\n )\n const payload = payment.payload as { authorization?: { validBefore?: string } }\n const validBeforeSeconds = Number(payload.authorization?.validBefore)\n if (Number.isFinite(validBeforeSeconds)) return validBeforeSeconds * 1000\n } catch {\n // If the header cannot be decoded, skip caching rather than hiding errors.\n }\n\n return 0\n}\n\nfunction parseProtocolReceiptHeader(value: string): Record<string, unknown> | undefined {\n try {\n return decodeBase64Json<Record<string, unknown>>(value)\n } catch {\n try {\n return JSON.parse(value) as Record<string, unknown>\n } catch {\n return undefined\n }\n }\n}\n\n/**\n * Captures a failed merchant retry response so callers can debug exactly why the\n * merchant rejected a payment Haven already funded. We preserve the status code,\n * statusText, headers, and full body text verbatim — this is the merchant's\n * response, so it never contains Haven-side secrets (delegate key, agent API key),\n * which only ever live in the outbound request.\n */\nasync function captureMerchantResponse(response: Response): Promise<CapturedMerchantResponse> {\n const merchant_body = await response.text().catch(() => '')\n return {\n merchant_status: response.status,\n merchant_status_text: response.statusText,\n merchant_headers: Object.fromEntries(response.headers.entries()),\n merchant_body,\n }\n}\n","/**\n * Shared semantic descriptions for Haven agent payment tools.\n *\n * Two surfaces in this repo expose Haven as a tool: the Claude / OpenAI\n * function-calling tool definitions in `tools.ts` (used for direct SDK\n * integrations) and the MCP server in `packages/mcp` (used by any MCP-speaking\n * agent runtime). The two surfaces use different tool *names* — the SDK's\n * tools are tuned for tool-calling conventions (`make_payment`,\n * `authorize_x402_payment`); the MCP tools follow the MCP `haven_*` naming\n * (`haven_pay_x402_quote`).\n *\n * The underlying *operations* are the same, so the descriptive prose should\n * live in one place. Both surfaces import from this module and compose their\n * own tool descriptions from these semantic fragments. Drift is caught by\n * tests asserting each consumer's description string contains the shared\n * `summary` from this module.\n */\n\nexport interface ToolDescription {\n /** One-line summary of the operation. Used as the first sentence of every\n * downstream description and as a stable substring for drift tests. */\n summary: string\n /** Natural-language user intents that should make an agent prefer this\n * tool over adjacent tools. Empty or omitted when the summary is enough. */\n selectionGuidance?: string\n /** Concrete behaviour the tool performs end-to-end, including which\n * non-custodial guarantee applies. */\n behavior: string\n /** What the agent should do next on error / pending-approval states.\n * Empty string if not applicable. */\n nextActionGuidance: string\n}\n\n/**\n * Build a single description string from the three fragments. Joined with\n * spaces so consumers can split on the summary substring if they need to.\n */\nexport function composeDescription(d: ToolDescription): string {\n return [d.summary, d.selectionGuidance, d.behavior, d.nextActionGuidance]\n .filter(Boolean)\n .join(' ')\n}\n\nexport const toolDescriptions = {\n quoteX402: {\n summary:\n 'Inspect an HTTP 402 x402 paid resource without creating a Haven payment, signature, approval, or on-chain transaction.',\n behavior:\n 'Probes the merchant directly and parses the 402 response. Pure read-only client behavior — Haven is not contacted.',\n nextActionGuidance:\n 'On success the returned quote is the input to haven_pay_x402_quote. Do not call the merchant again — Haven re-uses the captured request when paying.',\n },\n payX402: {\n summary:\n 'Pay an inspected x402 quote. The delegate key signs locally; Haven only validates and relays signed, on-chain-constrained payment transactions.',\n selectionGuidance:\n 'Do not use this for read-only allowance, budget, spend-limit, remaining-amount, reset-period, or what-can-I-spend questions; use the allowance lookup tool instead.',\n behavior:\n 'Signs the EIP-3009 payment from the delegate wallet, asks Haven for a Safe AllowanceModule top-up if needed, and returns the merchant response or a pending-approval state.',\n nextActionGuidance:\n 'If approval is needed, preserve the returned resume_state and wait for nextAction=retry_original_x402_request before resuming. ' +\n 'If the response carries phase=insufficient_funds and nextAction=fund_safe_or_raise_allowance, the payment cannot be retried until the originating Safe is funded or the agent allowance raised — stop and tell the user the shortfall reported on the response.',\n },\n payX402OneShot: {\n summary:\n 'Fetch an x402 paid HTTP resource in a single call. Handles the full probe -> pay -> retry round trip and returns the merchant response.',\n selectionGuidance:\n '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.',\n behavior:\n 'Calls the URL, parses any HTTP 402 x402 challenge, signs the EIP-3009 payment from the delegate wallet, asks Haven for a Safe AllowanceModule top-up if needed, then retries the original request with the X-PAYMENT header and returns the merchant response. If the resource returns a non-402 status, returns it unchanged without contacting Haven.',\n nextActionGuidance:\n 'If approval is needed, preserve the returned resume_state or paymentId and call the resume tool once nextAction=retry_original_x402_request. ' +\n 'If the response carries phase=insufficient_funds and nextAction=fund_safe_or_raise_allowance, the payment cannot be retried until the originating Safe is funded or the agent allowance raised — stop and tell the user the shortfall reported on the response.',\n },\n resumeX402: {\n summary:\n 'Resume an x402 payment after the Haven wallet owner approved the funding step.',\n behavior:\n 'Accepts either resume_state or payment_id, validates the original x402 details against the approved Haven funding, and retries the merchant request with the X-PAYMENT header. No new Haven approval is created.',\n nextActionGuidance:\n 'Only use when get_payment_status returns nextAction=retry_original_x402_request; do not start a new merchant session.',\n },\n // #1328: quoteMpp / payMpp / resumeMpp (the mpp_demo challenge/quote/resume\n // fragments) are retired along with the client surface they described —\n // MACHINE-PAYMENT-CHALLENGE was never produced by anything besides the now\n // deleted `/demo/mpp/*` route. Use the x402 fragments above instead.\n getPaymentStatus: {\n summary:\n 'Fetch structured Haven payment status, including phase and nextAction taxonomy for agent recovery.',\n behavior:\n 'Accepts a payment intent or approval request id and returns the full state taxonomy (phase, nextAction, rail, amount, merchant, resource url, idempotency key, message).',\n nextActionGuidance: '',\n },\n getResumeState: {\n summary:\n 'Rehydrate stored x402 resume_state by payment_id.',\n behavior:\n 'Returns the context that the agent originally received in a pending-approval response, reconstructed from Haven\\'s database. This is context only; signing still happens locally when a resume tool is called.',\n nextActionGuidance: '',\n },\n getAgent: {\n summary:\n 'Return the authenticated agent identity AND its live spend authority in one call: Haven wallet, delegate, chain, raw status, a readiness signal, and per-token remaining allowance (atomic + human-readable). The recommended first call in a new session to confirm who you are and whether you can pay right now.',\n selectionGuidance:\n 'Use this as the one-shot orientation/bootstrap at the start of a session, or whenever you need to confirm identity together with whether the agent can spend right now. For a detailed per-token breakdown (configured vs spent vs reset window) use haven_get_allowances.',\n behavior:\n 'Reads identity plus the live spend-authority snapshot in one shot — the on-chain AllowanceModule on the legacy rail, the active budget delegation on the delegation rail. readiness is \"ready\" when at least one token has remaining spend authority, \"needs_approval\" when the agent is active but has none, and \"revoked\" when the credential is not active. What an over-budget payment does differs by rail: on the legacy AllowanceModule rail it is queued for the wallet owner to approve in Haven; on the delegation rail there is no approval queue — an over-budget redemption reverts on-chain, so ask the owner to grant or raise the budget in Haven rather than waiting for an approval. allowances[] carries remainingAtomic and remainingDisplay per token. Identity fields (id, name, status, safeAddress, delegateAddress, chainId) are unchanged from before.',\n nextActionGuidance: '',\n },\n getAllowances: {\n summary:\n 'Return configured and on-chain allowance state for the authenticated agent. On-chain allowance is the real spend gate.',\n selectionGuidance:\n 'Use this when the user asks about allowance, budget, spend limit, remaining amount, remaining allowance, remaining budget, daily limit, reset period, what can I spend, or what the agent can still spend.',\n behavior:\n 'Returns the per-token spend authority for the account\\'s rail: the Safe AllowanceModule snapshot (allowance, spent, remaining, reset window) on the legacy rail, or the active budget delegation (remaining = the period budget; over-budget redemptions revert on-chain, nothing queues) on the delegation rail. Configured amounts from Haven are returned alongside.',\n nextActionGuidance: '',\n },\n listReceipts: {\n summary:\n 'List recent machine-payment receipts and evidence for bookkeeping.',\n selectionGuidance:\n 'Use this for transaction history, receipts, payment evidence, or bookkeeping; use the allowance tool instead for remaining allowance, budget, spend-limit, or what-can-I-spend questions.',\n behavior:\n 'Returns the agent\\'s recent machine-payment receipts ordered by recency. Proof header values are not returned.',\n nextActionGuidance: '',\n },\n verifyReceipt: {\n summary:\n 'Verify a payment receipt offline — confirm the agent authorised the transfer.',\n selectionGuidance:\n 'Use this to check a receipt you already hold; it needs no network and does not trust Haven. Use the history tool to fetch receipts in the first place.',\n behavior:\n 'Recovers the signer from the receipt authorisation and confirms it matches the agent delegate. Returns verified true/false with the recovered signer or a reason. Pure and local — no backend call.',\n nextActionGuidance: '',\n },\n payMcpTool: {\n summary:\n 'Call a named tool on an MCP merchant that requires an x402 payment, handling the full initialize → pay → retry round trip in one call.',\n selectionGuidance:\n 'Use this when the agent wants to call a specific tool on an MCP merchant (e.g. Soundside, Coinbase Bazaar) and payment is required. ' +\n 'Prefer this over haven_pay_x402 when you know the merchant_url and tool_name — it builds the JSON-RPC envelope internally. ' +\n 'Use haven_pay_x402 for arbitrary HTTP resources. ' +\n 'Do NOT use for read-only allowance or budget questions — use haven_get_allowances.',\n behavior:\n 'Builds the JSON-RPC tools/call envelope, runs the MCP Streamable-HTTP initialize handshake automatically (if the endpoint is MCP-shaped), ' +\n 'pays any HTTP 402 x402 challenge through Haven\\'s AllowanceModule path, and retries the request, returning the JSON-RPC result (the actual merchant output) on success. ' +\n 'Amounts within the on-chain allowance execute automatically; over-allowance transfers are queued as pending_approval — follow the response\\'s nextAction when present.',\n nextActionGuidance:\n 'If pending_approval is returned, preserve payment_id and resume_state and wait for the wallet owner to approve in Haven. ' +\n 'Use haven_resume_x402_payment once nextAction=retry_original_x402_request.',\n },\n discoverTools: {\n summary:\n 'Step 1 of a purchase: discover payable services from Haven\\'s curated merchant catalog — names, prices, and which pay tool to use next.',\n selectionGuidance:\n 'Use this when the user asks what the agent can buy, pay for, or which paid services exist — or when you need a resource URL for a service the user described. ' +\n 'Do NOT use for balance, budget, or spend-limit questions — use haven_get_allowances. ' +\n 'Do NOT use to pay — each returned entry names the pay tool to use next.',\n behavior:\n 'Use each entry\\'s suggested_tool field first — it names the exact next call. ' +\n 'Read-only lookup against Haven\\'s curated catalog; entries are periodically re-verified against the live merchant and degraded entries are flagged. ' +\n 'Use category for a case-insensitive category filter (for example, VPN or vpn), or search for a product name, category, or description term. ' +\n 'Returns name, description, price, rail, resource URL, tool_name, tool_arguments, and suggested_tool. ' +\n 'The catalog price (price_display/price_atomic, marked price_is_indicative) is a last-verified hint, NOT authoritative — the real price comes from the merchant\\'s live 402 at pay time. ' +\n 'Never creates a payment, signature, or approval.',\n nextActionGuidance:\n 'Pick an entry and pay it with the tool named in suggested_tool, passing the entry\\'s resource_url, tool_name, and tool_arguments for MCP merchants. Confirm the price from the live pay-tool result (not the catalog), and pass the user\\'s cap as max_amount_human in whole tokens (\"no more than 1 USDC\" → max_amount_human: \"1\") — never convert it to atomic units by hand (#1351).',\n },\n sweep_delegate: {\n summary:\n 'Sweep stranded USDC and/or ETH from the delegate wallet back to the originating Safe.',\n selectionGuidance:\n 'Use this when the user instructs you to recover stranded funds on the delegate wallet, or when a payment status returns nextAction=sweep_stranded_funds. ' +\n 'Do NOT use for normal payments — use haven_pay_x402. ' +\n 'Do NOT use to read balances only — use haven_get_allowances.',\n behavior:\n 'Reads the delegate EOA\\'s on-chain USDC and ETH balances. For each non-zero balance, signs and submits a transfer from the delegate EOA to the originating Safe (hardcoded destination). ' +\n 'The delegate key signs locally — Haven never sees it and the backend never constructs signed transactions (CASP/MiCA Red Line #2). ' +\n 'Returns tx hashes and recovered amounts. Returns an empty transfers list when nothing is stranded.',\n nextActionGuidance:\n 'If transfers is non-empty, confirm the amounts with the user. No further action required — funds are on their way back to the Safe.',\n },\n send: {\n summary:\n 'Send ETH or USDC directly from the agent\\'s Haven wallet to a recipient address.',\n selectionGuidance:\n 'Use this for plain transfers — refunding a user, paying a freelancer, topping up a co-agent\\'s wallet, or moving funds between addresses. ' +\n 'Do NOT use for x402 paid endpoints — use haven_pay_x402 instead. ' +\n 'Do NOT use for read-only allowance, budget, or what-can-I-spend questions — use haven_get_allowances.',\n behavior:\n 'Sends the requested amount through the Safe AllowanceModule. ' +\n 'Amounts within the remaining on-chain allowance for the asset execute automatically; ' +\n 'amounts that exceed the allowance are queued as pending_approval for the wallet owner to approve in Haven. ' +\n 'The agent\\'s signing key signs the AllowanceModule transfer hash; Haven never receives the key.',\n nextActionGuidance:\n 'If pending_approval is returned, preserve the payment_id and wait for the wallet owner to approve in Haven. ' +\n 'Poll haven_get_payment_status until nextAction=none.',\n },\n} as const satisfies Record<string, ToolDescription>\n\nexport type SharedToolKey = keyof typeof toolDescriptions\n","/**\n * Pre-built tool definitions for AI agent frameworks.\n *\n * These definitions describe Haven's direct SDK tool-calling surface in the\n * formats expected by Claude (Anthropic) and OpenAI.\n *\n * The agent payment surface used by these tools is shared with the\n * `@haven_ai/mcp` server — both consume `toolDescriptions` from\n * `./tool-descriptions.ts`. Each consumer composes its own user-visible string\n * from the same semantic fragments, so guidance lands in both surfaces at\n * once and a downstream test asserts the shared summary appears in every\n * consumer description.\n *\n * Usage with Claude:\n * const response = await anthropic.messages.create({\n * tools: havenTools.claude(),\n * ...\n * })\n *\n * Usage with OpenAI:\n * const response = await openai.chat.completions.create({\n * tools: havenTools.openai(),\n * ...\n * })\n */\n\nimport { composeDescription, toolDescriptions as sharedDescriptions } from './tool-descriptions.js'\n\n// ── JSON Schema (shared across formats) ──────────────────────────\n\nconst makePaymentSchema = {\n type: 'object' as const,\n properties: {\n token: {\n type: 'string' as const,\n description: 'Token to send. Gnosis Chain: EURe, USDC.e, xDAI. Base: USDC, ETH.',\n },\n amount: {\n type: 'string' as const,\n description: 'Amount to send as a decimal string, e.g. \"5.00\"',\n },\n to: {\n type: 'string' as const,\n description: 'Recipient Ethereum address (0x...)',\n },\n reason: {\n type: 'string' as const,\n description: 'Brief reason for this payment (for audit trail)',\n },\n },\n required: ['token', 'amount', 'to', 'reason'] as const,\n}\n\nconst getPaymentStatusSchema = {\n type: 'object' as const,\n properties: {\n payment_id: {\n type: 'string' as const,\n description: 'The payment ID returned from make_payment',\n },\n },\n required: ['payment_id'] as const,\n}\n\nconst getAllowancesSchema = {\n type: 'object' as const,\n properties: {},\n required: [] as const,\n}\n\nconst authorizeX402Schema = {\n type: 'object' as const,\n properties: {\n url: {\n type: 'string' as const,\n description: 'The URL that returned HTTP 402',\n },\n payTo: {\n type: 'string' as const,\n description: 'Payment recipient address from the 402 response',\n },\n amount: {\n type: 'string' as const,\n description: 'Payment amount in atomic units (e.g. \"1000000\" for 1 USDC)',\n },\n asset: {\n type: 'string' as const,\n description: 'Token contract address from the 402 response',\n },\n network: {\n type: 'string' as const,\n description: 'CAIP-2 chain ID. \"eip155:100\" for Gnosis Chain, \"eip155:8453\" for Base.',\n },\n description: {\n type: 'string' as const,\n description: 'Description of the resource being paid for',\n },\n idempotencyKey: {\n type: 'string' as const,\n description: 'Stable caller-supplied key for this user intent. Reuse it when resuming after user approval.',\n },\n },\n required: ['url', 'payTo', 'amount', 'asset', 'network'] as const,\n}\n\nconst resumeX402Schema = {\n type: 'object' as const,\n properties: {\n payment_id: {\n type: 'string' as const,\n description: 'The payment or approval request ID returned by authorize_x402_payment.',\n },\n url: {\n type: 'string' as const,\n description: 'The original URL that returned HTTP 402.',\n },\n payTo: {\n type: 'string' as const,\n description: 'Payment recipient address from the original 402 response.',\n },\n amount: {\n type: 'string' as const,\n description: 'Payment amount in atomic units from the original 402 response.',\n },\n asset: {\n type: 'string' as const,\n description: 'Token contract address from the original 402 response.',\n },\n network: {\n type: 'string' as const,\n description: 'CAIP-2 chain ID or x402 network from the original 402 response.',\n },\n description: {\n type: 'string' as const,\n description: 'Description of the resource being paid for.',\n },\n idempotencyKey: {\n type: 'string' as const,\n description: 'Stable caller-supplied key used for the original authorization.',\n },\n },\n required: ['payment_id', 'url', 'payTo', 'amount', 'asset', 'network'] as const,\n}\n\nconst MAKE_PAYMENT_DESCRIPTION =\n 'Request and sign a payment from the user-controlled Safe within approved on-chain limits. ' +\n 'For read-only allowance, budget, spend-limit, remaining-amount, or reset-period questions, use get_allowances instead of making a payment. ' +\n 'Haven authenticates the agent, validates the signed intent, and relays the Safe AllowanceModule transaction; it does not hold keys or control funds. ' +\n 'Gnosis Chain tokens: EURe, USDC.e, xDAI. Base tokens: USDC, ETH.'\n\n// Descriptions are composed from the shared semantic source so the SDK and MCP\n// surfaces stay in lockstep. Each constant prepends the shared `summary` (the\n// stable substring tests assert on) and then appends the SDK-specific guidance\n// for tool-calling consumers.\n\nconst GET_STATUS_DESCRIPTION =\n sharedDescriptions.getPaymentStatus.summary + ' ' +\n 'Accepts payment intent IDs and approval request IDs. Returns the current status, phase, next_action, transaction hash if available, and payment details.'\n\nconst GET_ALLOWANCES_DESCRIPTION = composeDescription(sharedDescriptions.getAllowances)\n\nconst AUTHORIZE_X402_DESCRIPTION =\n composeDescription(sharedDescriptions.payX402) + ' ' +\n 'In this SDK tool set, the allowance lookup tool is get_allowances. ' +\n 'When a paid API returns x402 payment requirements, use this tool to sign with the agent-owned delegate key and request a policy-limited Safe AllowanceModule top-up when needed. ' +\n 'Haven relays signed transactions only; the agent key authorizes payment and on-chain limits enforce spend. ' +\n 'If this returns pending_approval, tell the user it is waiting in Haven, preserve the original merchant/MCP session and x402 details, call get_payment_status later, and use resume_x402_payment only when next_action is retry_original_x402_request. Do not start a new merchant session or loop retries while approval is pending. ' +\n 'Use the returned payment_header as the X-PAYMENT header on the retry request when doing a manual HTTP retry.'\n\nconst RESUME_X402_DESCRIPTION =\n sharedDescriptions.resumeX402.summary + ' ' +\n 'Use this only after get_payment_status returns next_action=retry_original_x402_request. ' +\n 'It checks the approved payment, validates the original x402 details, and returns a merchant X-PAYMENT header without creating a new approval request or merchant session.'\n\nconst SWEEP_DELEGATE_DESCRIPTION = composeDescription(sharedDescriptions.sweep_delegate)\n\nconst sweepDelegateSchema = {\n type: 'object' as const,\n properties: {},\n required: [] as readonly string[],\n}\n\n// ── Claude (Anthropic) format ────────────────────────────────────\n\nexport interface ClaudeTool {\n name: string\n description: string\n input_schema: {\n type: 'object'\n properties: Record<string, unknown>\n required: readonly string[]\n }\n}\n\nfunction claudeTools(): ClaudeTool[] {\n return [\n {\n name: 'make_payment',\n description: MAKE_PAYMENT_DESCRIPTION,\n input_schema: makePaymentSchema,\n },\n {\n name: 'get_payment_status',\n description: GET_STATUS_DESCRIPTION,\n input_schema: getPaymentStatusSchema,\n },\n {\n name: 'get_allowances',\n description: GET_ALLOWANCES_DESCRIPTION,\n input_schema: getAllowancesSchema,\n },\n {\n name: 'authorize_x402_payment',\n description: AUTHORIZE_X402_DESCRIPTION,\n input_schema: authorizeX402Schema,\n },\n {\n name: 'resume_x402_payment',\n description: RESUME_X402_DESCRIPTION,\n input_schema: resumeX402Schema,\n },\n {\n name: 'haven_sweep_delegate',\n description: SWEEP_DELEGATE_DESCRIPTION,\n input_schema: sweepDelegateSchema,\n },\n ]\n}\n\n// ── OpenAI format ────────────────────────────────────────────────\n\nexport interface OpenAITool {\n type: 'function'\n function: {\n name: string\n description: string\n parameters: {\n type: 'object'\n properties: Record<string, unknown>\n required: readonly string[]\n }\n }\n}\n\nfunction openaiTools(): OpenAITool[] {\n return [\n {\n type: 'function',\n function: {\n name: 'make_payment',\n description: MAKE_PAYMENT_DESCRIPTION,\n parameters: makePaymentSchema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'get_payment_status',\n description: GET_STATUS_DESCRIPTION,\n parameters: getPaymentStatusSchema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'get_allowances',\n description: GET_ALLOWANCES_DESCRIPTION,\n parameters: getAllowancesSchema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'authorize_x402_payment',\n description: AUTHORIZE_X402_DESCRIPTION,\n parameters: authorizeX402Schema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'resume_x402_payment',\n description: RESUME_X402_DESCRIPTION,\n parameters: resumeX402Schema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'haven_sweep_delegate',\n description: SWEEP_DELEGATE_DESCRIPTION,\n parameters: sweepDelegateSchema,\n },\n },\n ]\n}\n\n// ── Public API ───────────────────────────────────────────────────\n\nexport const havenTools = {\n /** Tool definitions in Anthropic/Claude format */\n claude: claudeTools,\n\n /** Tool definitions in OpenAI function-calling format */\n openai: openaiTools,\n}\n","/**\n * The generic Haven payment skill — canonical copy.\n *\n * This SDK file is the single source of truth for the generic, secret-free\n * skill content: no wallet address, no budget numbers, no per-agent values.\n * The agent learns its live budget at runtime via the `haven_get_agent` /\n * `haven_get_allowances` MCP tools, and can read identity + configured budget\n * for fast first-turn orientation from the non-secret `agent.json` the\n * connector writes (see `packages/connect/src/storage.ts`), so the same file\n * works for every user. `packages/connect` imports this directly to\n * auto-install the skill into runtime skills folders.\n *\n * `packages/frontend/src/lib/agent-skill-bundle.ts` keeps a deliberately\n * decoupled inline copy (the download fallback): frontend has zero\n * `@haven_ai/*` dependencies so it can deploy standalone on Vercel without an\n * unpublished SDK export. A parity test in that package's test suite imports\n * this canonical string and asserts byte-for-byte equality, so the two copies\n * cannot drift.\n */\n\nexport 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 — 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\\`) — 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\\` — 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 — 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 —\n\\`agent.json\\` shows the configured budget, not what is left after recent\nspending:\n\n- \\`mcp__haven__haven_get_agent\\` — 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\\` — 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 — this is\nnormal, not an error.\n\n## Paying\n\n**Catalog purchases — 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 — 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 — 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 — 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 —\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 — 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 — both or\nnone together, never just one. If the settle result carries \\`settled: false\\`,\nfunding is queued for the user's approval — 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\\` → \\`mcp__haven__haven_submit\\` →\n\\`mcp__haven-signer__haven_x402_sign_header\\` →\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 — 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\\` — 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 — a ceiling the\nmerchant settles at or below — 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 — 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 — 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 — 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 — 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\\` — 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`\n\n/** Directory name for the installed skill folder. */\nexport const SKILL_FOLDER_NAME = 'haven-pay'\n","/**\n * The Node.js floor Haven's published packages support (#1161).\n *\n * ## Why this lives in the SDK\n *\n * Three packages need to enforce the same floor — `connect` (at setup),\n * `signer` and `mcp` (at startup) — and `@haven_ai/sdk` is the only dependency\n * all three already share. A copy per package is how the floor drifted in the\n * first place: `engines` said `>=24` everywhere while connect's runtime manifest\n * enforced `20.0.0`, so a connect run on Node v23 passed the guard, installed\n * the signer, and signed a real payment. Two numbers for one fact is one number\n * too many.\n *\n * Each consumer still owns its own refusal — the error type, the exit code, the\n * wording of \"what to do next\" — because a library must never terminate its\n * host process. This module only answers *is this version supported* and *what\n * should we tell the user*.\n *\n * ## Why a floor is enforced at all\n *\n * `engines` is advisory: npm emits `EBADENGINE` and installs anyway unless the\n * user happens to have `engine-strict` set. For a normal library that is a\n * reasonable default. For the **signer** it is not — it holds the delegate key\n * and produces every payment signature, so a subtle runtime incompatibility\n * shows up as a wrong or missing signature on a money path. \"It seemed to work\"\n * is precisely the evidence that cannot be relied on there.\n */\n\n/**\n * The minimum supported Node.js version, as `major.minor.patch`.\n *\n * MUST equal the `engines.node` floor declared by every published Haven\n * package. A guard test in each package asserts exactly that against its own\n * `package.json`, so the two cannot drift again silently.\n */\nexport const HAVEN_MINIMUM_NODE_VERSION = '22.0.0'\n\n/** Parse `v22.1.0` / `22.1` / `22` into a comparable triple. */\nfunction parseNodeVersion(value: string): [number, number, number] {\n const match = value.trim().match(/^v?(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?/)\n if (!match) return [0, 0, 0]\n return [Number(match[1] ?? 0), Number(match[2] ?? 0), Number(match[3] ?? 0)]\n}\n\n/**\n * Compare two Node versions. Negative when `left` is older.\n *\n * An unparseable version parses to `0.0.0` and therefore compares as older than\n * any real floor — fail-closed. A version string Haven cannot read is not\n * evidence of a supported runtime, and treating it as one would reopen exactly\n * the hole this module closes.\n */\nexport function compareNodeVersions(left: string, right: string): number {\n const leftParts = parseNodeVersion(left)\n const rightParts = parseNodeVersion(right)\n for (let i = 0; i < 3; i += 1) {\n if (leftParts[i] !== rightParts[i]) return leftParts[i] > rightParts[i] ? 1 : -1\n }\n return 0\n}\n\nexport function isSupportedNodeVersion(\n nodeVersion: string = process.versions.node,\n minimumNodeVersion: string = HAVEN_MINIMUM_NODE_VERSION,\n): boolean {\n return compareNodeVersions(nodeVersion, minimumNodeVersion) >= 0\n}\n\nexport interface UnsupportedNodeVersionMessageOptions {\n /**\n * What is being refused, in the user's terms — \"Haven setup\", \"The Haven\n * signer\". Leads the message so the reader knows what just stopped.\n */\n subject: string\n nodeVersion?: string\n minimumNodeVersion?: string\n /** Appended verbatim as the closing line. Used for the re-run instruction. */\n retryHint?: string\n}\n\n/**\n * The refusal text.\n *\n * Names the detected version, the required version, and **how to fix it** — the\n * previous message stopped after the two version numbers, which tells a user\n * they are stuck without telling them how to get unstuck. The version-manager\n * lines are the fix for nearly everyone; the closing caveat is there because the\n * runtime that *spawns* the signer is frequently not the shell that was\n * upgraded, and a desktop app can keep launching the old Node long after\n * `node -v` in a terminal says otherwise.\n */\nexport function unsupportedNodeVersionMessage(\n options: UnsupportedNodeVersionMessageOptions,\n): string {\n const nodeVersion = options.nodeVersion ?? process.versions.node\n const minimum = options.minimumNodeVersion ?? HAVEN_MINIMUM_NODE_VERSION\n const lines = [\n `${options.subject} requires Node.js >=${minimum}, but this is Node.js ${nodeVersion}.`,\n '',\n 'Upgrade Node, then try again:',\n ` nvm install ${major(minimum)} && nvm use ${major(minimum)} (nvm)`,\n ` fnm install ${major(minimum)} && fnm use ${major(minimum)} (fnm)`,\n ` volta install node@${major(minimum)} (volta)`,\n ` or download Node ${major(minimum)} from https://nodejs.org`,\n '',\n 'If you use a version manager, check that the agent runtime launching Haven picks ' +\n 'up the same version — upgrading your shell does not always change what a desktop ' +\n 'app spawns.',\n ]\n if (options.retryHint) lines.push('', options.retryHint)\n return lines.join('\\n')\n}\n\nfunction major(version: string): string {\n return String(parseNodeVersion(version)[0])\n}\n","import { HavenSigningError } from './types.js'\n\n/**\n * Gasless delegate-sweep primitives — the single source of truth shared by the\n * edge signer (which signs) and the Haven backend (which relays).\n *\n * A stranded delegate EOA holds USDC but no ETH, so a raw ERC-20 transfer can't\n * pay for its own gas. Instead the delegate signs an *off-chain* EIP-3009\n * `TransferWithAuthorization` and the Haven relayer submits it on-chain and pays\n * gas. The relayer is only a gas payer: it holds no allowance and is never a\n * spender, so a relayer compromise cannot move user funds.\n *\n * Framework-neutral on purpose: `buildSweepTypedData` returns a plain\n * `{ domain, types, primaryType, message }` that both viem\n * (`signTypedData`/`recoverTypedDataAddress`) and ethers v6\n * (`signTypedData`/`verifyTypedData`) accept, so the signer (viem) and backend\n * (ethers) stay in lockstep without sharing a crypto library.\n */\n\n/** Base mainnet. The only chain Haven sweeps today. */\nexport const SWEEP_BASE_CHAIN_ID = 8453\n\n/** Base Sepolia testnet — used by the dev environment / QA harness. */\nexport const SWEEP_BASE_SEPOLIA_CHAIN_ID = 84532\n\n/** Canonical Circle USDC on Base (FiatTokenV2_2). */\nexport const SWEEP_BASE_USDC_ADDRESS =\n '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'\n\n/** Circle's canonical Base Sepolia testnet USDC. */\nexport const SWEEP_BASE_SEPOLIA_USDC_ADDRESS =\n '0x036CbD53842c5426634e7929541eC2318f3dCF7e'\n\n/**\n * EIP-712 domain per chain. `name`/`version` are the on-chain `FiatTokenV2_2`\n * values; a mismatch makes the relayer's `transferWithAuthorization` revert, so\n * each is pinned to the known-good, **on-chain-verified** USDC values. Base\n * mainnet is \"USD Coin\"/\"2\"; Base Sepolia is \"USDC\"/\"2\" (verified via `name()`/\n * `version()`). Add a chain here only after verifying its USDC EIP-712 domain.\n */\nconst USDC_EIP712_DOMAIN_BY_CHAIN: Record<number, SweepEip712Domain> = {\n [SWEEP_BASE_CHAIN_ID]: {\n name: 'USD Coin',\n version: '2',\n chainId: SWEEP_BASE_CHAIN_ID,\n verifyingContract: SWEEP_BASE_USDC_ADDRESS,\n },\n [SWEEP_BASE_SEPOLIA_CHAIN_ID]: {\n name: 'USDC',\n version: '2',\n chainId: SWEEP_BASE_SEPOLIA_CHAIN_ID,\n verifyingContract: SWEEP_BASE_SEPOLIA_USDC_ADDRESS,\n },\n}\n\n/** USDC contract per sweepable chain. */\nconst USDC_ADDRESS_BY_CHAIN: Record<number, string> = {\n [SWEEP_BASE_CHAIN_ID]: SWEEP_BASE_USDC_ADDRESS,\n [SWEEP_BASE_SEPOLIA_CHAIN_ID]: SWEEP_BASE_SEPOLIA_USDC_ADDRESS,\n}\n\n/** Sweepable chains, for error messages. */\nconst SWEEPABLE_CHAIN_IDS = Object.keys(USDC_ADDRESS_BY_CHAIN).map(Number)\n\n/** True when the gasless sweep supports a chain (its USDC domain + address are known). */\nexport function isSweepableChain(chainId: number): boolean {\n return chainId in USDC_ADDRESS_BY_CHAIN\n}\n\n/** EIP-712 `TransferWithAuthorization` struct, per EIP-3009. */\nexport const TRANSFER_WITH_AUTHORIZATION_TYPES = {\n TransferWithAuthorization: [\n { name: 'from', type: 'address' },\n { name: 'to', type: 'address' },\n { name: 'value', type: 'uint256' },\n { name: 'validAfter', type: 'uint256' },\n { name: 'validBefore', type: 'uint256' },\n { name: 'nonce', type: 'bytes32' },\n ],\n} as const\n\nexport interface SweepEip712Domain {\n name: string\n version: string\n chainId: number\n verifyingContract: string\n}\n\n/**\n * A fully-specified EIP-3009 authorization. All amounts/times are decimal\n * strings (JSON-safe) and `nonce` is a 0x-prefixed 32-byte hex value. `token`\n * and `chainId` are carried explicitly so the signer can assert they are\n * canonical before signing.\n */\nexport interface SweepAuthorization {\n /** Delegate EOA the funds are swept FROM. */\n from: string\n /** Originating Safe the funds are swept TO. */\n to: string\n /** Atomic USDC amount (decimal string). */\n value: string\n /** Unix seconds the authorization becomes valid (decimal string, usually \"0\"). */\n validAfter: string\n /** Unix seconds the authorization expires (decimal string). */\n validBefore: string\n /** Random 0x-prefixed 32-byte hex nonce. */\n nonce: string\n /** USDC contract address. */\n token: string\n /** Chain id (8453 today). */\n chainId: number\n}\n\n/**\n * Haven's signature over the sweep authorization context, signed with the same\n * binding key the x402 expected-context uses. Lets the edge signer verify the\n * authorization actually came from Haven (and wasn't crafted by a compromised\n * hosted server pointing `to` at an attacker) before it signs.\n */\nexport interface SweepExpectedAuth {\n /**\n * Currently always 1. Typed as `number` for the same reason as\n * `X402ExpectedAuth.version` (#1143): it is inbound, so a stale signer must be\n * able to *receive* an unknown version in order to report it. The signer's\n * `SUPPORTED_SWEEP_BINDING_VERSIONS` is the authority on what it will sign.\n */\n version: number\n message: string\n signature: string\n signer: string\n}\n\n/** What `POST /machine-payments/sweep/prepare` returns when funds are stranded. */\nexport interface SweepPreparation {\n authorization: SweepAuthorization\n expectedAuth: SweepExpectedAuth\n}\n\n/** Wire response from `POST /machine-payments/sweep/prepare` (snake_case). */\nexport interface SweepPrepareResponse {\n /** Present and true when the delegate holds nothing to recover. */\n nothing_stranded?: boolean\n /**\n * Present and true when the stranded balance is below the sweep floor (#700):\n * it is left on the delegate as dust rather than recovered, because the gas to\n * sweep it would exceed its value. `min_usdc` carries the configured floor. No\n * `authorization` is built.\n */\n below_min?: boolean\n min_usdc?: string\n /** The authorization to sign — absent when nothing is stranded or below the floor. */\n authorization?: SweepAuthorization\n /** Haven's binding over the authorization — absent when nothing is stranded. */\n expected_auth?: SweepExpectedAuth\n asset?: string\n amount?: string\n amount_atomic?: string\n chain_id: number\n sign_instructions?: string\n message?: string\n}\n\n/** Wire response from `POST /machine-payments/sweep/submit` (snake_case). */\nexport interface SweepSubmitResponse {\n tx_hash: string\n asset: string\n amount: string\n amount_atomic: string\n from_address: string\n to_address: string\n chain_id: number\n explorer_url: string\n idempotent_replay?: boolean\n}\n\n/** Result of a submitted gasless sweep. */\nexport interface SweepSubmitResult {\n txHash: string\n amount: string\n amountAtomic: string\n asset: string\n fromAddress: string\n toAddress: string\n chainId: number\n explorerUrl: string\n}\n\nexport interface SweepTypedData {\n domain: SweepEip712Domain\n types: typeof TRANSFER_WITH_AUTHORIZATION_TYPES\n primaryType: 'TransferWithAuthorization'\n message: {\n from: string\n to: string\n value: bigint\n validAfter: bigint\n validBefore: bigint\n nonce: string\n }\n}\n\n/** Resolve the canonical USDC contract for a sweepable chain, or throw. */\nexport function sweepUsdcAddress(chainId: number): string {\n const address = USDC_ADDRESS_BY_CHAIN[chainId]\n if (!address) {\n throw new HavenSigningError(\n `Sweep is not supported on chain ${chainId}. Supported: ${SWEEPABLE_CHAIN_IDS.join(', ')}.`,\n )\n }\n return address\n}\n\n/** Resolve the USDC EIP-712 domain for a sweepable chain, or throw. */\nexport function sweepUsdcDomain(chainId: number): SweepEip712Domain {\n const domain = USDC_EIP712_DOMAIN_BY_CHAIN[chainId]\n if (!domain) {\n throw new HavenSigningError(\n `Sweep is not supported on chain ${chainId}. Supported: ${SWEEPABLE_CHAIN_IDS.join(', ')}.`,\n )\n }\n return domain\n}\n\nfunction sameAddress(a: string, b: string): boolean {\n return a.toLowerCase() === b.toLowerCase()\n}\n\n/**\n * Build the EIP-712 typed data for an authorization, validating that the token\n * and chain are canonical (the domain's `verifyingContract` must match the\n * authorization's `token`). Returns bigint-valued fields so both viem and\n * ethers v6 sign/recover identically.\n */\nexport function buildSweepTypedData(auth: SweepAuthorization): SweepTypedData {\n const domain = sweepUsdcDomain(auth.chainId)\n const expectedToken = sweepUsdcAddress(auth.chainId)\n if (!sameAddress(auth.token, expectedToken)) {\n throw new HavenSigningError(\n `Sweep token ${auth.token} is not the canonical USDC contract for chain ${auth.chainId}.`,\n )\n }\n if (!/^0x[0-9a-fA-F]{64}$/.test(auth.nonce)) {\n throw new HavenSigningError('Sweep nonce must be a 0x-prefixed 32-byte hex string.')\n }\n return {\n domain,\n types: TRANSFER_WITH_AUTHORIZATION_TYPES,\n primaryType: 'TransferWithAuthorization',\n message: {\n from: auth.from,\n to: auth.to,\n value: BigInt(auth.value),\n validAfter: BigInt(auth.validAfter),\n validBefore: BigInt(auth.validBefore),\n nonce: auth.nonce,\n },\n }\n}\n\n/**\n * Canonical, deterministic string the backend signs and the signer re-derives\n * for the authorization binding. The `Haven sweep authorization v1` namespace\n * (and `kind`) is distinct from the x402 expected-context namespace so an x402\n * binding can never be replayed as a sweep authorization even though they share\n * a signing key.\n */\nexport function buildSweepAuthorizationMessage(auth: SweepAuthorization): string {\n return `Haven sweep authorization v1\\n${stableStringify({\n version: 1,\n kind: 'haven.sweep.authorization',\n from: auth.from.toLowerCase(),\n to: auth.to.toLowerCase(),\n value: auth.value,\n validAfter: auth.validAfter,\n validBefore: auth.validBefore,\n nonce: auth.nonce.toLowerCase(),\n token: auth.token.toLowerCase(),\n chainId: auth.chainId,\n })}`\n}\n\n/** Deterministic JSON: object keys sorted, no incidental whitespace. */\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value)\n if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(',')}]`\n const object = value as Record<string, unknown>\n return `{${Object.keys(object)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${stableStringify(object[key])}`)\n .join(',')}}`\n}\n","/**\n * #1271 / #1301: bounded same-origin merchant MCP endpoint discovery.\n *\n * An agent handed a BASE merchant URL previously had to hand-probe /, /mcp,\n * /sse, … until something answered 402. The demo merchant (and the #1266\n * contract) serves a machine-readable discovery document at\n * `/.well-known/haven-demo-merchant` (also at `/`) naming `mcp_url`. This\n * helper fetches ONLY those two fixed same-origin paths — no redirects\n * (`redirect: 'error'`), a 5 s timeout, a 64 KB read cap — and accepts the\n * document's `mcp_url` ONLY when it stays on the same origin as the input.\n * Anything else returns null and the caller reports the original probe\n * failure. Discovery finds endpoints; it carries no payment authority and an\n * off-origin `mcp_url` is never even fetched — this must not grow into a\n * general network scanner (SSRF bound, per the issue).\n *\n * Originally hosted-only (mcp-server, #1271). Moved here in #1301 so the\n * local/self-signed MCP package (`@haven_ai/mcp`) can share the EXACT same\n * bounded implementation instead of re-deriving discovery semantics —\n * behavior is byte-identical to the pre-move mcp-server copy; the #1271\n * contract tests in packages/mcp-server/src/tools.test.ts pass unmodified\n * against this moved implementation.\n */\nexport const MERCHANT_DISCOVERY_PATHS = ['/.well-known/haven-demo-merchant', '/'] as const\nexport const DISCOVERY_MAX_BYTES = 64 * 1024\n\nexport async function discoverMerchantMcpUrl(inputUrl: string): Promise<string | null> {\n let input: URL\n try {\n input = new URL(inputUrl)\n } catch {\n return null\n }\n for (const path of MERCHANT_DISCOVERY_PATHS) {\n try {\n const res = await globalThis.fetch(`${input.origin}${path}`, {\n method: 'GET',\n headers: { accept: 'application/json' },\n redirect: 'error',\n signal: AbortSignal.timeout(5_000),\n })\n if (!res.ok) continue\n const contentLength = Number(res.headers.get('content-length') ?? 0)\n if (contentLength > DISCOVERY_MAX_BYTES) continue\n const text = await res.text()\n if (text.length > DISCOVERY_MAX_BYTES) continue\n const doc = JSON.parse(text) as { mcp_url?: unknown }\n if (typeof doc.mcp_url !== 'string') continue\n const resolved = new URL(doc.mcp_url)\n if (resolved.origin !== input.origin) continue\n return resolved.toString()\n } catch {\n continue\n }\n }\n return null\n}\n\n/** Trailing-slash/percent-case echoes compare equal; unparseable never does. */\nexport function sameUrl(a: string, b: string): boolean {\n try {\n const ua = new URL(a)\n const ub = new URL(b)\n return ua.origin === ub.origin && ua.pathname.replace(/\\/+$/, '') === ub.pathname.replace(/\\/+$/, '')\n } catch {\n return false\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/types.ts","../src/signer.ts","../src/receipt.ts","../src/base64.ts","../src/sweep.ts","../src/x402.ts","../src/provider.ts","../src/client.ts","../src/tool-descriptions.ts","../src/tools.ts","../src/skill-content.ts","../src/node-version.ts","../src/merchant-discovery.ts"],"names":["ethers","signHash","stableStringify","sameAddress","recoverTypedDataAddress","createHash","hashTypedData","AsyncLocalStorage","receipt","privateKeyToAccount","exact"],"mappings":";;;;;;;;;;;;AAiuBO,IAAM,iBAAA,GAAoB;AAAA;AAAA,EAE/B,sBAAA,EAAwB,0BAAA;AAAA;AAAA,EAExB,gBAAA,EAAkB,mBAAA;AAAA;AAAA,EAElB,gBAAA,EAAkB,mBAAA;AAAA;AAAA,EAElB,oBAAA,EAAsB,wBAAA;AAAA;AAAA,EAEtB,qBAAA,EAAuB,yBAAA;AAAA;AAAA,EAEvB,6BAAA,EAA+B,kCAAA;AAAA;AAAA,EAE/B,WAAA,EAAa,cAAA;AAAA;AAAA,EAEb,QAAA,EAAU,UAAA;AAAA;AAAA,EAEV,OAAA,EAAS,SAAA;AAAA;AAAA,EAET,MAAA,EAAQ,QAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQR,iBAAA,EAAmB,oBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOnB,kBAAA,EAAoB;AACtB;AAIO,IAAM,sBAAA,GAAyB;AAAA;AAAA,EAEpC,oBAAA,EAAsB,yBAAA;AAAA;AAAA,EAEtB,gBAAA,EAAkB,oBAAA;AAAA;AAAA,EAElB,IAAA,EAAM,MAAA;AAAA;AAAA,EAEN,mBAAA,EAAqB,wBAAA;AAAA;AAAA,EAErB,4BAAA,EAA8B,mCAAA;AAAA;AAAA,EAE9B,wBAAA,EAA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C,CAAA;AACpB,IAAA,MAAM,EAAA,GAAK,IAAI,GAAA,CAAI,CAAC,CAAA;AACpB,IAAA,OAAO,EAAA,CAAG,MAAA,KAAW,EAAA,CAAG,MAAA,IAAU,GAAG,QAAA,CAAS,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAA,KAAM,EAAA,CAAG,QAAA,CAAS,OAAA,CAAQ,QAAQ,EAAE,CAAA;AAAA,EACtG,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF","file":"index.cjs","sourcesContent":["// ── Client Configuration ─────────────────────────────────────────\n\nexport interface HavenClientConfig {\n /** Haven API key (sk_agent_xxx) */\n apiKey: string\n\n /** Agent's delegate EOA private key. If provided, the SDK handles signing automatically. */\n delegateKey?: string\n\n /** Haven API base URL (default: http://localhost:3001) */\n baseUrl?: string\n\n /** Optional wallet identity to send as the x402-wallet header. */\n x402Wallet?: string\n\n /** Timeout in ms for individual HTTP requests (default: 30000) */\n requestTimeout?: number\n /** Timeout (ms) for MERCHANT-facing requests — x402/MPP probes, MCP\n * handshakes, paid retries. Separate from requestTimeout (Haven API):\n * merchants may settle on-chain synchronously, so the default is\n * deliberately generous. #1300. */\n merchantTimeout?: number\n\n /** Timeout in ms when polling for tx confirmation (default: 90000) */\n confirmationTimeout?: number\n\n /** Polling interval in ms when waiting for confirmation (default: 3000) */\n pollingInterval?: number\n\n /**\n * Extra headers to attach to every request to the Haven API.\n *\n * Used by the MCP server to tag requests with `X-Haven-MCP-Tool: <name>`\n * so the backend can record an audit-log entry per tool invocation. Has\n * no effect on outbound merchant requests (x402 / MPP) — those are\n * standard HTTP and never carry Haven-internal headers.\n */\n defaultHeaders?: Record<string, string>\n\n /**\n * JSON-RPC RPC URLs keyed by EIP-155 chain ID.\n *\n * When provided for a chain, the SDK waits for ≥1 on-chain confirmation of\n * the AllowanceModule funding tx before retrying the merchant. This prevents\n * the race where the merchant's `balanceOf(delegate)` call runs before the\n * funding block has propagated to the merchant's RPC node.\n *\n * Without this option the SDK proceeds as soon as Haven's backend confirms\n * submission (backward-compatible default). Set it to a reliable RPC\n * endpoint (e.g. Alchemy / Infura) for production usage.\n *\n * @example { 8453: 'https://mainnet.base.org' }\n */\n chainRpcs?: Record<number, string>\n}\n\n// ── Payment Types ────────────────────────────────────────────────\n\nexport interface PaymentRequest {\n /** Token symbol: \"EURe\", \"USDC.e\", or \"xDAI\" */\n token: string\n\n /** Amount as a decimal string, e.g. \"5.00\" */\n amount: string\n\n /** Recipient Ethereum address (0x...) */\n to: string\n\n /**\n * Optional dedupe key (#1207): a retried request with the same key returns\n * the FIRST request's result instead of minting a second transfer or a\n * second approval. Same contract as /machine-payments/send. Max 128 chars.\n */\n idempotencyKey?: string\n}\n\nexport interface SignData {\n /** The hash to sign (keccak256, 0x-prefixed) */\n hash: string\n\n /**\n * Delegation rail: 'eip712_userop' (funding redemption) or\n * 'eip712_delegation' (erc7710 settlement child). Absent = legacy\n * AllowanceModule (raw ECDSA over `hash`). The session rail's\n * 'eip191_userop' is retired (#834).\n *\n * When present, `hash` is NOT what gets signed — `typed_data` is (#1138).\n */\n signature_scheme?: 'eip712_userop' | 'eip712_delegation'\n\n /**\n * EIP-712 payload the account validates, signed VERBATIM (#829). Present\n * whenever `signature_scheme` is — never reconstruct it from `components`.\n */\n typed_data?: {\n domain: Record<string, unknown>\n types: Record<string, unknown>\n primaryType: string\n message: Record<string, unknown>\n }\n\n /** Breakdown of values that were hashed — useful for debugging */\n components: {\n safe: string\n token: string\n to: string\n amount: string\n payment_token: string\n payment: string\n nonce: number\n }\n\n /** Human-readable signing instructions */\n instructions: string\n}\n\nexport interface PaymentIntent {\n /** Unique payment ID */\n paymentId: string\n\n /** Current status */\n status: 'pending_signature'\n\n /** ISO 8601 expiry timestamp */\n expiresAt: string\n\n /** Data needed to sign the payment */\n signData: SignData\n}\n\nexport type PaymentStatus =\n | 'pending_signature'\n | 'submitted'\n | 'confirmed'\n | 'pending_approval'\n | 'approved'\n | 'proposed'\n | 'executed'\n | 'rejected'\n | 'expired'\n | 'failed'\n\nexport interface PaymentResult {\n /** Unique payment ID */\n paymentId: string\n\n /** Final status */\n status: PaymentStatus\n\n /** Token that was sent */\n token: string\n\n /** Amount that was sent (human-readable) */\n amount: string\n\n /** Recipient address */\n to: string\n\n /** On-chain transaction hash (present when confirmed) */\n txHash: string | null\n\n /** Error message (present when failed) */\n errorMessage: string | null\n\n /** Block explorer URL for the transaction (chain-dependent) */\n explorerUrl: string | null\n\n /** ISO 8601 timestamps */\n createdAt: string\n signedAt: string | null\n submittedAt: string | null\n confirmedAt: string | null\n expiresAt: string\n\n /**\n * Platform fee surfaced on the result so it's never silently collected. Dark\n * today (`amount` \"0\", `applied` false); always present so it's visible the\n * moment fees go live.\n */\n fee?: PaymentFee | null\n}\n\n/** The Haven platform fee applied to a payment (#386). */\nexport interface PaymentFee {\n /** Human-readable fee amount (\"0\" while the fee module is dark). */\n amount: string\n /** Token the fee is denominated in. */\n token: string\n /** Fee as basis points of gross (0 while dark). */\n basisPoints: number\n /** True when a non-zero fee was actually applied. */\n applied: boolean\n}\n\n// ── x402 Types ──────────────────────────────────────────────────\n\n/** Payment requirements from an HTTP 402 response (x402 protocol). */\nexport interface X402PaymentRequired {\n x402Version: number\n resource: {\n url: string\n description?: string\n mimeType?: string\n }\n accepts: X402PaymentOption[]\n error?: string\n extensions?: Record<string, unknown>\n}\n\n/** A single payment option from x402 PaymentRequired. */\nexport interface X402PaymentOption {\n scheme: string // \"exact\"\n network: string // CAIP-2 chain ID or x402 network, e.g. \"eip155:8453\" or \"base\"\n amount: string // Atomic units\n maxAmountRequired?: string // Atomic units (official x402 field)\n resource?: string\n description?: string\n mimeType?: string\n asset: string // Token contract address\n payTo: string // Recipient address\n maxTimeoutSeconds: number\n /**\n * Merchant-supplied scheme metadata. Two keys are load-bearing for Haven\n * (#1453), both from MetaMask's erc7710 x402 shape:\n *\n * assetTransferMethod — 'erc7710' marks this entry as settleable by\n * redeeming a delegation chain. Absent/other means\n * the standard EIP-3009 authorization.\n * facilitatorAddresses — who may redeem it, pinned into the settlement\n * child's redeemer caveat (#1058).\n *\n * Left as an open record on purpose: the field is the merchant's, and\n * narrowing it to Haven's two keys would silently drop everything else a\n * merchant sends. Read it through `x402AssetTransferMethod` /\n * `x402FacilitatorAddresses` rather than indexing it raw.\n */\n extra?: Record<string, unknown>\n}\n\n/** Receipt returned after a successful x402 payment. */\nexport interface X402Receipt {\n success: boolean\n paymentId: string\n txHash: string\n token: string\n amount: string\n to: string\n resourceUrl: string\n explorerUrl: string\n accepted?: X402PaymentOption\n paymentHeader?: string\n merchantTo?: string | null\n payer?: string\n chainId?: number\n haven?: {\n paymentId: string\n fundingTxHash: string\n fundingExplorerUrl: string\n }\n merchant?: {\n payTo: string | null\n settlementTxHash?: string | null\n settlementExplorerUrl?: string | null\n }\n x402?: {\n amount: string\n token: string\n network: string\n asset: string\n resource: string\n }\n}\n\nexport interface X402AuthorizationOptions {\n /** Stable caller-supplied key for this user intent. Prevents duplicate approvals across fresh 402 quotes. */\n idempotencyKey?: string\n /**\n * #1307: the merchant MCP-tool call context this quote was made against\n * (merchant_url, tool_name, arguments, mcp_transport). Persisted on the\n * intent so `getX402MerchantCallContext` can rehydrate it by payment_id at\n * settle/complete time instead of the caller re-threading it. Optional —\n * omit for a non-MCP-tool x402 merchant (plain HTTP resource).\n */\n mcpCallContext?: X402McpCallContext\n /**\n * #1348: the agent's delegate address, when the caller already resolved it\n * from `getAgent()` in this same flow — skips `createX402Intent`'s internal\n * agent fetch (one full round trip on every guided purchase). Staleness\n * caveat (#1358 review): the backend derives the funding shape by comparing\n * `payTo` to the CURRENT delegate address, so a value made stale by a\n * delegate rotation mid-flow is not always a clean failure — a pinned-budget\n * agent gets a 403, but an open-budget delegation agent would route to the\n * settlement shape with the stale address. The window is one tool call\n * (previously sub-millisecond, now the merchant-quote duration), never\n * externally suppliable; server-truth hardening is tracked in #1360. Only\n * pass an address fetched in THIS flow; omit to keep the self-contained\n * fetch.\n */\n delegateAddress?: string\n}\n\n/**\n * Keyless x402 construct result.\n *\n * Returned by `createX402Intent` — the non-custodial half of an x402 payment.\n * It carries the unsigned funding hash (`signData.hash`, Safe → delegate EOA)\n * plus everything the *edge* needs to build and sign the EIP-3009 merchant\n * header itself. The construct path never signs; both delegate signatures\n * (funding hash + merchant header) happen on the machine that holds the key.\n */\nexport interface X402Intent {\n /** Haven payment id for the funding transfer. */\n paymentId: string\n /** Stable key used to create or refresh this x402 funding intent. */\n idempotencyKey: string\n status: 'pending_signature'\n /** ISO 8601 expiry of the funding intent, if returned. */\n expiresAt?: string\n /** The unsigned funding hash to sign with the delegate key (Safe → delegate EOA). */\n signData: SignData\n /** The selected x402 option — the edge needs this to build the EIP-3009 header. */\n accepted: X402PaymentOption\n /** Resource URL the 402 came from. */\n resourceUrl: string\n /** Merchant payTo address (the final recipient of the EIP-3009 transfer). */\n merchantTo: string\n /** Atomic amount the edge signer must authorize in the merchant header. */\n amountAtomic: string\n /** Token contract the merchant header must pay. */\n asset: string\n /** x402 network the merchant header must use. */\n network: string\n /** Haven-authenticated binding over the x402 expected context. */\n expectedAuth: X402ExpectedAuth\n /**\n * EIP-712 digest of `signData.typed_data`, present on the delegation rail\n * (#1138). The edge signer needs it to reconstruct the v2 expected-context\n * message that Haven signed.\n */\n expectedTypedDataHash?: string\n /** Delegate EOA the funding transfer tops up (the x402 payer). */\n fundingTo: string\n}\n\nexport interface X402ExpectedContext {\n paymentId: string\n payloadHash: string\n resourceUrl: string\n merchantTo: string\n amount: string\n asset: string\n network: string\n /** Optional ISO expiry for the funding/quote window. When present, it is bound into the Haven-authenticated context. */\n expiresAt?: string\n /**\n * EIP-712 digest of the typed data the account actually validates\n * (delegation rail, #1138). Present ⇒ the context is **version 2** and the\n * signer must sign that typed data, never `payloadHash`.\n *\n * On the delegation rail `payloadHash` is the bare ERC-4337 UserOp hash,\n * which is NOT what the account validates — binding it alone would leave the\n * edge signer unable to verify the payload it is being asked to sign. Binding\n * this digest makes Haven's declaration cover the real payload.\n */\n typedDataHash?: string\n}\n\nexport interface X402ExpectedAuth {\n /**\n * 1 = hash-only (legacy rail). 2 = carries `typedDataHash` (delegation rail,\n * #1138).\n *\n * Deliberately `number`, not a literal union (#1143). This is an **inbound**\n * value: a signer parses a context Haven produced, and a signer older than the\n * backend will legitimately receive a version it does not know. A closed union\n * makes that state unrepresentable, which pushed the rejection down to the\n * schema boundary and produced a raw validation error naming neither the cause\n * nor the fix. The supported set lives in the signer\n * (`SUPPORTED_X402_EXPECTED_VERSIONS`), which fails closed on anything outside\n * it with an actionable message.\n */\n version: number\n message: string\n signature: string\n signer: string\n}\n\n/** Serializable HTTP request state for retrying the same x402 merchant request. */\nexport interface X402RequestSnapshot {\n url: string\n method: string\n headers: [string, string][]\n body?: string\n}\n\nexport interface X402McpTransport {\n handshakeRequired: boolean\n source: 'path' | 'bazaar'\n}\n\n/**\n * #1307: the merchant MCP-tool call an x402 quote was made against — carried\n * through `createX402Intent`'s options so Haven can persist it for the\n * settle-leg rehydration handoff (`getX402MerchantCallContext`). Convenience\n * metadata for retrying the merchant's OWN JSON-RPC call, never payment\n * authority.\n */\nexport interface X402McpCallContext {\n merchantUrl: string\n toolName: string\n arguments?: Record<string, unknown>\n mcpTransport?: X402McpTransport\n}\n\n/**\n * Response shape of `getX402MerchantCallContext` — the stored merchant call\n * context for a payment_id, rehydrated instead of re-threaded (#1307).\n */\nexport interface X402MerchantCallContext {\n paymentId: string\n merchantUrl: string\n toolName: string\n arguments: Record<string, unknown>\n mcpTransport?: X402McpTransport\n}\n\n/** @internal */\nexport interface RawX402MerchantCallContext {\n payment_id: string\n merchant_url: string\n tool_name: string\n arguments?: Record<string, unknown>\n mcp_transport?: { handshake_required: boolean; source: 'path' | 'bazaar' }\n error?: string\n error_code?: string\n status?: string\n}\n\n/** Quote parsed from an HTTP 402 response without creating a Haven payment. */\nexport interface X402Quote {\n rail: 'x402'\n idempotencyKey: string\n paymentRequired: X402PaymentRequired\n accepted: X402PaymentOption\n request: X402RequestSnapshot\n mcpTransport?: X402McpTransport\n resourceUrl: string\n description: string | null\n mimeType: string | null\n amountAtomic: string\n amount: string\n token: string\n /**\n * #1351: decimals for `asset` on `network`, resolved from the SAME\n * address→token binding that produced `token` — the quote's own authority on\n * how many atomic units one human unit is. `null` when the merchant's asset\n * is not a token Haven recognises on that network, in which case `token` is\n * an unverified fallback label and NO human→atomic conversion is safe.\n * Consumers converting a human-denominated figure (a user-intent spending\n * cap) MUST fail closed on `null` rather than assume 6.\n */\n decimals: number | null\n asset: string\n network: string\n chainId: number | null\n merchantAddress: string\n maxTimeoutSeconds: number\n}\n\n/** State bundle an agent can persist while waiting for manual x402 approval. */\nexport interface X402ResumeState {\n rail: 'x402'\n paymentId: string\n idempotencyKey: string\n paymentRequired: X402PaymentRequired\n accepted: X402PaymentOption\n url: string\n request?: X402RequestSnapshot\n resourceUrl: string\n description: string | null\n amountAtomic: string\n amount: string\n token: string\n asset: string\n network: string\n chainId: number | null\n merchantAddress: string\n}\n\n// #1328: MppAuthorizationOptions / MppQuote / MppResumeState / ResumeAuthorizedMppInput\n// / ResumeMppPaymentInput / MachinePaymentChallenge / MachinePaymentReceipt were\n// the wire types for the retired mpp_demo challenge/quote/resume client surface\n// (`quoteMpp` / `payMppChallenge` / `resumeMppPayment` / `authorizeMachinePayment`,\n// all removed from client.ts). `MachinePaymentRail` stays — it is still the read-path\n// vocabulary for historical payment/evidence/status rows (mpp_demo, mpp_crypto,\n// stripe_deposit, spt all remain valid values there).\n\nexport type PaymentResumeState = X402ResumeState\n\nexport interface ResumeAuthorizedX402Input extends X402AuthorizationOptions {\n /** Payment or approval request ID returned by authorizeX402 / haven.fetch. */\n paymentId: string\n\n /** Original or freshly parsed x402 requirements for the merchant retry. */\n paymentRequired: X402PaymentRequired\n}\n\nexport interface ResumeX402PaymentInput extends X402AuthorizationOptions {\n /** Payment or approval request ID returned by authorizeX402 / haven.fetch. */\n paymentId: string\n\n /** Original paid URL. If paymentRequired is omitted, Haven will call it once to re-read the 402 challenge. */\n url: string\n\n /** Original fetch options. Reused for the 402 probe and final merchant retry. */\n init?: RequestInit\n\n /** Serializable original request captured by quoteX402() / pending approval errors. */\n request?: X402RequestSnapshot\n\n /** Original or freshly parsed x402 requirements. Supplying this avoids an extra merchant 402 probe. */\n paymentRequired?: X402PaymentRequired\n}\n\n// ── Machine Payment Types ───────────────────────────────────────\n//\n// The wire-shape TYPES for the retired mpp_demo challenge/quote/resume\n// client surface (MachinePaymentChallenge, MachinePaymentReceipt,\n// MppAuthorizationOptions, ResumeAuthorizedMppInput, ResumeMppPaymentInput)\n// were removed with it (#1328). MachinePaymentRail stays: it is still the\n// read-path vocabulary on historical payment/evidence/status responses.\n\nexport type MachinePaymentRail =\n | 'x402'\n | 'mpp_demo'\n | 'mpp_crypto'\n | 'stripe_deposit'\n | 'spt'\n\nexport interface HavenAgent {\n id: string\n name: string\n status: string\n safeAddress: string\n delegateAddress: string\n chainId: number\n /**\n * Which on-chain policy primitive gates this agent's spend (#1306): the\n * legacy Safe AllowanceModule (import-only accounts) or the delegation\n * rail's active budget delegations (#1090). Read-only reporting — the\n * on-chain state is the actual gate either way, this only says which\n * mechanism a caller should read/derive from.\n */\n executionRail: 'legacy' | 'delegation'\n}\n\nexport interface HavenAllowance {\n id: string\n tokenAddress: string\n tokenSymbol: string\n configuredAmount: string\n resetPeriodMin: number\n onchain: {\n amount: string\n spent: string\n remaining: string\n effectiveSpent: string\n resetTimeMin: number\n lastResetMin: number\n nonce: number\n isResetPending: boolean\n /**\n * Delegation rail only (#1319, provenance for #1145's fallback): true\n * when `remaining` came from a live on-chain enforcer read, false when\n * the read failed and `remaining` is the fallback full configured\n * budget. Undefined on the legacy AllowanceModule rail, which has no\n * fallback concept. Reporting only — the on-chain policy remains the\n * actual spend gate either way.\n */\n remainingIsFromChain?: boolean\n }\n}\n\nexport interface HavenAllowanceSummary {\n agentId: string\n safeAddress: string\n delegateAddress: string\n chainId: number\n allowances: HavenAllowance[]\n}\n\n/**\n * Post-purchase allowance/budget summary attached to a settled x402 payment\n * (#1310). Read-only reporting — the on-chain policy remains the actual\n * spend gate either way, this only says what is left after the purchase.\n *\n * Deliberately the SAME rail-labeled field spelling as #1306's\n * catalog-purchase preflight `allowance` block (never a new spelling),\n * minus the preflight-only `sufficient` field: post-purchase reporting\n * answers \"what is left\", not \"was this purchase covered\". Read through the\n * exact same source as {@link HavenAllowanceSummary} / `haven_get_allowances`\n * (`GET /machine-payments/allowances`; delegation-rail values are the #1090\n * `deriveDelegationBudgets`-backed enforcer read, never `agent_allowances`),\n * so this can never disagree with `haven_get_allowances` for the same\n * fixture.\n */\nexport interface PostPurchaseAllowanceSummary {\n /** Which on-chain policy primitive gates this agent's spend (#1306 labeling). */\n rail: 'legacy' | 'delegation'\n /** Remaining atomic units, read through the same source as {@link HavenAllowance.onchain.remaining}. */\n remaining_atomic: string\n /** Human-readable remaining, e.g. \"4.96 USDC\". Omitted when the token's decimals are unknown. */\n remaining_display?: string\n token_symbol?: string\n token_address?: string\n /** Minutes — mirrors {@link HavenAllowance.resetPeriodMin} / the delegation's period. */\n reset_period?: number\n source: 'allowance_module' | 'active_delegations'\n}\n\n/**\n * Affirmative spend-readiness for the authenticated agent, derived from the raw\n * agent status plus the remaining spend authority the backend reports per rail\n * (the on-chain AllowanceModule on the legacy rail; the active budget\n * delegation on the delegation rail — #1135):\n * - `ready` — active and at least one token has remaining spend authority.\n * - `needs_approval`— active but no remaining spend authority to auto-spend.\n * The over-budget outcome differs by rail: on the legacy\n * AllowanceModule rail the payment is queued for the wallet\n * owner to approve in Haven; on the delegation rail there is\n * NO approval queue — an over-budget redemption reverts\n * on-chain, so the owner must grant or raise the budget in\n * Haven before the agent can pay.\n * - `revoked` — the agent's status is not `active`; nothing auto-executes.\n *\n * Note: a hard-paused/disabled credential is rejected by the API before this\n * call returns, so it surfaces as an API error rather than `revoked`. `revoked`\n * is reached when the request authenticates but the agent status is non-active.\n *\n * Wallet token balance is intentionally NOT folded in here: the on-chain\n * remaining allowance is the gate Haven enforces, and insufficient wallet\n * funding surfaces at pay time as INSUFFICIENT_FUNDS.\n */\nexport type HavenAgentReadiness = 'ready' | 'needs_approval' | 'revoked'\n\n/** Compact, agent-facing per-token spend authority for the bootstrap summary. */\nexport interface HavenAgentAllowanceSummary {\n tokenSymbol: string\n /** Live on-chain remaining allowance in atomic units. */\n remainingAtomic: string\n /** Human-readable remaining, e.g. \"4.96 USDC\". */\n remainingDisplay: string\n /** Configured allowance amount (atomic) the owner granted. */\n configuredAmount: string\n resetPeriodMin: number\n isResetPending: boolean\n}\n\n/**\n * One-shot \"am I ready?\" bootstrap: identity + live spend authority + a\n * readiness signal, so an agent can answer \"who am I and can I pay right now\"\n * from a single call at session start. Superset of {@link HavenAgent}.\n */\nexport interface HavenAgentSummary extends HavenAgent {\n readiness: HavenAgentReadiness\n allowances: HavenAgentAllowanceSummary[]\n}\n\nexport interface HavenPaymentReceipt {\n id: string\n paymentId: string\n paymentIntentId?: string | null\n approvalRequestId?: string | null\n rail: string\n proofStatus: string\n txHash: string\n chainId: number\n resourceUrl: string\n merchantAddress: string | null\n payerAddress: string\n settlementAddress: string\n tokenSymbol: string\n tokenAddress: string\n amountRaw: string\n amount: string\n challengeId: string | null\n idempotencyKey: string | null\n challengePayload?: Record<string, unknown> | null\n selectedPayment?: Record<string, unknown> | null\n paymentProofHeaderName: string | null\n protocolReceiptHeaderName: string | null\n protocolReceiptPayload?: Record<string, unknown> | null\n merchantStatus: number | null\n confirmedAt: string | null\n createdAt: string\n updatedAt: string\n}\n\n// ── Delegate Sweep Types ─────────────────────────────────────────\n\n/** One transferred asset in a delegate sweep. */\nexport interface SweepEntry {\n /** 'USDC' or 'ETH' */\n asset: string\n /** Human-readable amount swept (e.g. \"0.12\") */\n amount: string\n /** Atomic amount swept */\n amountAtomic: string\n /** Transaction hash of the sweep transfer */\n txHash: string\n /** Block explorer URL for the tx */\n explorerUrl: string\n}\n\n/** Result of a `sweepDelegate()` call. */\nexport interface SweepResult {\n /** Address funds were swept FROM */\n fromAddress: string\n /** Address funds were swept TO (always the originating Safe) */\n toAddress: string\n /** Chain the sweep occurred on */\n chainId: number\n /** One entry per transferred asset. Empty when nothing was stranded. */\n transfers: SweepEntry[]\n}\n\n// ── Agent Payment State Types ────────────────────────────────────\n\nexport type PaymentStateKind = 'payment_intent' | 'approval_request'\n\nexport interface AgentPaymentEnumSchema {\n type: 'string'\n enum: readonly string[]\n description: string\n 'x-enumDescriptions': Record<string, string>\n}\n\nexport const AgentPaymentPhase = {\n /** The agent must sign and submit the prepared payment before Haven can relay it. */\n AgentSignatureRequired: 'agent_signature_required',\n /** Haven has received the signed payment and the agent should poll for confirmation. */\n PaymentSubmitted: 'payment_submitted',\n /** The direct payment is confirmed; the agent does not need to do more for this payment id. */\n PaymentConfirmed: 'payment_confirmed',\n /** The payment needs wallet owner approval in Haven before it can continue. */\n UserApprovalRequired: 'user_approval_required',\n /** The wallet owner approved the request and still needs to complete the funding payment. */\n UserExecutionRequired: 'user_execution_required',\n /** The funding payment was proposed and is waiting for the remaining account approvals. */\n WaitingForAdditionalApprovals: 'waiting_for_additional_approvals',\n /** The Haven funding leg was sent; the agent can continue the merchant/protocol leg. */\n FundingSent: 'funding_sent',\n /** The wallet owner rejected the request; the agent should stop and tell the user. */\n Rejected: 'rejected',\n /** The payment or approval request expired before completion. */\n Expired: 'expired',\n /** Haven could not complete the payment; the agent should stop and surface the failure. */\n Failed: 'failed',\n /**\n * Pre-flight check determined the delegate's existing balance plus the\n * remaining on-chain allowance cannot cover the requested amount, so no\n * payment intent was created. Distinct from `UserApprovalRequired`: there\n * is no approval that would fix this — the originating Safe needs more\n * funds or the agent's per-token allowance needs to be raised first.\n */\n InsufficientFunds: 'insufficient_funds',\n /**\n * Haven's funding leg (Safe → delegate) confirmed on-chain, but the\n * merchant rejected the x402 retry. The delegate wallet may hold stranded\n * USDC that was never settled to the merchant. The agent should stop, tell\n * the user, and wait for the sweep flow to reclaim the funds.\n */\n FundedButUnsettled: 'funded_but_unsettled',\n} as const\n\nexport type AgentPaymentPhase = (typeof AgentPaymentPhase)[keyof typeof AgentPaymentPhase]\n\nexport const AgentPaymentNextAction = {\n /** Sign with the delegate key and submit the payment to Haven. */\n SignAndSubmitPayment: 'sign_and_submit_payment',\n /** Poll getPaymentStatus later using this payment id. */\n CheckStatusLater: 'check_status_later',\n /** No further agent action is required for this payment id. */\n None: 'none',\n /** Wait for the wallet owner to approve or reject the request in Haven. */\n WaitForUserApproval: 'wait_for_user_approval',\n /** Wait for the wallet owner to finish sending the approved funding payment. */\n WaitForUserToCompletePayment: 'wait_for_user_to_complete_payment',\n /** Resume this payment id and retry the original x402 request with the merchant payment header. */\n RetryOriginalX402Request: 'retry_original_x402_request',\n /** Stop retrying this payment and tell the user what happened. */\n StopAndTellUser: 'stop_and_tell_user',\n /** Ask again only if the user still wants the payment after expiry. */\n RequestAgainIfUserStillWantsIt: 'request_again_if_user_still_wants_it',\n /** #1307: retry the SAME tool call, supplying the explicit context fields the server could not rehydrate. */\n RetryWithExplicitContext: 'retry_with_explicit_context',\n /**\n * The x402 funding/quote window expired. Re-quote the same logical merchant\n * operation with the same idempotency key to stay double-charge-safe.\n */\n PaymentWindowExpired: 'payment_window_expired',\n /**\n * Stop and tell the user that the originating Safe needs to be funded or\n * the agent's per-token allowance needs to be raised before the payment\n * can succeed. A user approval will not fix this state on its own.\n */\n FundSafeOrRaiseAllowance: 'fund_safe_or_raise_allowance',\n /**\n * The delegate wallet may hold funds that were sent from the Safe but never\n * settled to the merchant. The wallet owner should initiate a sweep to\n * return those funds to the originating Safe.\n */\n SweepStrandedFunds: 'sweep_stranded_funds',\n} as const\n\nexport type AgentPaymentNextAction = (typeof AgentPaymentNextAction)[keyof typeof AgentPaymentNextAction]\n\nexport const AgentPaymentFailureCode = {\n /** A merchant-authoritative x402 price exceeds the caller's pre-funding max_amount cap. */\n PriceExceedsMax: 'PRICE_EXCEEDS_MAX',\n /** The x402 funding/quote window expired before the signer or hosted settle step could finish. */\n PaymentWindowExpired: 'PAYMENT_WINDOW_EXPIRED',\n /** The Haven funding leg succeeded, but the merchant rejected the paid retry. */\n MerchantRejectedAfterFunding: 'MERCHANT_REJECTED_AFTER_FUNDING',\n /** #1300 review: funding is on-chain but the merchant never ANSWERED the\n * paid retry within the timeout. NOT proof of rejection — the merchant\n * holds a valid EIP-3009 authorization and may still settle late, so the\n * guidance is verify-then-sweep, never blind sweep. */\n MerchantUnresponsiveAfterFunding: 'MERCHANT_UNRESPONSIVE_AFTER_FUNDING',\n /**\n * #1307: the caller omitted merchant_url/tool_name (asking Haven to\n * rehydrate the stored MCP merchant-call context by payment_id), but no\n * usable context was stored for this intent — either it was never an\n * MCP-tool quote, or the stored context is incomplete. The fallback is\n * mechanical: re-send merchant_url, tool_name, arguments, and\n * mcp_transport explicitly (the version-skew path).\n */\n MerchantCallContextUnavailable: 'MERCHANT_CALL_CONTEXT_UNAVAILABLE',\n /**\n * #1351: the caller supplied BOTH the atomic `max_amount` and the\n * human-denominated `max_amount_human` cap for one purchase. Haven refuses\n * to guess which the user meant — the two differ by a factor of 10^decimals,\n * so picking wrong is exactly the silent-overspend this cap exists to\n * prevent. Rejected before any merchant probe, funding intent, or signature.\n */\n AmbiguousMaxAmount: 'AMBIGUOUS_MAX_AMOUNT',\n /**\n * #1351: a human-denominated cap was supplied, but it cannot be converted to\n * atomic units against THIS quote — either the quote's asset has no known\n * decimals on its network, or the cap carries more fraction digits than the\n * asset can represent (truncating it would silently change the user's cap).\n * The fallback is the exact atomic `max_amount`.\n */\n MaxAmountUnconvertible: 'MAX_AMOUNT_UNCONVERTIBLE',\n} as const\n\nexport type AgentPaymentFailureCode = (typeof AgentPaymentFailureCode)[keyof typeof AgentPaymentFailureCode]\n\n/**\n * Stable rail identifier carried on Haven agent payment responses and resume\n * state.\n *\n * Two layers of vocabulary share this enum because both reach the wire:\n *\n * - **Categorical rails** identify the rail family and are used as the\n * `PaymentResumeState` discriminator: `direct`, `x402` (`mpp` remains a\n * valid categorical VALUE on historical status reads, but #1328 retired\n * the `MppResumeState` variant that used to carry it — the mpp_demo\n * client resume flow no longer exists).\n * - **Granular rails** identify the specific protocol the backend persists\n * and returns on response bodies: `mpp_demo`, `mpp_crypto`,\n * `stripe_deposit`, `spt`. `x402` doubles as both categorical and\n * granular.\n *\n * Consumers reading the top-level `rail` field on a payment status response\n * should treat any `mpp*` value as the MPP family — this still applies to\n * historical `mpp_demo` rows, which remain readable.\n */\nexport const AgentPaymentRail = {\n /** Standard Haven payment from the user's Safe through an approved delegate allowance. */\n Direct: 'direct',\n /** x402 HTTP 402 payment flow with a Haven funding leg and merchant retry leg. */\n X402: 'x402',\n /** Machine Payment Protocol family — categorical value used as a resume-state discriminator. */\n Mpp: 'mpp',\n /** Haven internal MPP demo rail. Not for production traffic. */\n MppDemo: 'mpp_demo',\n /** Crypto-settled MPP rail. */\n MppCrypto: 'mpp_crypto',\n /** Stripe-deposit-backed MPP rail. */\n StripeDeposit: 'stripe_deposit',\n /** Stripe Payment Token MPP rail. */\n Spt: 'spt',\n} as const\n\nexport type AgentPaymentRail = (typeof AgentPaymentRail)[keyof typeof AgentPaymentRail]\n\nexport type PaymentPhase = AgentPaymentPhase\n\nexport type PaymentNextAction = AgentPaymentNextAction\n\nexport const AGENT_PAYMENT_PHASE_VALUES = Object.values(AgentPaymentPhase)\n\nexport const AGENT_PAYMENT_NEXT_ACTION_VALUES = Object.values(AgentPaymentNextAction)\n\nexport const AGENT_PAYMENT_FAILURE_CODE_VALUES = Object.values(AgentPaymentFailureCode)\n\nexport const AGENT_PAYMENT_RAIL_VALUES = Object.values(AgentPaymentRail)\n\nexport const AgentPaymentPhaseDescriptions: Record<AgentPaymentPhase, string> = {\n [AgentPaymentPhase.AgentSignatureRequired]: 'The agent must sign and submit the prepared payment before Haven can relay it.',\n [AgentPaymentPhase.PaymentSubmitted]: 'Haven has received the signed payment and the agent should poll for confirmation.',\n [AgentPaymentPhase.PaymentConfirmed]: 'The direct payment is confirmed; the agent does not need to do more for this payment id.',\n [AgentPaymentPhase.UserApprovalRequired]: 'The payment needs wallet owner approval in Haven before it can continue.',\n [AgentPaymentPhase.UserExecutionRequired]: 'The wallet owner approved the request and still needs to complete the funding payment.',\n [AgentPaymentPhase.WaitingForAdditionalApprovals]: 'The funding payment was proposed and is waiting for the remaining account approvals.',\n [AgentPaymentPhase.FundingSent]: 'The Haven funding leg was sent; the agent can continue the merchant/protocol leg.',\n [AgentPaymentPhase.Rejected]: 'The wallet owner rejected the request; the agent should stop and tell the user.',\n [AgentPaymentPhase.Expired]: 'The payment or approval request expired before completion.',\n [AgentPaymentPhase.Failed]: 'Haven could not complete the payment; the agent should stop and surface the failure.',\n [AgentPaymentPhase.InsufficientFunds]:\n 'Pre-flight check determined the delegate balance plus the remaining on-chain allowance cannot cover the requested amount, so no payment was created. The originating Safe must be funded or the agent allowance raised before retrying.',\n [AgentPaymentPhase.FundedButUnsettled]:\n \"Haven's funding leg confirmed on-chain but the merchant rejected the x402 retry. The delegate wallet may hold stranded funds. The agent should stop and wait for the wallet owner to sweep the stranded funds back to the Safe.\",\n}\n\nexport const AgentPaymentNextActionDescriptions: Record<AgentPaymentNextAction, string> = {\n [AgentPaymentNextAction.SignAndSubmitPayment]: 'Sign with the delegate key and submit the payment to Haven.',\n [AgentPaymentNextAction.CheckStatusLater]: 'Poll getPaymentStatus later using this payment id.',\n [AgentPaymentNextAction.None]: 'No further agent action is required for this payment id.',\n [AgentPaymentNextAction.WaitForUserApproval]: 'Wait for the wallet owner to approve or reject the request in Haven.',\n [AgentPaymentNextAction.WaitForUserToCompletePayment]: 'Wait for the wallet owner to finish sending the approved funding payment.',\n [AgentPaymentNextAction.RetryOriginalX402Request]: 'Resume this payment id and retry the original x402 request with the merchant payment header.',\n [AgentPaymentNextAction.StopAndTellUser]: 'Stop retrying this payment and tell the user what happened.',\n [AgentPaymentNextAction.RequestAgainIfUserStillWantsIt]: 'Ask again only if the user still wants the payment after expiry.',\n [AgentPaymentNextAction.PaymentWindowExpired]:\n 'The x402 funding/quote window expired. Re-quote with the same idempotency key before asking the signer to build a merchant payment header again.',\n [AgentPaymentNextAction.FundSafeOrRaiseAllowance]:\n 'Stop and tell the user that the originating Safe needs to be funded or the agent allowance raised before the payment can succeed.',\n [AgentPaymentNextAction.RetryWithExplicitContext]:\n 'Retry the same tool call, this time passing merchant_url, tool_name, arguments, and mcp_transport explicitly — the server had no stored context to rehydrate for this payment id.',\n [AgentPaymentNextAction.SweepStrandedFunds]:\n 'Tell the user that funds may be stranded in the delegate wallet and prompt them to initiate a sweep in Haven to return them to the originating Safe.',\n}\n\nexport const AgentPaymentFailureCodeDescriptions: Record<AgentPaymentFailureCode, string> = {\n [AgentPaymentFailureCode.PriceExceedsMax]:\n \"The merchant-authoritative x402 amount exceeds the caller's max_amount cap. No funding transfer was created; ask the user before retrying with a larger cap.\",\n [AgentPaymentFailureCode.PaymentWindowExpired]:\n 'The x402 funding/quote window expired before the signer or hosted settle step could finish. Re-quote via haven_pay_mcp_tool with the same idempotency key to avoid duplicate funding.',\n [AgentPaymentFailureCode.MerchantRejectedAfterFunding]:\n 'The Haven funding leg succeeded, but the merchant rejected the paid retry. Stop retrying the merchant and reconcile stranded delegate funds with haven_sweep_delegate.',\n [AgentPaymentFailureCode.MerchantUnresponsiveAfterFunding]:\n 'The Haven funding leg succeeded, but the merchant did not answer the paid retry before the timeout. The merchant may still settle late — check haven_get_payment_status (and retry haven_complete_mcp_tool once) BEFORE sweeping; sweep only if no settlement appears.',\n [AgentPaymentFailureCode.MerchantCallContextUnavailable]:\n 'merchant_url/tool_name were omitted and no stored merchant call context is available for this payment_id. Re-send merchant_url, tool_name, arguments, and mcp_transport explicitly.',\n [AgentPaymentFailureCode.AmbiguousMaxAmount]:\n 'Both max_amount (atomic units) and max_amount_human (whole tokens) were supplied for one purchase. Nothing was contacted and nothing was spent. Re-send with exactly ONE: max_amount_human for a cap the user stated in tokens, max_amount for an exact atomic figure.',\n [AgentPaymentFailureCode.MaxAmountUnconvertible]:\n \"max_amount_human could not be converted to atomic units against this quote's asset — either its decimals are unknown to Haven or the cap has more decimal places than the asset supports. Nothing was spent. Round the cap, or re-send it as an exact atomic max_amount.\",\n}\n\n/**\n * #1308: machine-readable warning codes carried in the `warnings` array on\n * x402 MCP tool responses. Warnings are ADVISORY — they never replace a\n * refusal, and existing failure codes stay authoritative for errors. The\n * legacy `cap_warning` string field is kept for compatibility; the structured\n * entry carries the same message under MISSING_MAX_AMOUNT.\n */\nexport const AgentPaymentWarningCode = {\n /** No max_amount cap was supplied — the live quoted price was accepted as-is. */\n MissingMaxAmount: 'MISSING_MAX_AMOUNT',\n /** The signing window closes soon; sign promptly or re-quote with the same idempotency key. */\n QuoteExpiresSoon: 'QUOTE_EXPIRES_SOON',\n /** The merchant URL was resolved via discovery — pass the RESOLVED url forward. */\n MerchantUrlDiscovered: 'MERCHANT_URL_DISCOVERED',\n /**\n * #1306: the catalog's last-verified price_atomic differs from the LIVE\n * merchant quote for a guided catalog purchase. The catalog price is only\n * ever indicative; the live quote in the same response is authoritative.\n */\n CatalogPriceDiffers: 'CATALOG_PRICE_DIFFERS',\n /**\n * #1306: the rail-aware allowance/budget pre-check could not be read (RPC\n * failure, etc). `sufficient` is reported as null rather than a fabricated\n * true/false — the on-chain policy remains the actual gate either way.\n */\n AllowanceCheckUnavailable: 'ALLOWANCE_CHECK_UNAVAILABLE',\n /**\n * #1319: the delegation-rail read itself SUCCEEDED, but the remaining\n * figure it returned is the #1145 fallback (the full configured budget)\n * rather than a live ERC20PeriodTransferEnforcer read — `sufficient` is a\n * real true/false, just computed from an optimistic number. Distinct from\n * {@link AgentPaymentWarningCode.AllowanceCheckUnavailable}, which fires\n * when the read failed outright and `sufficient` degrades to null. The\n * on-chain policy re-checks at redemption either way; this only says the\n * guidance shown here may be optimistic.\n */\n AllowanceReadOptimistic: 'ALLOWANCE_READ_OPTIMISTIC',\n} as const\n\nexport type AgentPaymentWarningCode =\n (typeof AgentPaymentWarningCode)[keyof typeof AgentPaymentWarningCode]\n\nexport interface AgentPaymentWarning {\n code: AgentPaymentWarningCode\n message: string\n}\n\n/**\n * #1308: the structured next-step contract on x402 MCP tool responses. It\n * EXTENDS the existing taxonomy — `next_action` values come from\n * AgentPaymentNextAction, never a parallel vocabulary. `next_arguments`\n * carries the small, literally-usable arguments; bulky pass-through fields\n * (payment_required) are named in `reason` and taken from the SAME response.\n */\nexport interface AgentNextStep {\n next_action: AgentPaymentNextAction\n /** Fully-qualified tool name for the next call, when one exists. */\n next_tool?: string\n /** Small literal arguments for next_tool. Bulky fields are referenced by reason. */\n next_arguments?: Record<string, unknown>\n /** False when the agent should stop and involve the user before continuing. */\n safe_to_continue: boolean\n reason: string\n}\n\n/**\n * #1349: compact, Haven-generated reporting evidence for a completed x402\n * merchant purchase. `status`, money fields, merchant endpoint/address, and\n * funding transaction come from Haven payment state; `product` and\n * `invoice_id` are optional merchant-supplied display metadata. The raw\n * merchant result remains separate evidence and MUST NOT be used to infer\n * settlement status.\n */\nexport interface AgentPurchaseSummary {\n /** Set only after Haven has completed the funding and merchant-settlement flow. */\n status: 'settled'\n product: string | null\n amount: string | null\n amount_atomic: string | null\n asset: string | null\n network: string | null\n merchant: {\n address: string | null\n resource_url: string | null\n }\n /** Merchant-supplied identifier, or null when the merchant did not supply one. */\n invoice_id: string | null\n funding_tx_hash: string | null\n /** Optional merchant receipt reference parsed from PAYMENT-RESPONSE; not Haven settlement proof. */\n settlement_tx_hash: string | null\n /** Same read-only allowance block returned at the top level, or null when unavailable. */\n allowance: PostPurchaseAllowanceSummary | null\n}\n\n/** #1308: compact reporting summary — what the agent tells the user. */\nexport interface AgentPaymentSummary {\n payment_id: string\n status: string\n amount?: string\n amount_atomic?: string\n token?: string\n network?: string\n expires_at?: string\n product?: string\n /**\n * Default reporting contract for a successful `haven_settle_mcp_tool` call.\n * The merchant's raw `result` remains available separately as advanced\n * evidence; do not parse it to determine whether a payment settled.\n */\n purchase_summary?: AgentPurchaseSummary\n}\n\nexport const AgentPaymentRailDescriptions: Record<AgentPaymentRail, string> = {\n [AgentPaymentRail.Direct]: 'Standard Haven payment from the user-controlled Safe through an approved delegate allowance.',\n [AgentPaymentRail.X402]: 'x402 HTTP 402 payment flow with a Haven funding leg and merchant retry leg.',\n [AgentPaymentRail.Mpp]: 'Categorical MPP rail value used as a resume-state discriminator. Response bodies carry a granular mpp_* value instead.',\n [AgentPaymentRail.MppDemo]: 'Haven internal MPP demo rail. Not for production traffic.',\n [AgentPaymentRail.MppCrypto]: 'Crypto-settled MPP rail.',\n [AgentPaymentRail.StripeDeposit]: 'Stripe-deposit-backed MPP rail.',\n [AgentPaymentRail.Spt]: 'Stripe Payment Token MPP rail.',\n}\n\nexport const AgentPaymentPhaseSchema: AgentPaymentEnumSchema = {\n type: 'string',\n enum: AGENT_PAYMENT_PHASE_VALUES,\n description: 'Stable Haven agent payment state phase.',\n 'x-enumDescriptions': AgentPaymentPhaseDescriptions,\n}\n\nexport const AgentPaymentNextActionSchema: AgentPaymentEnumSchema = {\n type: 'string',\n enum: AGENT_PAYMENT_NEXT_ACTION_VALUES,\n description: 'Stable next action an agent should take for a Haven payment state.',\n 'x-enumDescriptions': AgentPaymentNextActionDescriptions,\n}\n\nexport const AgentPaymentFailureCodeSchema: AgentPaymentEnumSchema = {\n type: 'string',\n enum: AGENT_PAYMENT_FAILURE_CODE_VALUES,\n description: 'Stable machine-readable failure codes for Haven agent payment recovery paths.',\n 'x-enumDescriptions': AgentPaymentFailureCodeDescriptions,\n}\n\nexport const AgentPaymentRailSchema: AgentPaymentEnumSchema = {\n type: 'string',\n enum: AGENT_PAYMENT_RAIL_VALUES,\n description: 'Stable rail identifier for Haven agent payment states.',\n 'x-enumDescriptions': AgentPaymentRailDescriptions,\n}\n\nexport interface PaymentStatusResult {\n paymentId: string\n kind: PaymentStateKind\n rail: string\n status: PaymentStatus | string\n phase: PaymentPhase\n nextAction: PaymentNextAction\n amount: string\n token: string\n resourceUrl: string | null\n merchantAddress: string | null\n /** Delegate EOA captured on the payment intent when it was created. */\n payerAddress?: string | null\n txHash: string | null\n expiresAt: string\n chainId: number\n message: string\n /** Platform fee surfaced so it's never silently collected (#386). */\n fee?: PaymentFee | null\n amountAtomic?: string | null\n asset?: string | null\n network?: string | null\n description?: string | null\n idempotencyKey?: string | null\n x402?: {\n amountAtomic: string | null\n asset: string | null\n network: string | null\n resourceUrl: string | null\n merchantAddress: string | null\n description: string | null\n idempotencyKey: string | null\n }\n mpp?: {\n amountAtomic: string | null\n asset: string | null\n network: string | null\n resourceUrl: string | null\n merchantAddress: string | null\n description: string | null\n idempotencyKey: string | null\n challengeId: string | null\n }\n}\n\nexport interface PendingApproval extends PaymentStatusResult {\n kind: 'approval_request'\n status: 'pending_approval' | 'pending' | string\n phase: typeof AgentPaymentPhase.UserApprovalRequired\n nextAction: typeof AgentPaymentNextAction.WaitForUserApproval\n requested?: string\n remaining?: string | null\n}\n\n\n/** @internal */\nexport interface RawX402AuthorizeResponse {\n success?: boolean\n payment_id: string\n kind?: string\n rail?: string\n status: string\n phase?: string\n next_action?: string\n message?: string\n remaining?: string | null\n requested?: string\n tx_hash?: string\n chain_id?: number\n safe_address?: string\n payer?: string\n token?: string\n amount?: string\n amount_atomic?: string | null\n asset?: string | null\n network?: string | null\n description?: string | null\n idempotency_key?: string | null\n to?: string\n merchant_to?: string | null\n merchant_address?: string | null\n x402_expected_auth?: X402ExpectedAuth\n resource_url?: string\n explorer_url?: string\n x402?: RawX402StateContext\n mpp?: RawMppStateContext\n challenge_id?: string\n expires_at?: string\n sign_data?: SignData\n error?: string\n}\n\n/** @internal Response of `POST /x402/:id/settle` (erc7710 direct settlement). */\nexport interface RawX402SettleResponse {\n success?: boolean\n payment_id?: string\n /** The backend-assembled MetaMask erc7710 X-PAYMENT header. */\n payment_header?: string\n status?: string\n error?: string\n}\n\n/**\n * Result of an erc7710 direct settlement (#1454).\n *\n * Deliberately NOT an `X402Receipt`. A 3009 receipt describes a completed\n * two-leg payment — funding tx included — whereas here nothing has settled yet\n * when this returns: the merchant redeems the delegation chain when the caller\n * retries with the header. Reusing the receipt type would let a caller read\n * `txHash` as \"paid\" on a payment that has not moved a cent.\n */\nexport interface X402Erc7710Settlement {\n paymentId: string\n /** Pass verbatim as the `X-PAYMENT` header on the merchant retry. */\n paymentHeader: string\n /** The merchant address the child delegation is pinned to. */\n merchantPayTo: string\n amountAtomic: string\n asset: string\n network: string\n /** Facilitators the child is redeemable by, when the merchant advertised any. */\n facilitatorAddresses: string[] | null\n}\n\n// ── API Response Shapes (raw, snake_case from server) ────────────\n\n/** @internal */\nexport interface RawCreateResponse {\n payment_id: string\n kind?: string\n status: string\n phase?: string\n next_action?: string\n message?: string\n remaining?: string | null\n requested?: string\n expires_at: string\n sign_data: {\n hash: string\n /** 'eip712_userop' = delegation rail; absent = legacy AllowanceModule (raw ECDSA). The session rail's 'eip191_userop' is retired (#834). */\n signature_scheme?: 'eip712_userop'\n components: {\n safe: string\n token: string\n to: string\n amount: string\n payment_token: string\n payment: string\n nonce: number\n }\n instructions: string\n }\n error?: string\n supported?: string[]\n}\n\n/** @internal */\nexport interface RawSignResponse {\n payment_id: string\n kind?: string\n status: string\n phase?: string\n next_action?: string\n message?: string\n remaining?: string | null\n requested?: string\n tx_hash?: string\n token?: string\n amount?: string\n amount_atomic?: string | null\n asset?: string | null\n network?: string | null\n description?: string | null\n idempotency_key?: string | null\n to?: string\n merchant_to?: string | null\n merchant_address?: string | null\n resource_url?: string\n rail?: string\n x402?: RawX402StateContext\n mpp?: RawMppStateContext\n challenge_id?: string\n explorer_url?: string\n chain_id?: number\n expires_at?: string\n error?: string\n details?: string\n}\n\n/** @internal */\nexport interface RawStatusResponse {\n payment_id: string\n status: string\n token: string\n amount: string\n to: string\n tx_hash: string | null\n explorer_url?: string | null\n chain_id?: number\n fee?: { amount: string; token: string; basis_points: number; applied: boolean } | null\n error_message: string | null\n created_at: string\n signed_at: string | null\n submitted_at: string | null\n confirmed_at: string | null\n expires_at: string\n}\n\n/** @internal */\nexport interface RawPaymentStatusResult {\n payment_id: string\n kind: PaymentStateKind\n rail: string\n status: string\n phase: PaymentPhase\n next_action: PaymentNextAction\n amount: string\n token: string\n resource_url: string | null\n merchant_address: string | null\n payer_address?: string | null\n tx_hash: string | null\n expires_at: string\n chain_id: number\n message: string\n fee?: { amount: string; token: string; basis_points: number; applied: boolean } | null\n amount_atomic?: string | null\n asset?: string | null\n network?: string | null\n description?: string | null\n idempotency_key?: string | null\n x402?: RawX402StateContext\n mpp?: RawMppStateContext\n}\n\n/** @internal */\nexport interface RawHavenAgent {\n id: string\n name: string\n status: string\n safe_address: string\n delegate_address: string\n chain_id: number\n execution_rail: string\n}\n\n/** @internal */\nexport interface RawHavenAllowance {\n id: string\n token_address: string\n token_symbol: string\n configured_amount: string\n reset_period_min: number\n onchain: {\n amount: string\n spent: string\n remaining: string\n effective_spent: string\n reset_time_min: number\n last_reset_min: number\n nonce: number\n is_reset_pending: boolean\n /** #1319 — see {@link HavenAllowance.onchain.remainingIsFromChain}. */\n remaining_is_from_chain?: boolean\n }\n}\n\n/** @internal */\nexport interface RawHavenAllowanceSummary {\n agent_id: string\n safe_address: string\n delegate_address: string\n chain_id: number\n allowances: RawHavenAllowance[]\n}\n\n/** @internal */\nexport interface RawHavenPaymentReceipt {\n id: string\n payment_id: string\n payment_intent_id?: string | null\n approval_request_id?: string | null\n rail: string\n proof_status: string\n tx_hash: string\n chain_id: number\n resource_url: string\n merchant_address: string | null\n payer_address: string\n settlement_address: string\n token_symbol: string\n token_address: string\n amount_raw: string\n amount_human: string\n challenge_id: string | null\n idempotency_key: string | null\n challenge_payload?: Record<string, unknown> | null\n selected_payment?: Record<string, unknown> | null\n payment_proof_header_name: string | null\n protocol_receipt_header_name: string | null\n protocol_receipt_payload?: Record<string, unknown> | null\n merchant_status: number | null\n confirmed_at: string | null\n created_at: string\n updated_at: string\n}\n\n/** @internal */\n/** One payable service in Haven's curated merchant catalog. */\nexport interface HavenCatalogEntry {\n id: string\n name: string\n description: string\n category: string\n resourceUrl: string\n rail: 'x402' | 'mpp'\n protocol: 'http' | 'mcp'\n toolName: string | null\n toolArguments: Record<string, unknown> | null\n priceDisplay: string | null\n priceAtomic: string | null\n asset: string | null\n network: string | null\n status: 'active' | 'degraded' | 'delisted'\n verifiedAt: string | null\n}\n\n/** @internal */\nexport interface RawCatalogEntry {\n id: string\n name: string\n description: string\n category: string\n resource_url: string\n rail: 'x402' | 'mpp'\n protocol: 'http' | 'mcp'\n tool_name: string | null\n tool_arguments: Record<string, unknown> | null\n price_display: string | null\n price_atomic: string | null\n asset: string | null\n network: string | null\n status: 'active' | 'degraded' | 'delisted'\n verified_at: string | null\n}\n\nexport interface RawHavenPaymentReceiptsResponse {\n receipts: RawHavenPaymentReceipt[]\n}\n\n/** @internal */\nexport interface RawX402StateContext {\n amount_atomic?: string | null\n asset?: string | null\n network?: string | null\n resource_url?: string | null\n merchant_address?: string | null\n description?: string | null\n idempotency_key?: string | null\n}\n\n/** @internal */\nexport interface RawMppStateContext {\n amount_atomic?: string | null\n asset?: string | null\n network?: string | null\n resource_url?: string | null\n merchant_address?: string | null\n description?: string | null\n idempotency_key?: string | null\n challenge_id?: string | null\n}\n\n// ── Error Types ──────────────────────────────────────────────────\n\nexport class HavenError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly statusCode?: number,\n public readonly paymentId?: string,\n ) {\n super(message)\n this.name = 'HavenError'\n }\n}\n\nexport class HavenApiError extends HavenError {\n constructor(\n message: string,\n statusCode: number,\n public readonly body?: unknown,\n paymentId?: string,\n ) {\n super(message, 'API_ERROR', statusCode, paymentId)\n this.name = 'HavenApiError'\n }\n}\n\n/**\n * #1300: quoteX402 hit a URL that answered something other than 402 — the\n * typed form of \"this is not the x402 endpoint\". Exists so consumers (the\n * hosted MCP's #1271 discovery trigger) can key on a class instead of\n * message text.\n */\n/**\n * #1300: a merchant-facing fetch hit the client-side merchantTimeout. Typed\n * so consumers can distinguish \"merchant never answered\" from a real HTTP\n * error response — the funded-retry path routes this to verify-then-sweep\n * guidance instead of a bare 504.\n */\nexport class MerchantTimeoutError extends HavenApiError {\n readonly merchantErrorCode = 'merchant_timeout' as const\n constructor(message: string) {\n super(message, 504)\n this.name = 'MerchantTimeoutError'\n }\n}\n\nexport class X402UnexpectedStatusError extends HavenApiError {\n readonly x402ErrorCode = 'unexpected_non_402_status' as const\n constructor(message: string, statusCode: number) {\n super(message, statusCode)\n this.name = 'X402UnexpectedStatusError'\n }\n}\n\nexport class HavenPaymentStateError extends HavenApiError {\n resumeState?: X402ResumeState\n\n constructor(\n message: string,\n statusCode: number,\n public readonly state: PaymentStatusResult,\n body?: unknown,\n ) {\n super(message, statusCode, body, state.paymentId)\n this.name = 'HavenPaymentStateError'\n }\n\n get status(): string {\n return this.state.status\n }\n\n get phase(): PaymentPhase {\n return this.state.phase\n }\n\n get nextAction(): PaymentNextAction {\n return this.state.nextAction\n }\n}\n\nexport class HavenSigningError extends HavenError {\n constructor(message: string) {\n super(message, 'SIGNING_ERROR')\n this.name = 'HavenSigningError'\n }\n}\n\n/**\n * Refusal codes the local signer returns when it does not recognise the\n * VERSION of a Haven-signed binding it was asked to sign (#1309). Distinct\n * from `AgentPaymentFailureCode`: these describe a **signer capability**\n * problem (this install cannot evaluate what Haven sent), not a payment-domain\n * outcome, and they never reach the backend's REST/OpenAPI surface — only the\n * local signer's own MCP tool responses (`haven_sign` / `haven_sign_x402` /\n * `haven_sign_sweep_delegate`). That is also why this pair does not go through\n * the `AgentPaymentFailureCode` four-gate (sdk → backend mirror → spec →\n * api-types): there is no backend mirror to keep in sync with.\n */\nexport const SignerRefusalCode = {\n /** `SUPPORTED_X402_EXPECTED_VERSIONS` in `@haven_ai/signer` does not include the received version. */\n UnsupportedExpectedContextVersion: 'UNSUPPORTED_EXPECTED_CONTEXT_VERSION',\n /** `SUPPORTED_SWEEP_BINDING_VERSIONS` in `@haven_ai/signer` does not include the received version. */\n UnsupportedSweepBindingVersion: 'UNSUPPORTED_SWEEP_BINDING_VERSION',\n} as const\n\nexport type SignerRefusalCode = (typeof SignerRefusalCode)[keyof typeof SignerRefusalCode]\n\n/**\n * Canonical recovery guidance for a stale local signer (#1309) — the ONE\n * string both the signer's structured refusal (`fallback` field, carried by\n * `HavenUnsupportedSignerVersionError`) and the hosted quote's advisory\n * `signer_compatibility.fallback` (#1155) render, so an agent that meets\n * either surface is told the identical fix. A second hand-maintained copy of\n * this sentence is exactly how the two surfaces could start disagreeing about\n * what to do.\n */\nexport const SIGNER_UPDATE_FALLBACK =\n 'Update @haven_ai/signer by rerunning `npx @haven_ai/connect@alpha`, which reinstalls the ' +\n 'pinned MCP runtime, then retry the same signing call. Nothing was signed or spent — the ' +\n 'quote or payment this version came from is unaffected and does not need to be re-quoted.'\n\n/**\n * Thrown by the local signer when a Haven-signed binding (x402 expected\n * context or sweep authorization) carries a version outside what this signer\n * install enforces (#1143, structured as #1309). Machine-readable: `code`,\n * `supportedVersions`, and `receivedVersion` are DERIVED from the signer's own\n * `SUPPORTED_X402_EXPECTED_VERSIONS` / `SUPPORTED_SWEEP_BINDING_VERSIONS`\n * constants at the throw site, never a second literal — see\n * `assertSupportedBindingVersion` in `@haven_ai/signer`.\n *\n * This narrows HOW the refusal is reported. It does not weaken it: nothing is\n * signed either way, and the version stays inside the Haven-signed binding\n * message (callers must not \"fix\" a mismatch by rewriting it).\n */\nexport class HavenUnsupportedSignerVersionError extends HavenError {\n constructor(\n message: string,\n code: SignerRefusalCode,\n public readonly supportedVersions: readonly number[],\n public readonly receivedVersion: number,\n public readonly fallback: string,\n ) {\n super(message, code)\n this.name = 'HavenUnsupportedSignerVersionError'\n }\n}\n\nexport class HavenTimeoutError extends HavenError {\n constructor(paymentId: string) {\n super(\n `Timed out waiting for payment ${paymentId} to confirm`,\n 'TIMEOUT',\n undefined,\n paymentId,\n )\n this.name = 'HavenTimeoutError'\n }\n}\n","import { ethers } from 'ethers'\nimport { HavenSigningError } from './types.js'\n\n/**\n * Sign a hash using raw ECDSA (no Ethereum message prefix).\n *\n * This matches what Safe's AllowanceModule `checkSignature` expects —\n * a direct ecrecover over the hash, NOT the \"\\x19Ethereum Signed Message\" variant.\n *\n * Uses ethers.SigningKey.sign() instead of wallet.signMessage() to avoid the prefix.\n */\nexport function signHash(privateKey: string, hash: string): string {\n try {\n const signingKey = new ethers.SigningKey(privateKey)\n const sig = signingKey.sign(hash)\n return sig.serialized // 0x + r(32) + s(32) + v(1)\n } catch (err) {\n throw new HavenSigningError(\n `Failed to sign hash: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/**\n * Sign a delegation-rail payment (#829).\n *\n * The delegate SMART ACCOUNT validates an EIP-712 signature over the packed\n * UserOperation — signing the bare 4337 hash would be rejected on-chain. The\n * backend sends the exact typed data in `sign_data.typed_data`; we sign it\n * verbatim and never reconstruct it (a second source of truth could drift\n * from the account's own rules).\n */\nexport interface Eip712TypedData {\n domain: Record<string, unknown>\n types: Record<string, unknown>\n primaryType: string\n message: Record<string, unknown>\n}\n\n/**\n * Sign backend-supplied EIP-712 typed data VERBATIM.\n *\n * One implementation for every typed-data scheme on purpose: the\n * `EIP712Domain` removal below is the kind of subtlety that rots when it is\n * copied. Today the backend's payloads do NOT carry `EIP712Domain` in `types`\n * (checked against a real `buildSettlementDelegation` payload — see\n * `__fixtures__/settlement-delegation-payload.json`), so the delete is\n * defensive rather than load-bearing; ethers derives the domain itself and\n * throws if it also finds it in `types`.\n *\n * `label` only shapes the error message. Nothing about the signature depends\n * on which caller asked.\n *\n * A consequence worth stating before someone refactors this (#1452 review):\n * because the two wrappers below differ ONLY in that label, calling the wrong\n * one for a given scheme produces a byte-identical signature and no test can\n * see it. That is safe today — both sign backend-supplied typed data verbatim\n * — but it stops being safe the moment either wrapper does anything the other\n * does not. If you add per-scheme behaviour, split the implementations rather\n * than branching inside this one.\n */\nasync function signTypedDataVerbatim(\n privateKey: string,\n typedData: Eip712TypedData,\n label: string,\n): Promise<string> {\n try {\n const wallet = new ethers.Wallet(privateKey)\n const types = { ...typedData.types }\n delete (types as Record<string, unknown>).EIP712Domain\n return await wallet.signTypedData(\n typedData.domain as never,\n types as never,\n typedData.message as never,\n )\n } catch (err) {\n throw new HavenSigningError(\n `Failed to sign ${label}: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\nexport async function signUserOpTypedDataForDelegation(\n privateKey: string,\n typedData: Eip712TypedData,\n): Promise<string> {\n return signTypedDataVerbatim(privateKey, typedData, 'delegation UserOperation')\n}\n\n/**\n * Sign the erc7710 x402 SETTLEMENT CHILD delegation (#1452, epic #1450).\n *\n * A different object from the UserOperation above, and a materially different\n * authority: this signature is what lets a merchant's facilitator redeem the\n * `[child, budget]` chain and pull the exact amount from the treasury. The\n * child's caveats — exact amount, payee pin, expiry, redeemer pin — are what\n * bound it, and they are enforced ON-CHAIN. Signing it verbatim is therefore\n * not a style preference: a reconstructed payload that differed from what the\n * DelegationManager will hash is the #829 failure, and it fails at redemption\n * rather than here.\n */\nexport async function signSettlementDelegationTypedData(\n privateKey: string,\n typedData: Eip712TypedData,\n): Promise<string> {\n return signTypedDataVerbatim(privateKey, typedData, 'x402 settlement delegation')\n}\n\n/**\n * Derive the Ethereum address from a private key.\n */\nexport function addressFromKey(privateKey: string): string {\n try {\n return new ethers.Wallet(privateKey).address\n } catch (err) {\n throw new HavenSigningError(\n `Invalid private key: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/**\n * Verify that a signature over a hash recovers to the expected address.\n */\nexport function verifySignature(hash: string, signature: string, expectedAddress: string): boolean {\n try {\n const recovered = ethers.recoverAddress(hash, signature)\n return recovered.toLowerCase() === expectedAddress.toLowerCase()\n } catch {\n return false\n }\n}\n","import { ethers } from 'ethers'\n\n/**\n * Verifiable payment receipts.\n *\n * A self-contained proof bundle for a settled Haven payment that anyone can\n * verify **independently of Haven**. The anchor is the agent delegate's\n * signature over the on-chain transfer hash: recover the signer and confirm it\n * is the agent's delegate, and you have cryptographic proof the agent authorised\n * exactly this transfer — no need to trust Haven's backend. The on-chain\n * `txHash` is the settlement source of truth (verify on any explorer).\n *\n * This lives in the SDK so agents and users can verify receipts client-side\n * with zero Haven trust.\n */\nexport const RECEIPT_VERSION = 'haven-receipt-1'\n\nexport interface PaymentReceipt {\n version: typeof RECEIPT_VERSION\n paymentId: string\n payment: {\n token: string\n tokenAddress: string\n amount: string\n amountSek: string | null\n recipient: string\n safe: string\n chainId: number\n settledAt: string | null\n resourceUrl: string | null\n }\n /** The agent's cryptographic authorisation — what makes the receipt verifiable. */\n authorization: {\n delegate: string\n signHash: string\n signature: string | null\n }\n onChain: {\n txHash: string | null\n chainId: number\n }\n}\n\nexport type ReceiptVerification =\n | { verified: true; recoveredSigner: string }\n | {\n verified: false\n reason: 'missing_signature' | 'bad_signature' | 'signer_mismatch'\n recoveredSigner?: string\n }\n\n/** Default ECDSA recovery (raw ecrecover over the hash, no message prefix). */\nfunction defaultRecover(hash: string, signature: string): string {\n return ethers.recoverAddress(hash, signature)\n}\n\n/**\n * Verify a receipt independently: recover the signer from the authorisation and\n * confirm it is the agent's delegate. Pure — `recover` is injectable but\n * defaults to standard ECDSA recovery, so this runs anywhere (no Haven backend).\n */\nexport function verifyPaymentReceipt(\n receipt: PaymentReceipt,\n recover: (hash: string, signature: string) => string = defaultRecover,\n): ReceiptVerification {\n const { delegate, signHash, signature } = receipt.authorization\n if (!signature) return { verified: false, reason: 'missing_signature' }\n\n let recovered: string\n try {\n recovered = recover(signHash, signature)\n } catch {\n return { verified: false, reason: 'bad_signature' }\n }\n\n if (recovered.toLowerCase() !== delegate.toLowerCase()) {\n return { verified: false, reason: 'signer_mismatch', recoveredSigner: recovered }\n }\n return { verified: true, recoveredSigner: recovered }\n}\n","/**\n * Runtime-agnostic base64 helpers — the single source of truth for the wire\n * encoding shared by the SDK and the edge signer (#325).\n *\n * Why this module exists: the SDK used `atob`/`btoa` (Web globals) while the\n * signer used `Buffer` (Node-only). Both worked because both currently run in\n * Node ≥ 16, but the duplication was a latent wire-incompatibility — and the\n * signer is headed for non-Node runtimes (browsers, Cloudflare Workers) where\n * `Buffer` does not exist (#314).\n *\n * Encoding contract:\n * - Output is ALWAYS standard base64 (`+`, `/`, padded). The x402 protocol's\n * reference implementation validates headers against\n * `/^[A-Za-z0-9+/]*={0,2}$/` — URL-safe output would be rejected.\n * - Decoding is tolerant: URL-safe input (`-`, `_`, unpadded) is normalized\n * before decoding, since third-party merchants are not guaranteed to be as\n * strict as the reference implementation.\n * - UTF-8 throughout. Naive `btoa(JSON.stringify(...))` throws on any\n * non-Latin-1 character (e.g. a merchant description with an emoji or\n * non-ASCII name); these helpers route through TextEncoder/TextDecoder on\n * the Web path so multibyte characters round-trip identically on both\n * runtimes.\n */\n\n/** Normalize URL-safe alphabet and missing padding to standard base64. */\nfunction normalizeBase64(value: string): string {\n const standard = value.replace(/-/g, '+').replace(/_/g, '/')\n const remainder = standard.length % 4\n return remainder === 0 ? standard : standard + '='.repeat(4 - remainder)\n}\n\n/** Encode a UTF-8 string as standard base64. */\nexport function encodeBase64Utf8(value: string): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(value, 'utf8').toString('base64')\n }\n const bytes = new TextEncoder().encode(value)\n let binary = ''\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i])\n }\n return btoa(binary)\n}\n\n/** Decode standard or URL-safe base64 to a UTF-8 string. */\nexport function decodeBase64Utf8(value: string): string {\n const normalized = normalizeBase64(value)\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(normalized, 'base64').toString('utf8')\n }\n const binary = atob(normalized)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i)\n }\n return new TextDecoder().decode(bytes)\n}\n\n/** Encode a JSON-serializable value as a standard-base64 string. */\nexport function encodeBase64Json(value: unknown): string {\n return encodeBase64Utf8(JSON.stringify(value))\n}\n\n/**\n * Decode a base64 JSON payload.\n *\n * Pass a `label` to get a wrapped error message instead of the raw\n * JSON/base64 error — call sites parsing untrusted merchant headers use this\n * to produce actionable failures.\n */\nexport function decodeBase64Json<T>(value: string, label?: string): T {\n try {\n return JSON.parse(decodeBase64Utf8(value)) as T\n } catch (err) {\n if (label) throw new Error(`Failed to decode ${label}`)\n throw err\n }\n}\n","import { HavenSigningError } from './types.js'\n\n/**\n * Gasless delegate-sweep primitives — the single source of truth shared by the\n * edge signer (which signs) and the Haven backend (which relays).\n *\n * A stranded delegate EOA holds USDC but no ETH, so a raw ERC-20 transfer can't\n * pay for its own gas. Instead the delegate signs an *off-chain* EIP-3009\n * `TransferWithAuthorization` and the Haven relayer submits it on-chain and pays\n * gas. The relayer is only a gas payer: it holds no allowance and is never a\n * spender, so a relayer compromise cannot move user funds.\n *\n * Framework-neutral on purpose: `buildSweepTypedData` returns a plain\n * `{ domain, types, primaryType, message }` that both viem\n * (`signTypedData`/`recoverTypedDataAddress`) and ethers v6\n * (`signTypedData`/`verifyTypedData`) accept, so the signer (viem) and backend\n * (ethers) stay in lockstep without sharing a crypto library.\n */\n\n/** Base mainnet. The only chain Haven sweeps today. */\nexport const SWEEP_BASE_CHAIN_ID = 8453\n\n/** Base Sepolia testnet — used by the dev environment / QA harness. */\nexport const SWEEP_BASE_SEPOLIA_CHAIN_ID = 84532\n\n/** Canonical Circle USDC on Base (FiatTokenV2_2). */\nexport const SWEEP_BASE_USDC_ADDRESS =\n '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'\n\n/** Circle's canonical Base Sepolia testnet USDC. */\nexport const SWEEP_BASE_SEPOLIA_USDC_ADDRESS =\n '0x036CbD53842c5426634e7929541eC2318f3dCF7e'\n\n/**\n * EIP-712 domain per chain. `name`/`version` are the on-chain `FiatTokenV2_2`\n * values; a mismatch makes the relayer's `transferWithAuthorization` revert, so\n * each is pinned to the known-good, **on-chain-verified** USDC values. Base\n * mainnet is \"USD Coin\"/\"2\"; Base Sepolia is \"USDC\"/\"2\" (verified via `name()`/\n * `version()`). Add a chain here only after verifying its USDC EIP-712 domain.\n */\nconst USDC_EIP712_DOMAIN_BY_CHAIN: Record<number, SweepEip712Domain> = {\n [SWEEP_BASE_CHAIN_ID]: {\n name: 'USD Coin',\n version: '2',\n chainId: SWEEP_BASE_CHAIN_ID,\n verifyingContract: SWEEP_BASE_USDC_ADDRESS,\n },\n [SWEEP_BASE_SEPOLIA_CHAIN_ID]: {\n name: 'USDC',\n version: '2',\n chainId: SWEEP_BASE_SEPOLIA_CHAIN_ID,\n verifyingContract: SWEEP_BASE_SEPOLIA_USDC_ADDRESS,\n },\n}\n\n/** USDC contract per sweepable chain. */\nconst USDC_ADDRESS_BY_CHAIN: Record<number, string> = {\n [SWEEP_BASE_CHAIN_ID]: SWEEP_BASE_USDC_ADDRESS,\n [SWEEP_BASE_SEPOLIA_CHAIN_ID]: SWEEP_BASE_SEPOLIA_USDC_ADDRESS,\n}\n\n/** Sweepable chains, for error messages. */\nconst SWEEPABLE_CHAIN_IDS = Object.keys(USDC_ADDRESS_BY_CHAIN).map(Number)\n\n/** True when the gasless sweep supports a chain (its USDC domain + address are known). */\nexport function isSweepableChain(chainId: number): boolean {\n return chainId in USDC_ADDRESS_BY_CHAIN\n}\n\n/** EIP-712 `TransferWithAuthorization` struct, per EIP-3009. */\nexport const TRANSFER_WITH_AUTHORIZATION_TYPES = {\n TransferWithAuthorization: [\n { name: 'from', type: 'address' },\n { name: 'to', type: 'address' },\n { name: 'value', type: 'uint256' },\n { name: 'validAfter', type: 'uint256' },\n { name: 'validBefore', type: 'uint256' },\n { name: 'nonce', type: 'bytes32' },\n ],\n} as const\n\nexport interface SweepEip712Domain {\n name: string\n version: string\n chainId: number\n verifyingContract: string\n}\n\n/**\n * A fully-specified EIP-3009 authorization. All amounts/times are decimal\n * strings (JSON-safe) and `nonce` is a 0x-prefixed 32-byte hex value. `token`\n * and `chainId` are carried explicitly so the signer can assert they are\n * canonical before signing.\n */\nexport interface SweepAuthorization {\n /** Delegate EOA the funds are swept FROM. */\n from: string\n /** Originating Safe the funds are swept TO. */\n to: string\n /** Atomic USDC amount (decimal string). */\n value: string\n /** Unix seconds the authorization becomes valid (decimal string, usually \"0\"). */\n validAfter: string\n /** Unix seconds the authorization expires (decimal string). */\n validBefore: string\n /** Random 0x-prefixed 32-byte hex nonce. */\n nonce: string\n /** USDC contract address. */\n token: string\n /** Chain id (8453 today). */\n chainId: number\n}\n\n/**\n * Haven's signature over the sweep authorization context, signed with the same\n * binding key the x402 expected-context uses. Lets the edge signer verify the\n * authorization actually came from Haven (and wasn't crafted by a compromised\n * hosted server pointing `to` at an attacker) before it signs.\n */\nexport interface SweepExpectedAuth {\n /**\n * Currently always 1. Typed as `number` for the same reason as\n * `X402ExpectedAuth.version` (#1143): it is inbound, so a stale signer must be\n * able to *receive* an unknown version in order to report it. The signer's\n * `SUPPORTED_SWEEP_BINDING_VERSIONS` is the authority on what it will sign.\n */\n version: number\n message: string\n signature: string\n signer: string\n}\n\n/** What `POST /machine-payments/sweep/prepare` returns when funds are stranded. */\nexport interface SweepPreparation {\n authorization: SweepAuthorization\n expectedAuth: SweepExpectedAuth\n}\n\n/** Wire response from `POST /machine-payments/sweep/prepare` (snake_case). */\nexport interface SweepPrepareResponse {\n /** Present and true when the delegate holds nothing to recover. */\n nothing_stranded?: boolean\n /**\n * Present and true when the stranded balance is below the sweep floor (#700):\n * it is left on the delegate as dust rather than recovered, because the gas to\n * sweep it would exceed its value. `min_usdc` carries the configured floor. No\n * `authorization` is built.\n */\n below_min?: boolean\n min_usdc?: string\n /** The authorization to sign — absent when nothing is stranded or below the floor. */\n authorization?: SweepAuthorization\n /** Haven's binding over the authorization — absent when nothing is stranded. */\n expected_auth?: SweepExpectedAuth\n asset?: string\n amount?: string\n amount_atomic?: string\n chain_id: number\n sign_instructions?: string\n message?: string\n}\n\n/** Wire response from `POST /machine-payments/sweep/submit` (snake_case). */\nexport interface SweepSubmitResponse {\n tx_hash: string\n asset: string\n amount: string\n amount_atomic: string\n from_address: string\n to_address: string\n chain_id: number\n explorer_url: string\n idempotent_replay?: boolean\n}\n\n/** Result of a submitted gasless sweep. */\nexport interface SweepSubmitResult {\n txHash: string\n amount: string\n amountAtomic: string\n asset: string\n fromAddress: string\n toAddress: string\n chainId: number\n explorerUrl: string\n}\n\nexport interface SweepTypedData {\n domain: SweepEip712Domain\n types: typeof TRANSFER_WITH_AUTHORIZATION_TYPES\n primaryType: 'TransferWithAuthorization'\n message: {\n from: string\n to: string\n value: bigint\n validAfter: bigint\n validBefore: bigint\n nonce: string\n }\n}\n\n/** Resolve the canonical USDC contract for a sweepable chain, or throw. */\nexport function sweepUsdcAddress(chainId: number): string {\n const address = USDC_ADDRESS_BY_CHAIN[chainId]\n if (!address) {\n throw new HavenSigningError(\n `Sweep is not supported on chain ${chainId}. Supported: ${SWEEPABLE_CHAIN_IDS.join(', ')}.`,\n )\n }\n return address\n}\n\n/** Resolve the USDC EIP-712 domain for a sweepable chain, or throw. */\nexport function sweepUsdcDomain(chainId: number): SweepEip712Domain {\n const domain = USDC_EIP712_DOMAIN_BY_CHAIN[chainId]\n if (!domain) {\n throw new HavenSigningError(\n `Sweep is not supported on chain ${chainId}. Supported: ${SWEEPABLE_CHAIN_IDS.join(', ')}.`,\n )\n }\n return domain\n}\n\nfunction sameAddress(a: string, b: string): boolean {\n return a.toLowerCase() === b.toLowerCase()\n}\n\n/**\n * Build the EIP-712 typed data for an authorization, validating that the token\n * and chain are canonical (the domain's `verifyingContract` must match the\n * authorization's `token`). Returns bigint-valued fields so both viem and\n * ethers v6 sign/recover identically.\n */\nexport function buildSweepTypedData(auth: SweepAuthorization): SweepTypedData {\n const domain = sweepUsdcDomain(auth.chainId)\n const expectedToken = sweepUsdcAddress(auth.chainId)\n if (!sameAddress(auth.token, expectedToken)) {\n throw new HavenSigningError(\n `Sweep token ${auth.token} is not the canonical USDC contract for chain ${auth.chainId}.`,\n )\n }\n if (!/^0x[0-9a-fA-F]{64}$/.test(auth.nonce)) {\n throw new HavenSigningError('Sweep nonce must be a 0x-prefixed 32-byte hex string.')\n }\n return {\n domain,\n types: TRANSFER_WITH_AUTHORIZATION_TYPES,\n primaryType: 'TransferWithAuthorization',\n message: {\n from: auth.from,\n to: auth.to,\n value: BigInt(auth.value),\n validAfter: BigInt(auth.validAfter),\n validBefore: BigInt(auth.validBefore),\n nonce: auth.nonce,\n },\n }\n}\n\n/**\n * Canonical, deterministic string the backend signs and the signer re-derives\n * for the authorization binding. The `Haven sweep authorization v1` namespace\n * (and `kind`) is distinct from the x402 expected-context namespace so an x402\n * binding can never be replayed as a sweep authorization even though they share\n * a signing key.\n */\nexport function buildSweepAuthorizationMessage(auth: SweepAuthorization): string {\n return `Haven sweep authorization v1\\n${stableStringify({\n version: 1,\n kind: 'haven.sweep.authorization',\n from: auth.from.toLowerCase(),\n to: auth.to.toLowerCase(),\n value: auth.value,\n validAfter: auth.validAfter,\n validBefore: auth.validBefore,\n nonce: auth.nonce.toLowerCase(),\n token: auth.token.toLowerCase(),\n chainId: auth.chainId,\n })}`\n}\n\n/** Deterministic JSON: object keys sorted, no incidental whitespace. */\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value)\n if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(',')}]`\n const object = value as Record<string, unknown>\n return `{${Object.keys(object)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${stableStringify(object[key])}`)\n .join(',')}}`\n}\n","/**\n * x402 protocol support for the Haven SDK.\n *\n * Provides:\n * - parsePaymentRequired() — extract payment requirements from a 402 response\n * - parsePaymentRequiredResponse() — async parser with JSON body fallback\n * - encodePaymentProof() — encode a receipt as a PAYMENT-SIGNATURE header\n *\n * The main authorizeX402() and fetchWithPayment() are methods on HavenClient\n * (see client.ts) since they need API access and signing.\n */\n\nimport { createHash } from 'node:crypto'\nimport { recoverTypedDataAddress } from 'viem'\nimport type { X402ExpectedContext, X402PaymentRequired, X402PaymentOption } from './types.js'\nimport type { PaymentRequirements } from 'x402/types'\nimport { decodeBase64Json, encodeBase64Json } from './base64.js'\nimport { buildSweepTypedData } from './sweep.js'\n\nconst BASE_USDC_ADDRESS = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913'\nconst BASE_SEPOLIA_USDC_ADDRESS = '0x036cbd53842c5426634e7929541ec2318f3dcf7e'\n/** USDC addresses the standard EIP-3009 exact scheme can pay (Base mainnet + Base Sepolia). */\nconst STANDARD_X402_USDC_ADDRESSES = new Set([BASE_USDC_ADDRESS, BASE_SEPOLIA_USDC_ADDRESS])\nconst X402_IDEMPOTENCY_BUCKET_MS = 300_000\nconst DECIMAL_ATOMIC_AMOUNT_RE = /^[0-9]+$/\nconst X402_PAYMENT_HEADER_MAX_LENGTH = 65_536\nconst BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/\nconst ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/\nconst SIGNATURE_RE = /^0x[0-9a-fA-F]{130}$/\nconst NONCE_RE = /^0x[0-9a-fA-F]{64}$/\n\n/**\n * Persisted, agent-scoped facts used to preflight a signed standard x402\n * payment header. This is an integrity comparison only: it never rebuilds,\n * modifies, persists, or submits the supplied authorization.\n */\nexport interface X402PaymentHeaderContext {\n merchantTo: string\n amountAtomic: string\n asset: string\n network: string\n resourceUrl: string\n payer: string\n chainId: number\n}\n\n/** A deliberately value-free refusal for untrusted payment-header input. */\nexport class X402PaymentHeaderValidationError extends Error {\n constructor() {\n super('Invalid X-PAYMENT header.')\n this.name = 'X402PaymentHeaderValidationError'\n }\n}\n\nfunction isPositiveDecimalAtomicAmount(value: string): boolean {\n return DECIMAL_ATOMIC_AMOUNT_RE.test(value) && BigInt(value) > 0n\n}\n\nfunction optionAuthorizationAmount(option: X402PaymentOption): string {\n return option.maxAmountRequired ?? option.amount\n}\n\n/**\n * Upper bound on the MERCHANT-requested part of the EIP-3009 authorization\n * window (#715, epic #713). The x402 library sets\n * `validBefore = now + maxTimeoutSeconds` straight from the MERCHANT's 402\n * challenge — without a cap, a malicious or sloppy merchant can request a\n * year-long window and a leaked signed authorization stays spendable that\n * whole time. 600 s is generous for any facilitator settle (typical is\n * 30–60 s); we CLAMP rather than reject so payments keep flowing while\n * exposure stays bounded. `validBefore` is a deadline, not a demand —\n * settling earlier is always valid.\n */\nexport const X402_MAX_AUTHORIZATION_WINDOW_SECONDS = 600\n\n/**\n * Forward margin ADDED on top of the (clamped) merchant timeout when the\n * authorization is actually signed (#1256). The x402 verify rule requires\n * `validBefore ≥ now + maxTimeoutSeconds` AT THE FACILITATOR — but the\n * upstream library computes `validBefore = now + maxTimeoutSeconds` at\n * SIGNING time, leaving zero forward margin. Haven's flow guarantees elapsed\n * time between the two (the funding UserOp confirms before the merchant\n * retry, ~1 min plus latency), so every purchase against a merchant whose\n * `maxTimeoutSeconds` exceeded that latency failed structurally — measured\n * live on Base mainnet: Anchor requires 300 s, and 226 s remained at verify.\n *\n * 300 s covers funding + retry latency with room to spare. The #715 exposure\n * ceiling becomes clamped-timeout + margin ≤ 900 s total forward — a\n * deliberate widening from 600 s, recorded on #1256: an authorization that\n * cannot pass verify protects no one, and 900 s is still bounded by the same\n * clamp discipline.\n */\nexport const X402_SETTLEMENT_FORWARD_MARGIN_SECONDS = 300\n\nfunction clampAuthorizationWindow(seconds: number | undefined): number {\n const requested = typeof seconds === 'number' && Number.isFinite(seconds) ? seconds : 30\n return Math.min(Math.max(Math.floor(requested), 1), X402_MAX_AUTHORIZATION_WINDOW_SECONDS)\n}\n\nfunction normalizePaymentOption(value: unknown): X402PaymentOption | null {\n const candidate = value as Partial<X402PaymentOption> | null\n if (\n !candidate ||\n typeof candidate !== 'object' ||\n typeof candidate.scheme !== 'string' ||\n typeof candidate.network !== 'string' ||\n typeof candidate.asset !== 'string' ||\n typeof candidate.payTo !== 'string'\n ) {\n return null\n }\n\n const amount =\n typeof candidate.amount === 'string'\n ? candidate.amount\n : typeof candidate.maxAmountRequired === 'string'\n ? candidate.maxAmountRequired\n : null\n\n if (!amount) return null\n if (!isPositiveDecimalAtomicAmount(amount)) return null\n if (\n candidate.maxAmountRequired !== undefined &&\n (\n typeof candidate.maxAmountRequired !== 'string' ||\n !isPositiveDecimalAtomicAmount(candidate.maxAmountRequired)\n )\n ) {\n return null\n }\n\n return {\n scheme: candidate.scheme,\n network: candidate.network,\n amount,\n maxAmountRequired: candidate.maxAmountRequired,\n resource: candidate.resource,\n description: candidate.description,\n mimeType: candidate.mimeType,\n asset: candidate.asset,\n payTo: candidate.payTo,\n maxTimeoutSeconds: clampAuthorizationWindow(candidate.maxTimeoutSeconds),\n extra: candidate.extra,\n }\n}\n\nexport function normalizePaymentRequired(value: unknown): X402PaymentRequired | null {\n const candidate = value as Partial<X402PaymentRequired> | null\n if (\n !candidate ||\n typeof candidate !== 'object' ||\n typeof candidate.x402Version !== 'number' ||\n !Array.isArray(candidate.accepts)\n ) {\n return null\n }\n\n const accepts = candidate.accepts\n .map((option) => normalizePaymentOption(option))\n .filter((option): option is X402PaymentOption => !!option && typeof option === 'object')\n\n if (accepts.length === 0) return null\n\n const first = accepts[0]\n const resourceUrl = candidate.resource?.url ?? first.resource\n if (!resourceUrl) return null\n\n const resource = {\n url: resourceUrl,\n description: candidate.resource?.description ?? first.description,\n mimeType: candidate.resource?.mimeType ?? first.mimeType,\n }\n\n return {\n x402Version: candidate.x402Version,\n resource,\n accepts,\n error: candidate.error,\n ...(candidate.extensions && typeof candidate.extensions === 'object'\n ? { extensions: candidate.extensions as Record<string, unknown> }\n : {}),\n }\n}\n\n// ── Supported networks ───────────────────────────────────────────\n\n/** Network identifiers that Haven can recognise in x402 payment requests. */\nexport const SUPPORTED_X402_NETWORKS: Record<string, string> = {\n 'eip155:100': 'Gnosis Chain',\n 'eip155:8453': 'Base',\n 'base': 'Base',\n 'eip155:84532': 'Base Sepolia',\n 'base-sepolia': 'Base Sepolia',\n}\n\n/** Networks supported by the official x402 EIP-3009 exact scheme. */\nconst STANDARD_X402_NETWORKS: Record<string, PaymentRequirements['network']> = {\n 'eip155:8453': 'base',\n 'base': 'base',\n 'eip155:84532': 'base-sepolia',\n 'base-sepolia': 'base-sepolia',\n}\n\n// ── Token address maps ────────────────────────────────────────────\n\n/** Known tokens on Gnosis Chain (chainId 100). */\nconst GNOSIS_TOKENS: Record<string, { symbol: string; decimals: number }> = {\n '0x0000000000000000000000000000000000000000': { symbol: 'xDAI', decimals: 18 },\n '0xcb444e90d8198415266c6a2724b7900fb12fc56e': { symbol: 'EURe', decimals: 18 },\n '0x2a22f9c3b484c3629090feed35f17ff8f88f76f0': { symbol: 'USDC.e', decimals: 6 },\n}\n\n/** Known tokens on Base (chainId 8453). */\nconst BASE_TOKENS: Record<string, { symbol: string; decimals: number }> = {\n '0x0000000000000000000000000000000000000000': { symbol: 'ETH', decimals: 18 },\n '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913': { symbol: 'USDC', decimals: 6 },\n}\n\n/** Known tokens on Base Sepolia (chainId 84532) — testnet. */\nconst BASE_SEPOLIA_TOKENS: Record<string, { symbol: string; decimals: number }> = {\n '0x0000000000000000000000000000000000000000': { symbol: 'ETH', decimals: 18 },\n '0x036cbd53842c5426634e7929541ec2318f3dcf7e': { symbol: 'USDC', decimals: 6 },\n}\n\n/** All known tokens across all supported chains (for display / resolution). */\nconst ALL_TOKENS: Record<string, { symbol: string; decimals: number }> = {\n ...GNOSIS_TOKENS,\n ...BASE_TOKENS,\n ...BASE_SEPOLIA_TOKENS,\n}\n\n/** Maps CAIP-2 network ID → token address map. */\nconst NETWORK_TOKENS: Record<string, Record<string, { symbol: string; decimals: number }>> = {\n 'eip155:100': GNOSIS_TOKENS,\n 'eip155:8453': BASE_TOKENS,\n 'base': BASE_TOKENS,\n 'eip155:84532': BASE_SEPOLIA_TOKENS,\n 'base-sepolia': BASE_SEPOLIA_TOKENS,\n}\n\n// ── Parser ───────────────────────────────────────────────────────\n\n/**\n * Parse an HTTP 402 response into x402 PaymentRequired data.\n *\n * Supports:\n * - v2: PAYMENT-REQUIRED header (base64 JSON)\n * - v1 fallback: X-PAYMENT header or response body\n */\nexport function parsePaymentRequired(response: Response): X402PaymentRequired {\n // v2: PAYMENT-REQUIRED header\n const v2Header = response.headers.get('PAYMENT-REQUIRED')\n if (v2Header) {\n const parsed = normalizePaymentRequired(\n decodeBase64Json<unknown>(v2Header, 'PAYMENT-REQUIRED header'),\n )\n if (parsed) return parsed\n }\n\n // v1: X-PAYMENT header\n const v1Header = response.headers.get('X-PAYMENT')\n if (v1Header) {\n const parsed = normalizePaymentRequired(\n decodeBase64Json<unknown>(v1Header, 'X-PAYMENT header'),\n )\n if (parsed) return parsed\n }\n\n throw new Error(\n 'No x402 payment headers found in 402 response. ' +\n 'Expected PAYMENT-REQUIRED (v2) or X-PAYMENT (v1) header.',\n )\n}\n\n/**\n * Parse an HTTP 402 response into x402 PaymentRequired data.\n *\n * Soundside and other Bazaar-style MCP endpoints return the PaymentRequired\n * object in the JSON body, while older Haven demos and many x402 examples use\n * base64 headers. This keeps the synchronous header parser intact and adds the\n * body fallback needed for those endpoints.\n */\nexport async function parsePaymentRequiredResponse(\n response: Response,\n): Promise<X402PaymentRequired> {\n try {\n return parsePaymentRequired(response)\n } catch (headerErr) {\n try {\n const body = await response.clone().json()\n const parsed = normalizePaymentRequired(body)\n if (parsed) return parsed\n } catch {\n // Fall through to the original, more specific header error below.\n }\n\n throw headerErr\n }\n}\n\n/**\n * Select the best payment option from the x402 accepts array.\n *\n * Preference order:\n * 1. Option on a Haven-supported network with a known token\n * 2. Any option on a Haven-supported network\n * 3. null — no compatible option\n */\nexport function selectPaymentOption(\n accepts: X402PaymentOption[],\n): X402PaymentOption | null {\n if (!accepts || accepts.length === 0) return null\n\n // First pass: find a supported network with a known token\n for (const opt of accepts) {\n if (opt.network in SUPPORTED_X402_NETWORKS) {\n const networkTokens = NETWORK_TOKENS[opt.network]\n if (\n networkTokens?.[opt.asset.toLowerCase()] &&\n isPositiveDecimalAtomicAmount(optionAuthorizationAmount(opt))\n ) {\n return opt\n }\n }\n }\n\n // Second pass: any supported network\n for (const opt of accepts) {\n if (\n opt.network in SUPPORTED_X402_NETWORKS &&\n isPositiveDecimalAtomicAmount(optionAuthorizationAmount(opt))\n ) {\n return opt\n }\n }\n\n // No compatible option found\n return null\n}\n\n/** The `extra.assetTransferMethod` value that marks an erc7710-settleable entry. */\nexport const ERC7710_ASSET_TRANSFER_METHOD = 'erc7710'\n\n/**\n * Read `extra.assetTransferMethod` defensively. `extra` is the merchant's own\n * object, so it is untrusted shape: anything that is not the exact string is\n * treated as \"not erc7710\" rather than coerced.\n */\nexport function x402AssetTransferMethod(option: X402PaymentOption): string | null {\n const raw = option.extra?.assetTransferMethod\n return typeof raw === 'string' ? raw : null\n}\n\n/** True when the merchant advertises this entry as erc7710-settleable. */\nexport function isErc7710Option(option: X402PaymentOption): boolean {\n return x402AssetTransferMethod(option) === ERC7710_ASSET_TRANSFER_METHOD\n}\n\n/**\n * The facilitator addresses a merchant advertises for an erc7710 entry, for\n * the #1058 redeemer pin — or `null` when it pins nothing.\n *\n * **An EMPTY array is `null`, not `[]`.** The backend rejects an empty\n * `redeemers` list with a 400 (`routes/x402.ts`), and the QA scenario already\n * treats empty as absent. Returning `[]` here would hand callers a value that\n * means \"pin to nobody\" — which is not a narrower pin, it is an unbuildable\n * delegation.\n *\n * Malformed entries are DROPPED rather than failing the whole option, and that\n * asymmetry is deliberate. A pin narrowed by a merchant's typo means the\n * facilitator that actually tries to redeem is not on the list, so redemption\n * reverts — and erc7710 has no funding leg, so nothing moved and nothing is\n * stranded. Refusing the option outright would instead deny a payment the\n * remaining valid facilitators could have settled. Losing the payment is the\n * worse outcome, precisely because the failure this issue closes (#1453) is the\n * one where funds move BEFORE the rejection.\n */\nexport function x402FacilitatorAddresses(option: X402PaymentOption): string[] | null {\n const raw = option.extra?.facilitatorAddresses\n if (!Array.isArray(raw)) return null\n const addresses = raw.filter((a): a is string => typeof a === 'string' && ADDRESS_RE.test(a))\n return addresses.length > 0 ? addresses : null\n}\n\n/** Shared shape test: scheme/network/asset/amount, ignoring settlement scheme. */\nfunction isPayableStandardOption(opt: X402PaymentOption): boolean {\n return (\n opt.scheme === 'exact' &&\n opt.network in STANDARD_X402_NETWORKS &&\n STANDARD_X402_USDC_ADDRESSES.has(opt.asset.toLowerCase()) &&\n isPositiveDecimalAtomicAmount(optionAuthorizationAmount(opt))\n )\n}\n\n/**\n * Select an option that can be paid with the official x402 EIP-3009 exact\n * scheme. Haven's older tx-hash proof path can describe more networks; the\n * merchant-verified path currently needs Base USDC.\n *\n * **Skips erc7710-tagged entries (#1453).** It used to return the first\n * positional match and never look at `extra.assetTransferMethod`, so a merchant\n * that listed its erc7710 entry first made a Haven client echo that option\n * while signing a standard EIP-3009 authorization. The merchant rejects the\n * mismatch cleanly — but on the legacy two-leg the Safe→delegate funding\n * transfer has already executed, so the visible result is a stranded delegate\n * balance for the sweep to reclaim. Only our own demo merchant's ordering was\n * holding that shut, and that pin binds our merchant, not the ones we do not\n * control.\n */\nexport function selectStandardPaymentOption(\n accepts: X402PaymentOption[],\n): X402PaymentOption | null {\n if (!accepts || accepts.length === 0) return null\n\n for (const opt of accepts) {\n // #1469: a null hole in accepts[] is unpayable data, not a crash. The\n // parsed-Response path filters these in normalizePaymentRequired, but at\n // least one caller (mcp-server, agent-supplied payment_required) reaches\n // here unsanitized — and a throw there became a 500 where every other\n // caller gets the clean no-compatible-option refusal.\n if (opt === null || typeof opt !== 'object') continue\n if (!isErc7710Option(opt) && isPayableStandardOption(opt)) return opt\n }\n\n return null\n}\n\n/**\n * Select the erc7710-settleable option, if the merchant advertises one.\n */\nexport function selectErc7710PaymentOption(\n accepts: X402PaymentOption[],\n): X402PaymentOption | null {\n if (!accepts || accepts.length === 0) return null\n\n for (const opt of accepts) {\n // #1469: a null hole in accepts[] is unpayable data, not a crash. The\n // parsed-Response path filters these in normalizePaymentRequired, but at\n // least one caller (mcp-server, agent-supplied payment_required) reaches\n // here unsanitized — and a throw there became a 500 where every other\n // caller gets the clean no-compatible-option refusal.\n if (opt === null || typeof opt !== 'object') continue\n if (isErc7710Option(opt) && isPayableStandardOption(opt)) return opt\n }\n\n return null\n}\n\n/** What a settlement-scheme decision resolved to. */\nexport interface X402SchemeSelection {\n scheme: 'erc7710' | 'eip3009'\n option: X402PaymentOption\n /** Redeemer pin for the settlement child; only ever set on erc7710. */\n facilitatorAddresses: string[] | null\n}\n\n/**\n * THE preference rule, in one place (#1450 owner decision, #1453).\n *\n * Prefer erc7710 whenever the account is on the delegation rail and the\n * merchant advertises `extra.assetTransferMethod: \"erc7710\"`; fall back to\n * the EIP-3009 bridge otherwise.\n *\n * Both halves of that condition are required, and the rail half is the\n * caller's to supply — the SDK cannot see which rail an account is on from a\n * 402 response alone. A legacy AllowanceModule account passing\n * `delegationRail: true` would select a scheme its account cannot settle; the\n * backend refuses that at authorize (`validateGenericSchemeRail`), which is\n * where a rail mismatch SHOULD fail, on-chain-adjacent rather than in a client\n * that could be lying to itself.\n *\n * Returns `null` when neither scheme has a payable entry — the caller decides\n * whether that is an error or a reason to look elsewhere.\n */\nexport function selectX402SettlementScheme(\n accepts: X402PaymentOption[],\n opts: { delegationRail: boolean },\n): X402SchemeSelection | null {\n if (opts.delegationRail) {\n const preferred = selectErc7710PaymentOption(accepts)\n if (preferred) {\n return {\n scheme: 'erc7710',\n option: preferred,\n facilitatorAddresses: x402FacilitatorAddresses(preferred),\n }\n }\n }\n\n const fallback = selectStandardPaymentOption(accepts)\n if (fallback) return { scheme: 'eip3009', option: fallback, facilitatorAddresses: null }\n\n return null\n}\n\nexport function x402AuthorizationAmount(option: X402PaymentOption): string {\n const amount = optionAuthorizationAmount(option)\n if (!isPositiveDecimalAtomicAmount(amount)) {\n throw new Error('Invalid x402 amount: must be a positive decimal atomic amount')\n }\n return amount\n}\n\n/**\n * Canonical Haven-authenticated x402 expected context, recomputed byte-for-byte\n * by the edge signer before it signs anything.\n *\n * **Two versions, and the version is derived — never passed in (#1138).**\n * `typedDataHash` present ⇒ v2, absent ⇒ v1. A v1 message is byte-identical to\n * what shipped before, so existing signers keep verifying legacy-rail bindings\n * unchanged.\n *\n * The version lives in both the header line and the payload so neither can be\n * reinterpreted as the other: a v2 context cannot be replayed as a v1 one that\n * drops the typed-data commitment, and a v1 context cannot be presented as v2.\n * That downgrade is exactly the attack the digest exists to stop — see\n * `assertExpectedBinding` in `@haven_ai/signer`, which refuses to raw-sign a\n * hash under a v2 binding and refuses to sign typed data without one.\n */\nexport function buildX402ExpectedMessage(context: X402ExpectedContext): string {\n const version = context.typedDataHash ? 2 : 1\n const payload: Record<string, unknown> = {\n version,\n kind: 'haven.x402.expected',\n paymentId: context.paymentId,\n payloadHash: context.payloadHash.toLowerCase(),\n resourceUrl: context.resourceUrl,\n merchantTo: context.merchantTo.toLowerCase(),\n amount: context.amount,\n asset: context.asset.toLowerCase(),\n network: context.network,\n }\n if (context.expiresAt) {\n payload.expiresAt = context.expiresAt\n }\n if (context.typedDataHash) {\n payload.typedDataHash = context.typedDataHash.toLowerCase()\n }\n return `Haven x402 expected context v${version}\\n${stableStringify(payload)}`\n}\n\nexport function toStandardPaymentRequirements(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n): PaymentRequirements {\n const network = STANDARD_X402_NETWORKS[option.network]\n if (!network) {\n throw new Error(`x402 exact payments are not supported on ${option.network}`)\n }\n\n if (option.scheme !== 'exact') {\n throw new Error(`Unsupported x402 scheme: ${option.scheme}`)\n }\n\n return {\n scheme: 'exact',\n network,\n maxAmountRequired: x402AuthorizationAmount(option),\n resource: option.resource ?? paymentRequired.resource.url,\n description:\n option.description ??\n paymentRequired.resource.description ??\n 'Haven x402 payment',\n mimeType:\n option.mimeType ??\n paymentRequired.resource.mimeType ??\n 'application/octet-stream',\n payTo: option.payTo,\n asset: option.asset,\n // Second enforcement point (#715): the parse path clamps too, but this is\n // the last stop before the x402 library turns the timeout into\n // `validBefore` — options constructed without parsing are bounded here.\n // The forward margin (#1256) is added ONLY here, at signing: the parse\n // path keeps recording the merchant's advertised timeout unchanged, and\n // the library's `validBefore = now + this value` then carries enough\n // slack to satisfy the facilitator's `validBefore ≥ now + maxTimeout`\n // verify rule after our funding leg confirms.\n maxTimeoutSeconds:\n clampAuthorizationWindow(option.maxTimeoutSeconds) +\n X402_SETTLEMENT_FORWARD_MARGIN_SECONDS,\n extra: option.extra,\n }\n}\n\n/**\n * Strictly validate an edge-signed EIP-3009 X-PAYMENT header against the\n * persisted x402 intent context before a hosted relay can submit funding.\n *\n * The merchant/facilitator remains the final protocol verifier. This closes a\n * separate hosted-relay integrity gap: malformed or context-mismatched input\n * must never cause Haven to relay the funding signature first.\n */\nexport async function validateStandardX402PaymentHeader(\n paymentHeader: string,\n context: X402PaymentHeaderContext,\n): Promise<void> {\n try {\n if (\n typeof paymentHeader !== 'string' ||\n paymentHeader.length === 0 ||\n paymentHeader.length > X402_PAYMENT_HEADER_MAX_LENGTH ||\n paymentHeader.length % 4 !== 0 ||\n !BASE64_RE.test(paymentHeader)\n ) {\n throw new Error('wire')\n }\n\n const decoded = decodeBase64Json<Record<string, unknown>>(paymentHeader)\n if (!decoded || typeof decoded !== 'object' || Array.isArray(decoded)) throw new Error('shape')\n const version = decoded.x402Version\n const payload = decoded.payload\n if ((version !== 1 && version !== 2) || !payload || typeof payload !== 'object' || Array.isArray(payload)) {\n throw new Error('shape')\n }\n\n if (version === 1) {\n if (!hasOnlyKeys(decoded, ['x402Version', 'scheme', 'network', 'payload'])) throw new Error('shape')\n if (decoded.scheme !== 'exact' || decoded.network !== standardX402WireNetwork(context.network)) {\n throw new Error('context')\n }\n } else {\n if (!hasOnlyKeys(decoded, ['x402Version', 'accepted', 'payload'])) throw new Error('shape')\n const accepted = selectStandardPaymentOption([decoded.accepted as X402PaymentOption])\n if (!accepted || !matchesHeaderContext(accepted, context)) throw new Error('context')\n }\n\n const record = payload as Record<string, unknown>\n if (!hasOnlyKeys(record, ['signature', 'authorization'])) throw new Error('shape')\n if (typeof record.signature !== 'string' || !SIGNATURE_RE.test(record.signature)) throw new Error('shape')\n const authorization = record.authorization\n if (!authorization || typeof authorization !== 'object' || Array.isArray(authorization)) throw new Error('shape')\n const auth = authorization as Record<string, unknown>\n if (!hasOnlyKeys(auth, ['from', 'to', 'value', 'validAfter', 'validBefore', 'nonce'])) throw new Error('shape')\n if (\n typeof auth.from !== 'string' || !ADDRESS_RE.test(auth.from) ||\n typeof auth.to !== 'string' || !ADDRESS_RE.test(auth.to) ||\n typeof auth.value !== 'string' || !isPositiveDecimalAtomicAmount(auth.value) ||\n typeof auth.validAfter !== 'string' || !DECIMAL_ATOMIC_AMOUNT_RE.test(auth.validAfter) ||\n typeof auth.validBefore !== 'string' || !DECIMAL_ATOMIC_AMOUNT_RE.test(auth.validBefore) ||\n typeof auth.nonce !== 'string' || !NONCE_RE.test(auth.nonce)\n ) {\n throw new Error('shape')\n }\n if (!sameAddress(auth.from, context.payer) || !sameAddress(auth.to, context.merchantTo) || auth.value !== context.amountAtomic) {\n throw new Error('context')\n }\n\n const validAfter = BigInt(auth.validAfter)\n const validBefore = BigInt(auth.validBefore)\n const now = BigInt(Math.floor(Date.now() / 1000))\n if (validBefore <= now || validAfter > validBefore) throw new Error('expired')\n\n // `buildSweepTypedData` pins the correct USDC EIP-712 domain for the\n // persisted chain + asset pair. Successful recovery makes the nonce and\n // every authorization field cryptographically covered by the delegate.\n const typedData = buildSweepTypedData({\n from: auth.from,\n to: auth.to,\n value: auth.value,\n validAfter: auth.validAfter,\n validBefore: auth.validBefore,\n nonce: auth.nonce,\n token: context.asset,\n chainId: context.chainId,\n })\n const recovered = await recoverTypedDataAddress({\n ...typedData,\n // `buildSweepTypedData` keeps the public domain framework-neutral;\n // viem brands contract addresses at this crypto call boundary only.\n domain: {\n ...typedData.domain,\n verifyingContract: typedData.domain.verifyingContract as `0x${string}`,\n },\n message: {\n ...typedData.message,\n from: typedData.message.from as `0x${string}`,\n to: typedData.message.to as `0x${string}`,\n nonce: typedData.message.nonce as `0x${string}`,\n },\n signature: record.signature as `0x${string}`,\n })\n if (!sameAddress(recovered, context.payer)) throw new Error('recovery')\n } catch {\n // Header values are attacker-controlled and may include merchant data.\n // Never propagate them into hosted errors, logs, or serialized telemetry.\n throw new X402PaymentHeaderValidationError()\n }\n}\n\nfunction hasOnlyKeys(value: Record<string, unknown>, allowed: string[]): boolean {\n return Object.keys(value).every((key) => allowed.includes(key)) &&\n allowed.every((key) => key in value)\n}\n\nfunction sameAddress(left: string, right: string): boolean {\n return left.toLowerCase() === right.toLowerCase()\n}\n\nfunction standardX402WireNetwork(network: string): PaymentRequirements['network'] | null {\n return STANDARD_X402_NETWORKS[network] ?? null\n}\n\nfunction matchesHeaderContext(option: X402PaymentOption, context: X402PaymentHeaderContext): boolean {\n if (\n option.scheme !== 'exact' ||\n !sameAddress(option.payTo, context.merchantTo) ||\n !sameAddress(option.asset, context.asset) ||\n option.network !== context.network ||\n x402AuthorizationAmount(option) !== context.amountAtomic\n ) return false\n // x402 v2 may scope an accepted option to a resource. When it does, that\n // resource is part of the header context and must match the intent.\n return option.resource === undefined || option.resource === context.resourceUrl\n}\n\nexport function buildX402IdempotencyKey(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n now = Date.now(),\n): string {\n const bucket = Math.floor(now / X402_IDEMPOTENCY_BUCKET_MS)\n const material = [\n paymentRequired.resource.url,\n paymentRequired.resource.description ?? '',\n option.payTo.toLowerCase(),\n option.asset.toLowerCase(),\n x402AuthorizationAmount(option),\n option.network,\n bucket,\n ].join('|')\n\n return `x402:${createHash('sha256').update(material).digest('hex').slice(0, 16)}`\n}\n\n/**\n * Encode a payment receipt as a base64 PAYMENT-SIGNATURE header value.\n *\n * This follows the x402 v2 protocol — the server's facilitator will\n * verify the on-chain transaction referenced by tx_hash.\n */\nexport function encodePaymentProof(receipt: {\n txHash: string\n paymentId: string\n token: string\n amount: string\n to: string\n resourceUrl?: string\n accepted?: X402PaymentOption\n payer?: string\n chainId?: number\n}): string {\n const payload = {\n x402Version: 2,\n resource: receipt.resourceUrl ? { url: receipt.resourceUrl } : undefined,\n accepted: receipt.accepted,\n payload: {\n type: 'haven_tx_hash',\n txHash: receipt.txHash,\n paymentId: receipt.paymentId,\n settledVia: 'haven',\n payer: receipt.payer,\n chainId: receipt.chainId,\n },\n }\n return encodeBase64Json(payload)\n}\n\n/**\n * Resolve a token symbol from a contract address.\n *\n * Checks all supported chains. For chain-specific resolution,\n * pass the optional `network` CAIP-2 string (e.g. \"eip155:100\").\n */\nexport function resolveTokenFromAddress(\n address: string,\n network?: string,\n): { symbol: string; decimals: number } | null {\n const lower = address.toLowerCase()\n\n if (network && network in NETWORK_TOKENS) {\n return NETWORK_TOKENS[network][lower] ?? null\n }\n\n return ALL_TOKENS[lower] ?? null\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') {\n const primitive = JSON.stringify(value)\n return primitive === undefined ? 'undefined' : primitive\n }\n // Match JSON.stringify's Date handling: serialize to the ISO string, not the\n // empty object the generic-object branch would produce (Object.keys(date) is\n // []). The backend builds the x402 expected-context message from a Postgres\n // TIMESTAMPTZ (a Date at runtime), so without this the signed message carried\n // \"expiresAt\":{} while the edge signer recomputed \"expiresAt\":\"<ISO>\" — a\n // mismatch that broke x402 signature verification once expires_at entered the\n // signed context.\n if (value instanceof Date) return JSON.stringify(value.toISOString())\n if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(',')}]`\n const object = value as Record<string, unknown>\n return `{${Object.keys(object)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${stableStringify(object[key])}`)\n .join(',')}}`\n}\n","import { ethers } from 'ethers'\n\nexport function createJsonRpcProvider(url: string): ethers.JsonRpcProvider {\n return new ethers.JsonRpcProvider(url)\n}\n\nexport function createWallet(privateKey: string, provider: ethers.JsonRpcProvider): ethers.Wallet {\n return new ethers.Wallet(privateKey, provider)\n}\n\nexport function createErc20Contract(\n address: string,\n abi: readonly string[],\n signer: ethers.Signer,\n): ethers.Contract {\n return new ethers.Contract(address, abi as string[], signer)\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { exact } from 'x402/schemes'\nimport { hashTypedData } from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport {\n signHash,\n signUserOpTypedDataForDelegation,\n signSettlementDelegationTypedData,\n addressFromKey,\n verifySignature,\n} from './signer.js'\nimport { verifyPaymentReceipt, type PaymentReceipt, type ReceiptVerification } from './receipt.js'\nimport type {\n HavenClientConfig,\n PaymentRequest,\n PaymentIntent,\n PaymentResult,\n PaymentStatus,\n PaymentPhase,\n PaymentNextAction,\n PaymentStatusResult,\n PaymentResumeState,\n SignData,\n SweepResult,\n X402AuthorizationOptions,\n RawCreateResponse,\n RawSignResponse,\n RawStatusResponse,\n RawPaymentStatusResult,\n X402PaymentRequired,\n X402PaymentOption,\n X402Intent,\n X402McpTransport,\n X402MerchantCallContext,\n RawX402MerchantCallContext,\n X402Quote,\n X402Receipt,\n X402RequestSnapshot,\n X402ResumeState,\n ResumeAuthorizedX402Input,\n ResumeX402PaymentInput,\n RawX402AuthorizeResponse,\n X402Erc7710Settlement,\n RawX402SettleResponse,\n HavenAgent,\n HavenAgentSummary,\n HavenAgentAllowanceSummary,\n HavenAgentReadiness,\n HavenAllowanceSummary,\n PostPurchaseAllowanceSummary,\n HavenPaymentReceipt,\n RawHavenAgent,\n RawHavenAllowanceSummary,\n RawHavenPaymentReceiptsResponse,\n RawHavenPaymentReceipt,\n HavenCatalogEntry,\n RawCatalogEntry,\n AgentPaymentWarning,\n} from './types.js'\nimport {\n AgentPaymentNextAction,\n AgentPaymentPhase,\n AgentPaymentRail,\n AgentPaymentWarningCode,\n HavenApiError,\n HavenPaymentStateError,\n MerchantTimeoutError,\n X402UnexpectedStatusError,\n HavenSigningError,\n HavenTimeoutError,\n} from './types.js'\nimport {\n buildX402IdempotencyKey,\n parsePaymentRequiredResponse,\n resolveTokenFromAddress,\n selectStandardPaymentOption,\n selectX402SettlementScheme,\n toStandardPaymentRequirements,\n x402AuthorizationAmount,\n} from './x402.js'\nimport type {\n SweepAuthorization,\n SweepPrepareResponse,\n SweepSubmitResponse,\n} from './sweep.js'\nimport { createJsonRpcProvider, createWallet, createErc20Contract } from './provider.js'\nimport { decodeBase64Json, encodeBase64Json } from './base64.js'\n\nconst DEFAULT_BASE_URL = 'http://localhost:3001'\n\nconst CHAIN_EXPLORER_TX: Record<number, string> = {\n 100: 'https://gnosisscan.io/tx',\n 8453: 'https://basescan.org/tx',\n}\n\n// Canonical USDC contract address per chain — the single source the sweep flow\n// resolves against. Base (8453) is the only chain Haven sweeps today; the x402\n// path keeps its own lowercase copy for header comparison (see x402.ts\n// BASE_TOKENS). Add a chain here to make its USDC sweepable.\nconst CHAIN_USDC: Record<number, string> = {\n 8453: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n 84532: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',\n}\n\nfunction buildExplorerUrl(chainId: number | undefined, txHash: string): string {\n const base = CHAIN_EXPLORER_TX[chainId ?? 8453] ?? CHAIN_EXPLORER_TX[8453]\n return `${base}/${txHash}`\n}\n\nfunction explorerUrlOrEmpty(chainId: number | undefined, txHash: string | null | undefined): string {\n return txHash ? buildExplorerUrl(chainId, txHash) : ''\n}\n\nconst DEFAULT_REQUEST_TIMEOUT = 30_000\n// #1300: merchant-facing default, CALIBRATED against this repo's own\n// tolerances (post-merge review finding): the demo merchant advertises\n// maxTimeoutSeconds: 300 in every PaymentRequired, and its synchronous\n// settlement wait inherits viem's 180 s waitForTransactionReceipt default —\n// so a shorter client bound would abort settlements the protocol contract\n// itself calls normal. 300 s keeps the hang bounded without racing the\n// merchant's own window. Override per client via config.merchantTimeout.\nconst DEFAULT_MERCHANT_TIMEOUT = 300_000\n// The best-effort MCP initialized-notification does not deserve the\n// settlement budget — its result is discarded either way.\nconst NOTIFY_TIMEOUT = 10_000\nconst DEFAULT_CONFIRMATION_TIMEOUT = 90_000\nconst DEFAULT_POLLING_INTERVAL = 3_000\n\nfunction formatAtomicAmount(atomic: bigint, decimals: number): string {\n // Defensive: negative atomics can't occur today (remaining is floored at 0n)\n // but would otherwise produce corrupt output like \"0.000...-5\".\n if (atomic < 0n) return '0.0'\n const s = atomic.toString().padStart(decimals + 1, '0')\n const intPart = s.slice(0, s.length - decimals) || '0'\n const fracPart = s.slice(s.length - decimals).replace(/0+$/, '') || '0'\n return `${intPart}.${fracPart}`\n}\n\n/** Parse an atomic-amount string, defaulting to 0n on malformed input. */\nfunction safeBigInt(value: string): bigint {\n try {\n return BigInt(value)\n } catch {\n return 0n\n }\n}\n\n/**\n * Derive the agent's spend-readiness from its raw status and per-token remaining\n * allowance. See {@link HavenAgentReadiness} for the contract.\n */\nfunction deriveReadiness(\n status: string,\n allowances: ReadonlyArray<{ remainingAtomic: string }>,\n): HavenAgentReadiness {\n if (status !== 'active') return 'revoked'\n const hasSpendable = allowances.some((a) => safeBigInt(a.remainingAtomic) > 0n)\n return hasSpendable ? 'ready' : 'needs_approval'\n}\n\n// ── MCP-over-x402 transport (issue #315) ──────────────────────────\n// MCP merchants (Soundside, the Coinbase reference) speak the Streamable\n// HTTP transport: an `initialize` handshake hands back an `mcp-session-id`\n// that must ride on every subsequent request, and responses arrive as SSE.\nconst MCP_PROTOCOL_VERSION = '2025-06-18'\nconst MCP_ACCEPT = 'application/json, text/event-stream'\nconst MCP_CLIENT_INFO = { name: 'haven-sdk', version: '1' }\n\n/** Cap the merchant body persisted to the reconciliation event (the full body is kept on the thrown error). */\nconst MERCHANT_BODY_SNIPPET_LIMIT = 1000\n\n/** A failed merchant retry response, captured verbatim for debugging and surfaced on the structured error. */\ninterface CapturedMerchantResponse {\n merchant_status: number\n merchant_status_text: string\n merchant_headers: Record<string, string>\n merchant_body: string\n}\n\nconst PAYMENT_STATE_STATUS_CODES: Record<string, number> = {\n pending: 202,\n pending_approval: 202,\n approved: 202,\n proposed: 202,\n executed: 200,\n pending_signature: 409,\n submitted: 409,\n expired: 410,\n failed: 502,\n rejected: 409,\n}\n\nfunction chainIdFromNetwork(network: string | undefined): number | undefined {\n if (network === 'base') return 8453\n // #1471: canonical in the x402 spec's NetworkSchema, and the backend maps\n // it as of the same change — the #1478 pin test enforces that every copy\n // widens together, which is exactly how this line got here.\n if (network === 'base-sepolia') return 84532\n if (!network?.startsWith('eip155:')) return undefined\n const chainId = Number(network.slice('eip155:'.length))\n return Number.isFinite(chainId) ? chainId : undefined\n}\n\nfunction chainIdOrNull(network: string | undefined): number | null {\n return chainIdFromNetwork(network) ?? null\n}\n\nfunction phaseForStatus(status: string): PaymentPhase | null {\n if (status === 'pending_signature') return AgentPaymentPhase.AgentSignatureRequired\n if (status === 'submitted') return AgentPaymentPhase.PaymentSubmitted\n if (status === 'confirmed') return AgentPaymentPhase.PaymentConfirmed\n if (status === 'pending' || status === 'pending_approval') return AgentPaymentPhase.UserApprovalRequired\n if (status === 'approved') return AgentPaymentPhase.UserExecutionRequired\n if (status === 'proposed') return AgentPaymentPhase.WaitingForAdditionalApprovals\n if (status === 'executed') return AgentPaymentPhase.FundingSent\n if (status === 'rejected') return AgentPaymentPhase.Rejected\n if (status === 'expired') return AgentPaymentPhase.Expired\n if (status === 'failed') return AgentPaymentPhase.Failed\n return null\n}\n\nfunction nextActionForStatus(status: string): PaymentNextAction | null {\n if (status === 'pending_signature') return AgentPaymentNextAction.SignAndSubmitPayment\n if (status === 'submitted') return AgentPaymentNextAction.CheckStatusLater\n if (status === 'confirmed') return AgentPaymentNextAction.None\n if (status === 'pending' || status === 'pending_approval') return AgentPaymentNextAction.WaitForUserApproval\n if (status === 'approved') return AgentPaymentNextAction.WaitForUserToCompletePayment\n if (status === 'proposed') return AgentPaymentNextAction.WaitForUserApproval\n if (status === 'executed') return AgentPaymentNextAction.RetryOriginalX402Request\n if (status === 'rejected') return AgentPaymentNextAction.StopAndTellUser\n if (status === 'expired') return AgentPaymentNextAction.RequestAgainIfUserStillWantsIt\n if (status === 'failed') return AgentPaymentNextAction.StopAndTellUser\n return null\n}\n\nfunction messageForState(\n label: string,\n status: string,\n paymentId: string,\n nextAction: PaymentNextAction,\n): string {\n if (status === 'pending' || status === 'pending_approval') {\n return `${label} is above the remaining agent budget and is waiting for user approval in Haven (payment_id: ${paymentId}).`\n }\n if (status === 'executed') {\n return 'The user completed the funding payment. Retry the original x402 request.'\n }\n if (status === 'rejected') {\n return `The user rejected this payment request (payment_id: ${paymentId}).`\n }\n if (status === 'expired') {\n return `This payment request expired (payment_id: ${paymentId}).`\n }\n return `${label} is ${status}; next_action=${nextAction} (payment_id: ${paymentId}).`\n}\n\nfunction sameAddress(a: string | null | undefined, b: string | null | undefined): boolean {\n return Boolean(a && b && a.toLowerCase() === b.toLowerCase())\n}\n\nfunction decimalFromUsdcAtomic(value: string): string {\n const amount = BigInt(value)\n const whole = amount / 1_000_000n\n const fraction = (amount % 1_000_000n).toString().padStart(6, '0').replace(/0+$/, '')\n return fraction ? `${whole}.${fraction}` : whole.toString()\n}\n\nfunction normalizeDecimal(value: string): string {\n if (!value.includes('.')) return value.replace(/^0+(?=\\d)/, '') || '0'\n const [whole, fraction = ''] = value.split('.')\n const normalizedWhole = whole.replace(/^0+(?=\\d)/, '') || '0'\n const normalizedFraction = fraction.replace(/0+$/, '')\n return normalizedFraction ? `${normalizedWhole}.${normalizedFraction}` : normalizedWhole\n}\n\nfunction parseMerchantSettlement(header: string | null): {\n settlementTxHash?: string | null\n} {\n if (!header) return {}\n const parsed = parseProtocolReceiptHeader(header)\n const tx =\n typeof parsed?.transaction === 'string'\n ? parsed.transaction\n : typeof parsed?.txHash === 'string'\n ? parsed.txHash\n : typeof parsed?.tx_hash === 'string'\n ? parsed.tx_hash\n : null\n return { settlementTxHash: tx }\n}\n\n/**\n * MCP-over-HTTP merchants expose their endpoint at a path ending in `/mcp`\n * (Soundside, the Coinbase reference — the convention). That path is the\n * primary auto-handshake signal. Trailing slashes and query/hash suffixes\n * are tolerated so `/mcp/`, `/mcp?x=1`, and `/foo/mcp` all match.\n */\nfunction isMcpUrl(url: string): boolean {\n try {\n return new URL(url).pathname.replace(/\\/+$/, '').endsWith('/mcp')\n } catch {\n return /\\/mcp(?:[/?#]|$)/.test(url)\n }\n}\n\n/**\n * Coinbase Bazaar's published-discovery extension. Its presence in a 402 body\n * marks an MCP-discoverable resource even when the URL doesn't end in `/mcp`,\n * so it is the second auto-handshake signal.\n */\nasync function responseHasBazaarExtension(response: Response): Promise<boolean> {\n try {\n const body = (await response.clone().json()) as { extensions?: { bazaar?: unknown } } | null\n return body?.extensions?.bazaar != null\n } catch {\n return false\n }\n}\n\n/**\n * Parse the `data:` frames of an MCP Streamable-HTTP SSE stream into the\n * JSON-RPC messages they carry. Multiple `data:` lines before a blank line are\n * concatenated into one payload per the SSE spec; non-JSON frames (keep-alives)\n * are skipped.\n */\nfunction parseSseJsonRpcMessages(text: string): Array<Record<string, unknown>> {\n const messages: Array<Record<string, unknown>> = []\n let dataLines: string[] = []\n\n const flush = (): void => {\n if (dataLines.length === 0) return\n try {\n messages.push(JSON.parse(dataLines.join('\\n')) as Record<string, unknown>)\n } catch {\n // Ignore keep-alives and non-JSON data frames.\n }\n dataLines = []\n }\n\n for (const line of text.split(/\\r?\\n/)) {\n if (line === '') {\n flush()\n continue\n }\n if (line.startsWith('data:')) {\n dataLines.push(line.slice(5).replace(/^ /, ''))\n }\n }\n flush()\n\n return messages\n}\n\n/** Pick the JSON-RPC response (result/error) from a set of SSE messages. */\nfunction selectJsonRpcResult(\n messages: Array<Record<string, unknown>>,\n): Record<string, unknown> | undefined {\n return messages.find((m) => 'result' in m || 'error' in m) ?? messages[messages.length - 1]\n}\n\n/**\n * Digest of a delegation-rail signing payload, or `undefined` when there is\n * none (#1138).\n *\n * Guarded because a payload that cannot be hashed is not a recoverable\n * condition to paper over: the edge signer derives this same digest before\n * signing, so an unhashable payload can never be signed by anyone. Surfacing it\n * as a named Haven error beats letting a raw viem type error escape from the\n * middle of intent construction.\n */\nfunction x402TypedDataDigest(typedData: unknown): string | undefined {\n if (!typedData || typeof typedData !== 'object') return undefined\n try {\n return hashTypedData(typedData as Parameters<typeof hashTypedData>[0])\n } catch (err) {\n throw new HavenSigningError(\n 'The x402 funding intent carried a sign_data.typed_data that is not a valid EIP-712 ' +\n 'payload (needs domain, types, primaryType, message), so its digest cannot be derived ' +\n 'and no signer could accept it. ' +\n `Underlying error: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/** Shared by {@link HavenClient.discoverTools} and {@link HavenClient.getCatalogEntry} (#1306). */\nfunction mapCatalogEntry(entry: RawCatalogEntry): HavenCatalogEntry {\n return {\n id: entry.id,\n name: entry.name,\n description: entry.description,\n category: entry.category,\n resourceUrl: entry.resource_url,\n rail: entry.rail,\n protocol: entry.protocol,\n toolName: entry.tool_name,\n toolArguments: entry.tool_arguments ?? null,\n priceDisplay: entry.price_display,\n priceAtomic: entry.price_atomic,\n asset: entry.asset,\n network: entry.network,\n status: entry.status,\n verifiedAt: entry.verified_at,\n }\n}\n\nexport class HavenClient {\n private readonly apiKey: string\n private readonly delegateKey: string | undefined\n private readonly baseUrl: string\n private readonly x402Wallet: string | undefined\n private readonly requestTimeout: number\n private readonly merchantTimeout: number\n private readonly confirmationTimeout: number\n private readonly pollingInterval: number\n private readonly chainRpcs: Record<number, string>\n private readonly inFlightX402 = new Map<string, Promise<X402Receipt>>()\n private readonly x402ReceiptCache = new Map<string, { expiresAt: number; receipt: X402Receipt }>()\n /**\n * Setup-time headers configured via `HavenClientConfig.defaultHeaders`.\n * Read-only after construction — use `withRequestContext` for per-call\n * scoping so concurrent requests don't race on shared mutable state.\n */\n private readonly defaultHeaders: Record<string, string>\n /**\n * Async-local store for per-request context (currently: extra headers).\n * Each `withRequestContext` invocation produces an isolated store, so\n * overlapping async work — like two MCP tool dispatches in flight at\n * the same time — see their own headers without stepping on each other.\n */\n private readonly requestContext = new AsyncLocalStorage<{ headers: Record<string, string> }>()\n\n /** Monotonic JSON-RPC id source for the MCP `initialize` handshake. */\n private mcpRequestId = 0\n\n /** Delegate address derived from the private key (if provided) */\n readonly delegateAddress: string | undefined\n\n constructor(config: HavenClientConfig) {\n this.apiKey = config.apiKey\n this.delegateKey = config.delegateKey\n this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '')\n this.x402Wallet = config.x402Wallet\n this.requestTimeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT\n this.merchantTimeout = config.merchantTimeout ?? DEFAULT_MERCHANT_TIMEOUT\n this.confirmationTimeout = config.confirmationTimeout ?? DEFAULT_CONFIRMATION_TIMEOUT\n this.pollingInterval = config.pollingInterval ?? DEFAULT_POLLING_INTERVAL\n this.chainRpcs = config.chainRpcs ?? {}\n this.defaultHeaders = { ...(config.defaultHeaders ?? {}) }\n\n if (this.delegateKey) {\n this.delegateAddress = addressFromKey(this.delegateKey)\n }\n }\n\n /**\n * Run `fn` with extra Haven-API headers scoped to the async work it\n * performs. Used by the MCP server to tag every Haven API request that\n * a single tool dispatch makes with `X-Haven-MCP-Tool: <name>` so the\n * backend can write an audit-log row attributing the call.\n *\n * The headers are held in an `AsyncLocalStorage` so overlapping\n * dispatches do not leak headers into each other's requests. The store\n * inherits across `await` boundaries, so any Haven API call made while\n * `fn` is awaiting will pick up the right headers.\n *\n * Has no effect on outbound merchant requests (x402 / MPP) — those\n * never go through the internal `request<T>` path that reads the\n * context.\n */\n withRequestContext<T>(headers: Record<string, string>, fn: () => Promise<T>): Promise<T> {\n return this.requestContext.run({ headers: { ...headers } }, fn)\n }\n\n // ── High-Level API ───────────────────────────────────────────────\n\n /**\n * Send a payment in one call.\n *\n * Creates the intent, signs the hash, submits the signature,\n * and polls until confirmed (or throws on failure/timeout).\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async pay(request: PaymentRequest): Promise<PaymentResult> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'Cannot use pay() without a delegateKey. Use createIntent() + submitSignature() for manual signing.',\n )\n }\n\n // Step 1: Create intent\n const intent = await this.createIntent(request)\n\n // Step 2: Sign\n const signature = this.sign(intent.signData.hash)\n\n // Step 3: Submit\n await this.submitSignature(intent.paymentId, signature)\n\n // Step 4: Wait for confirmation\n return this.waitForConfirmation(intent.paymentId)\n }\n\n // ── Step-by-Step API ─────────────────────────────────────────────\n\n /**\n * Step 1: Create a payment intent.\n *\n * Returns the intent with the hash to sign.\n */\n async createIntent(request: PaymentRequest): Promise<PaymentIntent> {\n const raw = await this.post<RawCreateResponse>('/payments', {\n token: request.token,\n amount: request.amount,\n to: request.to,\n ...(request.idempotencyKey ? { idempotency_key: request.idempotencyKey } : {}),\n })\n\n // Haven returns HTTP 202 with this status when the requested amount\n // exceeds the on-chain allowance. The payment is parked for the owner\n // to approve in the dashboard — there's nothing to sign yet, so the SDK\n // surfaces it as an explicit error rather than returning a malformed\n // intent with no signData.\n if (raw.status === 'pending_approval') {\n this.throwPaymentStateError('Payment', raw)\n }\n\n return {\n paymentId: raw.payment_id,\n status: 'pending_signature',\n expiresAt: raw.expires_at,\n signData: raw.sign_data,\n }\n }\n\n /**\n * Keyless x402 construct.\n *\n * The non-custodial half of an x402 payment: posts the funding request to\n * `/x402` and returns the unsigned funding hash plus the data the caller\n * needs to build and sign the EIP-3009 merchant header itself. Crucially it\n * does **not** sign — neither the funding hash nor the merchant header — so\n * it works without a `delegateKey`. Both delegate signatures happen on the\n * machine that holds the key (the edge); the hosted MCP server relays only.\n *\n * Use this from the hosted, keyless server. The all-in-one `authorizeX402`\n * remains for local clients that hold the key.\n *\n * Throws (via the shared payment-state path) when the amount exceeds the\n * on-chain allowance — there is nothing to sign until the user approves.\n */\n async createX402Intent(\n paymentRequired: X402PaymentRequired,\n options: X402AuthorizationOptions = {},\n ): Promise<X402Intent> {\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n if (!option) {\n throw new HavenApiError(\n 'No compatible payment option found in x402 requirements. ' +\n 'Haven supports standard x402 exact payments on Base USDC.',\n 400,\n )\n }\n\n // The funding transfer tops up the agent's delegate EOA. With no local key\n // we resolve that address from the authenticated agent record rather than\n // deriving it from a private key. #1348: a caller that already fetched the\n // agent in this flow passes delegateAddress and skips the duplicate fetch.\n const fundingTo = options.delegateAddress ?? (await this.getAgent()).delegateAddress\n if (!fundingTo) {\n throw new HavenApiError('Authenticated agent has no delegate address registered.', 502)\n }\n\n const idempotencyKey = options.idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option)\n const raw = await this.post<RawX402AuthorizeResponse>('/x402', {\n url: paymentRequired.resource.url,\n payTo: fundingTo,\n merchantPayTo: option.payTo,\n // #1360: this path ALWAYS means the EIP-3009 funding leg (payTo is the\n // agent's own delegate EOA). Saying so explicitly turns a stale/rotated\n // delegate address into the backend's LOUD shape-mismatch 400 instead\n // of a silent reroute to the erc7710 settlement branch (the #1358\n // review's open-budget misroute). Legacy-rail backends ignore the field.\n settlementScheme: 'eip3009',\n amount: x402AuthorizationAmount(option),\n asset: option.asset,\n network: option.network,\n description: paymentRequired.resource.description,\n idempotencyKey,\n // #1307: persisted so the settle leg can rehydrate it by payment_id.\n ...(options.mcpCallContext ? { mcpCallContext: options.mcpCallContext } : {}),\n // #1355: persisted so the SIGN leg can rehydrate it by payment_id — the\n // local signer's context fetch then carries the 402 PaymentRequired and\n // the agent passes only payment_id. Bounded: the backend rejects >64KB,\n // so an oversized blob is omitted here (signer falls back to the\n // caller-supplied copy) rather than failing the intent.\n ...(new TextEncoder().encode(JSON.stringify(paymentRequired)).length <= 65536\n ? { paymentRequired }\n : {}),\n })\n\n // Anything other than a signable funding intent (pending_approval,\n // expired, already-executed, error) is surfaced through the shared path.\n if (raw.status !== 'pending_signature') {\n this.throwPaymentStateError('x402 payment', raw)\n }\n if (!raw.sign_data?.hash) {\n throw new HavenApiError('No sign_hash returned from x402/authorize', 500, raw)\n }\n // #946/#1138: a delegation-rail funding intent signs the ACCOUNT's EIP-712\n // typed data, not the bare hash. This path is keyless by construction, so\n // it does not sign either one — it passes the payload through to whoever\n // holds the key (the local signer the connector installs). What it MUST\n // refuse is a scheme it cannot describe faithfully: handing a caller a\n // `hash` for a typed-data intent invites a raw ECDSA signature the account\n // rejects at the bundler, after the intent is claimed.\n if (raw.sign_data.signature_scheme !== undefined && !raw.sign_data.typed_data) {\n throw new HavenSigningError(\n `This account's x402 funding intent declares signature scheme ` +\n `'${raw.sign_data.signature_scheme}' but carried no typed_data to sign. ` +\n 'Refusing to fall back to the bare hash — the account would reject that signature ' +\n 'on-chain. This is a backend contract violation; report it rather than working around it.',\n )\n }\n if (!raw.x402_expected_auth) {\n throw new HavenApiError('No x402 expected-context binding returned from x402/authorize', 500, raw)\n }\n\n return {\n paymentId: raw.payment_id,\n idempotencyKey,\n status: 'pending_signature',\n expiresAt: raw.expires_at,\n signData: raw.sign_data,\n accepted: option,\n resourceUrl: paymentRequired.resource.url,\n merchantTo: raw.merchant_to ?? option.payTo,\n amountAtomic: x402AuthorizationAmount(option),\n asset: option.asset,\n network: option.network,\n expectedAuth: raw.x402_expected_auth,\n // #1138: the digest the delegation-rail expected context commits to.\n // Re-derived locally, exactly like every other context field the edge\n // signer is handed (amount, merchantTo, …) — none of them are trusted\n // because they arrived, they are trusted because the reconstructed\n // message has to match Haven's signature over it. A typed_data altered in\n // transit therefore fails message equality and is refused, and the signer\n // re-derives this digest a second time from the payload it actually signs.\n expectedTypedDataHash: x402TypedDataDigest(raw.sign_data.typed_data),\n fundingTo,\n }\n }\n\n /**\n * Step 2: Sign a hash with the delegate key.\n *\n * Returns the 65-byte signature (0x-prefixed).\n * Requires `delegateKey` to be set in the client config.\n */\n sign(hash: string): string {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'Cannot sign without a delegateKey. Pass the private key in HavenClient config, or sign externally.',\n )\n }\n\n const signature = signHash(this.delegateKey, hash)\n\n // Verify the signature locally before submitting\n if (!verifySignature(hash, signature, this.delegateAddress!)) {\n throw new HavenSigningError(\n 'Local signature verification failed — recovered address does not match delegate key.',\n )\n }\n\n return signature\n }\n\n /**\n * Sign a payment's `sign_data` with the correct scheme for its rail.\n *\n * Dispatching on the server-provided scheme means a caller never has to\n * know which rail an account is on; an unknown scheme is a hard error,\n * never a guessed signature. The session rail's 'eip191_userop' is retired\n * (#834) — the backend refuses those intents with HTTP 410 before any\n * sign_data reaches a client, so encountering it here is a hard error too.\n */\n private async signForData(signData: {\n hash: string\n signature_scheme?: string\n typed_data?: unknown\n }): Promise<string> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'Cannot sign without a delegateKey. Pass the private key in HavenClient config, or sign externally.',\n )\n }\n const scheme = signData.signature_scheme\n if (scheme === 'eip191_userop') {\n throw new HavenSigningError(\n \"The session rail is retired — 'eip191_userop' intents can no longer be signed. Re-onboard the account on the delegation rail.\",\n )\n }\n if (scheme === 'eip712_userop') {\n if (!signData.typed_data) {\n throw new HavenSigningError(\n 'sign_data.signature_scheme is eip712_userop but typed_data is missing — refusing to sign the bare hash (the account would reject it).',\n )\n }\n return signUserOpTypedDataForDelegation(this.delegateKey, signData.typed_data as never)\n }\n if (scheme === 'eip712_delegation') {\n // The erc7710 x402 settlement child (#1452, epic #1450). Same guard as\n // eip712_userop above, and for a sharper reason: this signature lets a\n // facilitator pull the exact amount from the treasury. Falling back to\n // the bare hash would produce a signature the DelegationManager rejects\n // at redemption — a failure that surfaces on-chain, after the agent has\n // already told the merchant it paid.\n if (!signData.typed_data) {\n throw new HavenSigningError(\n 'sign_data.signature_scheme is eip712_delegation but typed_data is missing — refusing to sign the bare hash (the settlement would be rejected on redemption).',\n )\n }\n return signSettlementDelegationTypedData(this.delegateKey, signData.typed_data as never)\n }\n if (scheme === undefined) {\n return signHash(this.delegateKey, signData.hash) // legacy AllowanceModule rail\n }\n throw new HavenSigningError(\n `Unknown sign_data.signature_scheme '${scheme}' — refusing to guess a signing scheme. Update @haven_ai/sdk.`,\n )\n }\n\n /**\n * Step 3: Submit a signature to execute the payment.\n *\n * The signature can come from `client.sign()` or from external signing.\n */\n async submitSignature(\n paymentId: string,\n signature: string,\n ): Promise<{ status: string; txHash?: string }> {\n const raw = await this.post<RawSignResponse>(\n `/payments/${paymentId}/sign`,\n { signature },\n )\n\n return {\n status: raw.status,\n txHash: raw.tx_hash,\n }\n }\n\n /**\n * Get the current status of a payment.\n */\n async getPayment(paymentId: string): Promise<PaymentResult> {\n const raw = await this.get<RawStatusResponse>(`/payments/${paymentId}`)\n return this.mapPaymentResult(raw)\n }\n\n /**\n * Get agent-actionable status for a payment intent or approval request.\n *\n * Use this for IDs returned by agent tools and machine-payment/x402 flows.\n * `getPayment()` remains available for payment-intent-only integrations.\n */\n async getPaymentStatus(paymentId: string): Promise<PaymentStatusResult> {\n const raw = await this.get<RawPaymentStatusResult>(`/machine-payments/${paymentId}/status`)\n return this.mapPaymentStatusResult(raw)\n }\n\n /**\n * Get the agent identity tied to this API key.\n */\n async getAgent(): Promise<HavenAgent> {\n // #1348: coalesce CONCURRENT reads into one HTTP GET — the guided\n // purchase flow legitimately wants the agent in two overlapping places\n // (the caller's preflight and the quote leg's x402-wallet resolution).\n // This is in-flight dedupe only, never a cache: the promise is cleared\n // the moment it settles, so sequential calls stay fresh reads and a\n // delegate rotation is picked up exactly as before.\n if (this.agentInFlight) return this.agentInFlight\n const request = this.fetchAgent()\n this.agentInFlight = request\n request.finally(() => {\n this.agentInFlight = null\n }).catch(() => {})\n return request\n }\n\n private agentInFlight: Promise<HavenAgent> | null = null\n\n private async fetchAgent(): Promise<HavenAgent> {\n const raw = await this.get<RawHavenAgent>('/machine-payments/agent')\n return {\n id: raw.id,\n name: raw.name,\n status: raw.status,\n safeAddress: raw.safe_address,\n delegateAddress: raw.delegate_address,\n chainId: raw.chain_id,\n // Defensive normalization, not trust: the backend contract is exactly\n // 'legacy' | 'delegation' (#1306), but an older/mismatched backend\n // during a rollout window should degrade to the wider legacy bucket\n // rather than propagate an unrecognized string.\n executionRail: raw.execution_rail === 'delegation' ? 'delegation' : 'legacy',\n }\n }\n\n /**\n * One-shot \"am I ready?\" bootstrap: identity + live spend authority + a\n * readiness signal, in a single call. Folds {@link getAgent} and\n * {@link getAllowances} together and derives a {@link HavenAgentReadiness}\n * so an agent can answer \"who am I and can I pay right now\" at session start\n * without two round trips and manual assembly.\n */\n async getAgentSummary(): Promise<HavenAgentSummary> {\n const [agent, allowanceSummary] = await Promise.all([\n this.getAgent(),\n this.getAllowances(),\n ])\n\n const allowances: HavenAgentAllowanceSummary[] = allowanceSummary.allowances.map((a) => {\n // Only format a human amount when we KNOW the token's decimals. Guessing a\n // default (e.g. 6) for an unregistered token would misformat an 18-decimal\n // balance by 12 orders of magnitude and mislead the agent about what it can\n // spend — so for unknown tokens we surface the exact atomic value, flagged.\n const token = resolveTokenFromAddress(a.tokenAddress)\n const remainingDisplay = token\n ? `${formatAtomicAmount(safeBigInt(a.onchain.remaining), token.decimals)} ${a.tokenSymbol}`\n : `${a.onchain.remaining} ${a.tokenSymbol} (atomic; unknown decimals)`\n return {\n tokenSymbol: a.tokenSymbol,\n remainingAtomic: a.onchain.remaining,\n remainingDisplay,\n configuredAmount: a.configuredAmount,\n resetPeriodMin: a.resetPeriodMin,\n isResetPending: a.onchain.isResetPending,\n }\n })\n\n return { ...agent, readiness: deriveReadiness(agent.status, allowances), allowances }\n }\n\n /**\n * Sweep stranded USDC and ETH from the delegate EOA back to the originating Safe.\n *\n * The delegate key held by this client signs and submits the transfer transactions\n * directly — Haven's backend never handles the key or constructs signed txs\n * (CASP/MiCA Red Line #2). Funds always go to the Safe linked to this agent.\n *\n * Requires `chainRpcs` to be set for the agent's chain in `HavenClientConfig`.\n */\n async sweepDelegate(): Promise<SweepResult> {\n if (!this.delegateKey) {\n throw new HavenSigningError('delegateKey is required for sweepDelegate.')\n }\n\n const agent = await this.getAgent()\n const { safeAddress, delegateAddress, chainId } = agent\n\n if (!delegateAddress) {\n throw new HavenApiError('Agent has no delegate address.', 422)\n }\n\n const rpcUrl = this.chainRpcs[chainId]\n if (!rpcUrl) {\n throw new HavenApiError(\n `chainRpcs[${chainId}] must be configured to sweep the delegate wallet.`,\n 422,\n )\n }\n\n const provider = createJsonRpcProvider(rpcUrl)\n const wallet = createWallet(this.delegateKey, provider)\n\n const ERC20_TRANSFER_ABI = ['function balanceOf(address) view returns (uint256)', 'function transfer(address to, uint256 amount) returns (bool)'] as const\n\n const transfers: SweepResult['transfers'] = []\n\n // ── 1. Sweep ERC-20 USDC ────────────────────────────────────────\n const usdcAddress = CHAIN_USDC[chainId]\n if (usdcAddress) {\n const usdcContract = createErc20Contract(usdcAddress, ERC20_TRANSFER_ABI, wallet)\n const usdcBalance: bigint = await usdcContract.balanceOf(delegateAddress)\n if (usdcBalance > 0n) {\n const tx = await usdcContract.transfer(safeAddress, usdcBalance)\n const receipt = await (tx as { wait: (n: number) => Promise<{ hash: string } | null> }).wait(1)\n const txHash: string = (receipt as { hash: string } | null)?.hash ?? (tx as { hash: string }).hash\n transfers.push({\n asset: 'USDC',\n amount: formatAtomicAmount(usdcBalance, 6),\n amountAtomic: usdcBalance.toString(),\n txHash,\n explorerUrl: buildExplorerUrl(chainId, txHash),\n })\n }\n }\n\n // ── 2. Sweep native ETH ─────────────────────────────────────────\n const ethBalance = await provider.getBalance(delegateAddress)\n if (ethBalance > 0n) {\n // Reserve gas for the native transfer. An EIP-1559 (type-2) tx is billed up\n // to maxFeePerGas, not gasPrice, so reserve against that — with a buffer for\n // base-fee drift between estimation and inclusion — or the send reverts with\n // \"insufficient funds for intrinsic transaction cost\".\n const fee = await provider.getFeeData()\n const effectiveGasPrice = fee.maxFeePerGas ?? fee.gasPrice ?? 1_000_000n\n const gasLimit = 21_000n\n const gasCost = effectiveGasPrice * gasLimit * 2n\n const ethToSend = ethBalance > gasCost ? ethBalance - gasCost : 0n\n if (ethToSend > 0n) {\n const tx = await wallet.sendTransaction({ to: safeAddress, value: ethToSend })\n const receipt = await tx.wait(1)\n const txHash: string = receipt?.hash ?? tx.hash\n transfers.push({\n asset: 'ETH',\n amount: formatAtomicAmount(ethToSend, 18),\n amountAtomic: ethToSend.toString(),\n txHash,\n explorerUrl: buildExplorerUrl(chainId, txHash),\n })\n }\n }\n\n return {\n fromAddress: delegateAddress,\n toAddress: safeAddress,\n chainId,\n transfers,\n }\n }\n\n /**\n * Hosted (keyless) split-signer sweep — step 1 of 2.\n *\n * Asks the backend to build a gasless EIP-3009 sweep authorization for the\n * delegate's stranded USDC. Returns `nothing_stranded` when the delegate is\n * empty, otherwise an `authorization` + Haven `expected_auth` to hand to the\n * edge signer's `haven_sign_sweep_delegate`. No key is required on this client.\n */\n async prepareSweep(): Promise<SweepPrepareResponse> {\n return this.post<SweepPrepareResponse>('/machine-payments/sweep/prepare', {})\n }\n\n /**\n * Hosted (keyless) split-signer sweep — step 2 of 2.\n *\n * Relays the delegate-signed authorization. The Haven relayer submits the\n * on-chain `transferWithAuthorization` and pays gas; this client never holds\n * the key.\n */\n async submitSweep(\n authorization: SweepAuthorization,\n signature: string,\n ): Promise<SweepSubmitResponse> {\n return this.post<SweepSubmitResponse>('/machine-payments/sweep/submit', {\n authorization,\n signature,\n })\n }\n\n /**\n * Get configured and on-chain allowances for the authenticated agent.\n */\n async getAllowances(): Promise<HavenAllowanceSummary> {\n const raw = await this.get<RawHavenAllowanceSummary>('/machine-payments/allowances')\n return {\n agentId: raw.agent_id,\n safeAddress: raw.safe_address,\n delegateAddress: raw.delegate_address,\n chainId: raw.chain_id,\n allowances: raw.allowances.map((allowance) => ({\n id: allowance.id,\n tokenAddress: allowance.token_address,\n tokenSymbol: allowance.token_symbol,\n configuredAmount: allowance.configured_amount,\n resetPeriodMin: allowance.reset_period_min,\n onchain: {\n amount: allowance.onchain.amount,\n spent: allowance.onchain.spent,\n remaining: allowance.onchain.remaining,\n effectiveSpent: allowance.onchain.effective_spent,\n resetTimeMin: allowance.onchain.reset_time_min,\n lastResetMin: allowance.onchain.last_reset_min,\n nonce: allowance.onchain.nonce,\n isResetPending: allowance.onchain.is_reset_pending,\n remainingIsFromChain: allowance.onchain.remaining_is_from_chain,\n },\n })),\n }\n }\n\n /**\n * Post-purchase allowance/budget summary for a settled payment (#1310).\n *\n * Reuses the EXACT rail-aware read path {@link getAllowances} / #1306's\n * catalog-purchase preflight `allowance` block use — `GET\n * /machine-payments/allowances`, with delegation-rail values coming from\n * the #1090 `deriveDelegationBudgets`-backed enforcer read, never\n * `agent_allowances` — so this can never disagree with\n * {@link getAllowances} for the same fixture. The settled token is\n * resolved from {@link getPaymentStatus} so callers pass only\n * `paymentId`, never a second haven_get_agent-style round trip.\n *\n * NEVER throws: any failed read (status lookup, agent lookup, or the\n * allowance/budget lookup itself) degrades to `{ allowance: null,\n * warnings: [ALLOWANCE_CHECK_UNAVAILABLE] }` rather than converting a\n * successful settlement into a failure — the on-chain policy remains the\n * actual spend gate regardless of whether this report can be produced.\n *\n * Freshness caveat (#1319): the delegation rail's on-chain enforcer read\n * can silently fall back to the optimistic full period budget without\n * throwing when the RPC read itself fails (#1145's fund-safe design,\n * unchanged here). {@link getAllowances}'s `onchain.remainingIsFromChain`\n * now carries that provenance on the wire, and the #1306 catalog-purchase\n * preflight (`haven_prepare_catalog_purchase`) surfaces it as a warning —\n * this summary does not (yet). `remaining_atomic` here reflects the last\n * successful chain read, not a guaranteed-live one, and callers should not\n * phrase it as guaranteed-fresh.\n */\n async getPostPurchaseAllowanceSummary(\n paymentId: string,\n ): Promise<{\n allowance: PostPurchaseAllowanceSummary | null\n warnings: AgentPaymentWarning[]\n /** Same authenticated payment-state read used to resolve the settled token. */\n payment: PaymentStatusResult | null\n }> {\n const unavailable = (detail: string): {\n allowance: null\n warnings: AgentPaymentWarning[]\n payment: null\n } => ({\n payment: null,\n allowance: null,\n warnings: [\n {\n code: AgentPaymentWarningCode.AllowanceCheckUnavailable,\n message:\n `Could not read the post-purchase allowance/budget for payment ${paymentId} (${detail}). ` +\n 'The payment itself succeeded — the on-chain policy remains the actual spend gate; this ' +\n 'only affects the remaining-budget figure reported here.',\n },\n ],\n })\n // #1320 review: all three reads in ONE parallel leg. Keep a successfully\n // read payment state even when a best-effort allowance read fails: it is\n // authoritative reporting data in its own right.\n const [statusResult, agentResult, allowanceResult] = await Promise.allSettled([\n this.getPaymentStatus(paymentId),\n this.getAgent(),\n this.getAllowances(),\n ])\n if (statusResult.status === 'rejected') {\n return unavailable(statusResult.reason instanceof Error ? statusResult.reason.message : String(statusResult.reason))\n }\n const status = statusResult.value\n if (agentResult.status === 'rejected') {\n return { ...unavailable(agentResult.reason instanceof Error ? agentResult.reason.message : String(agentResult.reason)), payment: status }\n }\n if (allowanceResult.status === 'rejected') {\n return { ...unavailable(allowanceResult.reason instanceof Error ? allowanceResult.reason.message : String(allowanceResult.reason)), payment: status }\n }\n try {\n const tokenAddress = status.asset ?? status.x402?.asset ?? null\n if (!tokenAddress) {\n return { ...unavailable('the settled payment does not carry a resolvable token address'), payment: status }\n }\n const rail = agentResult.value.executionRail\n const source = rail === 'delegation' ? 'active_delegations' : 'allowance_module'\n const match = allowanceResult.value.allowances.find(\n (a) => a.tokenAddress.toLowerCase() === tokenAddress.toLowerCase(),\n )\n if (!match) {\n // #1320 review: a missing row is UNKNOWN, not zero — an unexpected\n // address, rail mismatch, or read race must not report a confident\n // \"$0 remaining\" to the user.\n return { ...unavailable('no allowance/budget row matches the settled token'), payment: status }\n }\n // Same \"only format when decimals are known\" discipline as\n // getAgentSummary() above — an unregistered token surfaces the exact\n // atomic value rather than a misformatted guess.\n const token = resolveTokenFromAddress(match.tokenAddress)\n const remainingDisplay = token\n ? `${formatAtomicAmount(safeBigInt(match.onchain.remaining), token.decimals)} ${match.tokenSymbol}`\n : undefined\n return {\n payment: status,\n allowance: {\n rail,\n remaining_atomic: match.onchain.remaining,\n ...(remainingDisplay ? { remaining_display: remainingDisplay } : {}),\n token_symbol: match.tokenSymbol,\n token_address: match.tokenAddress,\n reset_period: match.resetPeriodMin,\n source,\n },\n warnings: [],\n }\n } catch (err) {\n return unavailable(err instanceof Error ? err.message : String(err))\n }\n }\n\n /**\n * `haven_get_payment_status` convenience: fetch status and, for a\n * genuinely SETTLED x402 payment, attach the same post-purchase\n * allowance/budget summary a settle response carries.\n *\n * #1310/#1311 parity: this is the ONE home for logic that was duplicated\n * verbatim in `packages/mcp-server/src/tools.ts` and `packages/mcp/src/tools.ts`\n * (both hosted and local `haven_get_payment_status` handlers) — extracted\n * here because both packages already depend on `@haven_ai/sdk` and call\n * methods on a `HavenClient` instance, so this needed no new dependency\n * edge. `funded_but_unsettled` is deliberately excluded: that phase means\n * the merchant did NOT accept the retry. Every other phase/rail returns\n * the status untouched.\n */\n async getPaymentStatusWithPostPurchaseAllowance(paymentId: string): Promise<\n PaymentStatusResult & {\n allowance?: PostPurchaseAllowanceSummary | null\n warnings?: AgentPaymentWarning[]\n }\n > {\n const status = await this.getPaymentStatus(paymentId)\n if (status.rail === AgentPaymentRail.X402 && status.phase === AgentPaymentPhase.PaymentConfirmed) {\n const { allowance, warnings } = await this.getPostPurchaseAllowanceSummary(paymentId)\n return { ...status, allowance, ...(warnings.length > 0 ? { warnings } : {}) }\n }\n return status\n }\n\n /**\n * Discover payable services from Haven's curated merchant catalog.\n *\n * Read-only: returns catalog entries (price, rail, protocol) so an agent\n * can choose a service and pay it with the regular payment tools in the\n * same session. Never creates payments or signatures.\n */\n async discoverTools(\n options: { category?: string; search?: string; rail?: 'x402' | 'mpp' } = {},\n ): Promise<HavenCatalogEntry[]> {\n const params = new URLSearchParams()\n if (options.category) params.set('category', options.category)\n if (options.search !== undefined) params.set('search', options.search)\n if (options.rail) params.set('rail', options.rail)\n const query = params.size > 0 ? `?${params.toString()}` : ''\n const raw = await this.get<{ entries: RawCatalogEntry[] }>(`/catalog${query}`)\n return raw.entries.map(mapCatalogEntry)\n }\n\n /**\n * Fetch one curated catalog entry by id (#1306).\n *\n * Chain-scoped for free by the backend's SQL when the client is\n * agent-authenticated (#1299): an unknown id and an id curated for a\n * DIFFERENT chain than this agent's both 404 identically — this method does\n * not (and must not) re-filter by chain in JS. Read-only, like\n * {@link discoverTools}.\n */\n async getCatalogEntry(id: string): Promise<HavenCatalogEntry> {\n const raw = await this.get<RawCatalogEntry>(`/catalog/${encodeURIComponent(id)}`)\n return mapCatalogEntry(raw)\n }\n\n /**\n * List recent machine-payment receipts/evidence for bookkeeping.\n */\n async listReceipts(options: { limit?: number } = {}): Promise<HavenPaymentReceipt[]> {\n const query = options.limit ? `?limit=${encodeURIComponent(String(options.limit))}` : ''\n const raw = await this.get<RawHavenPaymentReceiptsResponse>(`/machine-payments/receipts${query}`)\n return raw.receipts.map((receipt) => this.mapPaymentReceipt(receipt))\n }\n\n /**\n * Fetch the verifiable receipt bundle for a settled payment and verify it\n * locally. The server's own verification is ignored — the receipt is verified\n * here (independently of Haven) by recovering the signer from the\n * authorisation, so the result is trustworthy even if the backend lied.\n */\n async getReceipt(\n paymentId: string,\n ): Promise<{ receipt: PaymentReceipt; verification: ReceiptVerification }> {\n const { receipt } = await this.get<{ receipt: PaymentReceipt }>(\n `/payments/${paymentId}/receipt`,\n )\n return { receipt, verification: verifyPaymentReceipt(receipt) }\n }\n\n /**\n * Rehydrate the x402 resume-state bundle for a payment id (#1328: the MPP\n * resume-state variant retired along with the rest of the mpp_demo surface).\n *\n * The server returns stored protocol context only. The client still signs the\n * merchant proof locally when resumeX402Payment() runs.\n */\n async getResumeState(paymentId: string): Promise<PaymentResumeState> {\n return this.get<PaymentResumeState>(`/payments/${paymentId}/resume_state`)\n }\n\n /**\n * Poll until a payment reaches a terminal status (confirmed, failed, expired).\n */\n async waitForConfirmation(paymentId: string): Promise<PaymentResult> {\n const deadline = Date.now() + this.confirmationTimeout\n\n while (Date.now() < deadline) {\n const result = await this.getPayment(paymentId)\n\n if (result.status === 'confirmed' || result.status === 'failed' || result.status === 'expired') {\n return result\n }\n\n await sleep(this.pollingInterval)\n }\n\n throw new HavenTimeoutError(paymentId)\n }\n\n // ── x402 Protocol Support ────────────────────────────────────────\n\n /**\n * Authorize an x402 payment.\n *\n * Takes the parsed PaymentRequired from a 402 response, selects a compatible\n * option, funds the delegate wallet through Haven, and returns the standard\n * x402 header that the merchant can verify and settle.\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async authorizeX402(\n paymentRequired: X402PaymentRequired,\n options: X402AuthorizationOptions = {},\n ): Promise<X402Receipt> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'delegateKey is required for x402 payments. Pass it in the HavenClient config.',\n )\n }\n if (!this.delegateAddress) {\n throw new HavenSigningError('delegateAddress could not be derived from delegateKey.')\n }\n\n // 1. Select best payment option\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n if (!option) {\n throw new HavenApiError(\n 'No compatible payment option found in x402 requirements. ' +\n 'Haven supports standard x402 exact payments on Base USDC.',\n 400,\n )\n }\n\n const idempotencyKey = options.idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option)\n const cached = this.x402ReceiptCache.get(idempotencyKey)\n if (cached && cached.expiresAt > Date.now()) return cached.receipt\n\n const inFlight = this.inFlightX402.get(idempotencyKey)\n if (inFlight) return inFlight\n\n const promise = this.authorizeStandardX402(paymentRequired, option, idempotencyKey)\n this.inFlightX402.set(idempotencyKey, promise)\n\n try {\n return await promise\n } catch (err) {\n this.attachResumeState(err, {\n rail: 'x402',\n paymentRequired,\n accepted: option,\n idempotencyKey,\n })\n throw err\n } finally {\n this.inFlightX402.delete(idempotencyKey)\n }\n }\n\n /**\n * Probe a paid endpoint and return its x402 quote without creating a Haven\n * payment or approval request.\n */\n async quoteX402(\n url: string,\n init?: RequestInit,\n options: X402AuthorizationOptions = {},\n ): Promise<X402Quote> {\n const initialInit = this.withX402Wallet(init, this.x402PayerAddress())\n const request = this.snapshotX402Request(url, initialInit)\n const response = await this.merchantFetch(url, initialInit)\n\n if (response.status !== 402) {\n // #1300: typed, so consumers key on the class instead of message text.\n throw new X402UnexpectedStatusError(\n `Expected an x402 quote response with HTTP 402, got HTTP ${response.status}.`,\n response.status || 400,\n )\n }\n\n if (response.headers.get('MACHINE-PAYMENT-CHALLENGE')) {\n throw new HavenApiError('quoteX402 only supports standard x402 Payment Required responses.', 400)\n }\n\n const paymentRequired = await parsePaymentRequiredResponse(response)\n const mcpTransport = await this.detectX402McpTransport(url, paymentRequired, response)\n return this.buildX402Quote(paymentRequired, request, options.idempotencyKey, mcpTransport)\n }\n\n /**\n * Probe an MCP tool for its x402 quote without creating a payment.\n *\n * Unlike the generic {@link quoteX402} helper, this completes the\n * Streamable-HTTP MCP lifecycle before sending the unpaid `tools/call`.\n * Hosted MCP uses this path while remaining keyless: it resolves only the\n * agent's public delegate address for `x402-wallet`; signing remains local.\n * It refuses before the quote when the merchant does not establish a session;\n * callers that need a plain x402 endpoint must use {@link quoteX402}.\n */\n async quoteMcpX402(\n url: string,\n init?: RequestInit,\n options: X402AuthorizationOptions = {},\n ): Promise<X402Quote> {\n const wallet = await this.resolveX402WalletForMerchantCall()\n const sessionId = await this.mcpInitialize(url, init, wallet)\n if (!sessionId) {\n throw new HavenApiError(\n 'The merchant did not establish an MCP session before the x402 quote. No payment was created.',\n 502,\n { mcpSessionNotEstablished: true },\n )\n }\n\n let requestInit = this.withX402Wallet(init, wallet)\n requestInit = this.withMcpHeaders(requestInit, sessionId)\n\n const quote = await this.quoteX402(url, requestInit, options)\n // This dedicated helper established an MCP session even when the endpoint\n // uses a custom path and does not advertise Bazaar metadata. Preserve that\n // fact for the later, fresh session used by the paid retry.\n return {\n ...quote,\n mcpTransport: quote.mcpTransport ?? { handshakeRequired: true, source: 'path' },\n }\n }\n\n /**\n * Pay a previously inspected x402 quote and retry the exact captured request.\n */\n async payX402Quote(\n quote: X402Quote,\n options: X402AuthorizationOptions = {},\n ): Promise<Response> {\n const idempotencyKey = options.idempotencyKey ?? quote.idempotencyKey\n\n try {\n const receipt = await this.authorizeX402(quote.paymentRequired, { idempotencyKey })\n return this.retryX402Request(\n quote.request.url,\n this.requestInitFromSnapshot(quote.request),\n quote.paymentRequired,\n receipt,\n )\n } catch (err) {\n this.attachResumeState(err, {\n rail: 'x402',\n paymentRequired: quote.paymentRequired,\n accepted: quote.accepted,\n idempotencyKey,\n request: quote.request,\n })\n throw err\n }\n }\n\n private async authorizeStandardX402(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n idempotencyKey: string,\n ): Promise<X402Receipt> {\n // 2. Standard x402 settles from an EOA, so the SDK uses the agent-owned\n // delegate EOA for the merchant-facing EIP-3009 authorization. Haven does\n // not control this EOA or its private key.\n //\n // The only automated funding path is a separate Safe AllowanceModule\n // transfer signed by the agent key and constrained by the user's on-chain\n // allowance. Haven's backend relays that signed top-up; it is not the source\n // of payment authority.\n // Sign before funding so retries reuse one EIP-3009 nonce. If funding fails,\n // the unused authorization simply expires via validBefore.\n const paymentHeader = await this.createStandardX402Header(paymentRequired, option)\n const raw = await this.post<RawX402AuthorizeResponse>('/x402', {\n url: paymentRequired.resource.url,\n payTo: this.delegateAddress,\n merchantPayTo: option.payTo,\n amount: x402AuthorizationAmount(option),\n asset: option.asset,\n network: option.network,\n description: paymentRequired.resource.description,\n idempotencyKey,\n // #1360: same explicit funding-leg declaration as createX402Intent —\n // this local-key path derives payTo from the key (never stale), but the\n // declaration keeps both writers of the 3009 shape loud-by-default.\n settlementScheme: 'eip3009',\n })\n\n // If the backend already executed (shouldn't happen without sig), return\n if (raw.success && raw.tx_hash) {\n const receipt = this.mapX402ReceiptFromAuthorization(paymentRequired, option, paymentHeader, raw)\n this.cacheX402Receipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n const state = this.paymentStateFromRaw('x402 payment', raw)\n if (state?.nextAction === AgentPaymentNextAction.RetryOriginalX402Request) {\n const receipt = this.mapX402ReceiptFromStatus(paymentRequired, option, paymentHeader, state)\n this.cacheX402Receipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n this.throwIfNonSignableAuthorizationState('x402 payment', raw)\n\n // 3. Sign the hash\n if (!raw.sign_data?.hash) {\n throw new HavenApiError('No sign_hash returned from x402/authorize', 500, raw)\n }\n const sig = await this.signForData(raw.sign_data)\n\n // 4. Submit signature (reuse existing payments/:id/sign endpoint)\n const execResult = await this.post<RawSignResponse>(\n `/payments/${raw.payment_id}/sign`,\n { signature: sig },\n )\n\n if (execResult.status !== 'confirmed') {\n this.throwPaymentStateError('x402 payment', execResult)\n }\n\n // Wait for ≥1 on-chain confirmation before retrying the merchant so the\n // merchant's balanceOf(delegate) check sees the funded balance.\n await this.waitForFundingTx(\n execResult.tx_hash,\n execResult.chain_id ?? chainIdFromNetwork(option.network),\n )\n\n const receipt = this.mapX402ReceiptFromAuthorization(paymentRequired, option, paymentHeader, raw, execResult)\n this.cacheX402Receipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n /**\n * Pay a merchant through **erc7710 direct settlement** (#1454, epic #1450).\n *\n * The whole point of this path is what it does NOT do. There is no funding\n * leg: the merchant redeems a delegation chain and pulls from the treasury\n * directly, so the delegate EOA never holds the money, no sweep can strand\n * it, and the #713 reconciliation class does not apply. It is also why this\n * method is SMALLER than the 3009 path — the backend assembles the merchant\n * `X-PAYMENT` header in `assembleSettlementPayload`, so the SDK builds no\n * header locally.\n *\n * authorize (payTo = the MERCHANT) → sign the child → settle → header\n *\n * The caller then retries the merchant with that header. **Nothing has\n * settled when this returns** — that is why it does not return an\n * `X402Receipt`.\n *\n * Requires a delegation-rail account. The backend enforces that\n * (`validateGenericSchemeRail`), and so does this method, before building a\n * request the backend would only reject: an error a client can explain is\n * worth more than a 400 it has to decode.\n *\n * **MCP callers must pass `options.resourceUrl`.** An in-band MCP 402\n * challenge frequently carries no `resource` object at all, so\n * `paymentRequired.resource?.url` is undefined and the backend answers\n * \"Valid url is required\". The QA scenario this path was ported from falls\n * back to the request URL for exactly that reason — the SDK cannot, because\n * it never saw the request. Pass it.\n */\n async settleX402Erc7710(\n paymentRequired: X402PaymentRequired,\n options: { resourceUrl?: string } = {},\n ): Promise<X402Erc7710Settlement> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'delegateKey is required for x402 payments. Pass it in the HavenClient config.',\n )\n }\n const prepared = await this.prepareX402Erc7710(paymentRequired, options)\n const signature = await this.signForData(prepared.signData)\n const paymentHeader = await this.submitX402Erc7710(prepared.paymentId, signature)\n return { ...prepared.settlement, paymentHeader }\n }\n\n /**\n * The AUTHORIZE half of erc7710 settlement (#1456): select the scheme, build\n * the request, and return the child to be signed — without signing it.\n *\n * Split out because the hosted topology cannot use `settleX402Erc7710()`:\n * that method signs in-process with `delegateKey`, and hosted Haven does not\n * have one and must not. The hosted MCP server drives these two halves with\n * the LOCAL signer in between, so the key stays where it belongs and the\n * request shaping stays in one place rather than being reimplemented.\n */\n async prepareX402Erc7710(\n paymentRequired: X402PaymentRequired,\n options: {\n resourceUrl?: string\n /**\n * The account's rail, when the caller has ALREADY read it from\n * `GET /machine-payments/agent` — passing it skips a duplicate fetch\n * (#1456: the hosted tool reads the agent for the delegate address\n * anyway, and #1348 pins that path to exactly one agent round-trip).\n *\n * This is an optimisation, not a trust boundary: omit it and the rail is\n * read here, and either way the backend independently refuses erc7710\n * from a non-delegation account (`validateGenericSchemeRail`). A caller\n * that asserted the wrong rail would build a request the backend rejects.\n */\n delegationRail?: boolean\n } = {},\n ): Promise<{\n paymentId: string\n signData: SignData\n settlement: Omit<X402Erc7710Settlement, 'paymentHeader'>\n }> {\n\n // The rail half of the #1450 preference rule is not visible in a 402\n // response — it is a property of the ACCOUNT, so read it rather than let a\n // caller assert it. #1453's selector takes it as input for exactly this\n // reason, and this is the one place that input is sourced from truth.\n const delegationRail =\n options.delegationRail ?? (await this.getAgent()).executionRail === 'delegation'\n\n // Rail first, and BEFORE selection — the two failures have different\n // remedies and the caller needs the one that applies. Checking selection\n // first made a legacy-rail agent at an erc7710-only merchant get \"no\n // compatible payment option\", which is true and useless: the option is\n // there, the account cannot use it. (Found by this method's own tests.)\n if (!delegationRail) {\n throw new HavenApiError(\n 'erc7710 settlement requires a delegation-rail account; this one is not on it. ' +\n 'Use authorizeX402() for the standard EIP-3009 path.',\n 400,\n )\n }\n\n const selection = selectX402SettlementScheme(paymentRequired.accepts, { delegationRail })\n\n if (!selection || selection.scheme !== 'erc7710') {\n // Never silently reroute to the other scheme (#1454 AC). On a delegation\n // rail the only remaining reason is the merchant, so name that.\n throw new HavenApiError(\n 'This merchant does not advertise an erc7710 settlement option ' +\n \"(no accepts[] entry carries extra.assetTransferMethod: 'erc7710'). \" +\n 'Use authorizeX402() for the standard EIP-3009 path.',\n 400,\n )\n }\n\n const option = selection.option\n const merchantPayTo = option.payTo\n const amountAtomic = x402AuthorizationAmount(option)\n\n const raw = await this.post<RawX402AuthorizeResponse>('/x402', {\n url: options.resourceUrl ?? paymentRequired.resource?.url,\n // payTo = the MERCHANT is what selects direct settlement server-side.\n // The explicit settlementScheme must AGREE with that shape (#1360) —\n // disagreement is a 400 by design, so that a stale delegate address\n // becomes a loud mismatch instead of a silent reroute to the 3009 leg.\n payTo: merchantPayTo,\n settlementScheme: 'erc7710',\n amount: amountAtomic,\n asset: option.asset,\n network: option.network,\n // The v2 header echoes the accepted entry field-for-field, so the quoted\n // timeout must round-trip or the merchant rejects the echo (#1064).\n maxTimeoutSeconds: option.maxTimeoutSeconds,\n // #1058: forward the advertised facilitators verbatim — the child becomes\n // redeemable ONLY by them. `null` here means the merchant advertised none\n // (or an empty array, which the backend 400s on), so the field is OMITTED\n // rather than sent empty. See x402FacilitatorAddresses.\n ...(selection.facilitatorAddresses\n ? { facilitatorAddresses: selection.facilitatorAddresses }\n : {}),\n })\n\n if (!raw.payment_id) {\n throw new HavenApiError('No payment_id returned from x402/authorize', 500, raw)\n }\n const signData = raw.sign_data\n if (signData?.signature_scheme !== 'eip712_delegation' || !signData.typed_data) {\n // The backend chose a different scheme than the shape asked for. Refuse\n // loudly: signing whatever came back would be exactly the \"silent\n // reroute\" this path exists to make impossible.\n throw new HavenApiError(\n 'x402/authorize did not return an erc7710 settlement child ' +\n `(signature_scheme was ${JSON.stringify(signData?.signature_scheme)}). ` +\n 'Refusing to sign a payload this path did not ask for.',\n 500,\n raw,\n )\n }\n\n return {\n paymentId: raw.payment_id,\n signData,\n settlement: {\n paymentId: raw.payment_id,\n merchantPayTo,\n amountAtomic,\n asset: option.asset,\n network: option.network,\n facilitatorAddresses: selection.facilitatorAddresses,\n },\n }\n }\n\n /**\n * The SETTLE half (#1456): exchange the signed child for the merchant header.\n *\n * The SDK builds no header on this path — the backend assembles the MetaMask\n * erc7710 payload in `assembleSettlementPayload`. Whoever produced the\n * signature (an in-process delegate key, or the local edge signer over the\n * hosted boundary) is irrelevant here.\n */\n async submitX402Erc7710(paymentId: string, signature: string): Promise<string> {\n const settled = await this.post<RawX402SettleResponse>(\n `/x402/${paymentId}/settle`,\n { signature },\n )\n if (!settled.payment_header) {\n throw new HavenApiError(\n 'x402 settle returned no payment_header — the merchant cannot be retried.',\n 500,\n settled,\n )\n }\n return settled.payment_header\n }\n\n async resumeAuthorizedX402(input: ResumeAuthorizedX402Input): Promise<X402Receipt> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'delegateKey is required for x402 payments. Pass it in the HavenClient config.',\n )\n }\n if (!this.delegateAddress) {\n throw new HavenSigningError('delegateAddress could not be derived from delegateKey.')\n }\n\n const option = selectStandardPaymentOption(input.paymentRequired.accepts)\n if (!option) {\n throw new HavenApiError(\n 'No compatible payment option found in x402 requirements. ' +\n 'Haven supports standard x402 exact payments on Base USDC.',\n 400,\n )\n }\n\n const idempotencyKey = input.idempotencyKey ?? buildX402IdempotencyKey(input.paymentRequired, option)\n const cached = this.x402ReceiptCache.get(idempotencyKey)\n if (cached && cached.expiresAt > Date.now()) return cached.receipt\n\n const status = await this.getPaymentStatus(input.paymentId)\n this.assertCanResumeX402(status, input.paymentRequired, option)\n\n const paymentHeader = await this.createStandardX402Header(input.paymentRequired, option)\n const receipt = this.mapX402ReceiptFromStatus(input.paymentRequired, option, paymentHeader, status)\n this.cacheX402Receipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n async resumeX402Payment(input: ResumeX402PaymentInput | X402ResumeState): Promise<Response> {\n const inputInit = 'init' in input ? input.init : undefined\n const initialInit = this.withX402Wallet(\n inputInit ?? (input.request ? this.requestInitFromSnapshot(input.request) : undefined),\n this.x402PayerAddress(),\n )\n let paymentRequired = input.paymentRequired\n const url = input.url ?? input.request?.url\n\n if (!paymentRequired) {\n if (!url) {\n throw new HavenApiError('x402 resume requires the original URL or a captured request snapshot.', 400)\n }\n const response = await this.merchantFetch(url, initialInit)\n if (response.status !== 402) {\n throw new HavenApiError('Expected the original x402 request to return HTTP 402 before resuming.', 400)\n }\n paymentRequired = await parsePaymentRequiredResponse(response)\n }\n\n const receipt = await this.resumeAuthorizedX402({\n paymentId: input.paymentId,\n paymentRequired,\n idempotencyKey: input.idempotencyKey,\n })\n\n return this.retryX402Request(url ?? paymentRequired.resource.url, initialInit, paymentRequired, receipt)\n }\n\n /**\n * Fetch wrapper that automatically handles HTTP 402 responses.\n *\n * Works like the standard `fetch()` but intercepts 402 responses,\n * pays via x402 through Haven, and retries the request.\n *\n * ```ts\n * const response = await haven.fetch('https://paid-api.com/data')\n * const data = await response.json()\n * ```\n *\n * **MCP-over-x402 auto-handshake (issue #315):** when the endpoint is\n * MCP-shaped — the URL path ends in `/mcp`, or the 402 body carries a\n * Coinbase Bazaar `extensions.bazaar` block — the SDK runs the MCP\n * `initialize` handshake, threads the resulting `mcp-session-id`,\n * `Accept: application/json, text/event-stream`, and `x402-wallet` headers\n * through every request, and collapses SSE responses to the JSON-RPC\n * `result`. The caller just passes `(url, { body })` and never sees the\n * protocol plumbing. A non-MCP server (handshake error / no session id)\n * falls back to standard x402 behaviour.\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async fetch(\n url: string,\n init?: RequestInit,\n options: X402AuthorizationOptions = {},\n ): Promise<Response> {\n // Signal A: a `/mcp` path is the MCP-over-HTTP convention, so handshake\n // up front — before the probe — so the session id rides on the probe and\n // the retry alike. A non-MCP server yields `undefined` and we fall back.\n let mcpSessionId: string | undefined\n if (isMcpUrl(url)) {\n mcpSessionId = await this.mcpInitialize(url, init)\n }\n\n let requestInit = this.withX402Wallet(init, this.x402PayerAddress())\n if (mcpSessionId) requestInit = this.withMcpHeaders(requestInit, mcpSessionId)\n\n // 1. Make the original request\n const response = await this.merchantFetch(url, requestInit)\n\n // 2. Not a 402 — return as-is (collapsing SSE for MCP sessions)\n if (response.status !== 402) {\n return mcpSessionId ? this.surfaceMcpResult(response) : response\n }\n\n // #1328: the legacy MACHINE-PAYMENT-CHALLENGE / mpp_demo auto-handling is\n // retired — a 402 that isn't standard x402 (including a stray\n // MACHINE-PAYMENT-CHALLENGE header from a pre-retirement caller) is\n // returned to the agent unmodified rather than auto-paid.\n\n // 3. Parse x402 payment requirements\n let paymentRequired: X402PaymentRequired\n try {\n paymentRequired = await parsePaymentRequiredResponse(response)\n } catch {\n // Not a standard x402 402 response — return it unchanged.\n return response\n }\n\n // Signal B: a Bazaar `extensions.bazaar` block marks an MCP-discoverable\n // resource even without the `/mcp` convention. Handshake now (if we\n // haven't already) so the paid retry carries the session id.\n if (!mcpSessionId && (await responseHasBazaarExtension(response))) {\n mcpSessionId = await this.mcpInitialize(url, init)\n if (mcpSessionId) requestInit = this.withMcpHeaders(requestInit, mcpSessionId)\n }\n\n // 4. Pay through Haven\n const request = this.snapshotX402Request(url, requestInit)\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n const idempotencyKey = options.idempotencyKey ?? (option ? buildX402IdempotencyKey(paymentRequired, option) : undefined)\n let receipt: X402Receipt\n try {\n receipt = await this.authorizeX402(paymentRequired, options)\n } catch (err) {\n if (option && idempotencyKey) {\n this.attachResumeState(err, {\n rail: 'x402',\n paymentRequired,\n accepted: option,\n idempotencyKey,\n request,\n })\n }\n throw err\n }\n const retryResponse = await this.retryX402Request(url, requestInit, paymentRequired, receipt)\n return mcpSessionId ? this.surfaceMcpResult(retryResponse) : retryResponse\n }\n\n // ── MCP-over-x402 transport helpers (issue #315) ─────────────────\n\n /**\n * Run the MCP `initialize` handshake against a Streamable-HTTP endpoint and\n * return the `mcp-session-id` the server assigns.\n *\n * Returns `undefined` whenever the endpoint is not actually an MCP server —\n * a transport/HTTP error, a missing session id, or a JSON-RPC error in the\n * handshake response — so the caller can fall back to plain x402.\n */\n private async mcpInitialize(\n url: string,\n init?: RequestInit,\n wallet = this.x402PayerAddress(),\n ): Promise<string | undefined> {\n try {\n const headers = new Headers(init?.headers)\n headers.set('Content-Type', 'application/json')\n headers.set('Accept', MCP_ACCEPT)\n if (wallet && !headers.has('x402-wallet')) headers.set('x402-wallet', wallet)\n\n const response = await this.merchantFetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: ++this.mcpRequestId,\n method: 'initialize',\n params: {\n protocolVersion: MCP_PROTOCOL_VERSION,\n capabilities: {},\n clientInfo: MCP_CLIENT_INFO,\n },\n }),\n })\n\n if (!response.ok) return undefined\n\n const sessionId = response.headers.get('mcp-session-id')\n if (!sessionId) return undefined\n\n // A JSON-RPC error means the server spoke MCP but rejected the\n // handshake — treat it as non-MCP and fall back to standard x402.\n const message = await this.readMcpMessage(response)\n if (message && 'error' in message) return undefined\n\n // Per the MCP lifecycle, the client confirms initialization with a\n // `notifications/initialized` notification. Servers that gate tool\n // calls on it would otherwise reject every subsequent request.\n await this.mcpNotifyInitialized(url, init, sessionId, wallet)\n\n return sessionId\n } catch {\n return undefined\n }\n }\n\n /**\n * Send the MCP `notifications/initialized` notification that completes the\n * lifecycle handshake. Best-effort: the session is already established, so a\n * failed notification must not abort the payment.\n */\n private async mcpNotifyInitialized(\n url: string,\n init: RequestInit | undefined,\n sessionId: string,\n wallet = this.x402PayerAddress(),\n ): Promise<void> {\n try {\n const headers = new Headers(init?.headers)\n headers.set('Content-Type', 'application/json')\n headers.set('Accept', MCP_ACCEPT)\n headers.set('mcp-session-id', sessionId)\n if (wallet && !headers.has('x402-wallet')) headers.set('x402-wallet', wallet)\n\n // #1300 review: best-effort notification, discarded either way — do not\n // give it the settlement-sized budget.\n await this.merchantFetch(\n url,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }),\n },\n NOTIFY_TIMEOUT,\n )\n } catch {\n // Best-effort — see doc comment.\n }\n }\n\n /** Read a single JSON-RPC message from an MCP response (JSON or SSE body). */\n private async readMcpMessage(response: Response): Promise<Record<string, unknown> | undefined> {\n let text: string\n try {\n text = await response.clone().text()\n } catch {\n return undefined\n }\n\n if ((response.headers.get('content-type') ?? '').includes('text/event-stream')) {\n return selectJsonRpcResult(parseSseJsonRpcMessages(text))\n }\n\n try {\n return JSON.parse(text) as Record<string, unknown>\n } catch {\n return undefined\n }\n }\n\n /** Add the MCP transport headers (session id + SSE Accept) to a request. */\n private withMcpHeaders(init: RequestInit | undefined, sessionId: string): RequestInit {\n const headers = new Headers(init?.headers)\n headers.set('mcp-session-id', sessionId)\n headers.set('Accept', MCP_ACCEPT)\n return { ...init, headers }\n }\n\n /**\n * Collapse an MCP SSE response into a plain JSON response carrying the\n * JSON-RPC `result`, so callers of `fetch()` never see raw SSE framing.\n * Non-SSE responses pass through untouched.\n */\n private async surfaceMcpResult(response: Response): Promise<Response> {\n if (!(response.headers.get('content-type') ?? '').includes('text/event-stream')) {\n return response\n }\n\n let text: string\n try {\n text = await response.clone().text()\n } catch {\n return response\n }\n\n const message = selectJsonRpcResult(parseSseJsonRpcMessages(text))\n if (!message) return response\n\n const body = 'result' in message ? message.result : message\n const headers = new Headers(response.headers)\n headers.set('content-type', 'application/json')\n headers.delete('content-length')\n // Don't leak the transport session id back to the caller — the whole\n // point of the auto-handshake is that the agent never sees MCP plumbing.\n headers.delete('mcp-session-id')\n\n return new Response(JSON.stringify(body), {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n }\n\n private async retryX402Request(\n url: string,\n initialInit: RequestInit | undefined,\n paymentRequired: X402PaymentRequired,\n receipt: X402Receipt,\n ): Promise<Response> {\n if (!receipt.accepted) {\n throw new HavenApiError('No accepted x402 option was recorded for payment retry', 500)\n }\n if (!receipt.paymentHeader) {\n throw new HavenApiError('No x402 payment header was returned for payment retry', 500)\n }\n\n // 5. Retry with a merchant-verifiable x402 EIP-3009 payment header.\n const retryHeaders = new Headers(initialInit?.headers)\n retryHeaders.set('X-PAYMENT', receipt.paymentHeader)\n\n const retryResponse = await this.merchantFetch(url, {\n ...initialInit,\n headers: retryHeaders,\n })\n\n if (!retryResponse.ok) {\n const merchant = await captureMerchantResponse(retryResponse)\n await this.recordMerchantRetryRejected({\n rail: 'x402',\n paymentId: receipt.paymentId,\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n merchant,\n details: {\n merchant_to: receipt.merchantTo,\n delegate_to: receipt.to,\n },\n })\n\n throw new HavenApiError(\n 'x402 retry failed after Haven funded the delegate wallet; reconciliation may be required.',\n merchant.merchant_status,\n {\n marker: 'x402_retry_rejected_after_funding',\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n resource_url: receipt.resourceUrl,\n merchant_to: receipt.merchantTo,\n delegate_to: receipt.to,\n ...merchant,\n },\n )\n }\n\n const merchantSettlement = parseMerchantSettlement(retryResponse.headers.get('PAYMENT-RESPONSE'))\n if (receipt.merchant && merchantSettlement.settlementTxHash) {\n receipt.merchant.settlementTxHash = merchantSettlement.settlementTxHash\n receipt.merchant.settlementExplorerUrl = buildExplorerUrl(\n receipt.chainId,\n merchantSettlement.settlementTxHash,\n )\n }\n\n await this.reportMachinePaymentEvidence({\n paymentId: receipt.paymentId,\n rail: 'x402',\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n merchantStatus: retryResponse.status,\n challengePayload: paymentRequired as unknown as Record<string, unknown>,\n selectedPayment: receipt.accepted as unknown as Record<string, unknown>,\n paymentProofHeaderName: 'X-PAYMENT',\n paymentProofHeader: receipt.paymentHeader,\n protocolReceiptHeaderName: 'PAYMENT-RESPONSE',\n protocolReceiptHeader: retryResponse.headers.get('PAYMENT-RESPONSE') ?? undefined,\n })\n\n await this.reportMerchantReceipt(receipt.paymentId, retryResponse)\n\n return retryResponse\n }\n\n /**\n * #956: capture the merchant's OWN receipt when the paid response carries\n * one, and report it to Haven so the reporting feed can attach it next to\n * the Haven-generated payment evidence (#498). Two supported signals on the\n * paid response:\n *\n * x-receipt-json: base64-encoded JSON receipt document (inline)\n * x-receipt-url: https URL to the receipt document (reference)\n *\n * Strictly best-effort: absence is the normal case, and no failure here may\n * ever affect the completed payment — the response is already paid for.\n */\n private async reportMerchantReceipt(paymentId: string, response: Response): Promise<void> {\n try {\n const inlineB64 = response.headers.get('x-receipt-json')\n const url = response.headers.get('x-receipt-url')\n if (!inlineB64 && !url) return\n\n let body: Record<string, unknown> | null = null\n if (inlineB64) {\n // Mirror the backend's 64KB decoded cap exactly (base64 inflates 4/3)\n // — don't ship what the server will reject.\n if (inlineB64.length > Math.ceil((64 * 1024 * 4) / 3)) return\n const decoded = JSON.parse(Buffer.from(inlineB64, 'base64').toString('utf8')) as unknown\n if (decoded && typeof decoded === 'object') body = { json: decoded }\n } else if (url && url.startsWith('https://') && url.length <= 2048) {\n body = { url }\n }\n if (!body) return\n\n await this.post(`/machine-payments/${paymentId}/merchant-receipt`, body)\n } catch {\n // Best-effort by contract — a malformed header or a capture-endpoint\n // hiccup never surfaces to the caller of a successful payment.\n }\n }\n\n /**\n * Deliver an already-signed x402 payment header to the merchant and return\n * the merchant's response. Used by the hosted MCP server to complete the\n * merchant leg of an MCP tool payment after the edge signer has built the\n * `X-PAYMENT` header.\n *\n * Custody note: this never needs the delegate key. It relays a signed,\n * amount/merchant/nonce-bound EIP-3009 authorization the edge signer already\n * produced — the hosted server cannot mint or reuse signing authority.\n *\n * When the URL is MCP-shaped (`/mcp` path) or the quote-time transport context\n * says the merchant was Bazaar-discoverable, runs a fresh `initialize`\n * handshake (the quote-time session is gone once funding confirms; the x402\n * challenge is stateless w.r.t. the MCP session, so a fresh session is\n * accepted), threads the session + wallet headers, sets `X-PAYMENT`, and\n * collapses an SSE JSON-RPC response to its `result`.\n */\n /**\n * Wait for a payment's Safe→delegate funding tx to reach ≥1 on-chain\n * confirmation. The hosted x402 completion path MUST call this after funding\n * and before delivering the X-PAYMENT header, so the merchant's\n * balanceOf(delegate) / transferWithAuthorization verification sees the funded\n * balance — otherwise it rejects with \"Payment verification failed\". The\n * SDK's local path already does this (see authorizeStandardX402); the hosted\n * split flow regressed when the 5→3 collapse removed the incidental\n * inter-call latency that used to mask it. No-op when the funding tx hash or\n * a chain RPC (chainRpcs[chainId]) is unavailable.\n */\n async ensureFundingConfirmed(paymentId: string, fundingTxHash?: string): Promise<void> {\n const status = await this.getPaymentStatus(paymentId)\n await this.waitForFundingTx(fundingTxHash ?? status.txHash ?? undefined, status.chainId)\n }\n\n async completeX402MerchantCall(input: {\n url: string\n init?: RequestInit\n paymentId: string\n paymentHeader: string\n mcpTransport?: X402McpTransport\n }): Promise<{ status: number; ok: boolean; body: unknown; settlementTxHash?: string }> {\n const evidenceContext = await this.resolveX402MerchantCompletionContext({\n paymentId: input.paymentId,\n url: input.url,\n })\n const shouldHandshakeMcp =\n isMcpUrl(input.url) ||\n input.mcpTransport?.handshakeRequired === true\n const x402Wallet = shouldHandshakeMcp ? await this.resolveX402WalletForMerchantCall() : this.x402PayerAddress()\n let mcpSessionId: string | undefined\n if (shouldHandshakeMcp) {\n mcpSessionId = await this.mcpInitialize(input.url, input.init, x402Wallet)\n }\n\n let requestInit: RequestInit = this.withX402Wallet(input.init, x402Wallet) ?? {}\n if (mcpSessionId) requestInit = this.withMcpHeaders(requestInit, mcpSessionId)\n const headers = new Headers(requestInit.headers)\n headers.set('X-PAYMENT', input.paymentHeader)\n requestInit = { ...requestInit, headers }\n\n const response = await this.merchantFetch(input.url, requestInit)\n const surfaced = mcpSessionId ? await this.surfaceMcpResult(response) : response\n const protocolReceiptHeader = surfaced.headers.get('PAYMENT-RESPONSE') ?? undefined\n const settlement = parseMerchantSettlement(protocolReceiptHeader ?? null)\n\n const text = await surfaced.text()\n let body: unknown\n try {\n body = text ? JSON.parse(text) : null\n } catch {\n body = text\n }\n\n if (!surfaced.ok) {\n await this.recordMerchantRetryRejected({\n rail: 'x402',\n paymentId: evidenceContext.paymentId,\n txHash: evidenceContext.txHash,\n resourceUrl: evidenceContext.resourceUrl,\n merchant: {\n merchant_status: surfaced.status,\n merchant_status_text: surfaced.statusText,\n merchant_headers: Object.fromEntries(surfaced.headers.entries()),\n merchant_body: text,\n },\n details: {\n merchant_to: evidenceContext.merchantAddress,\n },\n })\n } else {\n await this.reportMachinePaymentEvidence({\n paymentId: evidenceContext.paymentId,\n rail: 'x402',\n txHash: evidenceContext.txHash,\n resourceUrl: evidenceContext.resourceUrl,\n merchantStatus: surfaced.status,\n paymentProofHeaderName: 'X-PAYMENT',\n paymentProofHeader: input.paymentHeader,\n protocolReceiptHeaderName: protocolReceiptHeader ? 'PAYMENT-RESPONSE' : undefined,\n protocolReceiptHeader,\n })\n // #956: the hosted-MCP completion path is a successful paid retry too —\n // capture the merchant's receipt exactly like the local flow does.\n await this.reportMerchantReceipt(evidenceContext.paymentId, surfaced)\n }\n\n return {\n status: surfaced.status,\n ok: surfaced.ok,\n body,\n settlementTxHash: settlement.settlementTxHash ?? undefined,\n }\n }\n\n /**\n * GET /x402/:id/merchant-call-context — the settle-leg twin of #1263's\n * sign-context fetch (#1307). Re-serves the stored merchant MCP-tool call\n * context (merchant_url, tool_name, arguments, mcp_transport) recorded at\n * quote time, so `haven_settle_mcp_tool` / `haven_complete_mcp_tool` can\n * omit those fields and let Haven rehydrate them by payment_id instead of\n * the caller re-threading them. Throws `HavenApiError` (404 unknown/foreign\n * payment_id, 409 no stored context, 410 expired) — the caller decides the\n * fallback (re-send the full context explicitly).\n */\n async getX402MerchantCallContext(paymentId: string): Promise<X402MerchantCallContext> {\n const raw = await this.get<RawX402MerchantCallContext>(\n `/x402/${paymentId}/merchant-call-context`,\n )\n return {\n paymentId: raw.payment_id,\n merchantUrl: raw.merchant_url,\n toolName: raw.tool_name,\n arguments: raw.arguments ?? {},\n ...(raw.mcp_transport\n ? {\n mcpTransport: {\n handshakeRequired: raw.mcp_transport.handshake_required,\n source: raw.mcp_transport.source,\n },\n }\n : {}),\n }\n }\n\n private async resolveX402MerchantCompletionContext(input: {\n paymentId: string\n url: string\n }): Promise<{\n paymentId: string\n txHash: string\n resourceUrl: string\n merchantAddress: string | null\n }> {\n const status = await this.getPaymentStatus(input.paymentId)\n\n if (status.rail !== 'x402') {\n throw new HavenPaymentStateError(\n `Payment ${status.paymentId} is ${status.rail}, not x402.`,\n 409,\n status,\n )\n }\n\n const readyForMerchantCompletion =\n status.nextAction === AgentPaymentNextAction.RetryOriginalX402Request ||\n (\n status.kind === 'payment_intent' &&\n status.status === 'confirmed' &&\n status.phase === AgentPaymentPhase.PaymentConfirmed &&\n status.nextAction === AgentPaymentNextAction.None\n )\n\n if (!readyForMerchantCompletion) {\n throw new HavenPaymentStateError(status.message, PAYMENT_STATE_STATUS_CODES[status.status] ?? 409, status)\n }\n\n if (!status.txHash) {\n throw new HavenApiError(\n `x402 payment ${status.paymentId} is ready for merchant completion but has no Haven transaction hash.`,\n 502,\n status,\n status.paymentId,\n )\n }\n\n const approvedResourceUrl = status.resourceUrl ?? status.x402?.resourceUrl ?? null\n if (approvedResourceUrl && approvedResourceUrl !== input.url) {\n throw new HavenApiError(\n 'x402 merchant completion does not match the approved resource URL.',\n 409,\n { status, url: input.url },\n status.paymentId,\n )\n }\n\n return {\n paymentId: status.paymentId,\n txHash: status.txHash,\n resourceUrl: approvedResourceUrl ?? input.url,\n merchantAddress: status.merchantAddress ?? status.x402?.merchantAddress ?? null,\n }\n }\n\n private async resolveX402WalletForMerchantCall(): Promise<string | undefined> {\n const localWallet = this.x402PayerAddress()\n if (localWallet) return localWallet\n\n try {\n const agent = await this.getAgent()\n return agent.delegateAddress ?? undefined\n } catch {\n return undefined\n }\n }\n\n // #1328: authorizeMachinePayment / authorizeMppDemoPayment / resumeAuthorizedMpp\n // / resumeMppPayment / fetchWithMachinePayment / retryMppRequest (the\n // MACHINE-PAYMENT-CHALLENGE / mpp_demo client surface) are retired — the\n // backend's POST /machine-payments/authorize refuses unconditionally now,\n // and MACHINE-PAYMENT-CHALLENGE was never produced by any other Haven\n // surface. Use the x402 flow (authorizeX402 / fetch / quoteX402 / payX402Quote)\n // for agent-to-merchant payments.\n\n private assertCanResumeX402(\n status: PaymentStatusResult,\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n ): void {\n if (status.rail !== 'x402') {\n throw new HavenPaymentStateError(\n `Payment ${status.paymentId} is ${status.rail}, not x402.`,\n 409,\n status,\n )\n }\n\n if (status.nextAction !== AgentPaymentNextAction.RetryOriginalX402Request) {\n throw new HavenPaymentStateError(status.message, PAYMENT_STATE_STATUS_CODES[status.status] ?? 409, status)\n }\n\n if (!status.txHash) {\n throw new HavenApiError(\n `x402 payment ${status.paymentId} is ready to retry but has no Haven transaction hash.`,\n 502,\n status,\n status.paymentId,\n )\n }\n\n if (status.resourceUrl && status.resourceUrl !== paymentRequired.resource.url) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved resource URL.',\n 409,\n { status, paymentRequired },\n status.paymentId,\n )\n }\n\n if (status.merchantAddress && !sameAddress(status.merchantAddress, option.payTo)) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved merchant.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n\n const optionChainId = chainIdFromNetwork(option.network)\n if (status.chainId && optionChainId && status.chainId !== optionChainId) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved network.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n\n if (status.token && status.token !== 'USDC') {\n throw new HavenApiError(\n 'x402 resume request does not match the approved token.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n\n const approvedAmount = status.amount ? normalizeDecimal(status.amount) : ''\n const requestedAmount = normalizeDecimal(decimalFromUsdcAtomic(x402AuthorizationAmount(option)))\n if (approvedAmount && approvedAmount !== requestedAmount) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved amount.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n }\n\n\n private mapX402ReceiptFromAuthorization(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n paymentHeader: string,\n raw: RawX402AuthorizeResponse,\n execResult?: RawSignResponse,\n ): X402Receipt {\n const txHash = execResult?.tx_hash ?? raw.tx_hash ?? ''\n const chainId = execResult?.chain_id ?? raw.chain_id ?? chainIdFromNetwork(option.network)\n const token = execResult?.token ?? raw.token ?? 'USDC'\n const amount = execResult?.amount ?? raw.amount ?? decimalFromUsdcAtomic(x402AuthorizationAmount(option))\n const to = execResult?.to ?? raw.to ?? this.delegateAddress ?? ''\n const explorerUrl = execResult?.explorer_url ?? raw.explorer_url ?? explorerUrlOrEmpty(chainId, txHash)\n const merchantTo = execResult?.merchant_to ?? raw.merchant_to ?? option.payTo\n const payer = raw.payer ?? raw.safe_address ?? raw.sign_data?.components.safe\n\n return this.buildX402Receipt({\n paymentId: raw.payment_id,\n txHash,\n token,\n amount,\n to,\n resourceUrl: paymentRequired.resource.url,\n explorerUrl,\n accepted: option,\n paymentHeader,\n merchantTo,\n payer,\n chainId,\n })\n }\n\n private mapX402ReceiptFromStatus(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n paymentHeader: string,\n status: PaymentStatusResult,\n ): X402Receipt {\n if (!status.txHash) {\n throw new HavenApiError(\n `x402 payment ${status.paymentId} is ready to retry but has no Haven transaction hash.`,\n 502,\n status,\n status.paymentId,\n )\n }\n\n return this.buildX402Receipt({\n paymentId: status.paymentId,\n txHash: status.txHash,\n token: status.token || 'USDC',\n amount: status.amount || decimalFromUsdcAtomic(x402AuthorizationAmount(option)),\n to: this.delegateAddress ?? '',\n resourceUrl: paymentRequired.resource.url,\n explorerUrl: explorerUrlOrEmpty(status.chainId, status.txHash),\n accepted: option,\n paymentHeader,\n merchantTo: status.merchantAddress ?? option.payTo,\n payer: this.x402Wallet,\n chainId: status.chainId || chainIdFromNetwork(option.network),\n })\n }\n\n private buildX402Receipt(input: {\n paymentId: string\n txHash: string\n token: string\n amount: string\n to: string\n resourceUrl: string\n explorerUrl: string\n accepted: X402PaymentOption\n paymentHeader: string\n merchantTo?: string | null\n payer?: string\n chainId?: number\n }): X402Receipt {\n const fundingExplorerUrl = input.explorerUrl || explorerUrlOrEmpty(input.chainId, input.txHash)\n\n return {\n success: true,\n paymentId: input.paymentId,\n txHash: input.txHash,\n token: input.token,\n amount: input.amount,\n to: input.to,\n resourceUrl: input.resourceUrl,\n explorerUrl: input.explorerUrl,\n accepted: input.accepted,\n paymentHeader: input.paymentHeader,\n merchantTo: input.merchantTo ?? input.accepted.payTo,\n payer: input.payer,\n chainId: input.chainId,\n haven: {\n paymentId: input.paymentId,\n fundingTxHash: input.txHash,\n fundingExplorerUrl,\n },\n merchant: {\n payTo: input.merchantTo ?? input.accepted.payTo,\n },\n x402: {\n amount: x402AuthorizationAmount(input.accepted),\n token: input.token,\n network: input.accepted.network,\n asset: input.accepted.asset,\n resource: input.accepted.resource ?? input.resourceUrl,\n },\n }\n }\n\n private async createStandardX402Header(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n ): Promise<string> {\n if (!this.delegateKey) {\n throw new HavenSigningError('delegateKey is required to sign x402 payment headers.')\n }\n\n const account = privateKeyToAccount(this.delegateKey as `0x${string}`)\n const requirements = toStandardPaymentRequirements(paymentRequired, option)\n\n const header = await exact.evm.createPaymentHeader(\n account,\n paymentRequired.x402Version,\n requirements,\n )\n if (paymentRequired.x402Version < 2) return header\n\n const payment = decodeBase64Json<{ payload: unknown }>(header)\n return encodeBase64Json({\n x402Version: paymentRequired.x402Version,\n accepted: option,\n payload: payment.payload,\n })\n }\n\n private cacheX402Receipt(\n idempotencyKey: string,\n paymentHeader: string,\n receipt: X402Receipt,\n ): void {\n const expiresAt = getPaymentHeaderValidBefore(paymentHeader)\n if (expiresAt > Date.now()) {\n this.x402ReceiptCache.set(idempotencyKey, { expiresAt, receipt })\n }\n }\n\n private async recordMerchantRetryRejected(input: {\n rail: string\n paymentId: string\n txHash: string\n resourceUrl: string\n merchant: CapturedMerchantResponse\n details?: Record<string, unknown>\n }): Promise<void> {\n try {\n await this.post('/machine-payments/reconciliation-events', {\n paymentId: input.paymentId,\n rail: input.rail,\n eventType: 'merchant_retry_rejected_after_payment',\n txHash: input.txHash,\n reason: `Merchant returned HTTP ${input.merchant.merchant_status} after Haven payment confirmation`,\n details: {\n resource_url: input.resourceUrl,\n retry_status: input.merchant.merchant_status,\n retry_body: input.merchant.merchant_body.slice(0, MERCHANT_BODY_SNIPPET_LIMIT) || null,\n ...input.details,\n },\n })\n } catch {\n // Best-effort durability: preserve the original retry failure for callers.\n }\n }\n\n private async reportMachinePaymentEvidence(input: {\n paymentId: string\n rail: string\n txHash: string\n resourceUrl: string\n merchantStatus: number\n challengePayload?: Record<string, unknown>\n selectedPayment?: Record<string, unknown>\n paymentProofHeaderName?: string\n paymentProofHeader?: string\n protocolReceiptHeaderName?: string\n protocolReceiptHeader?: string\n }): Promise<void> {\n try {\n await this.post('/machine-payments/evidence', {\n paymentId: input.paymentId,\n rail: input.rail,\n txHash: input.txHash,\n resourceUrl: input.resourceUrl,\n merchantStatus: input.merchantStatus,\n challengePayload: input.challengePayload,\n selectedPayment: input.selectedPayment,\n paymentProofHeaderName: input.paymentProofHeaderName,\n paymentProofHeader: input.paymentProofHeader,\n protocolReceiptHeaderName: input.protocolReceiptHeaderName,\n protocolReceiptHeader: input.protocolReceiptHeader,\n protocolReceiptPayload: input.protocolReceiptHeader\n ? parseProtocolReceiptHeader(input.protocolReceiptHeader)\n : undefined,\n })\n } catch {\n // Evidence reporting is best-effort. The paid resource response remains\n // the caller-visible result when merchant retry succeeded.\n }\n }\n\n /**\n * Wait for a funding tx to be mined with ≥1 confirmation before the\n * merchant retry, eliminating the race where the merchant's\n * `balanceOf(delegate)` runs before the funding block propagates.\n *\n * Skipped when `chainRpcs` does not include the chain; in that case Haven's\n * backend has already confirmed on-chain submission and callers accept the\n * small propagation window as a trade-off for not configuring an RPC URL.\n */\n private async waitForFundingTx(\n txHash: string | undefined,\n chainId: number | undefined,\n timeoutMs = 30_000,\n ): Promise<void> {\n if (!txHash || !chainId) return\n const rpcUrl = this.chainRpcs[chainId]\n if (!rpcUrl) return\n const provider = createJsonRpcProvider(rpcUrl)\n const onChainReceipt = await provider.waitForTransaction(txHash, 1, timeoutMs)\n if (!onChainReceipt || onChainReceipt.status !== 1) {\n throw new HavenApiError(\n 'Funding tx did not confirm on-chain within the timeout window.',\n 500,\n { txHash, chainId },\n )\n }\n }\n\n private throwIfNonSignableAuthorizationState(\n label: string,\n raw: RawX402AuthorizeResponse,\n ): void {\n if (raw.status === 'pending_signature') return\n this.throwPaymentStateError(label, raw)\n }\n\n private throwPaymentStateError(\n label: string,\n raw: RawX402AuthorizeResponse | RawSignResponse,\n ): never {\n const statusCode = PAYMENT_STATE_STATUS_CODES[raw.status] ?? 502\n const state = this.paymentStateFromRaw(label, raw)\n\n if (state) {\n throw new HavenPaymentStateError(state.message, statusCode, state, raw)\n }\n\n if (raw.status === 'pending_approval') {\n throw new HavenApiError(\n `${label} exceeds the on-chain allowance and was queued for owner approval (payment_id: ${raw.payment_id}).`,\n statusCode,\n raw,\n )\n }\n\n if (raw.status === 'expired') {\n throw new HavenApiError(\n `${label} expired before it could be completed (payment_id: ${raw.payment_id}).`,\n statusCode,\n raw,\n )\n }\n\n const paymentId = raw.payment_id ? ` (payment_id: ${raw.payment_id})` : ''\n const message = raw.error ?? `${label} ${raw.status}${paymentId}`\n throw new HavenApiError(message, statusCode, raw)\n }\n\n private paymentStateFromRaw(\n label: string,\n raw: RawX402AuthorizeResponse | RawSignResponse,\n ): PaymentStatusResult | null {\n if (!raw.payment_id || !raw.status) return null\n\n const phase = (raw.phase as PaymentPhase | undefined) ?? phaseForStatus(raw.status)\n const nextAction = (raw.next_action as PaymentNextAction | undefined) ?? nextActionForStatus(raw.status)\n if (!phase || !nextAction) return null\n\n const amount = raw.amount ?? raw.requested ?? ''\n const token = raw.token ?? ''\n const message =\n raw.message ??\n raw.error ??\n messageForState(label, raw.status, raw.payment_id, nextAction)\n\n return {\n paymentId: raw.payment_id,\n kind: raw.kind === 'payment_intent' ? 'payment_intent' : 'approval_request',\n rail: raw.rail ?? 'direct',\n status: raw.status === 'pending' ? 'pending_approval' : raw.status,\n phase,\n nextAction,\n amount,\n token,\n resourceUrl: raw.resource_url ?? null,\n merchantAddress: raw.merchant_address ?? raw.merchant_to ?? null,\n txHash: raw.tx_hash ?? null,\n expiresAt: raw.expires_at ?? '',\n chainId: raw.chain_id ?? 0,\n message,\n amountAtomic: raw.amount_atomic ?? raw.x402?.amount_atomic ?? raw.mpp?.amount_atomic ?? null,\n asset: raw.asset ?? raw.x402?.asset ?? raw.mpp?.asset ?? null,\n network: raw.network ?? raw.x402?.network ?? raw.mpp?.network ?? null,\n description: raw.description ?? raw.x402?.description ?? raw.mpp?.description ?? null,\n idempotencyKey: raw.idempotency_key ?? raw.x402?.idempotency_key ?? raw.mpp?.idempotency_key ?? null,\n x402: raw.x402\n ? {\n amountAtomic: raw.x402.amount_atomic ?? raw.amount_atomic ?? null,\n asset: raw.x402.asset ?? raw.asset ?? null,\n network: raw.x402.network ?? raw.network ?? null,\n resourceUrl: raw.x402.resource_url ?? raw.resource_url ?? null,\n merchantAddress: raw.x402.merchant_address ?? raw.merchant_address ?? raw.merchant_to ?? null,\n description: raw.x402.description ?? raw.description ?? null,\n idempotencyKey: raw.x402.idempotency_key ?? raw.idempotency_key ?? null,\n }\n : undefined,\n mpp: raw.mpp\n ? {\n amountAtomic: raw.mpp.amount_atomic ?? raw.amount_atomic ?? null,\n asset: raw.mpp.asset ?? raw.asset ?? null,\n network: raw.mpp.network ?? raw.network ?? null,\n resourceUrl: raw.mpp.resource_url ?? raw.resource_url ?? null,\n merchantAddress: raw.mpp.merchant_address ?? raw.merchant_address ?? raw.merchant_to ?? null,\n description: raw.mpp.description ?? raw.description ?? null,\n idempotencyKey: raw.mpp.idempotency_key ?? raw.idempotency_key ?? null,\n challengeId: raw.mpp.challenge_id ?? raw.challenge_id ?? null,\n }\n : undefined,\n }\n }\n\n private x402PayerAddress(): string | undefined {\n return this.delegateAddress ?? this.x402Wallet\n }\n\n private snapshotX402Request(url: string, init?: RequestInit): X402RequestSnapshot {\n return {\n url,\n method: init?.method ?? 'GET',\n headers: Array.from(new Headers(init?.headers).entries()),\n body: this.snapshotRequestBody(init?.body),\n }\n }\n\n private snapshotRequestBody(body: BodyInit | null | undefined): string | undefined {\n if (body == null) return undefined\n if (typeof body === 'string') return body\n if (body instanceof URLSearchParams) return body.toString()\n\n throw new HavenApiError(\n 'Quote helpers can only capture resumable request bodies that are strings or URLSearchParams. ' +\n 'For streams, blobs, or binary bodies, preserve the original request yourself and call the matching resume method with fresh init.',\n 400,\n )\n }\n\n private requestInitFromSnapshot(request: X402RequestSnapshot): RequestInit {\n return {\n method: request.method,\n headers: request.headers,\n body: request.body,\n }\n }\n\n private withX402Wallet(init?: RequestInit, wallet = this.x402PayerAddress()): RequestInit | undefined {\n if (!wallet) return init\n\n const headers = new Headers(init?.headers)\n if (!headers.has('x402-wallet')) {\n headers.set('x402-wallet', wallet)\n }\n\n return {\n ...init,\n headers,\n }\n }\n\n private buildX402Quote(\n paymentRequired: X402PaymentRequired,\n request: X402RequestSnapshot,\n idempotencyKey?: string,\n mcpTransport?: X402McpTransport,\n ): X402Quote {\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n if (!option) {\n throw new HavenApiError(\n 'No compatible payment option found in x402 requirements. ' +\n 'Haven supports standard x402 exact payments on Base USDC.',\n 400,\n )\n }\n\n const token = resolveTokenFromAddress(option.asset, option.network)\n return {\n rail: 'x402',\n idempotencyKey: idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option),\n paymentRequired,\n accepted: option,\n request,\n ...(mcpTransport ? { mcpTransport } : {}),\n resourceUrl: paymentRequired.resource.url,\n description: paymentRequired.resource.description ?? option.description ?? null,\n mimeType: paymentRequired.resource.mimeType ?? option.mimeType ?? null,\n amountAtomic: x402AuthorizationAmount(option),\n amount: decimalFromUsdcAtomic(x402AuthorizationAmount(option)),\n token: token?.symbol ?? 'USDC',\n // #1351: null when the asset is unrecognised on this network — the\n // `token` fallback above is a LABEL, not evidence of 6 decimals, and a\n // human-denominated cap must fail closed rather than convert against a\n // guess. Same resolution as `token`, so the two never disagree.\n decimals: token?.decimals ?? null,\n asset: option.asset,\n network: option.network,\n chainId: chainIdOrNull(option.network),\n merchantAddress: option.payTo,\n maxTimeoutSeconds: option.maxTimeoutSeconds,\n }\n }\n\n private async detectX402McpTransport(\n url: string,\n paymentRequired: X402PaymentRequired,\n response: Response,\n ): Promise<X402McpTransport | undefined> {\n if (isMcpUrl(url)) {\n return { handshakeRequired: true, source: 'path' }\n }\n if (paymentRequired.extensions?.bazaar != null) {\n return { handshakeRequired: true, source: 'bazaar' }\n }\n if (await responseHasBazaarExtension(response)) {\n return { handshakeRequired: true, source: 'bazaar' }\n }\n return undefined\n }\n\n private buildX402ResumeState(input: {\n paymentId: string\n paymentRequired: X402PaymentRequired\n accepted: X402PaymentOption\n idempotencyKey: string\n request?: X402RequestSnapshot\n }): X402ResumeState {\n const token = resolveTokenFromAddress(input.accepted.asset, input.accepted.network)\n return {\n rail: 'x402',\n paymentId: input.paymentId,\n idempotencyKey: input.idempotencyKey,\n paymentRequired: input.paymentRequired,\n accepted: input.accepted,\n url: input.request?.url ?? input.paymentRequired.resource.url,\n request: input.request,\n resourceUrl: input.paymentRequired.resource.url,\n description: input.paymentRequired.resource.description ?? input.accepted.description ?? null,\n amountAtomic: x402AuthorizationAmount(input.accepted),\n amount: decimalFromUsdcAtomic(x402AuthorizationAmount(input.accepted)),\n token: token?.symbol ?? 'USDC',\n asset: input.accepted.asset,\n network: input.accepted.network,\n chainId: chainIdOrNull(input.accepted.network),\n merchantAddress: input.accepted.payTo,\n }\n }\n\n // #1328: attachResumeState's 'mpp' branch (buildMppQuote / buildMppResumeState\n // / attachMppResumeState) is retired along with the rest of the MPP-demo\n // client surface — every remaining caller passes rail: 'x402' only, so this\n // is now a direct alias for attachX402ResumeState rather than a dispatcher.\n private attachResumeState(\n err: unknown,\n input: {\n rail: 'x402'\n paymentRequired: X402PaymentRequired\n accepted: X402PaymentOption\n idempotencyKey: string\n request?: X402RequestSnapshot\n },\n ): void {\n this.attachX402ResumeState(\n err,\n input.paymentRequired,\n input.accepted,\n input.idempotencyKey,\n input.request,\n )\n }\n\n private attachX402ResumeState(\n err: unknown,\n paymentRequired: X402PaymentRequired,\n accepted: X402PaymentOption,\n idempotencyKey: string,\n request?: X402RequestSnapshot,\n ): void {\n if (!(err instanceof HavenPaymentStateError)) return\n if (err.state.rail !== 'x402') return\n\n err.resumeState = this.buildX402ResumeState({\n paymentId: err.state.paymentId,\n paymentRequired,\n accepted,\n idempotencyKey,\n request,\n })\n }\n\n // ── Tool Execution (for agent frameworks) ────────────────────────\n\n /**\n * Execute a tool call by name and input.\n *\n * Designed to plug directly into agent tool-call handlers:\n *\n * ```ts\n * if (block.type === 'tool_use') {\n * const result = await haven.executeTool(block.name, block.input)\n * // send result back to the model\n * }\n * ```\n */\n async executeTool(\n toolName: string,\n input: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n if (toolName === 'make_payment') {\n const { token, amount, to } = input as {\n token: string\n amount: string\n to: string\n }\n\n try {\n const result = await this.pay({ token, amount, to })\n return {\n success: result.status === 'confirmed',\n payment_id: result.paymentId,\n status: result.status,\n tx_hash: result.txHash,\n token: result.token,\n amount: result.amount,\n to: result.to,\n explorer_url: result.explorerUrl,\n error: result.errorMessage,\n }\n } catch (err) {\n return this.toolError(err)\n }\n }\n\n if (toolName === 'authorize_x402_payment') {\n const { url, payTo, amount, asset, network, description, idempotencyKey } = input as {\n url: string\n payTo: string\n amount: string\n asset: string\n network: string\n description?: string\n idempotencyKey?: string\n }\n\n try {\n const receipt = await this.authorizeX402(\n this.toolX402PaymentRequired({ url, payTo, amount, asset, network, description }),\n { idempotencyKey },\n )\n return this.x402ToolReceipt(receipt)\n } catch (err) {\n return this.toolError(err)\n }\n }\n\n if (toolName === 'resume_x402_payment') {\n const { payment_id, url, payTo, amount, asset, network, description, idempotencyKey } = input as {\n payment_id: string\n url: string\n payTo: string\n amount: string\n asset: string\n network: string\n description?: string\n idempotencyKey?: string\n }\n\n try {\n const receipt = await this.resumeAuthorizedX402({\n paymentId: payment_id,\n paymentRequired: this.toolX402PaymentRequired({ url, payTo, amount, asset, network, description }),\n idempotencyKey,\n })\n return this.x402ToolReceipt(receipt)\n } catch (err) {\n return this.toolError(err)\n }\n }\n\n // #1328: the 'authorize_machine_payment' tool (mpp_demo only) is retired\n // along with the rest of the SDK's MPP-demo client surface — an unknown\n // toolName falls through to the Error below, same as any other retired name.\n\n if (toolName === 'get_payment_status') {\n const { payment_id } = input as { payment_id: string }\n const result = await this.getPaymentStatus(payment_id)\n return {\n payment_id: result.paymentId,\n kind: result.kind,\n rail: result.rail,\n status: result.status,\n phase: result.phase,\n next_action: result.nextAction,\n tx_hash: result.txHash,\n token: result.token,\n amount: result.amount,\n resource_url: result.resourceUrl,\n merchant_address: result.merchantAddress,\n amount_atomic: result.amountAtomic,\n asset: result.asset,\n network: result.network,\n description: result.description,\n idempotency_key: result.idempotencyKey,\n x402: result.x402,\n mpp: result.mpp,\n expires_at: result.expiresAt,\n chain_id: result.chainId,\n message: result.message,\n }\n }\n\n if (toolName === 'get_allowances') {\n return { ...await this.getAllowances() }\n }\n\n throw new Error(`Unknown tool: ${toolName}`)\n }\n\n private toolX402PaymentRequired(input: {\n url: string\n payTo: string\n amount: string\n asset: string\n network: string\n description?: string\n }): X402PaymentRequired {\n return {\n x402Version: 2,\n resource: { url: input.url, description: input.description },\n accepts: [\n {\n scheme: 'exact',\n network: input.network,\n amount: input.amount,\n asset: input.asset,\n payTo: input.payTo,\n maxTimeoutSeconds: 30,\n },\n ],\n }\n }\n\n private x402ToolReceipt(receipt: X402Receipt): Record<string, unknown> {\n return {\n success: true,\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n token: receipt.token,\n amount: receipt.amount,\n to: receipt.to,\n resource_url: receipt.resourceUrl,\n explorer_url: receipt.explorerUrl,\n payment_header: receipt.paymentHeader,\n merchant_to: receipt.merchantTo,\n payer: receipt.payer,\n chain_id: receipt.chainId,\n haven: receipt.haven,\n merchant: receipt.merchant,\n x402: receipt.x402,\n }\n }\n\n private toolError(err: unknown): Record<string, unknown> {\n if (err instanceof HavenPaymentStateError) {\n return {\n success: false,\n payment_id: err.state.paymentId,\n kind: err.state.kind,\n rail: err.state.rail,\n status: err.state.status,\n phase: err.state.phase,\n next_action: err.state.nextAction,\n tx_hash: err.state.txHash,\n token: err.state.token,\n amount: err.state.amount,\n resource_url: err.state.resourceUrl,\n merchant_address: err.state.merchantAddress,\n amount_atomic: err.state.amountAtomic,\n asset: err.state.asset,\n network: err.state.network,\n description: err.state.description,\n idempotency_key: err.state.idempotencyKey,\n x402: err.state.x402\n ? {\n amount_atomic: err.state.x402.amountAtomic,\n asset: err.state.x402.asset,\n network: err.state.x402.network,\n resource_url: err.state.x402.resourceUrl,\n merchant_address: err.state.x402.merchantAddress,\n description: err.state.x402.description,\n idempotency_key: err.state.x402.idempotencyKey,\n }\n : undefined,\n mpp: err.state.mpp\n ? {\n amount_atomic: err.state.mpp.amountAtomic,\n asset: err.state.mpp.asset,\n network: err.state.mpp.network,\n resource_url: err.state.mpp.resourceUrl,\n merchant_address: err.state.mpp.merchantAddress,\n description: err.state.mpp.description,\n idempotency_key: err.state.mpp.idempotencyKey,\n challenge_id: err.state.mpp.challengeId,\n }\n : undefined,\n resume_state: err.resumeState,\n expires_at: err.state.expiresAt,\n chain_id: err.state.chainId,\n message: err.state.message,\n error: err.message,\n }\n }\n\n if (err instanceof HavenApiError) {\n return {\n success: false,\n status_code: err.statusCode,\n error: err.message,\n body: err.body,\n }\n }\n\n return {\n success: false,\n error: err instanceof Error ? err.message : String(err),\n }\n }\n\n // ── HTTP Helpers ─────────────────────────────────────────────────\n\n private async post<T>(path: string, body: Record<string, unknown>): Promise<T> {\n return this.request<T>('POST', path, body)\n }\n\n private async get<T>(path: string): Promise<T> {\n return this.request<T>('GET', path)\n }\n\n /**\n * #1300: every MERCHANT-facing fetch goes through here. Haven API calls\n * have always been bounded (request() below); the merchant probes/retries\n * called globalThis.fetch bare, so a slow-loris merchant could hold a tool\n * call open forever. A caller-supplied signal still applies (combined via\n * AbortSignal.any); a timeout abort surfaces as a clear HavenApiError 504\n * naming the URL rather than a bare AbortError.\n */\n private async merchantFetch(\n url: string,\n init: RequestInit = {},\n timeoutMs = this.merchantTimeout,\n ): Promise<Response> {\n const timeoutSignal = AbortSignal.timeout(timeoutMs)\n const signal = init.signal ? AbortSignal.any([init.signal, timeoutSignal]) : timeoutSignal\n try {\n return await globalThis.fetch(url, { ...init, signal })\n } catch (err) {\n if (timeoutSignal.aborted) {\n throw new MerchantTimeoutError(`Merchant request timed out after ${timeoutMs}ms: ${url}`)\n }\n throw err\n }\n }\n\n private async request<T>(\n method: 'GET' | 'POST',\n path: string,\n body?: Record<string, unknown>,\n ): Promise<T> {\n const url = `${this.baseUrl}${path}`\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), this.requestTimeout)\n\n try {\n const contextHeaders = this.requestContext.getStore()?.headers ?? {}\n const res = await fetch(url, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n ...this.defaultHeaders,\n ...contextHeaders,\n },\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n })\n\n const data = await res.json()\n\n if (!res.ok) {\n const record = data as Record<string, unknown>\n const errorText = typeof record.error === 'string' ? record.error : undefined\n // agentAuth's structured refusals (#1130: agent_pending_approval,\n // agent_paused) carry their guidance as `detail` (singular) — without\n // this fallback the operator sees a bare error code and none of the\n // actionable text.\n const rawDetails = record.details ?? record.detail\n const detailsText =\n typeof rawDetails === 'string'\n ? rawDetails\n : rawDetails != null\n ? JSON.stringify(rawDetails)\n : undefined\n // Surface the backend's `details` alongside the generic `error` —\n // otherwise messages like \"On-chain execution failed\" mask the actual\n // revert reason (#684). The full body is still attached for callers.\n const message =\n errorText && detailsText\n ? `${errorText}: ${detailsText}`\n : errorText ?? detailsText ?? `API request failed`\n throw new HavenApiError(message, res.status, data)\n }\n\n return data as T\n } catch (err) {\n if (err instanceof HavenApiError) throw err\n if (err instanceof Error && err.name === 'AbortError') {\n throw new HavenApiError(`Request to ${path} timed out`, 408)\n }\n throw new HavenApiError(\n `Request to ${path} failed: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n )\n } finally {\n clearTimeout(timeout)\n }\n }\n\n // ── Mapping Helpers ──────────────────────────────────────────────\n\n private mapPaymentResult(raw: RawStatusResponse): PaymentResult {\n return {\n paymentId: raw.payment_id,\n status: raw.status as PaymentStatus,\n token: raw.token,\n amount: raw.amount,\n to: raw.to,\n txHash: raw.tx_hash,\n errorMessage: raw.error_message,\n explorerUrl: raw.explorer_url ?? (raw.tx_hash ? buildExplorerUrl(raw.chain_id, raw.tx_hash) : null),\n fee: raw.fee\n ? {\n amount: raw.fee.amount,\n token: raw.fee.token,\n basisPoints: raw.fee.basis_points,\n applied: raw.fee.applied,\n }\n : null,\n createdAt: raw.created_at,\n signedAt: raw.signed_at,\n submittedAt: raw.submitted_at,\n confirmedAt: raw.confirmed_at,\n expiresAt: raw.expires_at,\n }\n }\n\n private mapPaymentStatusResult(raw: RawPaymentStatusResult): PaymentStatusResult {\n return {\n paymentId: raw.payment_id,\n kind: raw.kind,\n rail: raw.rail,\n status: raw.status,\n phase: raw.phase,\n nextAction: raw.next_action,\n amount: raw.amount,\n token: raw.token,\n resourceUrl: raw.resource_url,\n merchantAddress: raw.merchant_address,\n payerAddress: raw.payer_address ?? null,\n txHash: raw.tx_hash,\n expiresAt: raw.expires_at,\n chainId: raw.chain_id,\n message: raw.message,\n fee: raw.fee\n ? {\n amount: raw.fee.amount,\n token: raw.fee.token,\n basisPoints: raw.fee.basis_points,\n applied: raw.fee.applied,\n }\n : null,\n amountAtomic: raw.amount_atomic ?? raw.x402?.amount_atomic ?? null,\n asset: raw.asset ?? raw.x402?.asset ?? null,\n network: raw.network ?? raw.x402?.network ?? null,\n description: raw.description ?? raw.x402?.description ?? null,\n idempotencyKey: raw.idempotency_key ?? raw.x402?.idempotency_key ?? null,\n x402: raw.x402\n ? {\n amountAtomic: raw.x402.amount_atomic ?? raw.amount_atomic ?? null,\n asset: raw.x402.asset ?? raw.asset ?? null,\n network: raw.x402.network ?? raw.network ?? null,\n resourceUrl: raw.x402.resource_url ?? raw.resource_url,\n merchantAddress: raw.x402.merchant_address ?? raw.merchant_address,\n description: raw.x402.description ?? raw.description ?? null,\n idempotencyKey: raw.x402.idempotency_key ?? raw.idempotency_key ?? null,\n }\n : undefined,\n }\n }\n\n private mapPaymentReceipt(raw: RawHavenPaymentReceipt): HavenPaymentReceipt {\n const receipt: HavenPaymentReceipt = {\n id: raw.id,\n paymentId: raw.payment_id,\n rail: raw.rail,\n proofStatus: raw.proof_status,\n txHash: raw.tx_hash,\n chainId: raw.chain_id,\n resourceUrl: raw.resource_url,\n merchantAddress: raw.merchant_address,\n payerAddress: raw.payer_address,\n settlementAddress: raw.settlement_address,\n tokenSymbol: raw.token_symbol,\n tokenAddress: raw.token_address,\n amountRaw: raw.amount_raw,\n amount: raw.amount_human,\n challengeId: raw.challenge_id,\n idempotencyKey: raw.idempotency_key,\n challengePayload: raw.challenge_payload,\n selectedPayment: raw.selected_payment,\n paymentProofHeaderName: raw.payment_proof_header_name,\n protocolReceiptHeaderName: raw.protocol_receipt_header_name,\n protocolReceiptPayload: raw.protocol_receipt_payload,\n merchantStatus: raw.merchant_status,\n confirmedAt: raw.confirmed_at,\n createdAt: raw.created_at,\n updatedAt: raw.updated_at,\n }\n\n if ('payment_intent_id' in raw) {\n receipt.paymentIntentId = raw.payment_intent_id ?? null\n }\n if ('approval_request_id' in raw) {\n receipt.approvalRequestId = raw.approval_request_id ?? null\n }\n\n return receipt\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction getPaymentHeaderValidBefore(paymentHeader: string): number {\n try {\n const payment = decodeBase64Json<{ payload?: { authorization?: { validBefore?: string } } }>(\n paymentHeader,\n )\n const payload = payment.payload as { authorization?: { validBefore?: string } }\n const validBeforeSeconds = Number(payload.authorization?.validBefore)\n if (Number.isFinite(validBeforeSeconds)) return validBeforeSeconds * 1000\n } catch {\n // If the header cannot be decoded, skip caching rather than hiding errors.\n }\n\n return 0\n}\n\nfunction parseProtocolReceiptHeader(value: string): Record<string, unknown> | undefined {\n try {\n return decodeBase64Json<Record<string, unknown>>(value)\n } catch {\n try {\n return JSON.parse(value) as Record<string, unknown>\n } catch {\n return undefined\n }\n }\n}\n\n/**\n * Captures a failed merchant retry response so callers can debug exactly why the\n * merchant rejected a payment Haven already funded. We preserve the status code,\n * statusText, headers, and full body text verbatim — this is the merchant's\n * response, so it never contains Haven-side secrets (delegate key, agent API key),\n * which only ever live in the outbound request.\n */\nasync function captureMerchantResponse(response: Response): Promise<CapturedMerchantResponse> {\n const merchant_body = await response.text().catch(() => '')\n return {\n merchant_status: response.status,\n merchant_status_text: response.statusText,\n merchant_headers: Object.fromEntries(response.headers.entries()),\n merchant_body,\n }\n}\n","/**\n * Shared semantic descriptions for Haven agent payment tools.\n *\n * Two surfaces in this repo expose Haven as a tool: the Claude / OpenAI\n * function-calling tool definitions in `tools.ts` (used for direct SDK\n * integrations) and the MCP server in `packages/mcp` (used by any MCP-speaking\n * agent runtime). The two surfaces use different tool *names* — the SDK's\n * tools are tuned for tool-calling conventions (`make_payment`,\n * `authorize_x402_payment`); the MCP tools follow the MCP `haven_*` naming\n * (`haven_pay_x402_quote`).\n *\n * The underlying *operations* are the same, so the descriptive prose should\n * live in one place. Both surfaces import from this module and compose their\n * own tool descriptions from these semantic fragments. Drift is caught by\n * tests asserting each consumer's description string contains the shared\n * `summary` from this module.\n */\n\nexport interface ToolDescription {\n /** One-line summary of the operation. Used as the first sentence of every\n * downstream description and as a stable substring for drift tests. */\n summary: string\n /** Natural-language user intents that should make an agent prefer this\n * tool over adjacent tools. Empty or omitted when the summary is enough. */\n selectionGuidance?: string\n /** Concrete behaviour the tool performs end-to-end, including which\n * non-custodial guarantee applies. */\n behavior: string\n /** What the agent should do next on error / pending-approval states.\n * Empty string if not applicable. */\n nextActionGuidance: string\n}\n\n/**\n * Build a single description string from the three fragments. Joined with\n * spaces so consumers can split on the summary substring if they need to.\n */\nexport function composeDescription(d: ToolDescription): string {\n return [d.summary, d.selectionGuidance, d.behavior, d.nextActionGuidance]\n .filter(Boolean)\n .join(' ')\n}\n\nexport const toolDescriptions = {\n quoteX402: {\n summary:\n 'Inspect an HTTP 402 x402 paid resource without creating a Haven payment, signature, approval, or on-chain transaction.',\n behavior:\n 'Probes the merchant directly and parses the 402 response. Pure read-only client behavior — Haven is not contacted.',\n nextActionGuidance:\n 'On success the returned quote is the input to haven_pay_x402_quote. Do not call the merchant again — Haven re-uses the captured request when paying.',\n },\n payX402: {\n summary:\n 'Pay an inspected x402 quote. The delegate key signs locally; Haven only validates and relays signed, on-chain-constrained payment transactions.',\n selectionGuidance:\n 'Do not use this for read-only allowance, budget, spend-limit, remaining-amount, reset-period, or what-can-I-spend questions; use the allowance lookup tool instead.',\n behavior:\n 'Signs the EIP-3009 payment from the delegate wallet, asks Haven for a Safe AllowanceModule top-up if needed, and returns the merchant response or a pending-approval state.',\n nextActionGuidance:\n 'If approval is needed, preserve the returned resume_state and wait for nextAction=retry_original_x402_request before resuming. ' +\n 'If the response carries phase=insufficient_funds and nextAction=fund_safe_or_raise_allowance, the payment cannot be retried until the originating Safe is funded or the agent allowance raised — stop and tell the user the shortfall reported on the response.',\n },\n payX402OneShot: {\n summary:\n 'Fetch an x402 paid HTTP resource in a single call. Handles the full probe -> pay -> retry round trip and returns the merchant response.',\n selectionGuidance:\n '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.',\n behavior:\n 'Calls the URL, parses any HTTP 402 x402 challenge, signs the EIP-3009 payment from the delegate wallet, asks Haven for a Safe AllowanceModule top-up if needed, then retries the original request with the X-PAYMENT header and returns the merchant response. If the resource returns a non-402 status, returns it unchanged without contacting Haven.',\n nextActionGuidance:\n 'If approval is needed, preserve the returned resume_state or paymentId and call the resume tool once nextAction=retry_original_x402_request. ' +\n 'If the response carries phase=insufficient_funds and nextAction=fund_safe_or_raise_allowance, the payment cannot be retried until the originating Safe is funded or the agent allowance raised — stop and tell the user the shortfall reported on the response.',\n },\n resumeX402: {\n summary:\n 'Resume an x402 payment after the Haven wallet owner approved the funding step.',\n behavior:\n 'Accepts either resume_state or payment_id, validates the original x402 details against the approved Haven funding, and retries the merchant request with the X-PAYMENT header. No new Haven approval is created.',\n nextActionGuidance:\n 'Only use when get_payment_status returns nextAction=retry_original_x402_request; do not start a new merchant session.',\n },\n // #1328: quoteMpp / payMpp / resumeMpp (the mpp_demo challenge/quote/resume\n // fragments) are retired along with the client surface they described —\n // MACHINE-PAYMENT-CHALLENGE was never produced by anything besides the now\n // deleted `/demo/mpp/*` route. Use the x402 fragments above instead.\n getPaymentStatus: {\n summary:\n 'Fetch structured Haven payment status, including phase and nextAction taxonomy for agent recovery.',\n behavior:\n 'Accepts a payment intent or approval request id and returns the full state taxonomy (phase, nextAction, rail, amount, merchant, resource url, idempotency key, message).',\n nextActionGuidance: '',\n },\n getResumeState: {\n summary:\n 'Rehydrate stored x402 resume_state by payment_id.',\n behavior:\n 'Returns the context that the agent originally received in a pending-approval response, reconstructed from Haven\\'s database. This is context only; signing still happens locally when a resume tool is called.',\n nextActionGuidance: '',\n },\n getAgent: {\n summary:\n 'Return the authenticated agent identity AND its live spend authority in one call: Haven wallet, delegate, chain, raw status, a readiness signal, and per-token remaining allowance (atomic + human-readable). The recommended first call in a new session to confirm who you are and whether you can pay right now.',\n selectionGuidance:\n 'Use this as the one-shot orientation/bootstrap at the start of a session, or whenever you need to confirm identity together with whether the agent can spend right now. For a detailed per-token breakdown (configured vs spent vs reset window) use haven_get_allowances.',\n behavior:\n 'Reads identity plus the live spend-authority snapshot in one shot — the on-chain AllowanceModule on the legacy rail, the active budget delegation on the delegation rail. readiness is \"ready\" when at least one token has remaining spend authority, \"needs_approval\" when the agent is active but has none, and \"revoked\" when the credential is not active. What an over-budget payment does differs by rail: on the legacy AllowanceModule rail it is queued for the wallet owner to approve in Haven; on the delegation rail there is no approval queue — an over-budget redemption reverts on-chain, so ask the owner to grant or raise the budget in Haven rather than waiting for an approval. allowances[] carries remainingAtomic and remainingDisplay per token. Identity fields (id, name, status, safeAddress, delegateAddress, chainId) are unchanged from before.',\n nextActionGuidance: '',\n },\n getAllowances: {\n summary:\n 'Return configured and on-chain allowance state for the authenticated agent. On-chain allowance is the real spend gate.',\n selectionGuidance:\n 'Use this when the user asks about allowance, budget, spend limit, remaining amount, remaining allowance, remaining budget, daily limit, reset period, what can I spend, or what the agent can still spend.',\n behavior:\n 'Returns the per-token spend authority for the account\\'s rail: the Safe AllowanceModule snapshot (allowance, spent, remaining, reset window) on the legacy rail, or the active budget delegation (remaining = the period budget; over-budget redemptions revert on-chain, nothing queues) on the delegation rail. Configured amounts from Haven are returned alongside.',\n nextActionGuidance: '',\n },\n listReceipts: {\n summary:\n 'List recent machine-payment receipts and evidence for bookkeeping.',\n selectionGuidance:\n 'Use this for transaction history, receipts, payment evidence, or bookkeeping; use the allowance tool instead for remaining allowance, budget, spend-limit, or what-can-I-spend questions.',\n behavior:\n 'Returns the agent\\'s recent machine-payment receipts ordered by recency. Proof header values are not returned.',\n nextActionGuidance: '',\n },\n verifyReceipt: {\n summary:\n 'Verify a payment receipt offline — confirm the agent authorised the transfer.',\n selectionGuidance:\n 'Use this to check a receipt you already hold; it needs no network and does not trust Haven. Use the history tool to fetch receipts in the first place.',\n behavior:\n 'Recovers the signer from the receipt authorisation and confirms it matches the agent delegate. Returns verified true/false with the recovered signer or a reason. Pure and local — no backend call.',\n nextActionGuidance: '',\n },\n payMcpTool: {\n summary:\n 'Call a named tool on an MCP merchant that requires an x402 payment, handling the full initialize → pay → retry round trip in one call.',\n selectionGuidance:\n 'Use this when the agent wants to call a specific tool on an MCP merchant (e.g. Soundside, Coinbase Bazaar) and payment is required. ' +\n 'Prefer this over haven_pay_x402 when you know the merchant_url and tool_name — it builds the JSON-RPC envelope internally. ' +\n 'Use haven_pay_x402 for arbitrary HTTP resources. ' +\n 'Do NOT use for read-only allowance or budget questions — use haven_get_allowances.',\n behavior:\n 'Builds the JSON-RPC tools/call envelope, runs the MCP Streamable-HTTP initialize handshake automatically (if the endpoint is MCP-shaped), ' +\n 'pays any HTTP 402 x402 challenge through Haven\\'s AllowanceModule path, and retries the request, returning the JSON-RPC result (the actual merchant output) on success. ' +\n 'Amounts within the on-chain allowance execute automatically; over-allowance transfers are queued as pending_approval — follow the response\\'s nextAction when present.',\n nextActionGuidance:\n 'If pending_approval is returned, preserve payment_id and resume_state and wait for the wallet owner to approve in Haven. ' +\n 'Use haven_resume_x402_payment once nextAction=retry_original_x402_request.',\n },\n discoverTools: {\n summary:\n 'Step 1 of a purchase: discover payable services from Haven\\'s curated merchant catalog — names, prices, and which pay tool to use next.',\n selectionGuidance:\n 'Use this when the user asks what the agent can buy, pay for, or which paid services exist — or when you need a resource URL for a service the user described. ' +\n 'Do NOT use for balance, budget, or spend-limit questions — use haven_get_allowances. ' +\n 'Do NOT use to pay — each returned entry names the pay tool to use next.',\n behavior:\n 'Use each entry\\'s suggested_tool field first — it names the exact next call. ' +\n 'Read-only lookup against Haven\\'s curated catalog; entries are periodically re-verified against the live merchant and degraded entries are flagged. ' +\n 'Use category for a case-insensitive category filter (for example, VPN or vpn), or search for a product name, category, or description term. ' +\n 'Returns name, description, price, rail, resource URL, tool_name, tool_arguments, and suggested_tool. ' +\n 'The catalog price (price_display/price_atomic, marked price_is_indicative) is a last-verified hint, NOT authoritative — the real price comes from the merchant\\'s live 402 at pay time. ' +\n 'Never creates a payment, signature, or approval.',\n nextActionGuidance:\n 'Pick an entry and pay it with the tool named in suggested_tool, passing the entry\\'s resource_url, tool_name, and tool_arguments for MCP merchants. Confirm the price from the live pay-tool result (not the catalog), and pass the user\\'s cap as max_amount_human in whole tokens (\"no more than 1 USDC\" → max_amount_human: \"1\") — never convert it to atomic units by hand (#1351).',\n },\n sweep_delegate: {\n summary:\n 'Sweep stranded USDC and/or ETH from the delegate wallet back to the originating Safe.',\n selectionGuidance:\n 'Use this when the user instructs you to recover stranded funds on the delegate wallet, or when a payment status returns nextAction=sweep_stranded_funds. ' +\n 'Do NOT use for normal payments — use haven_pay_x402. ' +\n 'Do NOT use to read balances only — use haven_get_allowances.',\n behavior:\n 'Reads the delegate EOA\\'s on-chain USDC and ETH balances. For each non-zero balance, signs and submits a transfer from the delegate EOA to the originating Safe (hardcoded destination). ' +\n 'The delegate key signs locally — Haven never sees it and the backend never constructs signed transactions (CASP/MiCA Red Line #2). ' +\n 'Returns tx hashes and recovered amounts. Returns an empty transfers list when nothing is stranded.',\n nextActionGuidance:\n 'If transfers is non-empty, confirm the amounts with the user. No further action required — funds are on their way back to the Safe.',\n },\n send: {\n summary:\n 'Send ETH or USDC directly from the agent\\'s Haven wallet to a recipient address.',\n selectionGuidance:\n 'Use this for plain transfers — refunding a user, paying a freelancer, topping up a co-agent\\'s wallet, or moving funds between addresses. ' +\n 'Do NOT use for x402 paid endpoints — use haven_pay_x402 instead. ' +\n 'Do NOT use for read-only allowance, budget, or what-can-I-spend questions — use haven_get_allowances.',\n behavior:\n 'Sends the requested amount through the Safe AllowanceModule. ' +\n 'Amounts within the remaining on-chain allowance for the asset execute automatically; ' +\n 'amounts that exceed the allowance are queued as pending_approval for the wallet owner to approve in Haven. ' +\n 'The agent\\'s signing key signs the AllowanceModule transfer hash; Haven never receives the key.',\n nextActionGuidance:\n 'If pending_approval is returned, preserve the payment_id and wait for the wallet owner to approve in Haven. ' +\n 'Poll haven_get_payment_status until nextAction=none.',\n },\n} as const satisfies Record<string, ToolDescription>\n\nexport type SharedToolKey = keyof typeof toolDescriptions\n","/**\n * Pre-built tool definitions for AI agent frameworks.\n *\n * These definitions describe Haven's direct SDK tool-calling surface in the\n * formats expected by Claude (Anthropic) and OpenAI.\n *\n * The agent payment surface used by these tools is shared with the\n * `@haven_ai/mcp` server — both consume `toolDescriptions` from\n * `./tool-descriptions.ts`. Each consumer composes its own user-visible string\n * from the same semantic fragments, so guidance lands in both surfaces at\n * once and a downstream test asserts the shared summary appears in every\n * consumer description.\n *\n * Usage with Claude:\n * const response = await anthropic.messages.create({\n * tools: havenTools.claude(),\n * ...\n * })\n *\n * Usage with OpenAI:\n * const response = await openai.chat.completions.create({\n * tools: havenTools.openai(),\n * ...\n * })\n */\n\nimport { composeDescription, toolDescriptions as sharedDescriptions } from './tool-descriptions.js'\n\n// ── JSON Schema (shared across formats) ──────────────────────────\n\nconst makePaymentSchema = {\n type: 'object' as const,\n properties: {\n token: {\n type: 'string' as const,\n description: 'Token to send. Gnosis Chain: EURe, USDC.e, xDAI. Base: USDC, ETH.',\n },\n amount: {\n type: 'string' as const,\n description: 'Amount to send as a decimal string, e.g. \"5.00\"',\n },\n to: {\n type: 'string' as const,\n description: 'Recipient Ethereum address (0x...)',\n },\n reason: {\n type: 'string' as const,\n description: 'Brief reason for this payment (for audit trail)',\n },\n },\n required: ['token', 'amount', 'to', 'reason'] as const,\n}\n\nconst getPaymentStatusSchema = {\n type: 'object' as const,\n properties: {\n payment_id: {\n type: 'string' as const,\n description: 'The payment ID returned from make_payment',\n },\n },\n required: ['payment_id'] as const,\n}\n\nconst getAllowancesSchema = {\n type: 'object' as const,\n properties: {},\n required: [] as const,\n}\n\nconst authorizeX402Schema = {\n type: 'object' as const,\n properties: {\n url: {\n type: 'string' as const,\n description: 'The URL that returned HTTP 402',\n },\n payTo: {\n type: 'string' as const,\n description: 'Payment recipient address from the 402 response',\n },\n amount: {\n type: 'string' as const,\n description: 'Payment amount in atomic units (e.g. \"1000000\" for 1 USDC)',\n },\n asset: {\n type: 'string' as const,\n description: 'Token contract address from the 402 response',\n },\n network: {\n type: 'string' as const,\n description: 'CAIP-2 chain ID. \"eip155:100\" for Gnosis Chain, \"eip155:8453\" for Base.',\n },\n description: {\n type: 'string' as const,\n description: 'Description of the resource being paid for',\n },\n idempotencyKey: {\n type: 'string' as const,\n description: 'Stable caller-supplied key for this user intent. Reuse it when resuming after user approval.',\n },\n },\n required: ['url', 'payTo', 'amount', 'asset', 'network'] as const,\n}\n\nconst resumeX402Schema = {\n type: 'object' as const,\n properties: {\n payment_id: {\n type: 'string' as const,\n description: 'The payment or approval request ID returned by authorize_x402_payment.',\n },\n url: {\n type: 'string' as const,\n description: 'The original URL that returned HTTP 402.',\n },\n payTo: {\n type: 'string' as const,\n description: 'Payment recipient address from the original 402 response.',\n },\n amount: {\n type: 'string' as const,\n description: 'Payment amount in atomic units from the original 402 response.',\n },\n asset: {\n type: 'string' as const,\n description: 'Token contract address from the original 402 response.',\n },\n network: {\n type: 'string' as const,\n description: 'CAIP-2 chain ID or x402 network from the original 402 response.',\n },\n description: {\n type: 'string' as const,\n description: 'Description of the resource being paid for.',\n },\n idempotencyKey: {\n type: 'string' as const,\n description: 'Stable caller-supplied key used for the original authorization.',\n },\n },\n required: ['payment_id', 'url', 'payTo', 'amount', 'asset', 'network'] as const,\n}\n\nconst MAKE_PAYMENT_DESCRIPTION =\n 'Request and sign a payment from the user-controlled Safe within approved on-chain limits. ' +\n 'For read-only allowance, budget, spend-limit, remaining-amount, or reset-period questions, use get_allowances instead of making a payment. ' +\n 'Haven authenticates the agent, validates the signed intent, and relays the Safe AllowanceModule transaction; it does not hold keys or control funds. ' +\n 'Gnosis Chain tokens: EURe, USDC.e, xDAI. Base tokens: USDC, ETH.'\n\n// Descriptions are composed from the shared semantic source so the SDK and MCP\n// surfaces stay in lockstep. Each constant prepends the shared `summary` (the\n// stable substring tests assert on) and then appends the SDK-specific guidance\n// for tool-calling consumers.\n\nconst GET_STATUS_DESCRIPTION =\n sharedDescriptions.getPaymentStatus.summary + ' ' +\n 'Accepts payment intent IDs and approval request IDs. Returns the current status, phase, next_action, transaction hash if available, and payment details.'\n\nconst GET_ALLOWANCES_DESCRIPTION = composeDescription(sharedDescriptions.getAllowances)\n\nconst AUTHORIZE_X402_DESCRIPTION =\n composeDescription(sharedDescriptions.payX402) + ' ' +\n 'In this SDK tool set, the allowance lookup tool is get_allowances. ' +\n 'When a paid API returns x402 payment requirements, use this tool to sign with the agent-owned delegate key and request a policy-limited Safe AllowanceModule top-up when needed. ' +\n 'Haven relays signed transactions only; the agent key authorizes payment and on-chain limits enforce spend. ' +\n 'If this returns pending_approval, tell the user it is waiting in Haven, preserve the original merchant/MCP session and x402 details, call get_payment_status later, and use resume_x402_payment only when next_action is retry_original_x402_request. Do not start a new merchant session or loop retries while approval is pending. ' +\n 'Use the returned payment_header as the X-PAYMENT header on the retry request when doing a manual HTTP retry.'\n\nconst RESUME_X402_DESCRIPTION =\n sharedDescriptions.resumeX402.summary + ' ' +\n 'Use this only after get_payment_status returns next_action=retry_original_x402_request. ' +\n 'It checks the approved payment, validates the original x402 details, and returns a merchant X-PAYMENT header without creating a new approval request or merchant session.'\n\nconst SWEEP_DELEGATE_DESCRIPTION = composeDescription(sharedDescriptions.sweep_delegate)\n\nconst sweepDelegateSchema = {\n type: 'object' as const,\n properties: {},\n required: [] as readonly string[],\n}\n\n// ── Claude (Anthropic) format ────────────────────────────────────\n\nexport interface ClaudeTool {\n name: string\n description: string\n input_schema: {\n type: 'object'\n properties: Record<string, unknown>\n required: readonly string[]\n }\n}\n\nfunction claudeTools(): ClaudeTool[] {\n return [\n {\n name: 'make_payment',\n description: MAKE_PAYMENT_DESCRIPTION,\n input_schema: makePaymentSchema,\n },\n {\n name: 'get_payment_status',\n description: GET_STATUS_DESCRIPTION,\n input_schema: getPaymentStatusSchema,\n },\n {\n name: 'get_allowances',\n description: GET_ALLOWANCES_DESCRIPTION,\n input_schema: getAllowancesSchema,\n },\n {\n name: 'authorize_x402_payment',\n description: AUTHORIZE_X402_DESCRIPTION,\n input_schema: authorizeX402Schema,\n },\n {\n name: 'resume_x402_payment',\n description: RESUME_X402_DESCRIPTION,\n input_schema: resumeX402Schema,\n },\n {\n name: 'haven_sweep_delegate',\n description: SWEEP_DELEGATE_DESCRIPTION,\n input_schema: sweepDelegateSchema,\n },\n ]\n}\n\n// ── OpenAI format ────────────────────────────────────────────────\n\nexport interface OpenAITool {\n type: 'function'\n function: {\n name: string\n description: string\n parameters: {\n type: 'object'\n properties: Record<string, unknown>\n required: readonly string[]\n }\n }\n}\n\nfunction openaiTools(): OpenAITool[] {\n return [\n {\n type: 'function',\n function: {\n name: 'make_payment',\n description: MAKE_PAYMENT_DESCRIPTION,\n parameters: makePaymentSchema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'get_payment_status',\n description: GET_STATUS_DESCRIPTION,\n parameters: getPaymentStatusSchema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'get_allowances',\n description: GET_ALLOWANCES_DESCRIPTION,\n parameters: getAllowancesSchema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'authorize_x402_payment',\n description: AUTHORIZE_X402_DESCRIPTION,\n parameters: authorizeX402Schema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'resume_x402_payment',\n description: RESUME_X402_DESCRIPTION,\n parameters: resumeX402Schema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'haven_sweep_delegate',\n description: SWEEP_DELEGATE_DESCRIPTION,\n parameters: sweepDelegateSchema,\n },\n },\n ]\n}\n\n// ── Public API ───────────────────────────────────────────────────\n\nexport const havenTools = {\n /** Tool definitions in Anthropic/Claude format */\n claude: claudeTools,\n\n /** Tool definitions in OpenAI function-calling format */\n openai: openaiTools,\n}\n","/**\n * The generic Haven payment skill — canonical copy.\n *\n * This SDK file is the single source of truth for the generic, secret-free\n * skill content: no wallet address, no budget numbers, no per-agent values.\n * The agent learns its live budget at runtime via the `haven_get_agent` /\n * `haven_get_allowances` MCP tools, and can read identity + configured budget\n * for fast first-turn orientation from the non-secret `agent.json` the\n * connector writes (see `packages/connect/src/storage.ts`), so the same file\n * works for every user. `packages/connect` imports this directly to\n * auto-install the skill into runtime skills folders.\n *\n * `packages/frontend/src/lib/agent-skill-bundle.ts` keeps a deliberately\n * decoupled inline copy (the download fallback): frontend has zero\n * `@haven_ai/*` dependencies so it can deploy standalone on Vercel without an\n * unpublished SDK export. A parity test in that package's test suite imports\n * this canonical string and asserts byte-for-byte equality, so the two copies\n * cannot drift.\n */\n\nexport 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 — 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\\`) — 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\\` — 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 — 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 —\n\\`agent.json\\` shows the configured budget, not what is left after recent\nspending:\n\n- \\`mcp__haven__haven_get_agent\\` — 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\\` — 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 — this is\nnormal, not an error.\n\n## Paying\n\n**Catalog purchases — 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 — 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 — 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 — 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 —\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 — 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 — both or\nnone together, never just one. If the settle result carries \\`settled: false\\`,\nfunding is queued for the user's approval — 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\\` →\n\\`mcp__haven-signer__haven_sign\\` → \\`mcp__haven__haven_submit\\` →\n\\`mcp__haven-signer__haven_x402_sign_header\\` →\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 — 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\\` — 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 — a ceiling the merchant settles at or below —\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 — 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 — 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 — 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 — 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\\` — 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`\n\n/** Directory name for the installed skill folder. */\nexport const SKILL_FOLDER_NAME = 'haven-pay'\n\n/**\n * The skill BODY — HAVEN_SKILL_MD with the YAML front-matter stripped.\n *\n * For runtimes whose instruction mechanism is a plain guidance file rather\n * than a skills folder (Codex's global AGENTS.md, #1332), the front-matter is\n * skill-registry metadata with no meaning and would render as a stray table.\n * Derived mechanically from the canonical string above, never maintained by\n * hand — the substance cannot fork per runtime.\n */\nexport const HAVEN_SKILL_BODY_MD = HAVEN_SKILL_MD.replace(/^---\\n[\\s\\S]*?\\n---\\n+/, '')\n","/**\n * The Node.js floor Haven's published packages support (#1161).\n *\n * ## Why this lives in the SDK\n *\n * Three packages need to enforce the same floor — `connect` (at setup),\n * `signer` and `mcp` (at startup) — and `@haven_ai/sdk` is the only dependency\n * all three already share. A copy per package is how the floor drifted in the\n * first place: `engines` said `>=24` everywhere while connect's runtime manifest\n * enforced `20.0.0`, so a connect run on Node v23 passed the guard, installed\n * the signer, and signed a real payment. Two numbers for one fact is one number\n * too many.\n *\n * Each consumer still owns its own refusal — the error type, the exit code, the\n * wording of \"what to do next\" — because a library must never terminate its\n * host process. This module only answers *is this version supported* and *what\n * should we tell the user*.\n *\n * ## Why a floor is enforced at all\n *\n * `engines` is advisory: npm emits `EBADENGINE` and installs anyway unless the\n * user happens to have `engine-strict` set. For a normal library that is a\n * reasonable default. For the **signer** it is not — it holds the delegate key\n * and produces every payment signature, so a subtle runtime incompatibility\n * shows up as a wrong or missing signature on a money path. \"It seemed to work\"\n * is precisely the evidence that cannot be relied on there.\n */\n\n/**\n * The minimum supported Node.js version, as `major.minor.patch`.\n *\n * MUST equal the `engines.node` floor declared by every published Haven\n * package. A guard test in each package asserts exactly that against its own\n * `package.json`, so the two cannot drift again silently.\n */\nexport const HAVEN_MINIMUM_NODE_VERSION = '22.0.0'\n\n/** Parse `v22.1.0` / `22.1` / `22` into a comparable triple. */\nfunction parseNodeVersion(value: string): [number, number, number] {\n const match = value.trim().match(/^v?(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?/)\n if (!match) return [0, 0, 0]\n return [Number(match[1] ?? 0), Number(match[2] ?? 0), Number(match[3] ?? 0)]\n}\n\n/**\n * Compare two Node versions. Negative when `left` is older.\n *\n * An unparseable version parses to `0.0.0` and therefore compares as older than\n * any real floor — fail-closed. A version string Haven cannot read is not\n * evidence of a supported runtime, and treating it as one would reopen exactly\n * the hole this module closes.\n */\nexport function compareNodeVersions(left: string, right: string): number {\n const leftParts = parseNodeVersion(left)\n const rightParts = parseNodeVersion(right)\n for (let i = 0; i < 3; i += 1) {\n if (leftParts[i] !== rightParts[i]) return leftParts[i] > rightParts[i] ? 1 : -1\n }\n return 0\n}\n\nexport function isSupportedNodeVersion(\n nodeVersion: string = process.versions.node,\n minimumNodeVersion: string = HAVEN_MINIMUM_NODE_VERSION,\n): boolean {\n return compareNodeVersions(nodeVersion, minimumNodeVersion) >= 0\n}\n\nexport interface UnsupportedNodeVersionMessageOptions {\n /**\n * What is being refused, in the user's terms — \"Haven setup\", \"The Haven\n * signer\". Leads the message so the reader knows what just stopped.\n */\n subject: string\n nodeVersion?: string\n minimumNodeVersion?: string\n /** Appended verbatim as the closing line. Used for the re-run instruction. */\n retryHint?: string\n}\n\n/**\n * The refusal text.\n *\n * Names the detected version, the required version, and **how to fix it** — the\n * previous message stopped after the two version numbers, which tells a user\n * they are stuck without telling them how to get unstuck. The version-manager\n * lines are the fix for nearly everyone; the closing caveat is there because the\n * runtime that *spawns* the signer is frequently not the shell that was\n * upgraded, and a desktop app can keep launching the old Node long after\n * `node -v` in a terminal says otherwise.\n */\nexport function unsupportedNodeVersionMessage(\n options: UnsupportedNodeVersionMessageOptions,\n): string {\n const nodeVersion = options.nodeVersion ?? process.versions.node\n const minimum = options.minimumNodeVersion ?? HAVEN_MINIMUM_NODE_VERSION\n const lines = [\n `${options.subject} requires Node.js >=${minimum}, but this is Node.js ${nodeVersion}.`,\n '',\n 'Upgrade Node, then try again:',\n ` nvm install ${major(minimum)} && nvm use ${major(minimum)} (nvm)`,\n ` fnm install ${major(minimum)} && fnm use ${major(minimum)} (fnm)`,\n ` volta install node@${major(minimum)} (volta)`,\n ` or download Node ${major(minimum)} from https://nodejs.org`,\n '',\n 'If you use a version manager, check that the agent runtime launching Haven picks ' +\n 'up the same version — upgrading your shell does not always change what a desktop ' +\n 'app spawns.',\n ]\n if (options.retryHint) lines.push('', options.retryHint)\n return lines.join('\\n')\n}\n\nfunction major(version: string): string {\n return String(parseNodeVersion(version)[0])\n}\n","/**\n * #1271 / #1301: bounded same-origin merchant MCP endpoint discovery.\n *\n * An agent handed a BASE merchant URL previously had to hand-probe /, /mcp,\n * /sse, … until something answered 402. The demo merchant (and the #1266\n * contract) serves a machine-readable discovery document at\n * `/.well-known/haven-demo-merchant` (also at `/`) naming `mcp_url`. This\n * helper fetches ONLY those two fixed same-origin paths — no redirects\n * (`redirect: 'error'`), a 5 s timeout, a 64 KB read cap — and accepts the\n * document's `mcp_url` ONLY when it stays on the same origin as the input.\n * Anything else returns null and the caller reports the original probe\n * failure. Discovery finds endpoints; it carries no payment authority and an\n * off-origin `mcp_url` is never even fetched — this must not grow into a\n * general network scanner (SSRF bound, per the issue).\n *\n * Originally hosted-only (mcp-server, #1271). Moved here in #1301 so the\n * local/self-signed MCP package (`@haven_ai/mcp`) can share the EXACT same\n * bounded implementation instead of re-deriving discovery semantics —\n * behavior is byte-identical to the pre-move mcp-server copy; the #1271\n * contract tests in packages/mcp-server/src/tools.test.ts pass unmodified\n * against this moved implementation.\n */\nexport const MERCHANT_DISCOVERY_PATHS = ['/.well-known/haven-demo-merchant', '/'] as const\nexport const DISCOVERY_MAX_BYTES = 64 * 1024\n\nexport async function discoverMerchantMcpUrl(inputUrl: string): Promise<string | null> {\n let input: URL\n try {\n input = new URL(inputUrl)\n } catch {\n return null\n }\n for (const path of MERCHANT_DISCOVERY_PATHS) {\n try {\n const res = await globalThis.fetch(`${input.origin}${path}`, {\n method: 'GET',\n headers: { accept: 'application/json' },\n redirect: 'error',\n signal: AbortSignal.timeout(5_000),\n })\n if (!res.ok) continue\n const contentLength = Number(res.headers.get('content-length') ?? 0)\n if (contentLength > DISCOVERY_MAX_BYTES) continue\n const text = await res.text()\n if (text.length > DISCOVERY_MAX_BYTES) continue\n const doc = JSON.parse(text) as { mcp_url?: unknown }\n if (typeof doc.mcp_url !== 'string') continue\n const resolved = new URL(doc.mcp_url)\n if (resolved.origin !== input.origin) continue\n return resolved.toString()\n } catch {\n continue\n }\n }\n return null\n}\n\n/** Trailing-slash/percent-case echoes compare equal; unparseable never does. */\nexport function sameUrl(a: string, b: string): boolean {\n try {\n const ua = new URL(a)\n const ub = new URL(b)\n return ua.origin === ub.origin && ua.pathname.replace(/\\/+$/, '') === ub.pathname.replace(/\\/+$/, '')\n } catch {\n return false\n }\n}\n"]}