@haven_ai/sdk 0.0.0-dev.202609031523.fd49e1a
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +581 -0
- package/dist/index.cjs +4726 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +2808 -0
- package/dist/index.d.ts +2808 -0
- package/dist/index.js +4628 -0
- package/dist/index.js.map +1 -0
- package/examples/mcp-x402-sse.ts +149 -0
- package/examples/x402_openapi_python.py +119 -0
- package/package.json +67 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/connector-channel.ts","../src/types.ts","../src/signer.ts","../src/base64.ts","../src/sweep.ts","../src/x402.ts","../src/haven-api-transport.ts","../src/payment-mappers.ts","../src/payment-state.ts","../src/mcp-merchant-transport.ts","../src/receipt.ts","../src/account-reads.ts","../src/provider.ts","../src/delegate-sweep.ts","../src/x402-protocol.ts","../src/x402-funding-leg.ts","../src/x402-erc7710.ts","../src/tool-adapter.ts","../src/merchant-completion.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","stableStringify","sameAddress","recoverTypedDataAddress","createHash","AsyncLocalStorage","buildExplorerUrl","signHash","payment","balance","receipt","privateKeyToAccount","exact","hashTypedData"],"mappings":";;;;;;;;;;;;AAsDO,IAAM,sBAAA,GAAyB;AAS/B,IAAM,uBAAA,GAA0B;AAevC,IAAM,eAAA,GAAkB,wBAAA;AAGjB,SAAS,mBAAmB,KAAA,EAAwB;AACzD,EAAA,OAAO,eAAA,CAAgB,KAAK,KAAK,CAAA;AACnC;AAgBO,SAAS,uBAAA,CACd,GAAA,EACA,QAAA,GAAmB,uBAAA,EACX;AACR,EAAA,MAAM,OAAA,GAAA,CAAW,GAAA,IAAO,EAAA,EAAI,IAAA,EAAK;AACjC,EAAA,IAAI,OAAA,KAAY,IAAI,OAAO,QAAA;AAC3B,EA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-tag the published Haven packages tell a user to re-run (#2423,\n * slice 3 of epic #2420).\n *\n * ## Why a constant and not a literal\n *\n * Roughly a dozen user- and agent-facing strings across `@haven_ai/sdk`,\n * `@haven_ai/signer`, `@haven_ai/connect` and the hosted MCP server say some\n * form of \"re-run `npx @haven_ai/connect@alpha`\". Every one of them was a\n * hard-coded literal, which is correct only for a build published under the\n * `alpha` dist-tag. Once `dev`-branch snapshots publish under a `dev` tag\n * (#2421), a snapshot build telling its tester to re-run `@alpha` would hand\n * them the production connector — silently replacing the very build they are\n * testing. So the tag becomes one build-time constant and every hint derives\n * from it.\n *\n * ## Who writes it\n *\n * `scripts/release-bump.mjs` rewrites {@link HAVEN_CONNECTOR_CHANNEL} from the\n * version it is bumping to, using exactly the rule `.github/workflows/publish.yml`\n * uses to pick the `--tag` for that same version:\n *\n * | version | dist-tag / channel |\n * |---|---|\n * | `0.1.34-alpha.0` | `alpha` |\n * | `0.0.0-dev.202609021200.abc1234` | `dev` |\n * | `0.2.0` | `latest` |\n *\n * One rule, two consumers. `scripts/ci/connector-channel-agreement.test.mjs`\n * executes the workflow's own shell and the bump script's own function over the\n * same version table and fails if they ever disagree.\n *\n * ## Build-time here, run-time there\n *\n * A published tarball cannot read a deployment's environment, so for the\n * published packages the channel is baked in at release time. A surface that is\n * *deployed* rather than published has no release at which to bake anything in,\n * so it reads the `HAVEN_CONNECTOR_CHANNEL` environment variable and falls back\n * to this constant. Two surfaces do that: the hosted MCP server\n * (`packages/mcp-server/src/connector-channel.ts`) and, since slice 2 (#2422),\n * the backend's connector handout (`parseConnectorChannel` in\n * `packages/backend/src/config.ts`). All three readers share one variable name,\n * one default and one validation pattern, and that agreement is EXECUTED rather\n * than asserted: `packages/backend/src/__tests__/connector-channel.test.ts`\n * runs this module's `resolveConnectorChannel` and the backend's\n * `parseConnectorChannel` over the same input table and fails if they ever\n * diverge.\n *\n * **This says nothing about how any environment is configured.** Setting the\n * variable anywhere is an operator action (epic #2420, operator step 3); no\n * code here can observe it and none of this comment asserts it has happened.\n */\n\n/** The published connector package. Never varies; only its tag does. */\nexport const CONNECTOR_PACKAGE_NAME = '@haven_ai/connect'\n\n/**\n * The npm dist-tag this build's re-run hints name.\n *\n * **Do not hand-edit.** `scripts/release-bump.mjs` owns this literal the same\n * way it owns `CONNECTOR_VERSION` and its siblings, and\n * `scripts/release-bump.test.mjs` fails if the two drift.\n */\nexport const HAVEN_CONNECTOR_CHANNEL = 'dev'\n\n/**\n * A channel is a bare npm dist-tag: lowercase, starts with a letter, and may\n * carry digits and hyphens. This is not only a tidiness check — the resulting\n * spec is interpolated into an `npx <spec> …` command line that a human pastes\n * into a real terminal, so the pattern is also a shell boundary. It cannot\n * express a different package, a registry, a path or a shell metacharacter:\n * a wrong value selects another Haven channel and nothing else.\n *\n * Deliberately identical to `CONNECTOR_CHANNEL_PATTERN` in the backend's\n * `config.ts` (#2422): two readers of one environment variable that disagree\n * about what is valid is a worse failure than either rule alone. Pinned by an\n * executing agreement test, not by this comment.\n */\nconst CHANNEL_PATTERN = /^[a-z][a-z0-9-]{0,31}$/\n\n/** True when `value` is a well-formed dist-tag. */\nexport function isConnectorChannel(value: string): boolean {\n return CHANNEL_PATTERN.test(value)\n}\n\n/**\n * Resolve a channel from a deployment's `HAVEN_CONNECTOR_CHANNEL`.\n *\n * - unset, empty or whitespace ⇒ `fallback` (dashboards store a cleared\n * variable as `\"\"`, and that must land on the production-safe value);\n * - well-formed ⇒ itself;\n * - anything else ⇒ **throws**. It does not quietly fall back: a typo such as\n * `dve` would then land on the production channel, and the environment would\n * look fixed while reproducing the exact defect this slice removes.\n *\n * Well-formed-but-wrong (`dve` again) is *not* caught here and cannot be — it\n * fails later at `npx`, where the error names the package. Stated rather than\n * implied.\n */\nexport function resolveConnectorChannel(\n raw: string | undefined | null,\n fallback: string = HAVEN_CONNECTOR_CHANNEL,\n): string {\n const trimmed = (raw ?? '').trim()\n if (trimmed === '') return fallback\n if (!isConnectorChannel(trimmed)) {\n throw new Error(\n `HAVEN_CONNECTOR_CHANNEL is set to ${JSON.stringify(raw)}, which is not a valid npm ` +\n 'dist-tag (lowercase letter first, then letters, digits or hyphens). Refusing to start ' +\n 'rather than fall back to the default channel, because falling back would hand out the ' +\n 'production connector while looking configured.',\n )\n }\n return trimmed\n}\n\n/** `@haven_ai/connect@<channel>` — the spec an `npx` invocation names. */\nexport function connectorSpec(channel: string = HAVEN_CONNECTOR_CHANNEL): string {\n return `${CONNECTOR_PACKAGE_NAME}@${channel}`\n}\n\n/**\n * The re-run command every hint embeds.\n *\n * `connectorRerunCommand()` → `npx @haven_ai/connect@alpha`\n * `connectorRerunCommand('--doctor')` → `npx @haven_ai/connect@alpha --doctor`\n *\n * `args` is appended verbatim so each call site keeps its own flags and its own\n * surrounding sentence. The wording of those sentences is deliberately NOT\n * moved here: several are inside signer refusal messages that users and agents\n * pattern-match on, and this change is meant to move the channel token and\n * nothing else.\n */\nexport function connectorRerunCommand(\n args?: string,\n options?: { channel?: string; npxFlags?: string },\n): string {\n const channel = options?.channel ?? HAVEN_CONNECTOR_CHANNEL\n const flags = options?.npxFlags ? `${options.npxFlags} ` : ''\n const command = `npx ${flags}${connectorSpec(channel)}`\n return args ? `${command} ${args}` : command\n}\n","import { HAVEN_CONNECTOR_CHANNEL, connectorRerunCommand } from './connector-channel.js'\n\n// ── 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 // #2361: merchants may carry additional resource fields (the demo\n // merchant's `serviceName`, for one). The v2 payment envelope echoes\n // `resource` back VERBATIM, so unknown keys must survive normalization\n // rather than being stripped into a shape the merchant never sent.\n [key: string]: unknown\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 * #1690: the payer identity Haven bound into the expected context (v3),\n * relayed VERBATIM to the signer's wire shape. Absent until the backend\n * flips X402_EMIT_PAYER_CONTEXT.\n */\n payerDelegate?: string\n payerAgentId?: string\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 * The DELEGATE ADDRESS this quote was created for (#1690). Present ⇒ the\n * context is **version 3** and the signer refuses to sign when this is not\n * its own delegate — the guard that turns \"quote as agent A, sign as agent\n * B\" from an on-chain revert three layers later into a named refusal.\n * Inside the Haven-signed message on purpose: outside it, it is forgeable.\n */\n payerDelegate?: string\n /** The paying agent's id, for the refusal message's diagnosis (#1690). */\n payerAgentId?: 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 /**\n * #2054: which selector produced `accepted`, and therefore which entry every\n * amount on this quote describes. `'standard'` is the untagged,\n * EIP-3009-settleable entry; `'erc7710'` means the merchant advertises NO\n * standard entry, so the quote describes its erc7710 one — settleable only\n * from a delegation-rail account, a fact the quote layer cannot see (the\n * rail is a property of the ACCOUNT, not of the 402). This field is\n * descriptive: the actual settlement scheme is still chosen later, with the\n * rail in hand, by `selectX402SettlementScheme`.\n */\n acceptedScheme: 'standard' | 'erc7710'\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 /**\n * @deprecated Use {@link HavenAgentSummary.spend_authority_readiness} —\n * same value, honest name. This signal covers hosted identity + on-chain\n * spend authority ONLY; it says nothing about the LOCAL signer, which the\n * hosted side cannot see (verify via a signer tool or connect --doctor).\n * Kept as an alias; removal earliest after the next release train (#1590).\n */\n readiness: HavenAgentReadiness\n /**\n * Spend-authority readiness: hosted identity + on-chain remaining spend\n * authority. Deliberately named for what it covers — the LOCAL signer's\n * availability is NOT included and must be verified separately (a signer\n * tool call, or the connector's `--doctor`, whose exact command this build\n * renders from `HAVEN_CONNECTOR_CHANNEL` — see `connector-channel.ts`).\n */\n spend_authority_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/**\n * How long this SDK waits for an on-chain confirmation before it stops\n * waiting (#1756).\n *\n * Lives here rather than in `client.ts` so the payment-confirmation poller\n * and the delegate sweep share ONE number instead of forking it. The SDK's\n * other chain waits are already bounded (`waitForFundingTx` at 30 s), so a\n * fourth independently chosen literal is exactly the drift this constant\n * exists to prevent.\n */\nexport const DEFAULT_CONFIRMATION_TIMEOUT_MS = 90_000\n\n/**\n * Whether a sweep transfer was observed to confirm (#1756).\n *\n * The distinction is the point: `unconfirmed` means the transfer was\n * BROADCAST and may still land, which is neither success nor failure. It must\n * never be collapsed into either — reporting a still-pending transaction as\n * done, or as failed, are the same defect in opposite directions.\n */\nexport type SweepConfirmation =\n /** A receipt was observed. The funds are in the Safe. */\n | 'confirmed'\n /**\n * Broadcast, but no receipt within `DEFAULT_CONFIRMATION_TIMEOUT_MS` (or the\n * node returned no receipt). The transaction is still in the mempool and may\n * mine at any time. `txHash` is the broadcast hash — check it on the\n * explorer before re-running the sweep, and expect a re-run to find nothing\n * stranded if it has since landed.\n */\n | 'unconfirmed'\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 /**\n * Transaction hash of the sweep transfer.\n *\n * The RECEIPT hash when `confirmation` is `confirmed`; the BROADCAST hash\n * when it is `unconfirmed` — which is the whole reason the sweep returns\n * instead of throwing on a deadline, since this hash is the only thing that\n * lets a user recover the transfer by hand (#1756).\n */\n txHash: string\n /** Block explorer URL for the tx */\n explorerUrl: string\n /**\n * Did this transfer confirm on-chain within the deadline? (#1756)\n *\n * `unconfirmed` entries have MOVED NOTHING YET and may still move. Do not\n * report a sweep as complete without checking this on every entry.\n */\n confirmation: SweepConfirmation\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 * True when ANY entry is `unconfirmed` — i.e. the sweep broadcast something\n * it could not confirm within the deadline (#1756).\n *\n * Derived from `transfers`, and present anyway because the consumer most\n * likely to misread this result is an LLM reading the JSON of the\n * `haven_sweep_delegate` tool, which will otherwise see a populated\n * `transfers` array and report the money as recovered.\n */\n unconfirmed: boolean\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 /**\n * #2115: RETIRED wire value — no live rail produces it. It described the\n * Safe rail's approval queue, which no longer exists. Kept so a stored value\n * still typechecks; see `AgentPaymentPhaseDescriptions` below for the\n * agent-visible wording, which this comment used to contradict.\n */\n UserApprovalRequired: 'user_approval_required',\n /** #2115: RETIRED wire value — no live rail produces it. Stop and tell the user. */\n UserExecutionRequired: 'user_execution_required',\n /** #2115: RETIRED wire value — no live rail produces it. Stop and tell the user. */\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 payment was rejected and cannot proceed; the agent should stop and tell the user. */\n Rejected: 'rejected',\n /** The payment 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 budget cannot cover the requested amount, so no\n * payment intent was created. The account must be funded or the agent's\n * budget raised before retrying — #2115: the old wording contrasted this\n * with `UserApprovalRequired` as if that were a live alternative, and named\n * the retired rail's Safe and per-token allowance as the fix.\n */\n InsufficientFunds: 'insufficient_funds',\n /**\n * Haven's funding leg (account → delegate, the #946 EIP-3009 bridge)\n * confirmed on-chain, but the merchant rejected the x402 retry. The delegate\n * wallet may hold stranded USDC that was never settled to the merchant. The\n * agent should stop, tell the user, and wait for the sweep flow to reclaim\n * 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 /**\n * #2115: RETIRED wire value — no live rail produces it and nothing maps to\n * it. Stop and tell the user rather than polling; no approval will arrive.\n */\n WaitForUserApproval: 'wait_for_user_approval',\n /** #2115: RETIRED wire value — no live rail produces it. Stop and tell the user rather than polling. */\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]: 'Retired wire value: no live rail produces it. It described the Safe rail\\'s approval queue, which no longer exists — an out-of-policy payment is declined before any money moves. If it is ever seen, stop and tell the user; no approval is pending.',\n [AgentPaymentPhase.UserExecutionRequired]: 'Retired wire value: no live rail produces it. Stop and tell the user.',\n [AgentPaymentPhase.WaitingForAdditionalApprovals]: 'Retired wire value: no live rail produces it. Stop and tell the user.',\n [AgentPaymentPhase.FundingSent]: 'The Haven funding leg was sent; the agent can continue the merchant/protocol leg.',\n [AgentPaymentPhase.Rejected]: 'The payment was rejected and cannot proceed; the agent should stop and tell the user.',\n [AgentPaymentPhase.Expired]: 'The payment 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 budget cannot cover the requested amount, so no payment was created. The account must be funded or the agent budget 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 account.\",\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]: 'Retired wire value: no live rail produces it, and nothing maps to it. It described a per-payment approval queue that no longer exists. If it is ever seen, stop and tell the user rather than polling — no approval will arrive.',\n [AgentPaymentNextAction.WaitForUserToCompletePayment]: 'Retired wire value: no live rail produces it. Stop and tell the user rather than polling.',\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 account needs to be funded or the agent budget 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 account.',\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 account, redeeming the agent\\'s on-chain budget delegation.',\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\n// ── PendingApproval (REMOVED, #2115) ────────────────────────────────────────\n//\n// `export interface PendingApproval extends PaymentStatusResult` stood here\n// with `nextAction: typeof AgentPaymentNextAction.WaitForUserApproval`. It is\n// REMOVED rather than retained-with-a-note, and the distinction from #2113's\n// retention decision is the point:\n//\n// - #2113 retained the `isPendingApproval` BRANCHES in both MCP runtimes and\n// the `pending` / `pending_approval` arms of `nextActionForStatus` here in\n// the SDK. Those are runtime code that still does useful work if a\n// pre-retirement row is ever read back — it answers `stop_and_tell_user`.\n// Retaining them is fail-closed.\n// - This was not runtime code. It was a TYPE asserting that a result with\n// `nextAction === 'wait_for_user_approval'` exists to be narrowed to. After\n// #2113 nothing in the SDK maps any status to `WaitForUserApproval`\n// (`nextActionForStatus` in `payment-state.ts`; zero non-test emissions\n// repo-wide), so no value the SDK produces can inhabit it. A consumer who\n// writes against it has written unreachable code with no runtime signal —\n// retaining it is not fail-closed, it is a promise the type system repeats.\n//\n// Its wire twin is already gone: #2105/PR #2112 deleted the `PendingApproval`\n// and `X402PendingApproval` schemas from `packages/backend/src/openapi/spec.ts`\n// outright (pinned by `spec.test.ts`), so the contract of record no longer\n// describes this shape on any response. This hand-written twin was what was\n// left, flagged on #1289 by that session.\n//\n// `PaymentStateKind` keeps `'approval_request'` and `AgentPaymentNextAction`\n// keeps `WaitForUserApproval` — both are retained wire values carrying the\n// #2055-style \"Retired wire value\" descriptions, and both are still reachable\n// from raw server data. What is gone is the interface that promised a\n// well-formed result of that shape.\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 /**\n * Pass verbatim as the `PAYMENT-SIGNATURE` header on the merchant retry —\n * that name ALONE. erc7710 is always x402 v2, and this header carries the\n * delegation chain, so also sending the legacy `X-PAYMENT` overflows the\n * merchant's header limit (HTTP 431, #2341).\n */\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 merchant catalog (epic #1717). */\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 * Where the entry came from. `operator` = curated in migrations/scripts\n * (the operator vouches; no verification badges). `ingestion` = submitted\n * through the Verified Payable Directory and passed domain-ownership proof\n * plus the read-only quote probe.\n */\n source: 'operator' | 'ingestion'\n /** True only for `ingestion` entries. See the epic's trust claim (never merchant honesty or quality). */\n domainVerified: boolean\n verifiedPayable: boolean\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 source: 'operator' | 'ingestion'\n domain_verified: boolean\n verified_payable: boolean\n}\n\nexport interface RawHavenPaymentReceiptsResponse {\n receipts: RawHavenPaymentReceipt[]\n}\n\n/** @internal */\n/** Wire shape of POST /catalog/submit (#1717, #1716). */\nexport interface CatalogSubmissionAccepted {\n id: string\n verify_token: string\n status: 'submitted' | 'ownership_verified' | 'verified_payable'\n}\n\n/** @internal Client-facing submission handle. */\nexport interface HavenCatalogSubmission {\n id: string\n verifyToken: string\n status: 'submitted' | 'ownership_verified' | 'verified_payable'\n}\n\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\n/**\n * #1521: the idempotency key resolved to a payment that has already settled,\n * and the delegate can no longer fund a fresh authorization for it.\n *\n * This is the typed form of \"you already bought this\". It exists because the\n * alternative was indefensible: the SDK used to mint a new EIP-3009\n * authorization against the spent delegate and hand it back paired with the\n * ORIGINAL payment's `txHash`, so the caller learned what had happened only\n * from a merchant-side balance error that reads identically to a broken\n * payment rail.\n *\n * `receipt` is the ORIGINAL payment — a real receipt for real settled funds,\n * deliberately carrying no `paymentHeader`, because any header minted here\n * would be exactly the unfundable artifact this error replaces.\n */\nexport class X402AlreadySettledError extends HavenApiError {\n readonly x402ErrorCode = 'already_settled' as const\n constructor(\n message: string,\n public readonly receipt: X402Receipt,\n /**\n * `settled` — the delegate was checked on-chain and cannot fund a fresh\n * authorization, so this payment demonstrably completed.\n * `unverifiable` — no `chainRpcs` entry for the chain, so fundability\n * could not be established either way. Same refusal, weaker claim; say\n * which, rather than assert what was not checked.\n */\n public readonly basis: 'settled' | 'unverifiable',\n ) {\n super(message, 409, undefined, receipt.paymentId)\n this.name = 'X402AlreadySettledError'\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 function signerUpdateFallback(channel: string = HAVEN_CONNECTOR_CHANNEL): string {\n return (\n `Update @haven_ai/signer by rerunning \\`${connectorRerunCommand(undefined, { channel })}\\`, 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\n/**\n * The same sentence rendered for THIS build's channel (#2423). Every existing\n * consumer keeps importing this constant and keeps getting a string; the only\n * thing that moved is that `alpha` is no longer typed into it.\n *\n * The hosted MCP server is the one caller that does NOT use this constant: it\n * is deployed rather than published, so it renders `signerUpdateFallback()`\n * with the channel its own environment names.\n */\nexport const SIGNER_UPDATE_FALLBACK = signerUpdateFallback()\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","/**\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 // #2361: spread the merchant's resource object FIRST so unknown fields\n // survive — the v2 payment envelope echoes `resource` verbatim, and a\n // reconstructed subset is a different object than the merchant advertised.\n const resource = {\n ...(candidate.resource && typeof candidate.resource === 'object' ? candidate.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 * The x402 wire header names, in one place (#2289).\n *\n * v2 renamed all three; v1's only name was `X-PAYMENT`, used in BOTH\n * directions. Haven had adopted the v2 names for everything it *reads* and\n * kept the v1 name for the one thing it *writes*, which is how a strict v2\n * merchant came to never see a payment header at all.\n *\n * The 2026-08-31 owner decision was to send both outbound names on every\n * retry rather than switch on `x402Version`: a v1 merchant ignores the name it\n * does not know, a v2 merchant ignores the legacy one, and no version\n * heuristic has to be right for a payment to land.\n *\n * **That is no longer unconditional (#2341).** It held while the cost of a\n * spare header was zero, and on the EIP-3009 bridge it still is. On erc7710 it\n * is not: that header carries a whole delegation chain, and duplicating it\n * overflowed the merchant's header limit — HTTP 431, every erc7710 settlement\n * refused. `x402PaymentHeaderNamesFor` below is the live rule; read it rather\n * than this paragraph, which records why the simpler rule was right first.\n */\n/** v2 client→server payment payload. The name a strict v2 merchant reads. */\nexport const X402_PAYMENT_HEADER_NAME = 'PAYMENT-SIGNATURE'\n/** v1 client→server payment payload; still accepted by most v2 merchants. */\nexport const X402_LEGACY_PAYMENT_HEADER_NAME = 'X-PAYMENT'\n/** v2 server→client payment requirements. */\nexport const X402_PAYMENT_REQUIRED_HEADER_NAME = 'PAYMENT-REQUIRED'\n/** v2 server→client settlement receipt. */\nexport const X402_PAYMENT_RESPONSE_HEADER_NAME = 'PAYMENT-RESPONSE'\n/**\n * Both wire names, v2 first — the value an EIP-3009 retry actually sends.\n *\n * **Not the general answer any more (#2341), and not what a recorder should\n * reach for.** This was the evidence record's `paymentProofHeaderName` while\n * both names always went on the wire; erc7710 now sends one, so a recorder\n * still reading this constant would log a legacy header that was never sent —\n * exactly the drift the previous wording promised it prevented. Use\n * `x402PaymentHeaderNamesSent(paymentHeader)`. Kept exported because it is a\n * published surface and removing it would break consumers.\n */\nexport const X402_PAYMENT_HEADER_NAMES_SENT =\n `${X402_PAYMENT_HEADER_NAME}, ${X402_LEGACY_PAYMENT_HEADER_NAME}`\n\n/**\n * Every payment header name Haven may put on the wire, v2 first.\n *\n * `deliverPayment` iterates this rather than the pair it is sending, so a name\n * it is NOT sending is explicitly deleted from the caller's headers instead of\n * being left as-is. Leaving one would resurrect the stale-header bug #2289\n * closed with `set`, one scheme over.\n */\nexport const X402_PAYMENT_HEADER_NAMES = [\n X402_PAYMENT_HEADER_NAME,\n X402_LEGACY_PAYMENT_HEADER_NAME,\n] as const\n\n/**\n * Which payment header names to put on the wire for THIS payload (#2341).\n *\n * #2289 set both names unconditionally, and on the EIP-3009 bridge that is\n * right: the header is a signature plus a six-field authorization, doubling it\n * costs nothing, and lenient v1-only merchants are real. On **erc7710** it is\n * not right, and it is not merely wasteful — the header carries the whole\n * `[child, budget]` delegation chain plus the UserOperation, so sending it\n * twice pushed the request past the server header-size limit and merchants\n * answered **HTTP 431 Request Header Fields Too Large**. Every erc7710\n * settlement failed, with the funding leg already spent on the hosted path.\n *\n * The rule is by SCHEME, not by byte count, because the scheme is what makes\n * the alias pointless rather than merely large: an erc7710 payload is always\n * `x402Version: 2` (the backend's `encodeXPaymentHeader` hardcodes it), and a\n * merchant that can redeem a delegation chain is by construction running x402\n * v2 plus the MetaMask erc7710 extension — it reads `PAYMENT-SIGNATURE`. The\n * legacy name cannot help it and can only cost the request. A size threshold\n * would be an arbitrary number that changes behaviour silently near its edge.\n *\n * An unreadable header falls back to BOTH names — the #2289 behaviour. Haven\n * builds this value itself, so a parse failure means something is already\n * wrong; the conservative answer there is the one that keeps v1 merchants\n * working rather than the one that happens to fix a size problem we cannot\n * confirm this payload has.\n */\nexport function x402PaymentHeaderNamesFor(paymentHeader: string): readonly string[] {\n const both = [X402_PAYMENT_HEADER_NAME, X402_LEGACY_PAYMENT_HEADER_NAME]\n let decoded: { accepted?: unknown } | null\n try {\n decoded = decodeBase64Json<{ accepted?: unknown }>(paymentHeader)\n } catch {\n return both\n }\n const accepted = decoded?.accepted\n if (!accepted || typeof accepted !== 'object' || Array.isArray(accepted)) return both\n return isErc7710Option(accepted as X402PaymentOption) ? [X402_PAYMENT_HEADER_NAME] : both\n}\n\n/**\n * What the evidence record's `paymentProofHeaderName` must say for THIS\n * payload, derived from the same decision the request makes.\n *\n * `X402_PAYMENT_HEADER_NAMES_SENT` was a constant when the answer was always\n * both. It no longer always is, so a recorder still reading the constant would\n * claim an erc7710 request carried a legacy header it never sent — the exact\n * drift that constant's own comment was written to prevent, one scheme later.\n */\nexport function x402PaymentHeaderNamesSent(paymentHeader: string): string {\n return x402PaymentHeaderNamesFor(paymentHeader).join(', ')\n}\n\n/**\n * The x402 v2 payment envelope: `{x402Version, resource?, accepted, payload,\n * extensions?}` per the spec's PaymentPayload (§5.2.2).\n *\n * The `resource` and `extensions` echoes are the #2361 fix, and they are not\n * optional politeness: the spec makes the extensions echo a MUST (\"the client\n * must include at least the info received\"), and CoinGecko's facilitator was\n * live-bisected rejecting the echo-less envelope with a bare 400 while\n * accepting the identical signature and `accepted`/`payload` bytes with the\n * echoes added (#2360, Base mainnet, 2026-09-01). Both objects are echoed\n * VERBATIM from the merchant's 402 — never reconstructed — and omitted when\n * the challenge carries none, which keeps the envelope byte-identical to the\n * pre-#2361 shape for echo-less merchants (Ampersend and Soundside settled\n * that shape live, so omission is the proven-compatible default).\n *\n * The `accepted` wrap itself is #303's shape and predates this helper — see\n * the #300/#303 history before \"fixing\" it: scheme/network live INSIDE\n * `accepted` in v2, never at the top level.\n */\nexport function x402V2PaymentEnvelope(\n paymentRequired: Pick<X402PaymentRequired, 'x402Version' | 'resource' | 'extensions'>,\n accepted: X402PaymentOption,\n payload: unknown,\n): Record<string, unknown> {\n const resource = paymentRequired.resource\n const extensions = paymentRequired.extensions\n return {\n x402Version: paymentRequired.x402Version,\n ...(resource && typeof resource === 'object' && !Array.isArray(resource)\n ? { resource }\n : {}),\n accepted,\n payload,\n ...(extensions && typeof extensions === 'object' && !Array.isArray(extensions)\n ? { extensions }\n : {}),\n }\n}\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 with the #1986 retired-rail 410 (#2245 —\n * previously a scheme-specific 400 that wrongly implied the legacy rail could\n * still settle via EIP-3009), which is where a rail mismatch SHOULD fail,\n * on-chain-adjacent rather than in a client 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 // Contents-derived, never caller-chosen (#1138, #1690): payerDelegate ⇒ 3,\n // else typedDataHash ⇒ 2, else 1. A v3 context still carries typedDataHash\n // on the delegation rail — the MODE rules key on typedDataHash presence\n // independently of the version, so v3 works in both hash and typed-data\n // modes.\n const version = context.payerDelegate ? 3 : 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 if (context.payerDelegate) {\n payload.payerDelegate = context.payerDelegate.toLowerCase()\n // Only meaningful alongside the delegate it identifies — an agent id with\n // no payer claim would be diagnosis without a guard.\n if (context.payerAgentId) {\n payload.payerAgentId = context.payerAgentId\n }\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 // #2361: the v2 envelope may carry the `resource`/`extensions` echoes\n // (spec PaymentPayload §5.2.2; the extensions echo is a spec MUST when\n // the challenge advertises them). They are echoes of merchant data, not\n // spend authority — validated structurally here, while the required\n // key set stays exactly what it was.\n if (!hasOnlyKeys(decoded, ['x402Version', 'accepted', 'payload'], ['resource', 'extensions'])) {\n throw new Error('shape')\n }\n if ('resource' in decoded && (!decoded.resource || typeof decoded.resource !== 'object' || Array.isArray(decoded.resource))) {\n throw new Error('shape')\n }\n if ('extensions' in decoded && (!decoded.extensions || typeof decoded.extensions !== 'object' || Array.isArray(decoded.extensions))) {\n throw new Error('shape')\n }\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(\n value: Record<string, unknown>,\n required: string[],\n optional: string[] = [],\n): boolean {\n return Object.keys(value).every((key) => required.includes(key) || optional.includes(key)) &&\n required.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 { AsyncLocalStorage } from 'node:async_hooks'\nimport type { HavenClientConfig } from './types.js'\nimport { HavenApiError } from './types.js'\n\nconst DEFAULT_BASE_URL = 'http://localhost:3001'\nconst DEFAULT_REQUEST_TIMEOUT = 30_000\n\ntype HavenApiTransportConfig = Pick<\n HavenClientConfig,\n 'apiKey' | 'baseUrl' | 'requestTimeout' | 'defaultHeaders'\n>\n\n/**\n * Internal Haven-API JSON transport.\n *\n * This module deliberately does not handle merchant requests. Merchant HTTP\n * has separate headers, timeout semantics, and error types in HavenClient.\n * The class is exported only for internal composition and direct tests; it is\n * not part of the package entrypoint.\n */\nexport class HavenApiTransport {\n private readonly apiKey: string\n private readonly baseUrl: string\n private readonly requestTimeout: number\n private readonly defaultHeaders: Record<string, string>\n private readonly requestContext = new AsyncLocalStorage<{ headers: Record<string, string> }>()\n\n constructor(config: HavenApiTransportConfig) {\n this.apiKey = config.apiKey\n this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '')\n this.requestTimeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT\n this.defaultHeaders = { ...(config.defaultHeaders ?? {}) }\n }\n\n /** Run `fn` with extra headers scoped to its asynchronous Haven API work. */\n withRequestContext<T>(headers: Record<string, string>, fn: () => Promise<T>): Promise<T> {\n return this.requestContext.run({ headers: { ...headers } }, fn)\n }\n\n async post<T>(path: string, body: Record<string, unknown>): Promise<T> {\n return this.request<T>('POST', path, body)\n }\n\n async get<T>(path: string): Promise<T> {\n return this.request<T>('GET', path)\n }\n\n 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 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 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","import type {\n HavenPaymentReceipt,\n PaymentResult,\n PaymentStatus,\n PaymentStatusResult,\n RawHavenPaymentReceipt,\n RawPaymentStatusResult,\n RawStatusResponse,\n} from './types.js'\n\nexport type ExplorerUrlBuilder = (chainId: number | undefined, txHash: string) => string\n\nexport function mapPaymentResult(\n raw: RawStatusResponse,\n buildExplorerUrl: ExplorerUrlBuilder,\n): 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\nexport function 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\nexport function 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","import type {\n PaymentNextAction,\n PaymentPhase,\n PaymentStatusResult,\n RawSignResponse,\n RawX402AuthorizeResponse,\n} from './types.js'\nimport {\n AgentPaymentNextAction,\n AgentPaymentPhase,\n HavenApiError,\n HavenPaymentStateError,\n} from './types.js'\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\nexport function paymentStateStatusCode(status: string, fallback = 502): number {\n return PAYMENT_STATE_STATUS_CODES[status] ?? fallback\n}\n\n// The three retired-queue statuses keep their descriptive phase labels on\n// purpose, and #2262 deliberately did not make `approved` the exception.\n// #2101 and #2145 both converted `nextActionForStatus` only and left every\n// arm of this function alone: `phase` is a descriptive label, `nextAction` is\n// the field the agent contract says to follow FIRST, and all three phases\n// these arms return — `user_approval_required`, `user_execution_required`,\n// `waiting_for_additional_approvals` — already carry the \"Retired wire value:\n// no live rail produces it. Stop and tell the user.\" text in\n// `AgentPaymentPhaseDescriptions` (`types.ts`). Re-pointing one of the three\n// at a different phase would make the status→phase correspondence lie in a\n// new way and would be a third handling of one fact.\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 // #2101: STOP, not wait. No live rail mints these payment statuses (410 on\n // the legacy rail, #1986; 403/502 at prepare on the delegation rail;\n // `approval_requests` dropped by #2055), so nothing will ever transition a\n // row out of them. `nextAction` is the field the agent contract says to\n // follow FIRST — emitting `wait_for_user_approval` here would contradict\n // the message beside it and send a compliant agent into a poll loop that\n // cannot terminate. The fail-closed branch is retained; its verdict is stop.\n if (status === 'pending' || status === 'pending_approval') return AgentPaymentNextAction.StopAndTellUser\n // #2262: `approved` closes the #2101 sweep — it was the one branch left\n // emitting a wait, sitting literally between two converted siblings. Same\n // proof as theirs, re-verified rather than inherited: `approved` was an\n // `approval_requests` status (table dropped by #2055), and no write in the\n // repository layer sets `payment_intents.status` to it — every INSERT/UPDATE\n // in `infra/repositories/payment-intents.ts`, `x402-authorizations.ts` and\n // `agent-rekeys.ts` sets `pending_signature`, `submitted`, `confirmed`,\n // `expired` or `failed`. So nothing can mint it, and the wait it returned\n // pointed at a user-execution step on the Safe rail, which has answered 410\n // to everything since #1986. An agent that followed it would wait forever.\n // Three places already said so — `AgentPaymentNextActionDescriptions` and\n // `AgentPaymentPhaseDescriptions` in `types.ts`, and README's next-action\n // table — so the tree contradicted itself here. Fail-closed branch retained;\n // its verdict is stop.\n if (status === 'approved') return AgentPaymentNextAction.StopAndTellUser\n if (status === 'proposed') return AgentPaymentNextAction.StopAndTellUser\n // #2145: `executed` joins its #2101 siblings, fail-closed. It was an\n // `approval_requests` status (table dropped, #2055) and cannot be\n // constructed as a payment_intents.status, so the retry instruction it\n // carried pointed at a state nothing can mint. The reachable producer of\n // retry_original_x402_request is the backend's status projection\n // (funded-but-undelivered on the eip3009 bridge), which arrives via the\n // response's own `next_action` — never through this status fallback.\n if (status === 'executed') return AgentPaymentNextAction.StopAndTellUser\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 // No live Haven rail mints these statuses for a payment: an out-of-policy\n // payment is refused during prepare (403/502 from POST /payments) with\n // nothing written, and the queue table the old text pointed at is gone.\n // The branch is kept fail-closed for a stored row from before the\n // retirement, but the message must not promise an approval that will\n // never arrive — the agent is told to stop, not to poll.\n return `${label} is not payable: it is outside the agent's on-chain budget and no approval is pending (payment_id: ${paymentId}). Ask the user to grant or raise the budget in Haven.`\n }\n if (status === 'approved') {\n // #2262: no live rail mints this status (it belonged to the dropped\n // approval queue), so the message must not promise a payment the user is\n // about to complete. Before this branch existed the generic template below\n // rendered \"<label> is approved; next_action=wait_for_user_to_complete_payment\",\n // which is the instruction, not the documentation, an agent acts on.\n return `This payment carries a retired status (\"approved\") that no live Haven rail produces (payment_id: ${paymentId}). Nothing is waiting to be completed — tell the user to review this payment in Haven.`\n }\n if (status === 'executed') {\n // #2145: no live rail mints this status (it belonged to the dropped\n // approval queue), so the message must not promise a retry.\n return `This payment carries a retired status (\"executed\") that no live Haven rail produces (payment_id: ${paymentId}). Do not retry it — tell the user to review this payment in Haven.`\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\nexport function 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\nexport function throwPaymentStateError(\n label: string,\n raw: RawX402AuthorizeResponse | RawSignResponse,\n): never {\n const statusCode = paymentStateStatusCode(raw.status)\n const state = 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 agent's on-chain budget and was declined; no approval is pending and none will arrive (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","import type { X402McpTransport, X402PaymentRequired } from './types.js'\nimport { MerchantTimeoutError } from './types.js'\nimport { X402_PAYMENT_HEADER_NAMES, x402PaymentHeaderNamesFor } from './x402.js'\n\nexport const DEFAULT_MERCHANT_TIMEOUT = 300_000\nexport const MCP_NOTIFICATION_TIMEOUT = 10_000\nexport const MCP_PROTOCOL_VERSION = '2025-06-18'\nexport const MCP_ACCEPT = 'application/json, text/event-stream'\n\nconst MCP_CLIENT_INFO = { name: 'haven-sdk', version: '1' } as const\n\nexport interface CapturedMerchantResponse {\n merchant_status: number\n merchant_status_text: string\n merchant_headers: Record<string, string>\n merchant_body: string\n}\n\ntype MerchantFetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>\n\nexport interface McpMerchantTransportOptions {\n merchantTimeout?: number\n fetch?: MerchantFetch\n}\n\n/**\n * Per-client MCP-over-HTTP merchant wire transport.\n *\n * This internal seam owns only protocol framing and bounded delivery. It does\n * not create payment authority: callers pass a public wallet address and an\n * already-signed, exact-context-bound payment header.\n */\nexport class McpMerchantTransport {\n private readonly merchantTimeout: number\n private readonly fetchImpl: MerchantFetch\n private requestId = 0\n\n constructor(options: McpMerchantTransportOptions = {}) {\n this.merchantTimeout = options.merchantTimeout ?? DEFAULT_MERCHANT_TIMEOUT\n // Resolve the global at call time, matching the former client helper and\n // preserving the SDK's established fetch-mocking/polyfill seam.\n this.fetchImpl = options.fetch ?? ((input, init) => globalThis.fetch(input, init))\n }\n\n /** Fetch a merchant with a settlement-sized timeout and caller cancellation. */\n async fetch(url: string, init: RequestInit = {}, timeoutMs = this.merchantTimeout): Promise<Response> {\n const timeoutSignal = AbortSignal.timeout(timeoutMs)\n const signal = init.signal ? AbortSignal.any([init.signal, timeoutSignal]) : timeoutSignal\n try {\n return await this.fetchImpl(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 /**\n * Establish an MCP Streamable-HTTP session. Any handshake failure degrades\n * to `undefined`, allowing the caller to fall back to plain x402.\n */\n async initialize(\n url: string,\n init?: RequestInit,\n wallet?: string,\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.fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: ++this.requestId,\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 const message = await this.readMessage(response)\n if (message && 'error' in message) return undefined\n\n await this.notifyInitialized(url, init, sessionId, wallet)\n return sessionId\n } catch {\n return undefined\n }\n }\n\n /** Add the MCP session and response-content negotiation headers. */\n withSessionHeaders(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 /** Read one JSON-RPC message from a JSON or SSE response without consuming it. */\n async readMessage(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 /**\n * Collapse an MCP SSE response to the JSON-RPC result. Non-SSE and\n * unparseable responses pass through with their original body untouched.\n */\n async surfaceResult(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 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 /** Detect MCP transport from the URL or Coinbase Bazaar extension. */\n async detect(\n url: string,\n paymentRequired: X402PaymentRequired,\n response: Response,\n ): Promise<X402McpTransport | undefined> {\n if (isMcpUrl(url)) return { handshakeRequired: true, source: 'path' }\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 /** Identify the conventional Streamable-HTTP MCP path without probing it. */\n isMcpUrl(url: string): boolean {\n return isMcpUrl(url)\n }\n\n /** Detect Bazaar metadata without consuming the merchant response. */\n hasBazaarExtension(response: Response): Promise<boolean> {\n return responseHasBazaarExtension(response)\n }\n\n /**\n * Deliver an already-signed x402 header without changing the caller body.\n *\n * #2289: x402 v2 reads `PAYMENT-SIGNATURE`; v1 reads `X-PAYMENT`. Sending\n * only the legacy name meant a strict v2 merchant never saw the header —\n * indistinguishable, from the merchant's side, from sending no header at\n * all, while on the EIP-3009 bridge the funding leg had already moved the\n * money.\n *\n * #2341: WHICH names go on is per-payload, not always both — see\n * `x402PaymentHeaderNamesFor`. Both for EIP-3009; `PAYMENT-SIGNATURE` alone\n * for erc7710, whose header carries a whole delegation chain and answered\n * HTTP 431 when duplicated. The decision is made here rather than by the\n * caller so every path inherits it, and it is read from the payload rather\n * than passed in, because a flag a caller supplies is a flag a caller can\n * get wrong.\n *\n * Always `set`, never `append`, so a stale header on the caller's `init` is\n * replaced rather than added to — a merchant that reads the first of two\n * values would otherwise verify a superseded authorization. The name NOT\n * being sent is deleted for the same reason: on erc7710 a stale `X-PAYMENT`\n * left in place would be a superseded authorization we chose not to\n * overwrite, which is worse than the duplicate this change removes.\n */\n async deliverPayment(\n url: string,\n init: RequestInit | undefined,\n paymentHeader: string,\n ): Promise<Response> {\n const headers = new Headers(init?.headers)\n const send = x402PaymentHeaderNamesFor(paymentHeader)\n for (const name of X402_PAYMENT_HEADER_NAMES) {\n if (send.includes(name)) headers.set(name, paymentHeader)\n else headers.delete(name)\n }\n return this.fetch(url, { ...init, headers })\n }\n\n private async notifyInitialized(\n url: string,\n init: RequestInit | undefined,\n sessionId: string,\n wallet?: string,\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 await this.fetch(\n url,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }),\n },\n MCP_NOTIFICATION_TIMEOUT,\n )\n } catch {\n // The session is established. Notification delivery remains best-effort.\n }\n }\n}\n\n/** Consume and preserve every diagnostic field of a failed merchant response. */\nexport async function captureMerchantResponse(\n response: Response,\n): 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\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\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\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:')) dataLines.push(line.slice(5).replace(/^ /, ''))\n }\n flush()\n\n return messages\n}\n\nfunction selectJsonRpcResult(\n messages: Array<Record<string, unknown>>,\n): Record<string, unknown> | undefined {\n return messages.find((message) => 'result' in message || 'error' in message) ?? messages.at(-1)\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","import { verifyPaymentReceipt, type PaymentReceipt, type ReceiptVerification } from './receipt.js'\nimport type {\n AgentPaymentWarning,\n HavenAgent,\n HavenAgentAllowanceSummary,\n HavenAgentReadiness,\n HavenAgentSummary,\n HavenAllowanceSummary,\n HavenPaymentReceipt,\n PaymentStatusResult,\n PostPurchaseAllowanceSummary,\n RawHavenAgent,\n RawHavenAllowanceSummary,\n RawHavenPaymentReceiptsResponse,\n} from './types.js'\nimport { AgentPaymentWarningCode } from './types.js'\nimport { HavenApiTransport } from './haven-api-transport.js'\nimport { mapPaymentReceipt } from './payment-mappers.js'\nimport { resolveTokenFromAddress } from './x402.js'\n\nexport type PaymentStatusReader = (paymentId: string) => Promise<PaymentStatusResult>\n\nexport interface AccountReadsOptions {\n transport: HavenApiTransport\n getPaymentStatus: PaymentStatusReader\n}\n\nfunction safeBigInt(value: string): bigint {\n try {\n return BigInt(value)\n } catch {\n return 0n\n }\n}\n\nfunction formatAtomicAmount(atomic: bigint, decimals: number): string {\n if (atomic < 0n) return '0.0'\n const value = atomic.toString().padStart(decimals + 1, '0')\n const whole = value.slice(0, value.length - decimals) || '0'\n const fraction = value.slice(value.length - decimals).replace(/0+$/, '') || '0'\n return `${whole}.${fraction}`\n}\n\nfunction deriveReadiness(\n status: string,\n allowances: ReadonlyArray<{ remainingAtomic: string }>,\n): HavenAgentReadiness {\n if (status !== 'active') return 'revoked'\n return allowances.some((allowance) => safeBigInt(allowance.remainingAtomic) > 0n)\n ? 'ready'\n : 'needs_approval'\n}\n\n/**\n * Internal read-only account boundary for HavenClient.\n *\n * It owns authenticated account/allowance/receipt reads and intentionally has\n * no signer, merchant delivery, or payment-state mutation capability. Exported\n * from this module for direct tests and composition only; it is not exported by\n * the SDK entrypoint.\n */\nexport class AccountReads {\n private readonly transport: HavenApiTransport\n private readonly getPaymentStatus: PaymentStatusReader\n private agentInFlight: Promise<HavenAgent> | null = null\n\n constructor(options: AccountReadsOptions) {\n this.transport = options.transport\n this.getPaymentStatus = options.getPaymentStatus\n }\n\n async getAgent(): Promise<HavenAgent> {\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 async getAgentSummary(): Promise<HavenAgentSummary> {\n const [agent, allowanceSummary] = await Promise.all([this.getAgent(), this.getAllowances()])\n const allowances: HavenAgentAllowanceSummary[] = allowanceSummary.allowances.map((allowance) => {\n const token = resolveTokenFromAddress(allowance.tokenAddress)\n const remainingDisplay = token\n ? `${formatAtomicAmount(safeBigInt(allowance.onchain.remaining), token.decimals)} ${allowance.tokenSymbol}`\n : `${allowance.onchain.remaining} ${allowance.tokenSymbol} (atomic; unknown decimals)`\n return {\n tokenSymbol: allowance.tokenSymbol,\n remainingAtomic: allowance.onchain.remaining,\n remainingDisplay,\n configuredAmount: allowance.configuredAmount,\n resetPeriodMin: allowance.resetPeriodMin,\n isResetPending: allowance.onchain.isResetPending,\n }\n })\n const readiness = deriveReadiness(agent.status, allowances)\n return { ...agent, readiness, spend_authority_readiness: readiness, allowances }\n }\n\n async getAllowances(): Promise<HavenAllowanceSummary> {\n const raw = await this.transport.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 async getPostPurchaseAllowanceSummary(paymentId: string): Promise<{\n allowance: PostPurchaseAllowanceSummary | null\n warnings: AgentPaymentWarning[]\n payment: PaymentStatusResult | null\n }> {\n const unavailable = (detail: string, payment: PaymentStatusResult | null = null) => ({\n payment,\n allowance: null,\n warnings: [{\n code: AgentPaymentWarningCode.AllowanceCheckUnavailable,\n message: `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 const [statusResult, agentResult, allowanceResult] = await Promise.allSettled([\n this.getPaymentStatus(paymentId), this.getAgent(), this.getAllowances(),\n ])\n if (statusResult.status === 'rejected') {\n return unavailable(statusResult.reason instanceof Error ? statusResult.reason.message : String(statusResult.reason))\n }\n const payment = statusResult.value\n if (agentResult.status === 'rejected') {\n return unavailable(agentResult.reason instanceof Error ? agentResult.reason.message : String(agentResult.reason), payment)\n }\n if (allowanceResult.status === 'rejected') {\n return unavailable(allowanceResult.reason instanceof Error ? allowanceResult.reason.message : String(allowanceResult.reason), payment)\n }\n try {\n const tokenAddress = payment.asset ?? payment.x402?.asset ?? null\n if (!tokenAddress) return unavailable('the settled payment does not carry a resolvable token address', payment)\n const match = allowanceResult.value.allowances.find(\n (allowance) => allowance.tokenAddress.toLowerCase() === tokenAddress.toLowerCase(),\n )\n if (!match) return unavailable('no allowance/budget row matches the settled token', payment)\n const token = resolveTokenFromAddress(match.tokenAddress)\n const remainingDisplay = token\n ? `${formatAtomicAmount(safeBigInt(match.onchain.remaining), token.decimals)} ${match.tokenSymbol}`\n : undefined\n const rail = agentResult.value.executionRail\n return {\n payment,\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: rail === 'delegation' ? 'active_delegations' : 'allowance_module',\n },\n warnings: [],\n }\n } catch (error) {\n return unavailable(error instanceof Error ? error.message : String(error))\n }\n }\n\n async listReceipts(options: { limit?: number } = {}): Promise<HavenPaymentReceipt[]> {\n const query = options.limit ? `?limit=${encodeURIComponent(String(options.limit))}` : ''\n const raw = await this.transport.get<RawHavenPaymentReceiptsResponse>(`/machine-payments/receipts${query}`)\n return raw.receipts.map(mapPaymentReceipt)\n }\n\n async getReceipt(paymentId: string): Promise<{ receipt: PaymentReceipt; verification: ReceiptVerification }> {\n const { receipt } = await this.transport.get<{ receipt: PaymentReceipt }>(`/payments/${paymentId}/receipt`)\n return { receipt, verification: verifyPaymentReceipt(receipt) }\n }\n\n private async fetchAgent(): Promise<HavenAgent> {\n const raw = await this.transport.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 executionRail: raw.execution_rail === 'delegation' ? 'delegation' : 'legacy',\n }\n }\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\n/**\n * `runner` is a `ContractRunner`, not a `Signer`: a read-only call such as\n * `balanceOf` only needs a provider, and requiring a signer would have forced\n * the #1521 balance check to construct a wallet it never uses.\n */\nexport function createErc20Contract(\n address: string,\n abi: readonly string[],\n runner: ethers.ContractRunner,\n): ethers.Contract {\n return new ethers.Contract(address, abi as string[], runner)\n}\n","import { createErc20Contract, createJsonRpcProvider, createWallet } from './provider.js'\nimport { sweepUsdcAddress, isSweepableChain, type SweepAuthorization, type SweepPrepareResponse, type SweepSubmitResponse } from './sweep.js'\nimport { DEFAULT_CONFIRMATION_TIMEOUT_MS, HavenApiError, HavenSigningError, type HavenAgent, type SweepConfirmation, type SweepResult } from './types.js'\nimport type { HavenApiTransport } from './haven-api-transport.js'\n\n/** The shape of an ethers v6 `TransactionResponse` this module actually uses. */\ninterface SweepTx {\n hash: string\n wait: (confirmations?: number, timeoutMs?: number) => Promise<{ hash: string } | null>\n}\n\n/**\n * Did a confirmation wait expire, as opposed to fail? (#1756)\n *\n * ethers v6 rejects with `code: 'TIMEOUT'` when the deadline passed and\n * `code: 'CALL_EXCEPTION'` when the transaction mined and reverted. Only the\n * first is \"still in flight\" — collapsing them is the same defect this fix\n * exists to remove, one layer out.\n *\n * The one assumption: the code is read off the error's OWN `code` property.\n * If a future ethers version nests it (e.g. under `info.error.code`) this\n * predicate silently stops recognising timeouts and every expiry throws\n * again. That fails loudly in the tests above — `neverMinesWait()` drives a\n * real `code: 'TIMEOUT'` rejection — so the shape is pinned, not assumed.\n */\nfunction isWaitTimeout(err: unknown): boolean {\n return (err as { code?: unknown } | null)?.code === 'TIMEOUT'\n}\n\n/**\n * Wait for one sweep transfer, bounded (#1756).\n *\n * Before this, both legs called `wait(1)` — which passes CONFIRMATIONS, not a\n * timeout, so it was as unbounded as a bare `wait()` while reading like a\n * deliberate choice. A fee-stuck sweep hung the calling agent forever, with no\n * error and no way to learn the hash it was waiting on.\n *\n * Expiry RETURNS `unconfirmed` rather than throwing. The backend's equivalents\n * (#1722 / #1735 / #1742) can leave a stuck transaction to a durable outbound\n * record and a bump worker; this code runs on the user's machine with no queue\n * behind it, so the CALLER is the only possible owner of a stuck transfer —\n * and throwing would destroy the one thing that owner needs, the tx hash.\n *\n * Everything that is not a timeout still throws, unchanged: a revert is a\n * revert.\n */\nasync function waitForSweepTx(tx: SweepTx): Promise<{ txHash: string; confirmation: SweepConfirmation }> {\n let receipt: { hash: string } | null\n try {\n receipt = await tx.wait(1, DEFAULT_CONFIRMATION_TIMEOUT_MS)\n } catch (err) {\n if (!isWaitTimeout(err)) throw err\n return { txHash: tx.hash, confirmation: 'unconfirmed' }\n }\n // A null receipt is \"no receipt yet\", never \"confirmed\" — the pre-#1756 code\n // substituted the broadcast hash here and reported the transfer as done.\n if (!receipt) return { txHash: tx.hash, confirmation: 'unconfirmed' }\n return { txHash: receipt.hash, confirmation: 'confirmed' }\n}\n\nexport class DelegateSweepApi {\n constructor(private readonly options: { transport: Pick<HavenApiTransport, 'post'>; delegateKey?: string; chainRpcs: Record<number, string>; getAgent: () => Promise<HavenAgent>; buildExplorerUrl: (chainId: number, hash: string) => string }) {}\n async sweepDelegate(): Promise<SweepResult> {\n if (!this.options.delegateKey) throw new HavenSigningError('delegateKey is required for sweepDelegate.')\n const agent = await this.options.getAgent()\n if (!agent.delegateAddress) throw new HavenApiError('Agent has no delegate address.', 422)\n const rpcUrl = this.options.chainRpcs[agent.chainId]\n if (!rpcUrl) throw new HavenApiError(`chainRpcs[${agent.chainId}] must be configured to sweep the delegate wallet.`, 422)\n const provider = createJsonRpcProvider(rpcUrl)\n const wallet = createWallet(this.options.delegateKey, provider)\n const transfers: SweepResult['transfers'] = []\n if (isSweepableChain(agent.chainId)) {\n const contract = createErc20Contract(sweepUsdcAddress(agent.chainId), ['function balanceOf(address) view returns (uint256)', 'function transfer(address to, uint256 amount) returns (bool)'], wallet)\n const balance = await contract.balanceOf(agent.delegateAddress) as bigint\n if (balance > 0n) { const tx = await contract.transfer(agent.safeAddress, balance); const { txHash, confirmation } = await waitForSweepTx(tx as SweepTx); transfers.push({ asset: 'USDC', amount: format(balance, 6), amountAtomic: balance.toString(), txHash, explorerUrl: this.options.buildExplorerUrl(agent.chainId, txHash), confirmation }) }\n }\n // Reached even when the USDC leg came back `unconfirmed`: a stuck ERC-20\n // transfer must not strand the native balance this sweep also exists to\n // recover (#1756). Before the bound, it did — the ETH leg never ran.\n const balance = await provider.getBalance(agent.delegateAddress)\n if (balance > 0n) { const fee = await provider.getFeeData(); const send = balance - ((fee.maxFeePerGas ?? fee.gasPrice ?? 1_000_000n) * 21_000n * 2n); if (send > 0n) { const tx = await wallet.sendTransaction({ to: agent.safeAddress, value: send }); const { txHash, confirmation } = await waitForSweepTx(tx as SweepTx); transfers.push({ asset: 'ETH', amount: format(send, 18), amountAtomic: send.toString(), txHash, explorerUrl: this.options.buildExplorerUrl(agent.chainId, txHash), confirmation }) } }\n return { fromAddress: agent.delegateAddress, toAddress: agent.safeAddress, chainId: agent.chainId, transfers, unconfirmed: transfers.some((t) => t.confirmation === 'unconfirmed') }\n }\n prepareSweep(): Promise<SweepPrepareResponse> { return this.options.transport.post('/machine-payments/sweep/prepare', {}) }\n submitSweep(authorization: SweepAuthorization, signature: string): Promise<SweepSubmitResponse> { return this.options.transport.post('/machine-payments/sweep/submit', { authorization, signature }) }\n}\nfunction format(value: bigint, decimals: number): string { const raw = value.toString().padStart(decimals + 1, '0'); return `${raw.slice(0, -decimals) || '0'}.${raw.slice(-decimals).replace(/0+$/, '') || '0'}` }\n","import {\n AgentPaymentNextAction,\n HavenApiError,\n HavenPaymentStateError,\n} from './types.js'\nimport type {\n PaymentStatusResult,\n X402McpTransport,\n X402PaymentOption,\n X402PaymentRequired,\n X402Quote,\n X402Receipt,\n X402RequestSnapshot,\n X402ResumeState,\n} from './types.js'\nimport {\n buildX402IdempotencyKey,\n resolveTokenFromAddress,\n selectErc7710PaymentOption,\n selectStandardPaymentOption,\n x402AuthorizationAmount,\n} from './x402.js'\nimport { paymentStateStatusCode } from './payment-state.js'\n\n/**\n * Protocol-level x402 shapes and request plumbing, owned by neither\n * settlement scheme (#1618, epic #1613).\n *\n * These are the parts of the x402 lifecycle that do not know how the money\n * moves: quote/receipt/resume shapes, the merchant request snapshot a resume\n * replays, the `x402-wallet` header, and the state checks that decide whether\n * a payment is resumable at all. The EIP-3009 funding leg\n * (`x402-funding-leg.ts`) and the erc7710 no-funding-leg path both build on\n * them, which is why they live here rather than inside either one — a\n * neutral primitive parked in the 3009 module would make the erc7710 module\n * import a funding leg it does not have.\n *\n * Everything here is a free function. There is no state to own: give the same\n * inputs, get the same shape. That is also what makes them cheap to test\n * directly, without constructing a client.\n */\n\nconst CHAIN_EXPLORER_TX: Record<number, string> = {\n 100: 'https://gnosisscan.io/tx',\n 8453: 'https://basescan.org/tx',\n}\n\nexport function 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\nexport function explorerUrlOrEmpty(\n chainId: number | undefined,\n txHash: string | null | undefined,\n): string {\n return txHash ? buildExplorerUrl(chainId, txHash) : ''\n}\n\nexport function 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\nexport function chainIdOrNull(network: string | undefined): number | null {\n return chainIdFromNetwork(network) ?? null\n}\n\nexport function sameAddress(\n a: string | null | undefined,\n b: string | null | undefined,\n): boolean {\n return Boolean(a && b && a.toLowerCase() === b.toLowerCase())\n}\n\nexport function 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\nexport function 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\n// ── Payer identity and the merchant-facing wallet header ────────────\n\n/**\n * The address a merchant should see as the payer. Both settlement schemes ask\n * this question; the answer differs only by which one is configured.\n */\nexport function x402PayerAddress(\n delegateAddress: string | undefined,\n x402Wallet: string | undefined,\n): string | undefined {\n return delegateAddress ?? x402Wallet\n}\n\nexport function withX402Wallet(\n init: RequestInit | undefined,\n wallet: string | undefined,\n): 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// ── Request snapshots (what a resume replays) ───────────────────────\n\nexport function 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\nexport function 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: snapshotRequestBody(init?.body),\n }\n}\n\nexport function requestInitFromSnapshot(request: X402RequestSnapshot): RequestInit {\n return {\n method: request.method,\n headers: request.headers,\n body: request.body,\n }\n}\n\n// ── Quote / receipt / resume shapes ─────────────────────────────────\n\n/**\n * #2054 (review finding) — the shared no-compatible-option refusal, made\n * honest about WHY when the answer is the erc7710 tag.\n *\n * Every EIP-3009 path that re-selects through `selectStandardPaymentOption`\n * (`authorizeX402`, `createX402Intent`, the resume path) used to claim \"Haven\n * supports standard x402 exact payments on Base USDC\" even when the merchant's\n * only Haven-compatible entry was erc7710-tagged — blaming the asset when the\n * limit is the settlement scheme. That message got one hop MORE misleading\n * once `buildX402Quote` started describing erc7710-only merchants: a local or\n * generic-SDK caller can now quote such a merchant successfully and then hit\n * this refusal at pay time, so the refusal has to name the real reason. The\n * base sentence is byte-identical to the pre-#2054 message; the erc7710 clause\n * is appended only when the tag is in fact the reason.\n */\nexport function noCompatiblePaymentOptionError(\n accepts: X402PaymentOption[],\n): HavenApiError {\n const erc7710Only = selectErc7710PaymentOption(accepts) !== null\n return new HavenApiError(\n 'No compatible payment option found in x402 requirements. ' +\n 'Haven supports standard x402 exact payments on Base USDC.' +\n (erc7710Only\n ? \" The only Haven-compatible option this merchant advertises is tagged \" +\n \"extra.assetTransferMethod: 'erc7710' (direct settlement), which this EIP-3009 \" +\n 'payment path cannot settle — the limitation is the settlement scheme, not the ' +\n 'asset. Paying this merchant requires a delegation-rail erc7710 flow ' +\n '(settleX402Erc7710, or the hosted MCP purchase tools).'\n : ''),\n 400,\n )\n}\n\nexport function buildX402Quote(\n paymentRequired: X402PaymentRequired,\n request: X402RequestSnapshot,\n idempotencyKey?: string,\n mcpTransport?: X402McpTransport,\n): X402Quote {\n // #2054: this used to be standard-only, so a merchant advertising ONLY an\n // erc7710-tagged entry — no untagged fallback — was refused as having \"no\n // compatible payment option\" before scheme selection could ever see the\n // entry Haven actually PREFERS on the delegation rail (#1450). The quote is\n // informational and rail-agnostic, so when no standard entry exists it now\n // DESCRIBES the erc7710 entry instead of throwing, and says which selector\n // produced it via `acceptedScheme`. `selectStandardPaymentOption`'s own\n // erc7710 skip is untouched — it is a #1453 correctness property, and the\n // 3009 settlement paths keep re-selecting through it, so an erc7710\n // described quote can never leak into an EIP-3009 authorization.\n const standard = selectStandardPaymentOption(paymentRequired.accepts)\n const option = standard ?? selectErc7710PaymentOption(paymentRequired.accepts)\n if (!option) {\n throw noCompatiblePaymentOptionError(paymentRequired.accepts)\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 acceptedScheme: standard ? 'standard' : 'erc7710',\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\nexport function 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 // #1521: absent for a receipt describing an ALREADY-SETTLED payment,\n // which has no live authorization to carry. `X402Receipt.paymentHeader`\n // was already optional; only these builders assumed otherwise.\n paymentHeader: string | undefined\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\nexport function 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\nexport function 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 = buildX402ResumeState({\n paymentId: err.state.paymentId,\n paymentRequired,\n accepted,\n idempotencyKey,\n request,\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.\nexport function 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 attachX402ResumeState(\n err,\n input.paymentRequired,\n input.accepted,\n input.idempotencyKey,\n input.request,\n )\n}\n\n/**\n * Does this payment's live state actually permit the resume the caller is\n * asking for, and does it describe the SAME purchase they are resuming?\n *\n * Every mismatch below is a 409 rather than a best-effort continue: a resume\n * that quietly retargets a different merchant, amount, network or resource is\n * a payment the user never approved.\n */\nexport function 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, paymentStateStatusCode(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","import { exact } from 'x402/schemes'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport {\n AgentPaymentNextAction,\n HavenApiError,\n HavenSigningError,\n X402AlreadySettledError,\n} from './types.js'\nimport type {\n PaymentStatusResult,\n RawSignResponse,\n RawX402AuthorizeResponse,\n SignData,\n X402PaymentOption,\n X402PaymentRequired,\n X402Receipt,\n} from './types.js'\nimport {\n toStandardPaymentRequirements,\n x402AuthorizationAmount,\n x402V2PaymentEnvelope,\n} from './x402.js'\nimport { paymentStateFromRaw, throwPaymentStateError } from './payment-state.js'\nimport { createErc20Contract, createJsonRpcProvider } from './provider.js'\nimport { decodeBase64Json, encodeBase64Json } from './base64.js'\nimport {\n buildX402Receipt,\n chainIdFromNetwork,\n decimalFromUsdcAtomic,\n explorerUrlOrEmpty,\n} from './x402-protocol.js'\n\n/**\n * The EIP-3009 funding-leg x402 lifecycle (#1618, epic #1613).\n *\n * This scheme moves money in TWO hops: Haven funds the agent's delegate EOA\n * from the account, and the delegate then signs a standard EIP-3009\n * authorization the merchant's facilitator settles. Everything peculiar to\n * that shape lives here — funding confirmation, the delegate's fundability\n * check, header minting from the local delegate key, and the receipt cache\n * keyed by the authorization's own expiry.\n *\n * What is NOT here is deliberate: the erc7710 direct-settlement path has no\n * funding leg at all, so it must not reach into this module. Anything both\n * schemes need is a free function in `x402-protocol.ts`.\n *\n * Non-custody is unchanged by the extraction. The delegate key never leaves\n * the caller's process, Haven never signs, and nothing here can widen what\n * the on-chain policy already permits.\n *\n * Internal to `HavenClient`. Exported for direct tests and composition only;\n * it is not part of the SDK's published entrypoint.\n */\n\nexport type PaymentPoster = <T>(path: string, body: Record<string, unknown>) => Promise<T>\nexport type DataSigner = (signData: SignData) => Promise<string>\nexport type AuthorizationStateAssertion = (label: string, raw: RawX402AuthorizeResponse) => void\n\nexport interface X402FundingLegOptions {\n /** The agent's local delegate key. Required to mint an EIP-3009 header. */\n delegateKey: string | undefined\n /** Derived from `delegateKey`; the address the funding leg pays into. */\n delegateAddress: string | undefined\n /** Payer override for clients without a local delegate key. */\n x402Wallet: string | undefined\n /** Chain id → RPC URL. Absent entries make on-chain reads unverifiable, never guessed. */\n chainRpcs: Record<number, string>\n post: PaymentPoster\n signForData: DataSigner\n assertSignableAuthorizationState: AuthorizationStateAssertion\n}\n\nexport class X402FundingLeg {\n private readonly delegateKey: string | undefined\n private readonly delegateAddress: string | undefined\n private readonly x402Wallet: string | undefined\n private readonly chainRpcs: Record<number, string>\n private readonly post: PaymentPoster\n private readonly signForData: DataSigner\n private readonly assertSignableAuthorizationState: AuthorizationStateAssertion\n\n /**\n * Receipts keyed by idempotency key, held only as long as the underlying\n * EIP-3009 authorization is valid. The cache belongs to this module rather\n * than to the facade because its expiry is read out of the authorization\n * header itself — a 3009 artifact.\n */\n private readonly receiptCache = new Map<string, { expiresAt: number; receipt: X402Receipt }>()\n\n constructor(options: X402FundingLegOptions) {\n this.delegateKey = options.delegateKey\n this.delegateAddress = options.delegateAddress\n this.x402Wallet = options.x402Wallet\n this.chainRpcs = options.chainRpcs\n this.post = options.post\n this.signForData = options.signForData\n this.assertSignableAuthorizationState = options.assertSignableAuthorizationState\n }\n\n // ── Receipt cache ────────────────────────────────────────────────\n\n /** A still-valid cached receipt for this key, or undefined. */\n cachedReceipt(idempotencyKey: string): X402Receipt | undefined {\n const cached = this.receiptCache.get(idempotencyKey)\n if (cached && cached.expiresAt > Date.now()) return cached.receipt\n return undefined\n }\n\n cacheReceipt(idempotencyKey: string, paymentHeader: string, receipt: X402Receipt): void {\n const expiresAt = getPaymentHeaderValidBefore(paymentHeader)\n if (expiresAt > Date.now()) {\n this.receiptCache.set(idempotencyKey, { expiresAt, receipt })\n }\n }\n\n // ── Authorization ────────────────────────────────────────────────\n\n async authorize(\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 // #1521: the authorization is minted AFTER the backend's answer is\n // classified, never before. Signing first meant that when the idempotency\n // key resolved to an already-settled payment, a brand-new authorization\n // had already been created against a delegate whose USDC was gone — and\n // it was handed back paired with the FIRST payment's tx_hash. Within one\n // authorize call the header is still created once and reused, which is\n // all the original \"reuse one EIP-3009 nonce\" note ever meant. If funding\n // fails later, the unused authorization simply expires via validBefore.\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 // The backend can report an ALREADY-EXECUTED payment in two different\n // shapes, and #1521 is reachable through both — the guard is therefore on\n // the meaning, not on one response shape:\n //\n // 1. `success` + `tx_hash` — the delegation rail's confirmed-intent\n // replay (`modules/x402/replay.ts`). Reached only by an idempotency\n // collision; the caller did not ask for THIS payment.\n // 2. `nextAction: retry_original_x402_request` — RETIRED PRODUCER\n // (#2131). This was the legacy rail's approval-queue replay:\n // `modules/x402/legacy-authorize.ts` returned `getAgentPaymentStatus`'s\n // body, which carries no `success` field at all, and that was the\n // DOCUMENTED post-approval retry loop. #1987 deleted that module and\n // #2055 dropped the `approval_requests` table behind it, so nothing\n // emits this value on any rail today (#2145 tracks giving it a live\n // producer). The branch is KEPT fail-closed rather than removed: it\n // costs nothing, and deleting a guard because its input is currently\n // unreachable is how the input comes back unguarded.\n //\n // In both, \"executed\" means the FUNDING leg executed, which is ambiguous:\n //\n // (a) funding confirmed, merchant never paid → the delegate still\n // holds the money and minting a header is correct;\n // (b) funding confirmed, merchant already paid → the delegate is\n // empty and any authorization minted here is unfundable.\n //\n // Only the delegate's on-chain balance separates them. The two shapes\n // differ in what an UNVERIFIABLE balance should mean, and they differ for\n // the same reason the explicit `resumeAuthorizedX402` path does: shape 1\n // is an accident, so \"can't tell\" refuses rather than mint a header we\n // cannot vouch for; shape 2 is the caller following documented steps, so\n // \"can't tell\" proceeds and only a balance verified ABSENT refuses —\n // otherwise every approval resume without a `chainRpcs` entry would break.\n const state = paymentStateFromRaw('x402 payment', raw)\n const executedReplay = raw.success && raw.tx_hash\n ? 'idempotency-collision' as const\n : state?.nextAction === AgentPaymentNextAction.RetryOriginalX402Request\n ? 'approval-resume' as const\n : null\n\n if (executedReplay) {\n const canFund = await this.delegateCanFund(\n raw.chain_id ?? state?.chainId ?? chainIdFromNetwork(option.network),\n option.asset,\n x402AuthorizationAmount(option),\n )\n const refuse = executedReplay === 'idempotency-collision'\n ? canFund !== true\n : canFund === false\n if (refuse) {\n const settledReceipt = state && executedReplay === 'approval-resume'\n ? this.receiptFromStatus(paymentRequired, option, undefined, state)\n : this.receiptFromAuthorization(paymentRequired, option, undefined, raw)\n throw new X402AlreadySettledError(\n canFund === false\n ? 'This x402 payment already settled — the delegate no longer holds the funds to ' +\n 'authorize it again. To buy the same item a second time, pass a distinct ' +\n '`idempotencyKey`; the synthesised key intentionally collapses repeat calls for ' +\n 'the same product within a 5-minute window so a retried request cannot pay twice.'\n : 'This x402 payment already settled, and whether the delegate can still fund a new ' +\n 'authorization could not be verified (no `chainRpcs` entry for this chain). Refusing ' +\n 'rather than issue an authorization that may be unfundable. To buy the same item a ' +\n 'second time, pass a distinct `idempotencyKey`; to finish an interrupted payment, ' +\n 'resume it by `paymentId`.',\n settledReceipt,\n canFund === false ? 'settled' : 'unverifiable',\n )\n }\n }\n\n const paymentHeader = await this.createPaymentHeader(paymentRequired, option)\n\n if (raw.success && raw.tx_hash) {\n const receipt = this.receiptFromAuthorization(paymentRequired, option, paymentHeader, raw)\n this.cacheReceipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n if (state?.nextAction === AgentPaymentNextAction.RetryOriginalX402Request) {\n const receipt = this.receiptFromStatus(paymentRequired, option, paymentHeader, state)\n this.cacheReceipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n this.assertSignableAuthorizationState('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 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.receiptFromAuthorization(paymentRequired, option, paymentHeader, raw, execResult)\n this.cacheReceipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n // ── Header minting ───────────────────────────────────────────────\n\n async createPaymentHeader(\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 // #2361: the shared envelope carries the resource/extensions echoes —\n // see `x402V2PaymentEnvelope`'s comment for why they are load-bearing.\n return encodeBase64Json(x402V2PaymentEnvelope(paymentRequired, option, payment.payload))\n }\n\n // ── Receipt mapping ──────────────────────────────────────────────\n\n receiptFromAuthorization(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n // #1521: `undefined` builds the receipt for a payment that already\n // settled. A settled payment has no live authorization to carry, and\n // minting one to fill this slot is precisely the defect that issue names.\n paymentHeader: string | undefined,\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 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 receiptFromStatus(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n // See `receiptFromAuthorization` — `undefined` is the settled case.\n paymentHeader: string | undefined,\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 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 // ── On-chain reads ───────────────────────────────────────────────\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 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 /**\n * Can the delegate EOA still fund an authorization for `amountAtomic`?\n *\n * #1521: the only question that separates a legitimate resume (funding\n * confirmed, merchant never paid — the delegate still holds the money) from\n * a replayed settled payment (funding confirmed, merchant paid, delegate\n * spent). The intent's own `status: 'confirmed'` is identical in both.\n *\n * The balance is asked of the CHAIN rather than of Haven's bookkeeping on\n * purpose: the merchant-settlement evidence record is written by this SDK\n * *after* the merchant call, so a client that dies between the two leaves\n * the backend believing the merchant was never paid — the exact case the\n * discriminator has to get right. The chain cannot be behind in that way.\n *\n * Returns `null` — never a guess — when `chainRpcs` has no entry for the\n * chain or the read fails. Callers must treat that as \"unverifiable\", not\n * as \"funded\".\n */\n async delegateCanFund(\n chainId: number | undefined,\n tokenAddress: string,\n amountAtomic: string,\n timeoutMs = 10_000,\n ): Promise<boolean | null> {\n if (!chainId || !this.delegateAddress) return null\n const rpcUrl = this.chainRpcs[chainId]\n if (!rpcUrl) return null\n try {\n const provider = createJsonRpcProvider(rpcUrl)\n const token = createErc20Contract(\n tokenAddress,\n ['function balanceOf(address) view returns (uint256)'] as const,\n provider,\n )\n // Bounded like `waitForFundingTx` above. This sits on a money\n // authorization path with no way for a caller to route around a stall,\n // so an unresponsive RPC must degrade to \"unverifiable\" rather than\n // hang the payment: a slow answer is worth less than a prompt refusal.\n const balance = await Promise.race([\n token.balanceOf(this.delegateAddress) as Promise<bigint>,\n new Promise<null>((resolve) => setTimeout(() => resolve(null), timeoutMs).unref?.()),\n ])\n if (balance === null) return null\n return balance >= BigInt(amountAtomic)\n } catch {\n // An RPC that is down, or an amount that will not parse, tells us\n // nothing about the delegate's balance. Saying so is the whole point of\n // the tri-state — and on the accidental-replay path it fails toward\n // refusing, never toward minting.\n return null\n }\n }\n}\n\n/**\n * The authorization's own `validBefore`, in milliseconds — the only honest\n * expiry for a cached receipt, since the header stops being usable then\n * whatever the SDK believes.\n */\nexport function 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","import {\n HavenApiError,\n HavenSigningError,\n} from './types.js'\nimport type {\n RawX402AuthorizeResponse,\n RawX402SettleResponse,\n SignData,\n X402Erc7710Settlement,\n X402McpCallContext,\n X402PaymentRequired,\n} from './types.js'\nimport {\n selectX402SettlementScheme,\n x402AuthorizationAmount,\n} from './x402.js'\n\n/**\n * The erc7710 direct-settlement lifecycle (#1619, epic #1613).\n *\n * The defining property of this scheme is an ABSENCE. 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. Nothing in this\n * module checks a delegate balance or waits for a funding transaction,\n * because on this path there is neither — and a test pins that, since the\n * defects this epic exists to prevent (#1510, #1511, #1521) were all a\n * funding-leg assumption leaking into a path that has none.\n *\n * It builds no merchant header either. The backend assembles the MetaMask\n * erc7710 payload in `assembleSettlementPayload`, which is why this module is\n * so much smaller than `x402-funding-leg.ts`.\n *\n * Non-custody: `settle()` signs in-process with the caller's delegate key,\n * while `prepare()`/`submit()` exist precisely so the hosted topology can\n * drive the two halves with the LOCAL signer in between — hosted Haven has no\n * key and must not. Neither half can widen what the delegation already\n * permits; the caveat enforcers decide that on-chain.\n *\n * Internal to `HavenClient`. Exported for direct tests and composition only;\n * it is not part of the SDK's published entrypoint.\n */\n\nexport type PaymentPoster = <T>(path: string, body: Record<string, unknown>) => Promise<T>\nexport type DataSigner = (signData: SignData) => Promise<string>\nexport type RailReader = () => Promise<{ executionRail?: string }>\n\nexport interface X402Erc7710Options {\n /** Required only by `settle()`, which signs in-process. */\n delegateKey: string | undefined\n post: PaymentPoster\n signForData: DataSigner\n /** Reads the ACCOUNT's rail — a property no 402 response can carry. */\n getAgent: RailReader\n}\n\nexport class X402Erc7710 {\n private readonly delegateKey: string | undefined\n private readonly post: PaymentPoster\n private readonly signForData: DataSigner\n private readonly getAgent: RailReader\n\n constructor(options: X402Erc7710Options) {\n this.delegateKey = options.delegateKey\n this.post = options.post\n this.signForData = options.signForData\n this.getAgent = options.getAgent\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 at the\n * rail seam — a non-delegation account gets the #1986 retired-rail 410 from\n * `POST /x402/authorize` whatever scheme it asks for (#2245) — and so does\n * this method, before building a request the backend would only reject: an\n * error a client can explain is worth more than a refusal 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 settle(\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.prepare(paymentRequired, options)\n const signature = await this.signForData(prepared.signData)\n const paymentHeader = await this.submit(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 prepare(\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 a\n * non-delegation account at the rail seam (the #1986 410; #2245 removed\n * the separate scheme-level 400). A caller that asserted the wrong rail\n * would build a request the backend rejects.\n */\n delegationRail?: boolean\n /**\n * #1547: the merchant MCP-tool call this authorization was quoted\n * against, persisted so the settle leg can rehydrate it by payment_id\n * (#1307) — the same option `createX402Intent` already carries. Without\n * it an erc7710 settle needs merchant_url/tool_name/arguments\n * re-threaded, which the guided catalog path (#1305) exists to remove.\n */\n mcpCallContext?: X402McpCallContext\n /**\n * #2041: replay key for this authorization, exactly as the 3009 path's\n * `createX402Intent` already sends one.\n *\n * The backend has supported full replay dedup on THIS branch all along —\n * `runDelegationAuthorize` looks an existing intent up by key before it\n * ever branches on the funding shape, and the erc7710 insert carries\n * `conflictTarget: 'x402_idempotency_key'`. The dedup was simply never\n * invoked, because this options bag had no way to say the key. A retried\n * call therefore minted a SECOND independently-signable settlement child\n * for the same purchase — a double-authorize hazard on the one scheme\n * whose signed artifact is spend authority rather than a funding step.\n *\n * Omitted, the backend behaves exactly as before (no key, no dedup).\n */\n idempotencyKey?: string\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 // #2373: the full 402 challenge, persisted verbatim by the backend\n // (#1355) so the settle handoff can echo its resource/extensions into\n // the X-PAYMENT envelope (#2361). This scheme decomposes the challenge\n // into the fields below for AUTHORITY; the stored copy exists for the\n // echo, which cannot be reconstructed from the decomposition — omitting\n // it is how every erc7710 payment failed a merchant that enforces the\n // spec's extensions-echo MUST. Same ≤64KB guard and omission behaviour\n // as the 3009 path (client.ts): an oversized challenge omits the field\n // rather than failing the payment, and the settle echo then omits too.\n ...(new TextEncoder().encode(JSON.stringify(paymentRequired)).length <= 65536\n ? { paymentRequired }\n : {}),\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 // #2041: sent only when the caller supplied one, so an omitting caller's\n // request body is byte-identical to the pre-#2041 shape.\n ...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}),\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 // #1307/#1547: persisted so the settle leg can rehydrate the merchant\n // call by payment_id on this scheme too, not only on the 3009 bridge.\n ...(options.mcpCallContext ? { mcpCallContext: options.mcpCallContext } : {}),\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 submit(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","import { HavenApiError, HavenPaymentStateError } from './types.js'\nimport type { X402PaymentRequired, X402Receipt } from './types.js'\n\n/**\n * The agent-tool adapter (#1620, epic #1613).\n *\n * `HavenClient.executeTool` exists so an agent framework can hand a tool call\n * straight through; these three functions are the translation layer it needs\n * — a 402 challenge built from flat tool arguments, a receipt flattened to\n * snake_case JSON, and an error rendered as a RESULT rather than thrown.\n *\n * That last one is the reason this is a distinct concern rather than\n * incidental formatting: a tool handler that throws loses the payment state\n * the model needs to decide what to do next, so `toolError` deliberately\n * preserves it (payment_id, phase, next_action) in a shape a model can read.\n *\n * Pure functions over their inputs — no client, no network, no state.\n */\n\nexport function 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\nexport function 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\nexport function 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","import {\n AgentPaymentNextAction,\n AgentPaymentPhase,\n HavenApiError,\n HavenPaymentStateError,\n} from './types.js'\nimport type {\n PaymentStatusResult,\n X402PaymentRequired,\n X402Receipt,\n} from './types.js'\nimport {\n captureMerchantResponse,\n McpMerchantTransport,\n} from './mcp-merchant-transport.js'\nimport type { CapturedMerchantResponse } from './mcp-merchant-transport.js'\nimport { x402PaymentHeaderNamesSent } from './x402.js'\nimport { buildExplorerUrl, x402PayerAddress } from './x402-protocol.js'\nimport { paymentStateStatusCode } from './payment-state.js'\nimport { decodeBase64Json } from './base64.js'\n\n/**\n * Merchant delivery and the evidence trail behind it (#1620, epic #1613).\n *\n * Where `mcp-merchant-transport.ts` (#1616) owns the wire — timeouts,\n * sessions, SSE framing — this module owns what has to be TRUE around a\n * merchant call once a payment exists: which wallet the merchant should see,\n * what the payment's live state permits, and what gets written down\n * afterwards.\n *\n * The reporting is deliberately best-effort and deliberately asymmetric. A\n * merchant that REJECTS a retry after Haven already moved money is a\n * reconciliation event and is recorded as one; a merchant that accepts is\n * evidence, plus its own receipt when it offers one. Neither write may ever\n * change the caller-visible outcome — the resource is already paid for, and\n * an exception thrown from bookkeeping would turn a completed payment into a\n * reported failure. That is why every one of these swallows.\n *\n * Scheme-neutral by construction: it is handed a receipt or a payment id and\n * never asks how the money moved, which is what lets the #1508 no-funding-leg\n * path through the same door as the 3009 path.\n *\n * Internal to `HavenClient`. Exported for direct tests and composition only.\n */\n\n/** #2292: what an agent says a merchant answered to a retry Haven did not make. */\nexport type X402MerchantOutcome = 'accepted' | 'rejected'\n\n/** #2292: what Haven wrote down for such a report. */\nexport interface X402MerchantOutcomeReport {\n paymentId: string\n outcome: X402MerchantOutcome\n /** Haven's own funding tx for this payment — the anchor, never caller-supplied. */\n txHash: string\n /** Haven's own recorded resource URL — likewise never caller-supplied. */\n resourceUrl: string\n recorded: 'reconciliation_event' | 'evidence'\n}\n\nconst MERCHANT_BODY_SNIPPET_LIMIT = 1000\n\n/**\n * Evidence-report retry policy for a RETRYABLE refusal (#2117).\n *\n * The backend already distinguishes two refusals on `POST\n * /machine-payments/evidence` and says so in the status code: `503`\n * (`settlement_unobservable`) means \"the chain could not be read, or the\n * settlement is not mined yet — report it again\", and `409` means \"that is a\n * settled no\". The SDK discarded that distinction in a bare `catch {}`,\n * treating both as best-effort silence — so on erc7710, where the reported hash\n * is the ONLY thing that produces an evidence row, a transaction that simply\n * had not been mined yet at report time meant the payment never reached the\n * user's books at all.\n *\n * Bounded, and terminal on anything that is not a 503: a retry loop against a\n * settled no is just noise, and the total wait has to stay far under any\n * caller's patience because the paid resource is already in hand. Four attempts\n * over ~7s of backoff covers the mine-latency case this exists for without ever\n * becoming a reason a completed payment feels slow.\n */\nconst EVIDENCE_RETRY_DELAYS_MS = [1_000, 2_000, 4_000]\n\n/** The backend's retryable refusal — see `modules/mpp/evidence.ts`. */\nconst EVIDENCE_RETRYABLE_STATUS = 503\n\nexport type PaymentPoster = <T>(path: string, body: Record<string, unknown>) => Promise<T>\nexport type PaymentStatusReader = (paymentId: string) => Promise<PaymentStatusResult>\nexport type AgentReader = () => Promise<{ delegateAddress?: string }>\n\nexport interface MerchantCompletionOptions {\n post: PaymentPoster\n merchantTransport: McpMerchantTransport\n getPaymentStatus: PaymentStatusReader\n getAgent: AgentReader\n delegateAddress: string | undefined\n x402Wallet: string | undefined\n /** Injectable only so tests do not spend the real backoff. */\n sleep?: (ms: number) => Promise<void>\n}\n\nexport class MerchantCompletion {\n private readonly post: PaymentPoster\n private readonly merchantTransport: McpMerchantTransport\n private readonly getPaymentStatus: PaymentStatusReader\n private readonly getAgent: AgentReader\n private readonly delegateAddress: string | undefined\n private readonly x402Wallet: string | undefined\n private readonly sleep: (ms: number) => Promise<void>\n\n constructor(options: MerchantCompletionOptions) {\n this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)))\n this.post = options.post\n this.merchantTransport = options.merchantTransport\n this.getPaymentStatus = options.getPaymentStatus\n this.getAgent = options.getAgent\n this.delegateAddress = options.delegateAddress\n this.x402Wallet = options.x402Wallet\n }\n\n async retryRequest(\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 retryResponse = await this.merchantTransport.deliverPayment(\n url,\n initialInit,\n receipt.paymentHeader,\n )\n\n if (!retryResponse.ok) {\n const merchant = await captureMerchantResponse(retryResponse)\n await this.recordRetryRejected({\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.reportEvidence({\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: x402PaymentHeaderNamesSent(receipt.paymentHeader),\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 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 async resolveCompletionContext(input: {\n paymentId: string\n url: string\n /** #1508: see completeX402MerchantCall's option of the same name. */\n noFundingLeg?: boolean\n }): Promise<{\n paymentId: string\n /** Null on a no-funding-leg scheme — there is no Haven-submitted tx. */\n txHash: string | null\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 // #1508: BOTH conditions below encode the EIP-3009 lifecycle, where\n // `confirmed` means Haven's funding transaction mined and its hash is the\n // evidence anchor. On a no-funding-leg scheme neither is reachable, and\n // #1456 reused this helper unadapted — so every hosted erc7710 call threw\n // `HavenPaymentStateError(status.message)`, surfacing as \"The payment was\n // submitted and is waiting for confirmation\" AFTER the settlement had\n // already succeeded, with the merchant never contacted.\n //\n // `submitted` is not a transient state to wait out here: it is the CORRECT\n // and final Haven-side state for erc7710 (`modules/x402/settle.ts` — \"The\n // intent flips to 'submitted'; final settlement is observed via the\n // merchant/receipt path\"). The merchant redeems the [child, budget] chain,\n // which is exactly the call this method is about to make.\n const readyForMerchantCompletion = input.noFundingLeg\n ? status.kind === 'payment_intent' && status.status === 'submitted'\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, paymentStateStatusCode(status.status, 409), status)\n }\n\n // Deliberately NOT relaxed to \"absent is fine\": on the funding-leg path a\n // missing hash still means the evidence anchor is gone and remains a 502.\n // The no-funding-leg path skips it because there is no such transaction to\n // be missing — not because the check is inconvenient.\n if (!input.noFundingLeg && !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 async resolveWalletForMerchantCall(): Promise<string | undefined> {\n const localWallet = x402PayerAddress(this.delegateAddress, this.x402Wallet)\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 async recordRetryRejected(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 /**\n * #2292: record what a merchant said to a retry **Haven did not make**.\n *\n * On the plain-HTTP x402 path Haven tells the agent to call the merchant\n * itself — that is the keyless design, not an oversight — so the two writes\n * above were reachable only from `completeX402MerchantCall`, where Haven IS\n * the caller. A manual retry had nowhere to put its outcome, which left\n * `intentStateFor`'s merchant-rejected branch dead on the one flow Haven\n * prescribes and made the 15-minute grace window the only route to\n * `funded_but_unsettled`.\n *\n * Three properties distinguish this from `recordRetryRejected` /\n * `reportEvidence`, and each is deliberate:\n *\n * 1. **It does not swallow.** Those two are bookkeeping hung off a call\n * whose outcome is already decided, so an exception there would turn a\n * completed payment into a reported failure. Here the report IS the\n * caller's request; silently dropping it would recreate the exact\n * unobservability #2292 exists to remove.\n * 2. **The anchor is server-side.** `txHash` and `resourceUrl` come from\n * the payment's own Haven record, never from the reporter — so a report\n * cannot be pointed at a different transaction or a different resource,\n * and it can never CONFIRM an intent (an erc7710 intent has no Haven\n * tx hash and is refused here rather than completed from a supplied one,\n * which is #2092's verified seam and stays its own path).\n * 3. **It is evidence, never authority.** Haven does not and must not check\n * the claim: verifying it would mean calling the merchant, which is the\n * property this whole path exists to preserve. What bounds a false\n * report is scope — the backend routes resolve the payment\n * `WHERE agent_id = $`, so a caller can only ever describe its own\n * payment — plus the fact that nothing financial keys off the claim:\n * the sweep is balance-driven, the intent's status/amount/recipient are\n * untouched, and a false `accepted` runs the server's own on-chain\n * residue check, which re-flags stranded funds independently.\n */\n async reportMerchantOutcome(input: {\n paymentId: string\n outcome: X402MerchantOutcome\n merchantStatus: number\n merchantBody?: string\n }): Promise<X402MerchantOutcomeReport> {\n if (!Number.isInteger(input.merchantStatus) || input.merchantStatus < 100 || input.merchantStatus > 599) {\n throw new HavenApiError(\n `merchant_status must be an integer HTTP status from 100 to 599 (received ${input.merchantStatus}).`,\n 400,\n undefined,\n input.paymentId,\n )\n }\n // A self-contradictory report is refused rather than recorded: this is\n // the one thing about the claim Haven CAN check without contacting the\n // merchant, so it checks it.\n const looksAccepted = input.merchantStatus >= 200 && input.merchantStatus < 300\n if (looksAccepted !== (input.outcome === 'accepted')) {\n throw new HavenApiError(\n `outcome \"${input.outcome}\" contradicts merchant_status ${input.merchantStatus}: ` +\n 'report \"accepted\" only for a 2xx and \"rejected\" only for a non-2xx.',\n 400,\n undefined,\n input.paymentId,\n )\n }\n\n const status = await this.getPaymentStatus(input.paymentId)\n if (status.rail !== 'x402') {\n throw new HavenPaymentStateError(\n `Payment ${status.paymentId} is ${status.rail}, not x402 — there is no merchant retry to report.`,\n 409,\n status,\n )\n }\n if (status.status !== 'confirmed' || !status.txHash) {\n throw new HavenPaymentStateError(\n `Payment ${status.paymentId} has no confirmed Haven funding transaction to anchor a ` +\n `merchant report to (status ${status.status}). ${status.message}`,\n paymentStateStatusCode(status.status, 409),\n status,\n )\n }\n const resourceUrl = status.resourceUrl ?? status.x402?.resourceUrl ?? null\n if (!resourceUrl) {\n throw new HavenApiError(\n `Payment ${status.paymentId} has no recorded resource URL, so a merchant report cannot be stored.`,\n 409,\n status,\n status.paymentId,\n )\n }\n\n const txHash = status.txHash\n if (input.outcome === 'rejected') {\n await this.post('/machine-payments/reconciliation-events', {\n paymentId: status.paymentId,\n rail: 'x402',\n eventType: 'merchant_retry_rejected_after_payment',\n txHash,\n reason: `Agent-reported: merchant returned HTTP ${input.merchantStatus} to a manual retry after Haven payment confirmation`,\n details: {\n resource_url: resourceUrl,\n retry_status: input.merchantStatus,\n retry_body: input.merchantBody?.slice(0, MERCHANT_BODY_SNIPPET_LIMIT) || null,\n reported_by: 'agent_manual_retry',\n },\n })\n return { paymentId: status.paymentId, outcome: 'rejected', txHash, resourceUrl, recorded: 'reconciliation_event' }\n }\n\n await this.post('/machine-payments/evidence', {\n paymentId: status.paymentId,\n rail: 'x402',\n txHash,\n resourceUrl,\n merchantStatus: input.merchantStatus,\n })\n return { paymentId: status.paymentId, outcome: 'accepted', txHash, resourceUrl, recorded: 'evidence' }\n }\n\n async reportEvidence(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 const body = {\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\n // Still best-effort in the sense that matters — nothing here may change\n // the caller-visible outcome, because the resource is already paid for and\n // delivered. What changed (#2117) is that a RETRYABLE refusal is no longer\n // swallowed identically to a terminal one. On erc7710 this report is the\n // only thing that produces an evidence row, and therefore the only thing\n // that puts the payment in the user's books.\n for (let attempt = 0; ; attempt += 1) {\n try {\n await this.post('/machine-payments/evidence', body)\n return\n } catch (err) {\n const retryable =\n err instanceof HavenApiError && err.statusCode === EVIDENCE_RETRYABLE_STATUS\n if (!retryable || attempt >= EVIDENCE_RETRY_DELAYS_MS.length) return\n await this.sleep(EVIDENCE_RETRY_DELAYS_MS[attempt])\n }\n }\n }\n}\n\nexport function 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/**\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 */\n\nexport function 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","import { hashTypedData } from 'viem'\nimport {\n signHash,\n signUserOpTypedDataForDelegation,\n signSettlementDelegationTypedData,\n addressFromKey,\n verifySignature,\n} from './signer.js'\nimport type { PaymentReceipt, ReceiptVerification } from './receipt.js'\nimport type {\n HavenClientConfig,\n PaymentRequest,\n PaymentIntent,\n PaymentResult,\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 X402McpCallContext,\n X402MerchantCallContext,\n RawX402MerchantCallContext,\n X402Quote,\n X402Receipt,\n X402RequestSnapshot,\n X402ResumeState,\n ResumeAuthorizedX402Input,\n ResumeX402PaymentInput,\n RawX402AuthorizeResponse,\n X402Erc7710Settlement,\n HavenAgent,\n HavenAgentSummary,\n HavenAgentAllowanceSummary,\n HavenAllowanceSummary,\n PostPurchaseAllowanceSummary,\n HavenPaymentReceipt,\n CatalogSubmissionAccepted,\n HavenCatalogEntry,\n HavenCatalogSubmission,\n RawCatalogEntry,\n AgentPaymentWarning,\n} from './types.js'\nimport {\n AgentPaymentNextAction,\n AgentPaymentPhase,\n AgentPaymentRail,\n HavenApiError,\n HavenPaymentStateError,\n X402UnexpectedStatusError,\n X402AlreadySettledError,\n HavenSigningError,\n HavenTimeoutError,\n DEFAULT_CONFIRMATION_TIMEOUT_MS,\n} from './types.js'\nimport {\n buildX402IdempotencyKey,\n parsePaymentRequiredResponse,\n resolveTokenFromAddress,\n selectStandardPaymentOption,\n toStandardPaymentRequirements,\n x402AuthorizationAmount,\n x402PaymentHeaderNamesSent,\n} from './x402.js'\nimport type {\n SweepAuthorization,\n SweepPrepareResponse,\n SweepSubmitResponse,\n} from './sweep.js'\nimport { HavenApiTransport } from './haven-api-transport.js'\nimport {\n mapPaymentResult,\n mapPaymentStatusResult,\n} from './payment-mappers.js'\nimport {\n paymentStateFromRaw,\n paymentStateStatusCode,\n throwPaymentStateError,\n} from './payment-state.js'\nimport { McpMerchantTransport } from './mcp-merchant-transport.js'\nimport { AccountReads } from './account-reads.js'\nimport { DelegateSweepApi } from './delegate-sweep.js'\nimport {\n assertCanResumeX402,\n attachResumeState,\n buildExplorerUrl,\n buildX402Quote,\n chainIdFromNetwork,\n chainIdOrNull,\n decimalFromUsdcAtomic,\n explorerUrlOrEmpty,\n noCompatiblePaymentOptionError,\n requestInitFromSnapshot,\n sameAddress,\n snapshotX402Request,\n withX402Wallet,\n x402PayerAddress,\n} from './x402-protocol.js'\nimport { X402FundingLeg } from './x402-funding-leg.js'\nimport { X402Erc7710 } from './x402-erc7710.js'\nimport { toolError, toolX402PaymentRequired, x402ToolReceipt } from './tool-adapter.js'\nimport { MerchantCompletion, parseMerchantSettlement } from './merchant-completion.js'\nimport type { X402MerchantOutcome, X402MerchantOutcomeReport } from './merchant-completion.js'\n\nconst DEFAULT_POLLING_INTERVAL = 3_000\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\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 source: entry.source,\n domainVerified: entry.domain_verified,\n verifiedPayable: entry.verified_payable,\n }\n}\n\nexport class HavenClient {\n private readonly delegateKey: string | undefined\n private readonly havenApi: HavenApiTransport\n private readonly accountReads: AccountReads\n private readonly delegateSweep: DelegateSweepApi\n private readonly x402Wallet: string | undefined\n private readonly merchantTransport: McpMerchantTransport\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 /**\n * The EIP-3009 funding-leg lifecycle (#1618). The facade holds a reference\n * and delegates; it does not reimplement any of it.\n */\n private readonly fundingLeg: X402FundingLeg\n /**\n * The erc7710 direct-settlement lifecycle (#1619). Separate from the funding\n * leg on purpose: this scheme has no funding leg to share.\n */\n private readonly erc7710: X402Erc7710\n /**\n * Merchant delivery and the evidence trail behind it (#1620). Scheme-neutral\n * on purpose — both settlement schemes finish through the same door.\n */\n private readonly merchantCompletion: MerchantCompletion\n /** Delegate address derived from the private key (if provided) */\n readonly delegateAddress: string | undefined\n\n constructor(config: HavenClientConfig) {\n this.delegateKey = config.delegateKey\n this.havenApi = new HavenApiTransport(config)\n this.accountReads = new AccountReads({\n transport: this.havenApi,\n getPaymentStatus: (paymentId) => this.getPaymentStatus(paymentId),\n })\n this.delegateSweep = new DelegateSweepApi({\n transport: this.havenApi,\n delegateKey: config.delegateKey,\n chainRpcs: config.chainRpcs ?? {},\n getAgent: () => this.getAgent(),\n buildExplorerUrl: (chainId, hash) => buildExplorerUrl(chainId, hash),\n })\n this.x402Wallet = config.x402Wallet\n this.merchantTransport = new McpMerchantTransport({ merchantTimeout: config.merchantTimeout })\n // #1756 moved the 90 s literal to `types.ts` so the delegate sweep shares\n // this number rather than choosing a fourth one. Same value, same default.\n this.confirmationTimeout = config.confirmationTimeout ?? DEFAULT_CONFIRMATION_TIMEOUT_MS\n this.pollingInterval = config.pollingInterval ?? DEFAULT_POLLING_INTERVAL\n this.chainRpcs = config.chainRpcs ?? {}\n if (this.delegateKey) {\n this.delegateAddress = addressFromKey(this.delegateKey)\n }\n // Constructed LAST: the funding leg pays into `delegateAddress`, which is\n // only derived on the line above.\n this.fundingLeg = new X402FundingLeg({\n delegateKey: this.delegateKey,\n delegateAddress: this.delegateAddress,\n x402Wallet: this.x402Wallet,\n chainRpcs: this.chainRpcs,\n post: (path, body) => this.post(path, body),\n signForData: (signData) => this.signForData(signData),\n assertSignableAuthorizationState: (label, raw) =>\n this.throwIfNonSignableAuthorizationState(label, raw),\n })\n this.merchantCompletion = new MerchantCompletion({\n post: (path, body) => this.post(path, body),\n merchantTransport: this.merchantTransport,\n getPaymentStatus: (paymentId) => this.getPaymentStatus(paymentId),\n getAgent: () => this.getAgent(),\n delegateAddress: this.delegateAddress,\n x402Wallet: this.x402Wallet,\n })\n this.erc7710 = new X402Erc7710({\n delegateKey: this.delegateKey,\n post: (path, body) => this.post(path, body),\n signForData: (signData) => this.signForData(signData),\n getAgent: () => this.getAgent(),\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.havenApi.withRequestContext(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 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 noCompatiblePaymentOptionError(paymentRequired.accepts)\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 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 payerDelegate: (raw as { payer_delegate?: string }).payer_delegate,\n payerAgentId: (raw as { payer_agent_id?: string }).payer_agent_id,\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 mapPaymentResult(raw, buildExplorerUrl)\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 mapPaymentStatusResult(raw)\n }\n\n /**\n * Get the agent identity tied to this API key.\n */\n async getAgent(): Promise<HavenAgent> {\n return this.accountReads.getAgent()\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 return this.accountReads.getAgentSummary()\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 return this.delegateSweep.sweepDelegate()\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.delegateSweep.prepareSweep()\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.delegateSweep.submitSweep(authorization, signature)\n }\n\n /**\n * Get configured and on-chain allowances for the authenticated agent.\n */\n async getAllowances(): Promise<HavenAllowanceSummary> {\n return this.accountReads.getAllowances()\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 payment: PaymentStatusResult | null\n }> {\n return this.accountReads.getPostPurchaseAllowanceSummary(paymentId)\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 merchant catalog (epic #1717).\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: {\n category?: string\n search?: string\n rail?: 'x402' | 'mpp'\n /**\n * Filter on the entry's provenance (epic #1717): `'verified'` returns\n * only self-submitted, domain-verified, probe-verified directory\n * entries; `'operator'` only the operator-curated ones; `'any'` (the\n * default) returns the merged listing.\n */\n verified?: 'any' | 'verified' | 'operator'\n } = {},\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 let entries = raw.entries.map(mapCatalogEntry)\n if (options.verified === 'verified') entries = entries.filter((e) => e.source === 'ingestion')\n if (options.verified === 'operator') entries = entries.filter((e) => e.source === 'operator')\n return entries\n }\n\n /**\n * Submit a merchant's payable (x402/MCP) endpoint to the Verified Payable\n * Directory (epic #1717, #1716). Queue-only: writes a submission row and\n * returns the id + verify_token. The request path makes no outbound\n * request; domain-ownership proof and the read-only quote probe run later\n * on the leader-locked monitor. Ownership proof is ALWAYS required before\n * any listing — this method cannot skip it. `website` is a honeypot field\n * that bots fill; leave it unset.\n */\n async submitCatalogEntry(\n resourceUrl: string,\n options: { website?: string } = {},\n ): Promise<HavenCatalogSubmission> {\n const accepted = await this.post<CatalogSubmissionAccepted>('/catalog/submit', {\n resource_url: resourceUrl,\n ...(options.website ? { website: options.website } : {}),\n })\n return {\n id: accepted.id,\n verifyToken: accepted.verify_token,\n status: accepted.status,\n }\n }\n\n /**\n * Fetch one submission's coarse status by id (epic #1717, #1716). Public\n * and read-only. While the submission can still prove ownership the\n * response carries the exact well-known / DNS-TXT `instructions`; the\n * verify token is never returned here.\n */\n async getCatalogSubmissionStatus(\n id: string,\n ): Promise<{\n id: string\n status: 'submitted' | 'ownership_verified' | 'verified_payable' | 'failed' | 'delisted'\n instructions?: {\n expires_at: string\n well_known: { url: string; content: string; instruction: string }\n dns_txt: { name: string; value: string; instruction: string }\n } | null\n }> {\n return this.get(`/catalog/submit/${encodeURIComponent(id)}`)\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 return this.accountReads.listReceipts(options)\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 return this.accountReads.getReceipt(paymentId)\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 noCompatiblePaymentOptionError(paymentRequired.accepts)\n }\n\n const idempotencyKey = options.idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option)\n const cached = this.fundingLeg.cachedReceipt(idempotencyKey)\n if (cached) return cached\n\n const inFlight = this.inFlightX402.get(idempotencyKey)\n if (inFlight) return inFlight\n\n const promise = this.fundingLeg.authorize(paymentRequired, option, idempotencyKey)\n this.inFlightX402.set(idempotencyKey, promise)\n\n try {\n return await promise\n } catch (err) {\n 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 = withX402Wallet(init, x402PayerAddress(this.delegateAddress, this.x402Wallet))\n const request = snapshotX402Request(url, initialInit)\n const response = await this.merchantTransport.fetch(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.merchantTransport.detect(url, paymentRequired, response)\n return 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.merchantCompletion.resolveWalletForMerchantCall()\n const sessionId = await this.merchantTransport.initialize(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 = withX402Wallet(init, wallet)\n requestInit = this.merchantTransport.withSessionHeaders(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.merchantCompletion.retryRequest(\n quote.request.url,\n requestInitFromSnapshot(quote.request),\n quote.paymentRequired,\n receipt,\n )\n } catch (err) {\n 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 /**\n * Pay a merchant through **erc7710 direct settlement** (#1454, epic #1450).\n *\n * **Nothing has settled when this returns** — that is why it does not return\n * an `X402Receipt`; the caller still has to retry the merchant with the\n * header. **MCP callers must pass `options.resourceUrl`**, because an in-band\n * MCP 402 challenge frequently carries no `resource` object at all.\n *\n * Both caveats, and why this scheme has no funding leg, are explained where\n * the lifecycle lives: `x402-erc7710.ts` (#1619).\n */\n async settleX402Erc7710(\n paymentRequired: X402PaymentRequired,\n options: { resourceUrl?: string } = {},\n ): Promise<X402Erc7710Settlement> {\n return this.erc7710.settle(paymentRequired, options)\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.\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 — passing it\n * skips a duplicate fetch (#1456). An optimisation, not a trust\n * boundary: the backend independently refuses a non-delegation account\n * at the rail seam (the #1986 retired-rail 410, #2245).\n */\n delegationRail?: boolean\n /**\n * #1547: the merchant MCP-tool call this authorization was quoted\n * against, persisted so the settle leg can rehydrate it by payment_id\n * (#1307).\n */\n mcpCallContext?: X402McpCallContext\n /**\n * #2041: replay key, as `createX402Intent` already takes one. Without it\n * a retried authorize mints a second signable settlement child instead\n * of replaying the first.\n */\n idempotencyKey?: string\n } = {},\n ): Promise<{\n paymentId: string\n signData: SignData\n settlement: Omit<X402Erc7710Settlement, 'paymentHeader'>\n }> {\n return this.erc7710.prepare(paymentRequired, options)\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. Whoever produced the signature (an in-process delegate\n * key, or the local edge signer over the hosted boundary) is irrelevant.\n */\n async submitX402Erc7710(paymentId: string, signature: string): Promise<string> {\n return this.erc7710.submit(paymentId, signature)\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 noCompatiblePaymentOptionError(input.paymentRequired.accepts)\n }\n\n const idempotencyKey = input.idempotencyKey ?? buildX402IdempotencyKey(input.paymentRequired, option)\n const cached = this.fundingLeg.cachedReceipt(idempotencyKey)\n if (cached) return cached\n\n const status = await this.getPaymentStatus(input.paymentId)\n assertCanResumeX402(status, input.paymentRequired, option)\n\n // #1521: the same fundability question as the authorize path, with the\n // opposite default. Here the caller NAMED this payment, so an\n // unverifiable balance is not grounds to refuse the thing they asked for\n // — only a balance verified ABSENT is, because then the authorization\n // this would mint is known to be unfundable.\n const canFund = await this.fundingLeg.delegateCanFund(\n status.chainId ?? chainIdFromNetwork(option.network),\n option.asset,\n x402AuthorizationAmount(option),\n )\n if (canFund === false) {\n throw new X402AlreadySettledError(\n `x402 payment ${status.paymentId} has already settled — the delegate no longer holds the ` +\n 'funds to authorize it again, so there is nothing left to resume.',\n this.fundingLeg.receiptFromStatus(input.paymentRequired, option, undefined, status),\n 'settled',\n )\n }\n\n const paymentHeader = await this.fundingLeg.createPaymentHeader(input.paymentRequired, option)\n const receipt = this.fundingLeg.receiptFromStatus(input.paymentRequired, option, paymentHeader, status)\n this.fundingLeg.cacheReceipt(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 = withX402Wallet(\n inputInit ?? (input.request ? requestInitFromSnapshot(input.request) : undefined),\n x402PayerAddress(this.delegateAddress, this.x402Wallet),\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.merchantTransport.fetch(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.merchantCompletion.retryRequest(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 (this.merchantTransport.isMcpUrl(url)) {\n mcpSessionId = await this.merchantTransport.initialize(url, init)\n }\n\n let requestInit = withX402Wallet(init, x402PayerAddress(this.delegateAddress, this.x402Wallet))\n if (mcpSessionId) requestInit = this.merchantTransport.withSessionHeaders(requestInit, mcpSessionId)\n\n // 1. Make the original request\n const response = await this.merchantTransport.fetch(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.merchantTransport.surfaceResult(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 this.merchantTransport.hasBazaarExtension(response))) {\n mcpSessionId = await this.merchantTransport.initialize(url, init)\n if (mcpSessionId) requestInit = this.merchantTransport.withSessionHeaders(requestInit, mcpSessionId)\n }\n\n // 4. Pay through Haven\n const request = 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 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.merchantCompletion.retryRequest(url, requestInit, paymentRequired, receipt)\n return mcpSessionId ? this.merchantTransport.surfaceResult(retryResponse) : retryResponse\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 * merchant 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 the x402 payment\n * header under the names that scheme requires (#2341), 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 merchant 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 `X402FundingLeg.authorize`); the hosted\n * split flow regressed when the 5→3 collapse removed the incidental\n * inter-call latency that used to mask it.\n *\n * **NOT a no-op when the funding tx hash is absent** (#1508). The WAIT is\n * skipped without a hash or a chain RPC, but the `GET /payments/:id` read\n * below runs UNCONDITIONALLY — it is how the fallback hash and the chainId\n * are obtained. That distinction is load-bearing: this method must never be\n * called on a scheme with no funding leg, because the read itself fails once\n * the intent reaches a status the backend maps to a non-2xx (`submitted` is a\n * 409), turning a settled payment into a reported error. The previous wording\n * here said \"No-op when the funding tx hash ... is unavailable\", and the\n * hosted erc7710 path was written against that promise — see\n * `deliverMerchantPayment`'s `noFundingLeg` option.\n */\n async ensureFundingConfirmed(paymentId: string, fundingTxHash?: string): Promise<void> {\n const status = await this.getPaymentStatus(paymentId)\n await this.fundingLeg.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 /**\n * #1508: the payment settles with NO funding leg (erc7710). This method was\n * written for EIP-3009 and encodes that lifecycle in two places — the\n * readiness gate wants `confirmed`, and a Haven funding tx hash is\n * mandatory. Neither is reachable on a scheme where the MERCHANT redeems\n * the delegation chain: the intent sits at `submitted` by design, and there\n * is no Haven-submitted transaction at all. Set this to take the\n * no-funding-leg path through both.\n */\n noFundingLeg?: boolean\n }): Promise<{ status: number; ok: boolean; body: unknown; settlementTxHash?: string }> {\n const evidenceContext = await this.merchantCompletion.resolveCompletionContext({\n paymentId: input.paymentId,\n url: input.url,\n noFundingLeg: input.noFundingLeg === true,\n })\n // Non-null on the funding-leg path (the gate below throws without it) and\n // always null on erc7710. Bound once so the evidence calls — which require\n // a string — are provably unreachable without one.\n const fundingTxHash = evidenceContext.txHash\n const shouldHandshakeMcp =\n this.merchantTransport.isMcpUrl(input.url) ||\n input.mcpTransport?.handshakeRequired === true\n const x402Wallet = shouldHandshakeMcp ? await this.merchantCompletion.resolveWalletForMerchantCall() : x402PayerAddress(this.delegateAddress, this.x402Wallet)\n let mcpSessionId: string | undefined\n if (shouldHandshakeMcp) {\n mcpSessionId = await this.merchantTransport.initialize(input.url, input.init, x402Wallet)\n }\n\n let requestInit: RequestInit = withX402Wallet(input.init, x402Wallet) ?? {}\n if (mcpSessionId) requestInit = this.merchantTransport.withSessionHeaders(requestInit, mcpSessionId)\n\n const response = await this.merchantTransport.deliverPayment(input.url, requestInit, input.paymentHeader)\n const surfaced = mcpSessionId ? await this.merchantTransport.surfaceResult(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 // #1508: both evidence surfaces below require a txHash — the backend\n // answers `400 txHash is required` without one, and these calls swallow\n // failures, so an erc7710 row would vanish silently rather than fail\n // loudly. Skipping deliberately (owner decision 2026-08-17) instead of\n // writing a row that cannot be written: their consumer is funding-leg\n // reconciliation (#713 — stranded delegate balances), and this rail has\n // no funding leg to strand. The merchant receipt below still runs, so the\n // paid call remains recorded.\n if (!input.noFundingLeg && fundingTxHash) {\n await this.merchantCompletion.recordRetryRejected({\n rail: 'x402',\n paymentId: evidenceContext.paymentId,\n txHash: fundingTxHash,\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 }\n } else {\n // #2092: the evidence anchor is scheme-dependent, and skipping it on\n // erc7710 (#1508) left a whole settlement scheme with no\n // `machine_payment_evidence` row — and therefore invisible to the Fortnox\n // reporting feed, `GET /receipts`, transaction history, and the\n // merchant-receipt capture on the very next line (which 404s without an\n // evidence row). The #1508 reasoning — \"evidence's consumer is\n // funding-leg reconciliation, and this rail has no funding leg\" — was\n // true about #713 and incomplete about everything else evidence feeds.\n //\n // On the funding-leg path the anchor is Haven's funding transaction; on\n // erc7710 it is the MERCHANT's settlement transaction, which the merchant\n // just handed us in `PAYMENT-RESPONSE`. Both are reported through the\n // same call, so the backend and every consumer keep one code path. The\n // backend verifies the erc7710 hash on-chain before it confirms anything\n // (#2092), so reporting it is a claim, not an authority.\n const evidenceTxHash = input.noFundingLeg\n ? (settlement.settlementTxHash ?? undefined)\n : (fundingTxHash ?? undefined)\n // #2117: when the merchant returned no settlement transaction there is\n // simply nothing to report, and inventing an anchor client-side is what\n // the backend's on-chain verification exists to prevent. That gap is\n // closed SERVER-side instead, by the passive settlement sweep\n // (`modules/x402/settlement-sweeper.ts`), which finds the settlement by\n // this payment's own intent-unique delegation child. Do not \"fix\" this\n // branch by fabricating a hash.\n if (evidenceTxHash) {\n await this.merchantCompletion.reportEvidence({\n paymentId: evidenceContext.paymentId,\n rail: 'x402',\n txHash: evidenceTxHash,\n resourceUrl: evidenceContext.resourceUrl,\n merchantStatus: surfaced.status,\n paymentProofHeaderName: x402PaymentHeaderNamesSent(input.paymentHeader),\n paymentProofHeader: input.paymentHeader,\n protocolReceiptHeaderName: protocolReceiptHeader ? 'PAYMENT-RESPONSE' : undefined,\n protocolReceiptHeader,\n })\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.merchantCompletion.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 * #2292: report the outcome of a merchant retry the AGENT performed.\n *\n * The hosted `haven_complete_mcp_tool` / `completeX402MerchantCall` path is\n * for merchants Haven calls itself. On the plain-HTTP x402 path Haven never\n * talks to the merchant, so the outcome of that retry had no way back —\n * see `MerchantCompletion.reportMerchantOutcome` for what is verified about\n * a caller-asserted report and what deliberately is not.\n */\n async reportX402MerchantOutcome(input: {\n paymentId: string\n outcome: X402MerchantOutcome\n merchantStatus: number\n merchantBody?: string\n }): Promise<X402MerchantOutcomeReport> {\n return await this.merchantCompletion.reportMerchantOutcome(input)\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 /**\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 throwIfNonSignableAuthorizationState(\n label: string,\n raw: RawX402AuthorizeResponse,\n ): void {\n if (raw.status === 'pending_signature') return\n throwPaymentStateError(label, raw)\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 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 toolX402PaymentRequired({ url, payTo, amount, asset, network, description }),\n { idempotencyKey },\n )\n return x402ToolReceipt(receipt)\n } catch (err) {\n return 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: toolX402PaymentRequired({ url, payTo, amount, asset, network, description }),\n idempotencyKey,\n })\n return x402ToolReceipt(receipt)\n } catch (err) {\n return 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 // ── HTTP Helpers ─────────────────────────────────────────────────\n\n private async post<T>(path: string, body: Record<string, unknown>): Promise<T> {\n return this.havenApi.post<T>(path, body)\n }\n\n private async get<T>(path: string): Promise<T> {\n return this.havenApi.get<T>(path)\n }\n\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\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 / declined 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 payment locally and returns the merchant response. Settlement is either direct account-to-merchant with no funding leg, or a bridge that first redeems the agent\\'s budget delegation to fund the delegate wallet for an EIP-3009 authorization. A payment outside the on-chain budget is declined before any money moves; nothing is queued for a human to approve later.',\n nextActionGuidance:\n 'Preserve the returned resume_state — it identifies this payment if you need to ask about it later. ' +\n 'This tool performs the merchant retry itself, so do not wait on a signal while the call is in flight. ' +\n 'If the process crashes after this call and a later haven_get_payment_status reports nextAction=retry_original_x402_request, Haven\\'s funding leg confirmed but no merchant response was ever recorded — call the resume tool with the preserved resume_state or payment_id instead of paying again. ' +\n 'If the response carries phase=insufficient_funds and nextAction=fund_safe_or_raise_allowance, the payment cannot be retried until the account is funded or the agent budget raised — 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 payment locally, then retries the original request with the signed payment header (sent under PAYMENT-SIGNATURE, plus the legacy X-PAYMENT on the EIP-3009 path only) and returns the merchant response. Settlement is either direct account-to-merchant with no funding leg, or a bridge that first redeems the agent\\'s budget delegation to fund the delegate wallet for an EIP-3009 authorization. A payment outside the on-chain budget is declined before any money moves; nothing is queued for a human to approve later. If the resource returns a non-402 status, returns it unchanged without contacting Haven.',\n nextActionGuidance:\n 'Preserve the returned resume_state or paymentId — either identifies this payment if you need to ask about it later. ' +\n 'This tool performs the merchant retry itself, so do not wait on a signal while the call is in flight. ' +\n 'If the process crashes after this call and a later haven_get_payment_status reports nextAction=retry_original_x402_request, Haven\\'s funding leg confirmed but no merchant response was ever recorded — call the resume tool with the preserved resume_state or payment_id instead of paying again. ' +\n 'If the response carries phase=insufficient_funds and nextAction=fund_safe_or_raise_allowance, the payment cannot be retried until the account is funded or the agent budget raised — stop and tell the user the shortfall reported on the response.',\n },\n resumeX402: {\n summary:\n 'Resume an x402 payment whose Haven-side authorization already succeeded but whose merchant retry did not complete.',\n behavior:\n 'Accepts either resume_state or payment_id, validates the original x402 details against the authorized Haven funding, and retries the merchant request with the signed payment header (sent under PAYMENT-SIGNATURE, plus the legacy X-PAYMENT on the EIP-3009 path only). No new Haven payment is created.',\n nextActionGuidance:\n 'Only call this after haven_get_payment_status reports nextAction=retry_original_x402_request — that means Haven\\'s funding leg confirmed but no merchant response was ever recorded, most often because the process crashed between funding and the merchant retry. ' +\n 'Any other nextAction reports a conflict instead of retrying, so do not call this speculatively. ' +\n 'Do not start a new merchant session and do not pay again — that would pay twice for one resource.',\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 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 x402 context the agent originally received when the payment was authorized, 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, spend_authority_readiness, and per-token remaining allowance (atomic + human-readable). The recommended first call in a new session to confirm who you are and whether Haven will let you spend 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 agent\\'s active on-chain budget delegation. spend_authority_readiness (readiness is a deprecated alias, same value) 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. It covers hosted identity + on-chain spend authority ONLY — the hosted server cannot see the LOCAL signer, so \"ready\" does not mean the signer can start; verify the signer with a signer tool call or connect --doctor. An over-budget payment is declined before any money moves: there is no approval queue, 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: the active budget delegation (remaining = the period budget, which re-arms natively at the period boundary). An over-budget payment is declined before any money moves; nothing queues. 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 against the agent\\'s on-chain budget delegation, and retries the request, returning the JSON-RPC result (the actual merchant output) on success. ' +\n 'Amounts within the remaining on-chain budget execute automatically; anything outside it is declined before any money moves — follow the response\\'s nextAction when present.',\n nextActionGuidance:\n 'On a decline, report the reason to the user and ask them to raise the budget in Haven — there is no approval queue to wait on. ' +\n 'This tool retries the merchant itself while it runs, so do not wait on a signal mid-call. ' +\n 'If the process crashes after payment, a later haven_get_payment_status call may report nextAction=retry_original_x402_request — resume via haven_resume_x402_payment instead of paying again.',\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 'Use verified=verified to show only self-submitted directory entries that passed domain-ownership proof and a live quote probe — never treat those badges as proof of merchant honesty, quality, or reliability. ' +\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, suggested_tool, and the provenance badges source/domain_verified/verified_payable. ' +\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.',\n },\n submitCatalogEntry: {\n summary:\n 'Submit a merchant\\'s payable (x402/MCP) endpoint to Haven\\'s Verified Payable Directory for verification and listing.',\n selectionGuidance:\n 'Use this when a merchant or seller asks to be listed in the directory, or when you have discovered a payable endpoint and want it registered. ' +\n 'The submission is queue-only: it books a spot and returns a verify_token. The seller must then prove control of the domain (a well-known line or DNS TXT record); only after that plus a live quote probe does the entry become listed. ' +\n 'Do NOT use to pay — check the returned status with getCatalogSubmissionStatus instead.',\n behavior:\n 'Sends the https resource_url to Haven\\'s public submission endpoint. The request path makes no outbound request to the merchant. ' +\n 'Returns id + verify_token + status; the verify_token is shown exactly once. Ownership proof is always required later and cannot be skipped from the agent side. ' +\n 'The website field is a honeypot for bots — leave it unset.',\n nextActionGuidance:\n 'Give the verify_token and the well-known instructions (from getCatalogSubmissionStatus) to the merchant so they can publish the proof line, then poll the submission status until it reaches verified_payable or failed.',\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 'Each transfer carries confirmation: \"confirmed\" (a receipt was seen — the funds are in the Safe) or \"unconfirmed\" ' +\n '(broadcast but not confirmed within 90 seconds — still in the mempool, may still land). The top-level unconfirmed flag is true when any transfer is unconfirmed.',\n nextActionGuidance:\n 'If transfers is non-empty, confirm the amounts with the user. ' +\n 'Report a transfer as recovered ONLY when its confirmation is \"confirmed\". ' +\n 'For an \"unconfirmed\" transfer, tell the user it was submitted but not yet confirmed, give them its txHash and explorerUrl to check, and do not re-run the sweep immediately — a re-run after it lands will simply find nothing stranded.',\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 by redeeming the agent\\'s on-chain budget delegation, account to recipient with no funding leg. ' +\n 'Budget, recipient and expiry are enforced on-chain while the transfer is prepared, so a request outside them is declined before any money moves and before the agent is asked to sign — it is never queued for a human to approve later. ' +\n 'The agent\\'s signing key signs the account\\'s typed data; Haven never receives the key.',\n nextActionGuidance:\n 'On a decline, report the reason to the user and ask them to grant or raise the budget in Haven — there is nothing to poll and no approval will arrive. ' +\n 'After a successful send, 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 the same payment.',\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 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 account within its on-chain budget. ' +\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 and relays the signed transaction that redeems the agent budget delegation; 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. 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; funding, when the scheme needs it, is redeemed from the agent budget delegation and is bounded by it. ' +\n 'Haven relays signed transactions only; the agent key authorizes payment and on-chain limits enforce spend. ' +\n 'A payment outside the on-chain budget is declined before any money moves — report the decline and ask the user to raise the budget in Haven; do not loop retries and do not wait for an approval, because none is queued. Preserve the original merchant/MCP session and x402 details. ' +\n 'On a manual HTTP retry always set PAYMENT-SIGNATURE (x402 v2) to the returned payment_header; a strict v2 merchant reads only that name. Also set X-PAYMENT (v1) on the EIP-3009 funding path for legacy merchants, but NEVER on erc7710 — that header carries a delegation chain and duplicating it is refused with HTTP 431.'\n\n// #2145: the backend now emits nextAction=retry_original_x402_request from\n// GET /payments/:id (agent-payment-status.ts) when the funding leg confirmed\n// but no merchant response was ever recorded — the crash-recovery case, after\n// a 15-minute grace window. This tool's gate requires that exact nextAction,\n// so it is reachable again on purpose; the description tells an agent to gate\n// on the structured field rather than call this speculatively.\nconst RESUME_X402_DESCRIPTION =\n sharedDescriptions.resumeX402.summary + ' ' +\n 'Only call this after get_payment_status reports nextAction=retry_original_x402_request — that means Haven\\'s funding leg confirmed but no merchant response was ever recorded (typically a crash between funding and the merchant retry). ' +\n 'Any other nextAction reports a conflict instead of retrying — do not call this speculatively, and do not pay again.'\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; a payment above the remaining budget is declined —\nnothing is paid past the rules the user set.\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.\nThat namespacing is Claude-family; other runtimes name the servers by their\nown config keys (Codex: \\`haven\\`, \\`haven_signer\\`). Tool results carry the\nexact next step (\\`next_action\\`, \\`next_tool\\`, \\`next_arguments\\`, plus the\nruntime-neutral \\`next_tool_server\\` + \\`next_tool_name\\` — the bare tool name\non that logical server, whatever your runtime calls it).\nFollow those fields first; the prose below is fallback and orientation, not\nthe 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 \\`spend_authority_readiness\\` (\\`ready\\` / \\`needs_approval\\` /\n \\`revoked\\`) and live remaining per-token allowance, in one shot. That signal\n covers hosted identity and on-chain spend authority only — it cannot see the\n local signer; the signer is verified by calling any signer tool.\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 declined before any money moves — tell the user; they can raise\nthe budget in the Haven dashboard, or wait for the period reset.\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 has not confirmed — follow the result's guidance fields and check\nstatus later, do 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\\`. Call that last step with\n\\`payment_id\\` and the signer's \\`payment_header\\` ONLY. It does not take\n\\`payment_required\\`: Haven rehydrates the merchant call context\n(\\`merchant_url\\`, \\`tool_name\\`, \\`arguments\\`, \\`mcp_transport\\`) and the\n402 server-side from \\`payment_id\\`, exactly as at settle. Pass that context\nexplicitly only as a version-skew fallback when Haven has no stored context\nfor the id — \\`merchant_url\\` and \\`tool_name\\` both or none together, never\njust one.\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\n\\`to\\`, \\`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 and sign in the local Haven signer. On THIS path Haven does not talk to\nthe merchant: \\`mcp__haven-signer__haven_sign_x402\\` returns both\n\\`signature\\` and \\`payment_header\\`; relay \\`signature\\` with\n\\`mcp__haven__haven_submit\\`, then retry the paywalled URL yourself with\n\\`payment_header\\`. Do not pass that call's \\`x402_binding\\` to\n\\`mcp__haven-signer__haven_x402_sign_header\\` — the one-shot already spent it\nbuilding the header, so the call can only refuse. Then tell Haven what the\nmerchant answered: \\`mcp__haven__haven_report_x402_outcome\\` with the\n\\`payment_id\\`, \\`outcome\\` (\\`\"accepted\"\\` for a 2xx, else \\`\"rejected\"\\`)\nand the \\`merchant_status\\` you got. Because Haven never contacted that\nmerchant, this is the only way it can learn the purchase failed — without it a\nfailed purchase reads as complete for fifteen minutes. (The SDK's own\n\\`haven_pay_x402\\` tool does perform the merchant retry itself; that tool is\nnot part of the hosted MCP surface.) If the process\ncrashes after payment, a later \\`mcp__haven__haven_get_payment_status\\` call\nmay report \\`nextAction: 'retry_original_x402_request'\\` — only then call\n\\`mcp__haven__haven_resume_x402_payment\\` with the preserved resume state or\npayment id, instead of paying again.\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 merchant's\nown quoted price for that call — a ceiling the merchant settles at or below —\nso present it as the most the user will pay. It is a price, not an approval:\nthe payment goes through only if it also fits the cap you set and the on-chain\nbudget the user signed, which is enforced on-chain rather than by Haven.\n\n**Status:** \\`mcp__haven__haven_get_payment_status\\` with a \\`payment_id\\` to\ncheck on in-flight payments. Do not poll in a tight loop.\n\n## Declines and stop signals\n\n- A payment outside the agent's rules — above the remaining budget, wrong\n recipient, or expired budget — is declined before any money moves. Nothing\n is queued; tell the user, who can raise the budget in Haven.\n- \\`safe_to_continue: false\\` on a guidance block is a stop 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- \\`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"]}
|