@haven_ai/sdk 0.0.0-dev.202609241737.2d2b91b → 0.0.0-dev.202609241802.ea320de

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/connector-channel.ts","../src/types.ts","../src/userop-binding.ts","../src/base64.ts","../src/sweep.ts","../src/x402.ts","../src/next-step.ts","../src/node-version.ts"],"names":["stableStringify","sameAddress"],"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,EAAA,IAAI,CAAC,kBAAA,CAAmB,OAAO,CAAA,EAAG;AAChC,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,kCAAA,EAAqC,IAAA,CAAK,SAAA,CAAU,GAAG,CAAC,CAAA,qPAAA;AAAA,KAI1D;AAAA,EACF;AACA,EAAA,OAAO,OAAA;AACT;AAGO,SAAS,aAAA,CAAc,UAAkB,uBAAA,EAAiC;AAC/E,EAAA,OAAO,CAAA,EAAG,sBAAsB,CAAA,CAAA,EAAI,OAAO,CAAA,CAAA;AAC7C;AAcO,SAAS,qBAAA,CACd,MACA,OAAA,EACQ;AACR,EAAA,MAAM,OAAA,GAAU,SAAS,OAAA,IAAW,uBAAA;AACpC,EAAA,MAAM,QAAQ,OAAA,EAAS,QAAA,GAAW,CAAA,EAAG,OAAA,CAAQ,QAAQ,CAAA,CAAA,CAAA,GAAM,EAAA;AAC3D,E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AA,EACpB;AACT,EAAA,OAAO,mBAAA,CAAoB,WAAA,EAAa,kBAAkB,CAAA,IAAK,CAAA;AACjE;AAyBO,SAAS,8BACd,OAAA,EACQ;AACR,EAAA,MAAM,WAAA,GAAc,OAAA,CAAQ,WAAA,IAAe,OAAA,CAAQ,QAAA,CAAS,IAAA;AAC5D,EAAA,MAAM,OAAA,GAAU,QAAQ,kBAAA,IAAsB,0BAAA;AAC9C,EAAA,MAAM,KAAA,GAAQ;AAAA,IACZ,GAAG,OAAA,CAAQ,OAAO,CAAA,oBAAA,EAAuB,OAAO,yBAAyB,WAAW,CAAA,CAAA,CAAA;AAAA,IACpF,EAAA;AAAA,IACA,+BAAA;AAAA,IACA,iBAAiB,KAAA,CAAM,OAAO,CAAC,CAAA,YAAA,EAAe,KAAA,CAAM,OAAO,CAAC,CAAA,WAAA,CAAA;AAAA,IAC5D,iBAAiB,KAAA,CAAM,OAAO,CAAC,CAAA,YAAA,EAAe,KAAA,CAAM,OAAO,CAAC,CAAA,WAAA,CAAA;AAAA,IAC5D,CAAA,qBAAA,EAAwB,KAAA,CAAM,OAAO,CAAC,CAAA,wBAAA,CAAA;AAAA,IACtC,CAAA,mBAAA,EAAsB,KAAA,CAAM,OAAO,CAAC,CAAA,wBAAA,CAAA;AAAA,IACpC,EAAA;AAAA,IACA;AAAA,GAGF;AACA,EAAA,IAAI,QAAQ,SAAA,EAAW,KAAA,CAAM,IAAA,CAAK,EAAA,EAAI,QAAQ,SAAS,CAAA;AACvD,EAAA,OAAO,KAAA,CAAM,KAAK,IAAI,CAAA;AACxB;AAEA,SAAS,MAAM,OAAA,EAAyB;AACtC,EAAA,OAAO,MAAA,CAAO,gBAAA,CAAiB,OAAO,CAAA,CAAE,CAAC,CAAC,CAAA;AAC5C","file":"chunk-FR5R26V3.js","sourcesContent":["/**\n * The npm dist-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 funding tx (account → delegate EOA) 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). The backend spec makes it\n * required; the legacy AllowanceModule reading — absent = raw ECDSA over\n * `hash` — is retired (#2850), and the SDK client refuses an absent scheme.\n * The session rail's '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 /**\n * The PAYER account (the user's smart account). Not to be confused with\n * `account`, which on the funding shapes holds the DELEGATE account\n * address.\n */\n payer_account?: 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 payload (`signData`, account → 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 payload + 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 payload to sign with the delegate key (account → 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 /** #3097: `resourceUrl` (the merchant's declaration) is not `request.url` (what was quoted). */\n resourceUrlDiffersFromRequest: boolean\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 /** The agent's Haven account (smart account) address. */\n accountAddress: 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 (retired — no account can enter it since\n * #1984, and it cannot spend since #1986) 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 /**\n * #3128: human-readable `onchain.remaining`, e.g. \"4.96 USDC\" — the SAME\n * string {@link HavenAgentAllowanceSummary.remainingDisplay} carries for\n * this allowance, computed by one function from `onchain.remaining` and\n * the token's decimals, so the two reads cannot disagree. Additive; the\n * wire carries no display form (it is derived client-side).\n */\n remainingDisplay: string\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 accountAddress: 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 * #3126 — the answer to \"is there money actually HELD behind my budget?\",\n * asked as a sufficiency signal rather than a balance.\n *\n * Every other agent-readable figure in this package describes SPEND\n * AUTHORITY — what the agent is PERMITTED to move this period\n * ({@link HavenAllowanceSummary}). This shape answers the different question\n * of whether the account HOLDS funds behind that authority, and deliberately\n * answers it as `covered: boolean | null`, never as a figure: a constrained\n * actor has no business reading the treasury total, and the boolean answers\n * the only decision an agent has (attempt the payment, or tell the user\n * funds are missing).\n *\n * The naming keeps the two concepts apart (the #3126 binding constraint):\n * `budgetRemainingAtomic` is AUTHORITY — the same value\n * {@link HavenAllowanceSummary} reports per token as `onchain.remaining` —\n * while `covered` speaks only of HELD funds. Nothing here is named like the\n * authority fields (`remaining`, `available`); nothing here returns a\n * balance.\n *\n * `covered: null` means the chain read FAILED — unverifiable, never a\n * guess. The same honesty rule `x402-funding-leg.ts`'s `delegateCanFund`\n * established (#1521): treat null as \"we do not know\", not as \"funded\" or\n * as absence; `coverageError` carries why.\n */\nexport interface HavenBalanceCoverage {\n /**\n * true: the chain reports the agent's account holds at least\n * `checkedAmountAtomic` of the token. false: the chain read succeeded and\n * reports LESS — tell the user funds are missing rather than retrying.\n * null: the chain read failed — unverifiable, never treated as absence.\n */\n covered: boolean | null\n /** Present only when `covered` is null: why the chain read could not answer. */\n coverageError?: string\n chainId: number\n tokenAddress: string\n tokenSymbol: string\n /** The amount the coverage question was asked about, in atomic units. */\n checkedAmountAtomic: string\n /**\n * Context, AUTHORITY not holdings: the agent's remaining spend authority\n * for the requested token, in atomic units — the same derivation\n * {@link HavenAllowanceSummary} reports (`onchain.remaining`; the #1090\n * derivation, the #1145 enforcer read). Zero when no active budget row\n * names the token. Compare it with `covered`, never instead of it.\n */\n budgetRemainingAtomic: string\n /**\n * Provenance of `budgetRemainingAtomic` (#1319, same semantics as\n * {@link HavenAllowance.onchain.remainingIsFromChain}): true when the\n * budget figure came from a live enforcer read, false when it fell back\n * to the configured budget. Absent when no budget row existed for the\n * token (nothing was read).\n */\n budgetRemainingIsFromChain?: boolean\n}\n\n/** @internal wire shape of {@link HavenBalanceCoverage}. */\nexport interface RawHavenBalanceCoverage {\n covered: boolean | null\n coverage_error?: string\n chain_id: number\n token_address: string\n token_symbol: string\n checked_amount_atomic: string\n budget_remaining_atomic: string\n budget_remaining_is_from_chain?: boolean\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 active budget delegation on the delegation rail — #1135; the retired\n * AllowanceModule rail used an on-chain allowance instead):\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 retired\n * AllowanceModule rail the payment was 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/**\n * Compact, agent-facing per-token spend authority for the bootstrap summary.\n *\n * #3128: a deliberately DIFFERENT view of the same allowance as\n * {@link HavenAllowance} — flat, no `onchain` block, no spent/nonce/reset-time\n * detail — but never a disjoint one: every field here is present on or\n * derived from the {@link HavenAllowance} with the same `id`, and\n * `remainingAtomic` / `remainingDisplay` equal that allowance's\n * `onchain.remaining` / `remainingDisplay` byte for byte (pinned by test). A\n * client that wants the id AND a display amount can therefore use either\n * read alone.\n */\nexport interface HavenAgentAllowanceSummary {\n /** #3128: the {@link HavenAllowance.id} this row summarises. */\n id: string\n tokenSymbol: string\n /** #3128: the {@link HavenAllowance.tokenAddress}. */\n tokenAddress: 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\n/**\n * #2960 — one party vocabulary for \"who paid\" a Haven payment, additive\n * alongside every existing lone `payer*`/`*Address` field (same discipline\n * as the #2907 `safe`/`account` dual-emit, except these four are DISTINCT\n * addresses, not same-value twins of one old field).\n */\nexport interface PaymentParties {\n treasuryAccount: string | null\n delegate: string | null\n delegateAccount: string | null\n merchant: string | null\n}\n\n/** @internal wire shape of {@link PaymentParties}. */\nexport interface RawPaymentParties {\n treasury_account: string | null\n delegate: string | null\n delegate_account: string | null\n merchant: string | null\n}\n\n/**\n * #3132 (owner decision 3 on #3130): what population a list row came from and\n * what narrowed it, as two values. Receipts are `{ source: 'agent', filter:\n * null }` — this agent's evidence rows only, no query-time narrowing. The\n * wallet feed (`GET /transactions`, the CLI's `activity list`) is\n * `source: 'wallet'` with `filter: 'agent'` when `agentId` narrows it, and it\n * is a DIFFERENT population (explorer window plus synthesized intents; sweeps\n * and funding legs included), never this view. A receipt read is not a\n * transaction-history read.\n */\nexport interface HavenListScope {\n source: 'wallet' | 'agent'\n filter: 'agent' | 'account' | 'account+agent' | null\n}\n\nexport interface HavenPaymentReceipt {\n id: string\n /** #3132: present when the backend states it (absent on an older backend). */\n scope?: HavenListScope\n paymentId: string\n paymentIntentId?: string | null\n approvalRequestId?: string | null\n /**\n * #3134: the payment protocol this receipt settled on — one of the\n * evidence-eligible rails (`x402`, `mpp_demo`, `mpp_crypto`, `spt`) — under the\n * name the transactions feed uses for the same concept. Distinct from\n * `scope.source`, which names the LIST population (#3132) — the transaction\n * row carries the same two. Same name, narrower domain: never `'direct'`\n * here — the feed's SQL default for an intent that names no protocol has no\n * receipt analogue, because no protocol means no evidence row.\n */\n source: string\n /** @deprecated (#3134) twin of {@link source}; removed once all three release clocks have moved — see `mapPaymentReceipt`. */\n rail: string\n /**\n * #3134: the evidence row's recorded proof status, under the transactions\n * feed's name. Same name, different nullability: `string` here because a\n * receipt IS the evidence row, `string | null` on the feed, where a row may\n * LEFT JOIN to none (#3132) — do not share a non-null-asserting helper.\n */\n paymentProofStatus: string\n /** @deprecated (#3134) twin of {@link paymentProofStatus}; removed once all three release clocks have moved — see `mapPaymentReceipt`. */\n proofStatus: string\n /**\n * @deprecated (#2998) meaning depends on the settlement scheme — the\n * account → delegate funding transaction on eip3009, the (only) settlement\n * transaction on erc7710. Prefer {@link fundingTxHash} / {@link settlementTxHash}, which\n * name which is which.\n */\n txHash: string\n /** The account → delegate funding transaction, relayed by Haven (#2998); null on erc7710 (no funding leg) and on retired mpp-rail rows. */\n fundingTxHash: string | null\n /**\n * The delegate → merchant settlement transaction (#2998). Trust level differs\n * by scheme: on erc7710 it is `txHash` itself and Haven VERIFIED it on-chain\n * before the receipt existed; on eip3009 it is the merchant's claim as relayed\n * (PAYMENT-RESPONSE), NOT verified on-chain by Haven — cite it as such.\n */\n settlementTxHash: string | null\n chainId: number\n /** #3134: the paid resource, under the transactions feed's protocol-prefixed name (`string | null` there; a receipt always has one). */\n x402ResourceUrl: string\n /** @deprecated (#3134) twin of {@link x402ResourceUrl}; removed once all three release clocks have moved — see `mapPaymentReceipt`. */\n resourceUrl: string\n /** #3134: the merchant paid, under the transactions feed's protocol-prefixed name. */\n x402MerchantAddress: string | null\n /** @deprecated (#3134) twin of {@link x402MerchantAddress}; removed once all three release clocks have moved — see `mapPaymentReceipt`. */\n merchantAddress: string | null\n payerAddress: string\n /** #2960: additive alongside `payerAddress` above (`parties.treasury_account` only). */\n parties?: PaymentParties\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 /**\n * #3125 — the merchant's `PAYMENT-RESPONSE` object relayed VERBATIM:\n * opaque, unvalidated, unverified, MERCHANT-CONTROLLED third-party data.\n * Haven neither authors nor verifies anything inside it, including\n * `protocolReceiptPayload.payer` —\n * that `payer` is the merchant's claim, NOT Haven's record, and is not\n * {@link payerAddress} (Haven's own, authoritative; field observation\n * 2026-09-18: the two held different addresses on every row read). For who\n * paid, read `parties` ({@link PaymentParties}) — `treasuryAccount`,\n * `delegate`, `delegateAccount`, `merchant` are Haven-derived and\n * authoritative; anything inside this object is not.\n *\n * Deliberately NOT namespaced or key-prefixed on the wire (#3125): the\n * relay must stay the merchant's object verbatim (its `transaction` key\n * feeds `settlementTxHash`), and prefixing the envelope could not prefix\n * the merchant-controlled keys inside it — the `payer` collision lives\n * there, so provenance is made legible at the read surfaces instead (this\n * comment and the tool descriptions).\n */\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 agent's Haven account. */\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 agent's Haven account) */\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 account 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 * #2914: the account-vocabulary spelling, and the only one — the\n * pre-#2907 `fund_safe_or_raise_allowance` wire value (and the\n * `AgentPaymentNextActionAccountAlias` seam #2908 added to bridge it) are\n * retired along with the rest of the #2908 compatibility window.\n */\n FundAccountOrRaiseAllowance: 'fund_account_or_raise_allowance',\n /**\n * The delegate wallet may hold funds that were sent from the agent's Haven\n * account but never settled to the merchant. The wallet owner should initiate\n * a sweep to return those funds to that account.\n */\n SweepStrandedFunds: 'sweep_stranded_funds',\n /**\n * #2970: a `submitted` erc7710 x402 intent whose settlement window has\n * passed with no on-chain settlement evidence Haven could verify. Distinct\n * from {@link CheckStatusLater}, which this REPLACES once the window is\n * past — but it is not futile: Haven's settlement sweep (120s tick) scans\n * each candidate over its own window plus a 120s clock-skew allowance, so\n * it can still attribute the settlement for a short while after this value\n * first appears. Poll {@link CheckStatusLater}'s tool\n * (`haven_get_payment_status`) once more, roughly two minutes later; if it\n * still shows no evidence, tell the user the goods were delivered but\n * Haven holds no verified settlement evidence for this payment. If the\n * agent holds the merchant's real settlement transaction hash (from\n * `PAYMENT-RESPONSE`'s `transaction` field, or a prior settle/complete\n * result's `settlement_tx_hash`), report it with the hosted\n * `haven_report_settlement_evidence` tool instead of waiting —\n * `haven_report_x402_outcome` takes no hash and refuses a non-`confirmed`\n * intent.\n */\n AwaitingSettlementEvidence: 'awaiting_settlement_evidence',\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 merchant rejected the paid retry. On eip3009 the funding leg had succeeded (sweep);\n * on erc7710 there is no funding leg — nothing to sweep, follow the message (#2983). */\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 * may still settle late, so the guidance is verify-then-act. On eip3009\n * the funding leg had succeeded (verify-then-sweep); on erc7710 there is\n * no funding leg — nothing to sweep, follow the message (#3000). */\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 /**\n * #2979: the merchant answered a `tools/call` probe with its own\n * machine-readable \"cannot settle right now\" refusal (HTTP 503,\n * `{ error: 'merchant_not_ready', reason_code, ... }`) instead of a 402\n * challenge — e.g. its settlement wallet is out of gas. No 402 was ever\n * issued and no payment was created; this is honest and (per\n * `retry_after_s`, when present) usually transient, unlike a permanent\n * endpoint miss.\n */\n MerchantNotReady: 'MERCHANT_NOT_READY',\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 account, redeemed through the agent's budget delegation. */\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.FundAccountOrRaiseAllowance]:\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 [AgentPaymentNextAction.AwaitingSettlementEvidence]:\n \"The settlement window passed with no verified on-chain evidence yet. If you hold the merchant's real settlement transaction hash, report it with haven_report_settlement_evidence. Otherwise, Haven's settlement sweep may still attribute it within about two minutes — poll getPaymentStatus once more, then tell the user the goods were delivered but unverified if it still shows nothing.\",\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 merchant rejected the paid retry. eip3009: the funding leg succeeded — stop retrying the merchant and reconcile stranded delegate funds with haven_sweep_delegate. erc7710: no funding leg, nothing to sweep — follow the message (re-quote later, or check haven_get_payment_status after the window first).',\n [AgentPaymentFailureCode.MerchantUnresponsiveAfterFunding]:\n 'The merchant did not answer the paid retry before the timeout. The merchant may still settle late. eip3009: the funding leg succeeded — check haven_get_payment_status, retry haven_complete_mcp_tool once, sweep only if no settlement appears. erc7710: no funding leg, nothing to sweep, and haven_complete_mcp_tool has no erc7710 branch — do not retry it; check haven_get_payment_status after the payment window and re-quote only if it shows no settlement.',\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 [AgentPaymentFailureCode.MerchantNotReady]:\n 'The merchant refused the probe with its own \"cannot settle right now\" signal instead of a 402 challenge. No payment was created. Often transient — retry later (see retry_after_s in the message, if given) rather than treating this as a broken or wrong endpoint.',\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 /**\n * #2991: the quote tools' `expected_settlement_scheme` prediction of what\n * `haven_prepare_catalog_purchase` / `haven_pay_mcp_tool` will actually\n * select could not be computed — the agent's execution rail could not be\n * read from Haven, so `expected_settlement_scheme` is `null` rather than a\n * guess. `accepted_scheme` (the merchant's offer) is unaffected.\n */\n X402SchemeUnknown: 'X402_SCHEME_UNKNOWN',\n /**\n * #2968: the merchant answered 200 and handed over goods, but Haven holds NO\n * on-chain evidence that the payment moved. `settled: false` beside this code\n * is not a failure — it is the absence of proof, and the two must travel\n * together so an agent can tell \"the user has the goods\" apart from \"the\n * money moved\". Carries the intent's `expires_at`: after that instant the\n * settlement can no longer land at all.\n */\n SettlementUnconfirmed: 'SETTLEMENT_UNCONFIRMED',\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 /** From `AgentPaymentNextAction`. */\n next_action: AgentPaymentNextAction\n /**\n * Claude-family namespaced tool name for the next call\n * (`mcp__<server>__<tool>`), when one exists.\n *\n * **Namespaced with the DEFAULT server names**, which is the most the hosted\n * server can know: local server names are the client's own config and never\n * reach Haven. Two runtimes are already not the default — Codex names servers\n * by config key (`haven`, `haven_signer`), and a connector run with\n * `--name <slug>` wires `haven-<slug>` / `haven-signer-<slug>` (#1694). On\n * either, this field and `next_tool_server` name a server the client does not\n * have. Prefer {@link AgentNextStep.next_tool_server_role} plus\n * {@link AgentNextStep.next_tool_name} whenever your servers are not the\n * default pair; see #2550.\n */\n next_tool?: string\n /**\n * The server half of `next_tool`, unprefixed — `haven` or `haven-signer`.\n * Carries the same default-name caveat as `next_tool` (#1588, #2550).\n */\n next_tool_server?: string\n /** The bare tool name, callable on whichever server plays the role below. */\n next_tool_name?: string\n /**\n * Which of the CLIENT'S OWN servers to call (#2550). Runtime-neutral, and\n * the field to resolve against when your server names are not the defaults —\n * it names a role rather than a name the hosted server had to guess.\n */\n next_tool_server_role?: 'hosted' | 'signer'\n /** Small literal arguments for next_tool. Bulky fields are referenced by reason. */\n next_arguments?: Record<string, unknown>\n /**\n * #3101 (epic #3105, decision 3): present exactly when `next_tool` is\n * absent — why no tool is named (the payment id is unknown, nothing is left\n * to do, the arguments could not be built). `next_tool` is never null.\n */\n next_tool_omitted_reason?: string\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 /** #2960: additive alongside `payerAddress` above (`parties.delegate` only). */\n parties?: PaymentParties\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 account_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 /** The payer account — NOT the delegate `account`. */\n payer_account?: 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 /** #2960: additive alongside `payer_address` above (`parties.delegate` only). */\n parties?: RawPaymentParties\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 account_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 account_address?: string\n delegate_address: string\n chain_id: number\n allowances: RawHavenAllowance[]\n}\n\n/** @internal */\nexport interface RawHavenPaymentReceipt {\n id: string\n /** #3132: present on a backend that states list scope per row; absent on older backends. */\n scope?: { source: 'wallet' | 'agent'; filter: 'agent' | 'account' | 'account+agent' | null }\n payment_id: string\n payment_intent_id?: string | null\n approval_request_id?: string | null\n rail: string\n proof_status: string\n /** @deprecated (#2998) — see `funding_tx_hash` / `settlement_tx_hash`. */\n tx_hash: string\n funding_tx_hash?: string | null\n settlement_tx_hash?: string | null\n chain_id: number\n resource_url: string\n merchant_address: string | null\n payer_address: string\n /** #2960: additive alongside `payer_address` above (`parties.treasury_account` only). */\n parties?: RawPaymentParties\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 for the listing; the catalog refresh probe still\n * checks the endpoint, see `verifiedPayable`). `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 — the one ownership claim. See the epic's trust claim (never merchant honesty or quality). */\n domainVerified: boolean\n /**\n * True when Haven watched this endpoint answer a live quote (#2978): the\n * directory probe for `ingestion` rows, the periodic catalog refresh probe\n * for `operator` rows (`status === 'active'` with `verifiedAt` set). False\n * for a degraded row of either source. `discoverTools({ verified:\n * 'verified' })` filters on this field, not on `source`.\n */\n verifiedPayable: boolean\n /**\n * The merchant this entry belongs to (#3078). OPTIONAL on purpose: an\n * installed SDK may face a backend that predates the merchant layer, and\n * `discoverTools` must keep working against it — the field is absent, not\n * null, in that case.\n */\n merchant?: HavenCatalogMerchant\n}\n\n/** A catalog entry's merchant as the wire carries it (#3078). */\nexport interface HavenCatalogMerchant {\n id: string\n slug: string\n name: string\n /** `coming_soon` never reaches an entry in practice (a prospect has no offers). */\n listingStatus: 'live' | 'coming_soon'\n /** Haven-run test content: the demo store and the stranded-funds fixture. */\n isTestMerchant: boolean\n}\n\n/** @internal */\nexport interface RawCatalogEntryMerchant {\n id: string\n slug: string\n name: string\n listing_status: 'live' | 'coming_soon'\n is_test_merchant: 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 /** Absent from a backend older than #3078; null when the join resolved nothing. */\n merchant?: RawCatalogEntryMerchant | null\n}\n\nexport interface RawHavenPaymentReceiptsResponse {\n receipts: RawHavenPaymentReceipt[]\n /** #3128 — optional on the wire so an older backend still maps. */\n total?: number\n has_more?: boolean\n next_cursor?: string | null\n}\n\n/**\n * #3128: one page of receipts. `total` is the count Haven holds for the\n * agent (an empty page with `total: 0` means no receipt exists — there is no\n * indexing delay behind this list); `hasMore` says the page was cut at the\n * limit; `nextCursor` is fed back as `cursor` for the next page. Against a\n * backend older than #3128 the three are `null` — \"unknown\", never a\n * fabricated 0 / false.\n */\nexport interface HavenPaymentReceiptsPage {\n receipts: HavenPaymentReceipt[]\n total: number | null\n hasMore: boolean | null\n nextCursor: string | null\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 /**\n * #2979: `body` is the merchant's own JSON, when the non-402 response\n * carried one — e.g. the demo merchant's `/mcp` readiness gate answers\n * `503 { error: 'merchant_not_ready', reason_code, ... }`. Optional and\n * best-effort: a non-JSON or unreadable body leaves this `undefined`, same\n * as before this field existed. Consumers key on it (not on the message\n * string) to distinguish an honest, machine-readable merchant refusal from\n * a genuine \"this is not the x402 endpoint\" miss, which otherwise look\n * identical — both are just \"some non-402 status\".\n */\n constructor(message: string, statusCode: number, body?: unknown) {\n super(message, statusCode, body)\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 * #2972: `MerchantCompletion.reportSettlementEvidence` /\n * `HavenClient.reportSettlementEvidence` refuse a `0x00…00` settlement hash\n * BEFORE any network call — see `isZeroSettlementTxHash`. That marker is\n * never a real transaction (the demo merchant's own \"delivered, not settled\"\n * value), so posting it to `POST /machine-payments/evidence` could only ever\n * come back refused, at the cost of a real round trip. A typed error rather\n * than a `HavenApiError`-shaped 400: no request was ever attempted, so there\n * is no HTTP status or response body to carry.\n */\nexport class HavenZeroSettlementHashError extends HavenError {\n constructor(paymentId: string) {\n super(\n 'settlement_tx_hash is the zero hash (0x00…00), which is never a real settlement ' +\n 'transaction — refused before any report was sent.',\n 'ZERO_SETTLEMENT_HASH',\n 400,\n paymentId,\n )\n this.name = 'HavenZeroSettlementHashError'\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 { encodeAbiParameters, getAddress, isAddress, keccak256, type Hex } from 'viem'\nimport { HavenError } from './types.js'\n\n/**\n * #3271: the integrity check every client runs before signing a direct\n * delegation-rail payment's typed data.\n *\n * A direct payment (`POST /payments`, surfaced as `haven_send` / `haven_pay`)\n * is signed as the HybridDeleGator's EIP-712 `PackedUserOperation`, and Haven\n * returns two things for it: that typed data, and `payload_hash` — the\n * ERC-4337 v0.7 UserOperation hash of the same operation. Nothing used to tie\n * the two together at signing time. The typed data is multi-KB and reaches the\n * signer through a language model when it is relayed by hand, so one corrupted\n * character produced a valid-looking signature over the wrong digest, and the\n * first sign of it was `AA24 signature error` from the bundler (#3271,\n * reproduced on dev 2026-09-24).\n *\n * This recomputes the v0.7 hash from the typed data's own message and domain\n * and refuses unless it equals `payload_hash`, and it pins the parts of the\n * typed data the hash does NOT cover (domain name/version/verifyingContract,\n * the field list, the EntryPoint). It is a CORRUPTION check: the caller supplies\n * both values, so it proves they describe the same operation, never that Haven\n * prepared it. Provenance is the byte-free sign context (`payment_id`); what the\n * signer will sign at all is #3272.\n *\n * Pure viem, no ethers: `@haven_ai/sdk/edge` re-exports it for the edge signer,\n * and `edge-imports.test.ts` pins that graph.\n */\n\n/** Version of the direct-payment sign context (`GET /payments/:id/sign-context`). */\nexport const DIRECT_SIGN_CONTEXT_VERSION = 1\n\n/** The HybridDeleGator EIP-712 domain, in the canonical EIP-712 field order. */\nconst EIP712_DOMAIN_FIELDS = [\n { name: 'name', type: 'string' },\n { name: 'version', type: 'string' },\n { name: 'chainId', type: 'uint256' },\n { name: 'verifyingContract', type: 'address' },\n] as const\n\n/** The ERC-4337 v0.7 EntryPoint — the only one the delegation rail submits to. */\nexport const ENTRY_POINT_V07 = '0x0000000071727De22E5E9d8BAf0edAc6f37da032'\n\n/**\n * The HybridDeleGator EIP-712 domain constants and the `PackedUserOperation`\n * field list, vendored from `@metamask/smart-accounts-kit`\n * (`contracts.HybridDeleGator.constants`, `SIGNABLE_USER_OP_TYPED_DATA`) so the\n * published packages need no runtime dependency on the kit. Pinned equal to the\n * kit's values by `userop-binding.test.ts`.\n */\nexport const HYBRID_DELEGATOR_DOMAIN_NAME = 'HybridDeleGator'\nexport const HYBRID_DELEGATOR_DOMAIN_VERSION = '1'\nexport const PACKED_USER_OPERATION_FIELDS: ReadonlyArray<{ name: string; type: string }> = [\n { name: 'sender', type: 'address' },\n { name: 'nonce', type: 'uint256' },\n { name: 'initCode', type: 'bytes' },\n { name: 'callData', type: 'bytes' },\n { name: 'accountGasLimits', type: 'bytes32' },\n { name: 'preVerificationGas', type: 'uint256' },\n { name: 'gasFees', type: 'bytes32' },\n { name: 'paymasterAndData', type: 'bytes' },\n { name: 'entryPoint', type: 'address' },\n]\n\n/** Refusal raised when UserOperation typed data (a direct payment, or the SDK's x402 funding leg) does not match its `payload_hash`. */\nexport class HavenUserOpBindingError extends HavenError {\n constructor(message: string) {\n super(message, 'USEROP_BINDING_MISMATCH')\n this.name = 'HavenUserOpBindingError'\n }\n}\n\n/** True when the typed data is a `PackedUserOperation` (the direct-payment shape). */\nexport function isPackedUserOperationTypedData(value: unknown): boolean {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { primaryType?: unknown }).primaryType === 'PackedUserOperation'\n )\n}\n\nconst HEX = /^0x[0-9a-fA-F]*$/\nconst BYTES32 = /^0x[0-9a-fA-F]{64}$/\n\nfunction refuse(detail: string): never {\n throw new HavenUserOpBindingError(\n `Refusing to sign: this UserOperation typed data does not match its payload_hash (${detail}). ` +\n 'The payload was altered between the Haven result and this call — sign by payment_id so the ' +\n 'signer fetches the exact bytes, or pass typed_data_b64 from the result unchanged.',\n )\n}\n\nfunction hexField(message: Record<string, unknown>, key: string, pattern: RegExp): Hex {\n const value = message[key]\n if (typeof value !== 'string' || !pattern.test(value)) refuse(`message.${key} is not well-formed`)\n return value as Hex\n}\n\nfunction uintField(message: Record<string, unknown>, key: string): bigint {\n const value = message[key]\n try {\n if (typeof value === 'bigint') return value\n if ((typeof value === 'string' && /^(0x[0-9a-fA-F]+|[0-9]+)$/.test(value)) || typeof value === 'number') {\n const n = BigInt(value)\n if (n >= 0n) return n\n }\n } catch {\n // fall through to the refusal\n }\n return refuse(`message.${key} is not an unsigned integer`)\n}\n\nfunction addressField(value: unknown, where: string): `0x${string}` {\n if (typeof value !== 'string' || !isAddress(value, { strict: false })) refuse(`${where} is not an address`)\n return getAddress(value as string)\n}\n\n/**\n * Compute the ERC-4337 v0.7 UserOperation hash from a HybridDeleGator\n * `PackedUserOperation` typed-data object — the value Haven returns as\n * `payload_hash` for a direct payment (`getUserOperationHash`, entryPoint 0.7).\n */\nexport function packedUserOperationHash(typedData: unknown): Hex {\n if (!isPackedUserOperationTypedData(typedData)) refuse('primaryType is not PackedUserOperation')\n const td = typedData as { domain?: Record<string, unknown>; message?: Record<string, unknown> }\n const message = td.message\n if (!message || typeof message !== 'object') refuse('message is missing')\n const chainId = uintField({ chainId: td.domain?.chainId }, 'chainId')\n const inner = keccak256(\n encodeAbiParameters(\n [\n { type: 'address' },\n { type: 'uint256' },\n { type: 'bytes32' },\n { type: 'bytes32' },\n { type: 'bytes32' },\n { type: 'uint256' },\n { type: 'bytes32' },\n { type: 'bytes32' },\n ],\n [\n addressField(message.sender, 'message.sender'),\n uintField(message, 'nonce'),\n keccak256(hexField(message, 'initCode', HEX)),\n keccak256(hexField(message, 'callData', HEX)),\n hexField(message, 'accountGasLimits', BYTES32),\n uintField(message, 'preVerificationGas'),\n hexField(message, 'gasFees', BYTES32),\n keccak256(hexField(message, 'paymasterAndData', HEX)),\n ],\n ),\n )\n return keccak256(\n encodeAbiParameters(\n [{ type: 'bytes32' }, { type: 'address' }, { type: 'uint256' }],\n [inner, addressField(message.entryPoint, 'message.entryPoint'), chainId],\n ),\n )\n}\n\n/**\n * Refuse (throw `HavenUserOpBindingError`) unless this `PackedUserOperation`\n * typed data is the operation `payloadHash` names, in the HybridDeleGator\n * domain of its own sender, against the v0.7 EntryPoint. Returns the\n * recomputed hash.\n */\nexport function assertUserOpTypedDataBinding(typedData: unknown, payloadHash: string): Hex {\n if (typeof payloadHash !== 'string' || !BYTES32.test(payloadHash)) refuse('payload_hash is not a 32-byte hex string')\n if (!isPackedUserOperationTypedData(typedData)) refuse('primaryType is not PackedUserOperation')\n const td = typedData as {\n domain?: Record<string, unknown>\n types?: Record<string, unknown>\n message?: Record<string, unknown>\n }\n const domain = td.domain ?? {}\n const message = td.message ?? {}\n if (domain.name !== HYBRID_DELEGATOR_DOMAIN_NAME) refuse('domain.name is not HybridDeleGator')\n if (domain.version !== HYBRID_DELEGATOR_DOMAIN_VERSION) refuse('domain.version is not 1')\n if (addressField(domain.verifyingContract, 'domain.verifyingContract') !== addressField(message.sender, 'message.sender')) {\n refuse('domain.verifyingContract is not message.sender')\n }\n if (addressField(message.entryPoint, 'message.entryPoint') !== getAddress(ENTRY_POINT_V07)) {\n refuse('message.entryPoint is not the v0.7 EntryPoint')\n }\n const fields = (td.types ?? {}).PackedUserOperation\n if (\n !Array.isArray(fields) ||\n fields.length !== PACKED_USER_OPERATION_FIELDS.length ||\n fields.some(\n (f, i) =>\n !f ||\n (f as { name?: unknown }).name !== PACKED_USER_OPERATION_FIELDS[i].name ||\n (f as { type?: unknown }).type !== PACKED_USER_OPERATION_FIELDS[i].type,\n )\n ) {\n refuse('types.PackedUserOperation is not the HybridDeleGator field list')\n }\n const extraTypes = Object.keys(td.types ?? {}).filter((k) => k !== 'PackedUserOperation' && k !== 'EIP712Domain')\n if (extraTypes.length > 0) refuse(`unexpected types: ${extraTypes.join(', ')}`)\n // The domain separator is not covered by payload_hash, and viem honours a\n // supplied `types.EIP712Domain` and any extra domain key (e.g. `salt`) when\n // it builds the digest — so both are pinned exactly, or a corrupted domain\n // would pass this check and still sign over the wrong digest.\n const domainKeys = Object.keys(domain).sort()\n if (domainKeys.join(',') !== [...EIP712_DOMAIN_FIELDS.map((f) => f.name)].sort().join(',')) {\n refuse(`domain keys are not exactly ${EIP712_DOMAIN_FIELDS.map((f) => f.name).join(', ')}`)\n }\n const declaredDomain = (td.types ?? {}).EIP712Domain\n if (\n declaredDomain !== undefined &&\n (!Array.isArray(declaredDomain) ||\n declaredDomain.length !== EIP712_DOMAIN_FIELDS.length ||\n declaredDomain.some(\n (f, i) =>\n !f ||\n (f as { name?: unknown }).name !== EIP712_DOMAIN_FIELDS[i].name ||\n (f as { type?: unknown }).type !== EIP712_DOMAIN_FIELDS[i].type,\n ))\n ) {\n refuse('types.EIP712Domain is not the canonical name/version/chainId/verifyingContract list')\n }\n const recomputed = packedUserOperationHash(typedData)\n if (recomputed.toLowerCase() !== payloadHash.toLowerCase()) refuse('recomputed UserOperation hash differs')\n return recomputed\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 /** The agent's Haven account 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). This cap applies only to the signed authorization, never to the\n * advertised requirements echoed in `accepted`. A merchant requiring more\n * than the bounded lifetime can still reject at verification; preserving its\n * offer does not widen Haven's signing policy.\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 // Keep the merchant offer intact for v2 `accepted` matching. Only the\n // signing conversion may cap its authorization lifetime (#3117).\n // Retain legacy fallback behavior for missing or unusable timeouts.\n // Integer, because the authorize body types it `integer` and the child's\n // timestamp caveat is built from it — the old clamp floored, so keeping a\n // fractional value here would 400 a merchant that used to work (#3117).\n maxTimeoutSeconds:\n typeof candidate.maxTimeoutSeconds === 'number' &&\n Number.isFinite(candidate.maxTimeoutSeconds) && candidate.maxTimeoutSeconds >= 1\n ? Math.floor(candidate.maxTimeoutSeconds)\n : 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 * True when the entry is EIP-3009-`authorization`-shaped: what this SDK can\n * construct with `exact.evm.createPaymentHeader` (#3116).\n *\n * The [exact EVM specification](https://github.com/x402-foundation/x402/blob/main/specs/schemes/exact/scheme_exact_evm.md)\n * distinguishes three payloads by `extra.assetTransferMethod`: EIP-3009 signs\n * `signature`/`authorization`, Permit2 signs `signature`/`permit2Authorization`,\n * and erc7710 carries a delegation chain. Haven constructs exactly one of\n * those payloads — the EIP-3009 `authorization` one — so an entry counts as\n * EIP-3009-compatible ONLY when its advertised method and flow agree with\n * that payload, by name: an omitted key means the mechanism default\n * (`eip3009` / `authorization`), and any value that is present but not\n * exactly the supported string — including a non-string, malformed value —\n * makes the entry unsupported.\n *\n * `extra.assetTransferMethod` / `extra.paymentFlow` are protocol-reserved\n * keys ([v2 specification §6.1](https://github.com/x402-foundation/x402/blob/main/specs/x402-specification-v2.md),\n * which also requires clients to refuse a `paymentFlow` they do not\n * recognize), so their values are READ as claims, never ignored. Merchant\n * shape is untrusted, same defensive posture as `x402AssetTransferMethod` —\n * but here a malformed value reads as UNSUPPORTED rather than as the\n * default, because the cost of guessing the default wrong is a signature\n * the merchant's verifier refuses after the funding leg has already moved\n * funds. 'erc7710' fails this test like any other non-3009 method and is\n * selected by `selectErc7710PaymentOption` instead.\n */\nfunction isEip3009ConstructibleOption(option: X402PaymentOption): boolean {\n const rawMethod = option.extra?.assetTransferMethod\n if (rawMethod !== undefined && rawMethod !== 'eip3009') return false\n const rawFlow = option.extra?.paymentFlow\n if (rawFlow !== undefined && rawFlow !== 'authorization') return false\n return true\n}\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 two-leg bridge the account→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 // #3116: non-erc7710 is no longer assumed EIP-3009-compatible. A permit2\n // entry, or one advertising a paymentFlow this SDK does not recognize,\n // must be skipped here rather than signed into an EIP-3009 payload the\n // exact-EVM specification does not define for it.\n if (!isEip3009ConstructibleOption(opt)) continue\n if (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 // #3116: an erc7710 selector must not fall through to an entry whose\n // method/flow is neither erc7710 nor constructible EIP-3009 — an\n // unsupported entry stays unsupported on BOTH selectors, so a challenge\n // that offers only incompatible shapes is refused, never guessed at.\n if (!isEip3009ConstructibleOption(opt)) continue\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 // #3116, last stop before `exact.evm.createPaymentHeader`: the requirements\n // produced here can ONLY become an EIP-3009 `authorization` payload, so an\n // entry advertising any other transfer method or an unrecognized payment\n // flow must refuse here even if a future caller bypasses the selectors.\n // Permit2 signs `signature`/`permit2Authorization` — a payload this SDK\n // does not construct (implementing Permit2 is out of scope by design) —\n // and §6.1 forbids constructing a payment for a paymentFlow the client\n // does not recognize. Both refuse BEFORE any funding or signing.\n if (!isEip3009ConstructibleOption(option)) {\n throw new Error(\n 'Unsupported x402 payment requirements: this SDK constructs EIP-3009 ' +\n 'authorization payments only. The merchant advertised a different ' +\n 'extra.assetTransferMethod or an unrecognized extra.paymentFlow.',\n )\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 // Signing-only policy (#715/#3117): parsed and directly supplied options\n // share this cap before the library computes validBefore. Keep the offer\n // echoed in `accepted` unchanged. The forward margin (#1256) adds time\n // for funding/retry, but does not guarantee a merchant timeout above the\n // total bounded lifetime can pass facilitator verification.\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 type { AgentNextStep, AgentPaymentNextAction } from './types.js'\n\n/**\n * #3101 (epic #3105, slice 2/5): the typed next-step builder.\n *\n * Every hosted payment tool ends by naming the agent's next tool and its\n * arguments (#1308). Until this module, the tool was a free string and the\n * arguments a `Record<string, unknown>`, so nothing tied the keys to the tool\n * named beside them — three sites handed `{ payment_id: null }` to a tool\n * whose `payment_id` is a required string, and the compiler could not see it.\n *\n * The builder is generic over a TARGET MAP the caller supplies: bare tool\n * name → { role, validate }. It is deliberately schema-library-agnostic (the\n * SDK carries no zod): the hosted server derives each target's argument type\n * from its own zod shape and passes a `validate` closure; this module only\n * needs to know the role (to render `mcp__<server>__<tool>`) and how to say\n * whether arguments parse. Keyed on the bare name + role (decision 1) so the\n * namespaced string is rendered in exactly one place and the runtime-neutral\n * `next_tool_server` / `next_tool_name` / `next_tool_server_role` fields are\n * derived from the same input rather than parsed back out of a literal.\n *\n * Decisions 3 and 8: `nextTool` is REQUIRED on the input and may be `null` —\n * a site that forgets it is a compile error; a site with no next tool says\n * why, and the wire omits `next_tool` and carries `next_tool_omitted_reason`.\n * `next_tool` is never null on the wire.\n */\nexport type NextToolServerRole = 'hosted' | 'signer'\n\n/** The DEFAULT server name each role is wired under (#1588, #2550). */\nexport const NEXT_TOOL_SERVER_NAMES: Record<NextToolServerRole, string> = {\n hosted: 'haven',\n signer: 'haven-signer',\n}\n\n/** Default server name → role. An unknown server yields no role rather than a guess (#2550). */\nexport const NEXT_TOOL_SERVER_ROLES: Record<string, NextToolServerRole> = {\n haven: 'hosted',\n 'haven-signer': 'signer',\n}\n\n/** Renders the Claude-family namespaced tool name — the one string clients have followed since #1308. */\nexport function renderNextTool(role: NextToolServerRole, name: string): string {\n return `mcp__${NEXT_TOOL_SERVER_NAMES[role]}__${name}`\n}\n\n/** Parses a namespaced literal back into its parts; `role` is absent for an unknown server. */\nexport function parseNextTool(literal: string): { server: string; name: string; role?: NextToolServerRole } | null {\n const m = /^mcp__([a-z0-9-]+)__([a-z0-9_]+)$/.exec(literal)\n if (!m) return null\n const role = NEXT_TOOL_SERVER_ROLES[m[1]]\n return { server: m[1], name: m[2], ...(role ? { role } : {}) }\n}\n\n/**\n * One target the builder may hand off to. `TArgs` is the argument type the\n * caller derived from the tool's declared schema; `validate` is the runtime\n * twin of that type and returns `null` when the arguments parse, else why not.\n */\nexport interface NextStepTarget<TArgs> {\n role: NextToolServerRole\n validate: (input: unknown) => string | null\n /** Phantom carrier for the argument type; never read at runtime. */\n readonly _args?: TArgs\n}\n\nexport type NextStepTargets = Record<string, NextStepTarget<unknown>>\n\n/** The argument type a target carries. */\nexport type NextStepArguments<Targets extends NextStepTargets, T extends keyof Targets> =\n Targets[T] extends NextStepTarget<infer A> ? A : never\n\n/**\n * The handoff half of a next step: a registered tool with arguments that\n * tool accepts, or no tool with the reason. A discriminated union over the\n * target map's keys, so a wrong key, a missing required key, an unregistered\n * tool name and an omitted `nextTool` are each a compile error at the site.\n */\nexport type NextStepHandoff<Targets extends NextStepTargets> =\n | { [T in keyof Targets & string]: { nextTool: T; nextArguments: NextStepArguments<Targets, T> } }[keyof Targets & string]\n | { nextTool: null; nextToolOmittedReason: string }\n\nexport type NextStepInput<Targets extends NextStepTargets> = NextStepHandoff<Targets> & {\n nextAction: AgentPaymentNextAction\n safeToContinue: boolean\n reason: string\n}\n\n/** The wire shape: `AgentNextStep` (its `next_tool` family) — never a null `next_tool`. */\nexport type NextStep = AgentNextStep\n\n/**\n * Per-`next_action` default tool (decision 9): the tool a site names unless it\n * has a reason to override. Only actions with ONE sensible target are listed;\n * `retry_original_x402_request` is absent because its only live emitter names\n * no tool on purpose (the agent's own HTTP retry); `sign_and_submit_payment`\n * is absent because the signer tool\n * depends on the settlement scheme (`haven_sign` for erc7710 delegations,\n * `haven_sign_x402` for the EIP-3009 bridge) and a wrong default there would be\n * worse than none.\n */\nexport const DEFAULT_NEXT_TOOL_BY_ACTION = {\n check_status_later: 'haven_get_payment_status',\n sweep_stranded_funds: 'haven_sweep_delegate',\n // `retry_original_x402_request` is NOT here: its only live emitter\n // (state-direct-recovery.ts, erc7710) names no tool on purpose — the retry\n // is the agent's own HTTP call — so a default would contradict the site.\n} as const satisfies Partial<Record<AgentPaymentNextAction, string>>\n\nexport function defaultNextToolFor(action: AgentPaymentNextAction): string | undefined {\n return (DEFAULT_NEXT_TOOL_BY_ACTION as Partial<Record<AgentPaymentNextAction, string>>)[action]\n}\n\n/**\n * Builds a `nextStep` function bound to a target map. The returned function\n * renders the wire fields from the bare name + role, and re-validates the\n * arguments at runtime: on a mismatch it FAILS SAFE — omits the tool and says\n * why in `next_tool_omitted_reason` — rather than throwing out of a handler\n * that has already moved money. The compile-time twin makes that branch\n * unreachable from typed sites; it exists for callers that bypass the types.\n */\nexport function createNextStepBuilder<Targets extends NextStepTargets>(targets: Targets) {\n return function nextStep(input: NextStepInput<Targets>): NextStep {\n // The generic mapped union does not narrow inside this body; the\n // structural view below is what the union guarantees at every call site.\n const i = input as unknown as {\n nextTool: string | null\n nextArguments?: unknown\n nextToolOmittedReason?: string\n }\n const base = {\n next_action: input.nextAction,\n safe_to_continue: input.safeToContinue,\n reason: input.reason,\n }\n if (i.nextTool === null) {\n return { ...base, next_tool_omitted_reason: i.nextToolOmittedReason ?? 'no next tool' }\n }\n const target = targets[i.nextTool]\n if (!target) {\n return { ...base, next_tool_omitted_reason: `${i.nextTool} is not a registered next-step target` }\n }\n const problem = target.validate(i.nextArguments)\n if (problem) {\n return { ...base, next_tool_omitted_reason: `next_arguments do not parse under ${i.nextTool}: ${problem}` }\n }\n return {\n ...base,\n next_tool: renderNextTool(target.role, i.nextTool),\n next_tool_server: NEXT_TOOL_SERVER_NAMES[target.role],\n next_tool_name: i.nextTool,\n next_tool_server_role: target.role,\n next_arguments: i.nextArguments as Record<string, unknown>,\n }\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"]}
@@ -115,9 +115,9 @@ var AgentPaymentNextAction = {
115
115
  */
116
116
  FundAccountOrRaiseAllowance: "fund_account_or_raise_allowance",
117
117
  /**
118
- * The delegate wallet may hold funds that were sent from the Safe but never
119
- * settled to the merchant. The wallet owner should initiate a sweep to
120
- * return those funds to the originating Safe.
118
+ * The delegate wallet may hold funds that were sent from the agent's Haven
119
+ * account but never settled to the merchant. The wallet owner should initiate
120
+ * a sweep to return those funds to that account.
121
121
  */
122
122
  SweepStrandedFunds: "sweep_stranded_funds",
123
123
  /**
@@ -191,7 +191,7 @@ var AgentPaymentFailureCode = {
191
191
  MerchantNotReady: "MERCHANT_NOT_READY"
192
192
  };
193
193
  var AgentPaymentRail = {
194
- /** Standard Haven payment from the user's Safe through an approved delegate allowance. */
194
+ /** Standard Haven payment from the user's account, redeemed through the agent's budget delegation. */
195
195
  Direct: "direct",
196
196
  /** x402 HTTP 402 payment flow with a Haven funding leg and merchant retry leg. */
197
197
  X402: "x402",
@@ -1394,5 +1394,5 @@ exports.x402FacilitatorAddresses = x402FacilitatorAddresses;
1394
1394
  exports.x402PaymentHeaderNamesFor = x402PaymentHeaderNamesFor;
1395
1395
  exports.x402PaymentHeaderNamesSent = x402PaymentHeaderNamesSent;
1396
1396
  exports.x402V2PaymentEnvelope = x402V2PaymentEnvelope;
1397
- //# sourceMappingURL=chunk-CSWZXQ2L.cjs.map
1398
- //# sourceMappingURL=chunk-CSWZXQ2L.cjs.map
1397
+ //# sourceMappingURL=chunk-M57KOLAN.cjs.map
1398
+ //# sourceMappingURL=chunk-M57KOLAN.cjs.map