@haven_ai/sdk 0.5.0-alpha.1 → 0.6.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/{base64-BUMXmruY.d.cts → base64-cD9kR4JL.d.cts} +243 -16
- package/dist/{base64-BUMXmruY.d.ts → base64-cD9kR4JL.d.ts} +243 -16
- package/dist/{chunk-KQ7JXKTV.js → chunk-3WSEX3GW.js} +315 -6
- package/dist/chunk-3WSEX3GW.js.map +1 -0
- package/dist/{chunk-GLNG2GF7.js → chunk-63GPTEEY.js} +42 -6
- package/dist/chunk-63GPTEEY.js.map +1 -0
- package/dist/{chunk-QSSVOPWA.cjs → chunk-CK4NLLMO.cjs} +333 -17
- package/dist/chunk-CK4NLLMO.cjs.map +1 -0
- package/dist/{chunk-JKUIE45B.cjs → chunk-S42QSWJY.cjs} +42 -6
- package/dist/chunk-S42QSWJY.cjs.map +1 -0
- package/dist/edge.cjs +85 -57
- package/dist/edge.d.cts +24 -4
- package/dist/edge.d.ts +24 -4
- package/dist/edge.js +3 -3
- package/dist/index.cjs +485 -294
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +47 -3
- package/dist/index.d.ts +47 -3
- package/dist/index.js +192 -21
- package/dist/index.js.map +1 -1
- package/dist/test-support.cjs +18 -18
- package/dist/test-support.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-GLNG2GF7.js.map +0 -1
- package/dist/chunk-JKUIE45B.cjs.map +0 -1
- package/dist/chunk-KQ7JXKTV.js.map +0 -1
- package/dist/chunk-QSSVOPWA.cjs.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/signer.ts","../src/haven-api-transport.ts","../src/payment-mappers.ts","../src/payment-state.ts","../src/x402-retry-target.ts","../src/mcp-merchant-transport.ts","../src/receipt.ts","../src/account-reads.ts","../src/provider.ts","../src/delegate-sweep.ts","../src/x402-protocol.ts","../src/account-naming.ts","../src/x402-funding-leg.ts","../src/x402-erc7710.ts","../src/tool-adapter.ts","../src/merchant-completion.ts","../src/client.ts","../src/tool-descriptions.ts","../src/tools.ts","../src/agent-guidance.ts","../src/skill-content.ts","../src/merchant-discovery.ts"],"names":["buildExplorerUrl","ethers","signHash","payment","balance","receipt","mcpTransport"],"mappings":";;;;;;;;;;AAWO,SAAS,QAAA,CAAS,YAAoB,IAAA,EAAsB;AACjE,EAAA,IAAI;AACF,IAAA,MAAM,UAAA,GAAa,IAAI,MAAA,CAAO,UAAA,CAAW,UAAU,CAAA;AACnD,IAAA,MAAM,GAAA,GAAM,UAAA,CAAW,IAAA,CAAK,IAAI,CAAA;AAChC,IAAA,OAAO,GAAA,CAAI,UAAA;AAAA,EACb,SAAS,GAAA,EAAK;AACZ,IAAA,MAAM,IAAI,iBAAA;AAAA,MACR,wBAAwB,GAAA,YAAe,KAAA,GAAQ,IAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC,CAAA;AAAA,KAC1E;AAAA,EACF;AACF;AAwCA,eAAe,qBAAA,CACb,UAAA,EACA,SAAA,EACA,KAAA,EACiB;AACjB,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,IAAI,MAAA,CAAO,MAAA,CAAO,UAAU,CAAA;AAC3C,IAAA,MAAM,KAAA,GAAQ,EAAE,GAAG,SAAA,CAAU,KAAA,EAAM;AACnC,IAAA,OAAQ,KAAA,CAAkC,YAAA;AAC1C,IAAA,OAAO,MAAM,MAAA,CAAO,aAAA;AAAA,MAClB,SAAA,CAAU,MAAA;AAAA,MACV,KAAA;AAAA,MACA,SAAA,CAAU;AAAA,KACZ;AAAA,EACF,SAAS,GAAA,EAAK;AACZ,IAAA,MAAM,IAAI,iBAAA;AAAA,MACR,CAAA,eAAA,EAAkB,KAAK,CAAA,EAAA,EAAK,GAAA,YAAe,QAAQ,GAAA,CAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC,CAAA;AAAA,KA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,CAAS,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAA,KAAM,EAAA,CAAG,QAAA,CAAS,OAAA,CAAQ,QAAQ,EAAE,CAAA;AAAA,EACtG,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF","file":"index.js","sourcesContent":["import { ethers } from 'ethers'\nimport { HavenSigningError } from './types.js'\n\n/**\n * Sign a hash using raw ECDSA (no Ethereum message prefix).\n *\n * This matches what the retired Safe AllowanceModule rail's `checkSignature` expected —\n * a direct ecrecover over the hash, NOT the \"\\x19Ethereum Signed Message\" variant.\n *\n * Uses ethers.SigningKey.sign() instead of wallet.signMessage() to avoid the prefix.\n */\nexport function signHash(privateKey: string, hash: string): string {\n try {\n const signingKey = new ethers.SigningKey(privateKey)\n const sig = signingKey.sign(hash)\n return sig.serialized // 0x + r(32) + s(32) + v(1)\n } catch (err) {\n throw new HavenSigningError(\n `Failed to sign hash: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/**\n * Sign a delegation-rail payment (#829).\n *\n * The delegate SMART ACCOUNT validates an EIP-712 signature over the packed\n * UserOperation — signing the bare 4337 hash would be rejected on-chain. The\n * backend sends the exact typed data in `sign_data.typed_data`; we sign it\n * verbatim and never reconstruct it (a second source of truth could drift\n * from the account's own rules).\n */\nexport interface Eip712TypedData {\n domain: Record<string, unknown>\n types: Record<string, unknown>\n primaryType: string\n message: Record<string, unknown>\n}\n\n/**\n * Sign backend-supplied EIP-712 typed data VERBATIM.\n *\n * One implementation for every typed-data scheme on purpose: the\n * `EIP712Domain` removal below is the kind of subtlety that rots when it is\n * copied. Today the backend's payloads do NOT carry `EIP712Domain` in `types`\n * (checked against a real `buildSettlementDelegation` payload — see\n * `__fixtures__/settlement-delegation-payload.json`), so the delete is\n * defensive rather than load-bearing; ethers derives the domain itself and\n * throws if it also finds it in `types`.\n *\n * `label` only shapes the error message. Nothing about the signature depends\n * on which caller asked.\n *\n * A consequence worth stating before someone refactors this (#1452 review):\n * because the two wrappers below differ ONLY in that label, calling the wrong\n * one for a given scheme produces a byte-identical signature and no test can\n * see it. That is safe today — both sign backend-supplied typed data verbatim\n * — but it stops being safe the moment either wrapper does anything the other\n * does not. If you add per-scheme behaviour, split the implementations rather\n * than branching inside this one.\n */\nasync function signTypedDataVerbatim(\n privateKey: string,\n typedData: Eip712TypedData,\n label: string,\n): Promise<string> {\n try {\n const wallet = new ethers.Wallet(privateKey)\n const types = { ...typedData.types }\n delete (types as Record<string, unknown>).EIP712Domain\n return await wallet.signTypedData(\n typedData.domain as never,\n types as never,\n typedData.message as never,\n )\n } catch (err) {\n throw new HavenSigningError(\n `Failed to sign ${label}: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\nexport async function signUserOpTypedDataForDelegation(\n privateKey: string,\n typedData: Eip712TypedData,\n): Promise<string> {\n return signTypedDataVerbatim(privateKey, typedData, 'delegation UserOperation')\n}\n\n/**\n * Sign the erc7710 x402 SETTLEMENT CHILD delegation (#1452, epic #1450).\n *\n * A different object from the UserOperation above, and a materially different\n * authority: this signature is what lets a merchant's facilitator redeem the\n * `[child, budget]` chain and pull the exact amount from the treasury. The\n * child's caveats — exact amount, payee pin, expiry, redeemer pin — are what\n * bound it, and they are enforced ON-CHAIN. Signing it verbatim is therefore\n * not a style preference: a reconstructed payload that differed from what the\n * DelegationManager will hash is the #829 failure, and it fails at redemption\n * rather than here.\n */\nexport async function signSettlementDelegationTypedData(\n privateKey: string,\n typedData: Eip712TypedData,\n): Promise<string> {\n return signTypedDataVerbatim(privateKey, typedData, 'x402 settlement delegation')\n}\n\n/**\n * Derive the Ethereum address from a private key.\n */\nexport function addressFromKey(privateKey: string): string {\n try {\n return new ethers.Wallet(privateKey).address\n } catch (err) {\n throw new HavenSigningError(\n `Invalid private key: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/**\n * Verify that a signature over a hash recovers to the expected address.\n */\nexport function verifySignature(hash: string, signature: string, expectedAddress: string): boolean {\n try {\n const recovered = ethers.recoverAddress(hash, signature)\n return recovered.toLowerCase() === expectedAddress.toLowerCase()\n } catch {\n return false\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { HavenClientConfig } from './types.js'\nimport { HavenApiError } from './types.js'\nimport {\n HAVEN_CLIENT_HEADER,\n SDK_CLIENT_IDENTITY,\n readClientUpdate,\n type HavenClientUpdate,\n} from './client-identity.js'\n\nconst DEFAULT_BASE_URL = 'http://localhost:3001'\nconst DEFAULT_REQUEST_TIMEOUT = 30_000\n\ntype HavenApiTransportConfig = Pick<\n HavenClientConfig,\n 'apiKey' | 'baseUrl' | 'requestTimeout' | 'defaultHeaders' | 'clientIdentity'\n>\n\n/** Headers minus any case-spelling of `X-Haven-Client` (#3303 review, N1). */\nfunction withoutClientHeader(headers: Record<string, string>): Record<string, string> {\n const target = HAVEN_CLIENT_HEADER.toLowerCase()\n return Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== target))\n}\n\n/**\n * Per-dispatch state carried through `AsyncLocalStorage`: the extra headers,\n * and the last `client_update` the backend sent during this dispatch (#3303),\n * so an MCP tool result can surface the hint its own requests received.\n */\ninterface RequestContextStore {\n headers: Record<string, string>\n clientUpdate?: HavenClientUpdate\n}\n\n/**\n * Internal Haven-API JSON transport.\n *\n * This module deliberately does not handle merchant requests. Merchant HTTP\n * has separate headers, timeout semantics, and error types in HavenClient.\n * The class is exported only for internal composition and direct tests; it is\n * not part of the package entrypoint.\n */\nexport class HavenApiTransport {\n private readonly apiKey: string\n private readonly baseUrl: string\n private readonly requestTimeout: number\n private readonly defaultHeaders: Record<string, string>\n private readonly clientIdentity: string\n private readonly requestContext = new AsyncLocalStorage<RequestContextStore>()\n private lastClientUpdate: HavenClientUpdate | undefined\n\n constructor(config: HavenApiTransportConfig) {\n this.apiKey = config.apiKey\n this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '')\n this.requestTimeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT\n this.defaultHeaders = { ...(config.defaultHeaders ?? {}) }\n this.clientIdentity = config.clientIdentity ?? SDK_CLIENT_IDENTITY\n }\n\n /**\n * The newest `client_update` the backend sent (#3303): inside a\n * `withRequestContext` dispatch, the one that dispatch's own requests\n * received; outside one, the latest this transport has seen.\n */\n clientUpdate(): HavenClientUpdate | undefined {\n const store = this.requestContext.getStore()\n return store ? store.clientUpdate : this.lastClientUpdate\n }\n\n private recordClientUpdate(data: unknown): void {\n if (data === null || typeof data !== 'object' || Array.isArray(data)) return\n const hint = readClientUpdate((data as Record<string, unknown>).client_update)\n if (!hint) return\n this.lastClientUpdate = hint\n const store = this.requestContext.getStore()\n if (store) store.clientUpdate = hint\n }\n\n /** Run `fn` with extra headers scoped to its asynchronous Haven API work. */\n withRequestContext<T>(headers: Record<string, string>, fn: () => Promise<T>): Promise<T> {\n return this.requestContext.run({ headers: { ...headers } }, fn)\n }\n\n async post<T>(path: string, body: Record<string, unknown>): Promise<T> {\n return this.request<T>('POST', path, body)\n }\n\n async get<T>(path: string): Promise<T> {\n return this.request<T>('GET', path)\n }\n\n async request<T>(\n method: 'GET' | 'POST',\n path: string,\n body?: Record<string, unknown>,\n ): Promise<T> {\n const url = `${this.baseUrl}${path}`\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), this.requestTimeout)\n\n try {\n const contextHeaders = this.requestContext.getStore()?.headers ?? {}\n const res = await fetch(url, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n ...withoutClientHeader(this.defaultHeaders),\n ...withoutClientHeader(contextHeaders),\n // Last, and any other spelling of it dropped above (fetch would\n // JOIN `x-haven-client` and `X-Haven-Client` into one unparseable\n // value), so neither `defaultHeaders` nor a dispatch context can\n // misname the client; `clientIdentity` is the one way to set it.\n [HAVEN_CLIENT_HEADER]: this.clientIdentity,\n },\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n })\n\n const data = await res.json()\n this.recordClientUpdate(data)\n\n if (!res.ok) {\n const record = data as Record<string, unknown>\n const errorText = typeof record.error === 'string' ? record.error : undefined\n const rawDetails = record.details ?? record.detail\n const detailsText =\n typeof rawDetails === 'string'\n ? rawDetails\n : rawDetails != null\n ? JSON.stringify(rawDetails)\n : undefined\n const message =\n errorText && detailsText\n ? `${errorText}: ${detailsText}`\n : errorText ?? detailsText ?? 'API request failed'\n throw new HavenApiError(message, res.status, data)\n }\n\n return data as T\n } catch (err) {\n if (err instanceof HavenApiError) throw err\n if (err instanceof Error && err.name === 'AbortError') {\n throw new HavenApiError(`Request to ${path} timed out`, 408)\n }\n throw new HavenApiError(\n `Request to ${path} failed: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n )\n } finally {\n clearTimeout(timeout)\n }\n }\n}\n","import type {\n HavenPaymentReceipt,\n PaymentParties,\n PaymentResult,\n PaymentStatus,\n PaymentStatusResult,\n RawHavenPaymentReceipt,\n RawPaymentParties,\n RawPaymentStatusResult,\n RawStatusResponse,\n} from './types.js'\n\n/** #2960: one mapper, reused by every raw shape carrying `parties`. */\nfunction mapParties(raw: RawPaymentParties | undefined): PaymentParties | undefined {\n if (!raw) return undefined\n return {\n treasuryAccount: raw.treasury_account,\n delegate: raw.delegate,\n delegateAccount: raw.delegate_account,\n merchant: raw.merchant,\n }\n}\n\nexport type ExplorerUrlBuilder = (chainId: number | undefined, txHash: string) => string\n\nexport function mapPaymentResult(\n raw: RawStatusResponse,\n buildExplorerUrl: ExplorerUrlBuilder,\n): PaymentResult {\n return {\n paymentId: raw.payment_id,\n status: raw.status as PaymentStatus,\n token: raw.token,\n amount: raw.amount,\n to: raw.to,\n txHash: raw.tx_hash,\n errorMessage: raw.error_message,\n explorerUrl: raw.explorer_url ?? (raw.tx_hash ? buildExplorerUrl(raw.chain_id, raw.tx_hash) : null),\n fee: raw.fee\n ? {\n amount: raw.fee.amount,\n token: raw.fee.token,\n basisPoints: raw.fee.basis_points,\n applied: raw.fee.applied,\n }\n : null,\n createdAt: raw.created_at,\n signedAt: raw.signed_at,\n submittedAt: raw.submitted_at,\n confirmedAt: raw.confirmed_at,\n expiresAt: raw.expires_at,\n }\n}\n\nexport function mapPaymentStatusResult(raw: RawPaymentStatusResult): PaymentStatusResult {\n return {\n paymentId: raw.payment_id,\n kind: raw.kind,\n rail: raw.rail,\n status: raw.status,\n phase: raw.phase,\n nextAction: raw.next_action,\n amount: raw.amount,\n token: raw.token,\n resourceUrl: raw.resource_url,\n merchantAddress: raw.merchant_address,\n payerAddress: raw.payer_address ?? null,\n parties: mapParties(raw.parties),\n txHash: raw.tx_hash,\n expiresAt: raw.expires_at,\n chainId: raw.chain_id,\n message: raw.message,\n fee: raw.fee\n ? {\n amount: raw.fee.amount,\n token: raw.fee.token,\n basisPoints: raw.fee.basis_points,\n applied: raw.fee.applied,\n }\n : null,\n amountAtomic: raw.amount_atomic ?? raw.x402?.amount_atomic ?? null,\n asset: raw.asset ?? raw.x402?.asset ?? null,\n network: raw.network ?? raw.x402?.network ?? null,\n description: raw.description ?? raw.x402?.description ?? null,\n idempotencyKey: raw.idempotency_key ?? raw.x402?.idempotency_key ?? null,\n x402: raw.x402\n ? {\n amountAtomic: raw.x402.amount_atomic ?? raw.amount_atomic ?? null,\n asset: raw.x402.asset ?? raw.asset ?? null,\n network: raw.x402.network ?? raw.network ?? null,\n resourceUrl: raw.x402.resource_url ?? raw.resource_url,\n merchantAddress: raw.x402.merchant_address ?? raw.merchant_address,\n description: raw.x402.description ?? raw.description ?? null,\n idempotencyKey: raw.x402.idempotency_key ?? raw.idempotency_key ?? null,\n }\n : undefined,\n }\n}\n\n/**\n * #3134 (epic #3130, owner decision 1): the receipt surface converges on the\n * TRANSACTION feed's names for the four concepts the two surfaces share —\n * `paymentProofStatus`, `x402MerchantAddress`, `x402ResourceUrl`, `source` —\n * at this mapper only. The backend receipts wire stays snake_case and the\n * transactions wire is frozen, so the survivor is the transaction-side name\n * in every pair; the argument per pair is in `scripts/ci/vocabulary-map.json`.\n *\n * DUAL-EMIT, one full release. The old receipt names (`proofStatus`,\n * `merchantAddress`, `resourceUrl`, `rail`) are emitted beside the new ones so\n * a published client reading the old name keeps working. REMOVAL CONDITION,\n * written here where the twin is minted (precedent:\n * `packages/backend/src/middleware/retired-safe-names.ts`): delete the four\n * old keys — and their `singleSurface.receipt` rows in the vocabulary map,\n * and invert the tests that pin their presence — only when ALL THREE clocks\n * have moved past the release whose CHANGELOG names these twins:\n * `npm view @haven_ai/sdk dist-tags` reads a `latest` at or above it,\n * `npm view @haven_ai/mcp dist-tags` reads a `latest` at or above it, and the\n * hosted mcp-server deploy reports a `serverInfo.version` on MCP `initialize`\n * (`HOSTED_SERVER_VERSION` in `packages/mcp-server/src/server.ts`) at or past\n * the release that shipped them — each read against the registry / the live\n * server's handshake (which needs an agent API key: the hosted `initialize`\n * is behind `Authorization: Bearer`, and `/healthz` carries no version),\n * never inferred from a green promotion (a promotion can be half green;\n * mcp-server is not on npm). Until then this comment is the\n * contract, and the guard's `singleSurface.receipt` rows are what keep the\n * twins from reading as undeclared divergence.\n */\nexport function mapPaymentReceipt(raw: RawHavenPaymentReceipt): HavenPaymentReceipt {\n const receipt: HavenPaymentReceipt = {\n id: raw.id,\n paymentId: raw.payment_id,\n source: raw.rail,\n rail: raw.rail,\n paymentProofStatus: raw.proof_status,\n proofStatus: raw.proof_status,\n txHash: raw.tx_hash,\n fundingTxHash: raw.funding_tx_hash ?? null,\n settlementTxHash: raw.settlement_tx_hash ?? null,\n chainId: raw.chain_id,\n x402ResourceUrl: raw.resource_url,\n resourceUrl: raw.resource_url,\n x402MerchantAddress: raw.merchant_address,\n merchantAddress: raw.merchant_address,\n payerAddress: raw.payer_address,\n parties: mapParties(raw.parties),\n settlementAddress: raw.settlement_address,\n tokenSymbol: raw.token_symbol,\n tokenAddress: raw.token_address,\n amountRaw: raw.amount_raw,\n amount: raw.amount_human,\n challengeId: raw.challenge_id,\n idempotencyKey: raw.idempotency_key,\n challengePayload: raw.challenge_payload,\n selectedPayment: raw.selected_payment,\n paymentProofHeaderName: raw.payment_proof_header_name,\n protocolReceiptHeaderName: raw.protocol_receipt_header_name,\n protocolReceiptPayload: raw.protocol_receipt_payload,\n merchantStatus: raw.merchant_status,\n confirmedAt: raw.confirmed_at,\n createdAt: raw.created_at,\n updatedAt: raw.updated_at,\n }\n\n if ('payment_intent_id' in raw) {\n receipt.paymentIntentId = raw.payment_intent_id ?? null\n }\n // #3132: carried when the backend states it; the mapper otherwise drops\n // every key it does not name, which is why the declaration is per row.\n if (raw.scope) {\n receipt.scope = { source: raw.scope.source, filter: raw.scope.filter }\n }\n if ('approval_request_id' in raw) {\n receipt.approvalRequestId = raw.approval_request_id ?? null\n }\n\n return receipt\n}\n","import type {\n PaymentNextAction,\n PaymentPhase,\n PaymentStatusResult,\n RawSignResponse,\n RawX402AuthorizeResponse,\n} from './types.js'\nimport {\n AgentPaymentNextAction,\n AgentPaymentPhase,\n HavenApiError,\n HavenPaymentStateError,\n} from './types.js'\n\nconst PAYMENT_STATE_STATUS_CODES: Record<string, number> = {\n pending: 202,\n pending_approval: 202,\n approved: 202,\n proposed: 202,\n executed: 200,\n pending_signature: 409,\n submitted: 409,\n expired: 410,\n failed: 502,\n rejected: 409,\n}\n\nexport function paymentStateStatusCode(status: string, fallback = 502): number {\n return PAYMENT_STATE_STATUS_CODES[status] ?? fallback\n}\n\n// The three retired-queue statuses keep their descriptive phase labels on\n// purpose, and #2262 deliberately did not make `approved` the exception.\n// #2101 and #2145 both converted `nextActionForStatus` only and left every\n// arm of this function alone: `phase` is a descriptive label, `nextAction` is\n// the field the agent contract says to follow FIRST, and all three phases\n// these arms return — `user_approval_required`, `user_execution_required`,\n// `waiting_for_additional_approvals` — already carry the \"Retired wire value:\n// no live rail produces it. Stop and tell the user.\" text in\n// `AgentPaymentPhaseDescriptions` (`types.ts`). Re-pointing one of the three\n// at a different phase would make the status→phase correspondence lie in a\n// new way and would be a third handling of one fact.\nfunction phaseForStatus(status: string): PaymentPhase | null {\n if (status === 'pending_signature') return AgentPaymentPhase.AgentSignatureRequired\n if (status === 'submitted') return AgentPaymentPhase.PaymentSubmitted\n if (status === 'confirmed') return AgentPaymentPhase.PaymentConfirmed\n if (status === 'pending' || status === 'pending_approval') return AgentPaymentPhase.UserApprovalRequired\n if (status === 'approved') return AgentPaymentPhase.UserExecutionRequired\n if (status === 'proposed') return AgentPaymentPhase.WaitingForAdditionalApprovals\n if (status === 'executed') return AgentPaymentPhase.FundingSent\n if (status === 'rejected') return AgentPaymentPhase.Rejected\n if (status === 'expired') return AgentPaymentPhase.Expired\n if (status === 'failed') return AgentPaymentPhase.Failed\n return null\n}\n\nfunction nextActionForStatus(status: string): PaymentNextAction | null {\n if (status === 'pending_signature') return AgentPaymentNextAction.SignAndSubmitPayment\n if (status === 'submitted') return AgentPaymentNextAction.CheckStatusLater\n if (status === 'confirmed') return AgentPaymentNextAction.None\n // #2101: STOP, not wait. No live rail mints these payment statuses (410 on\n // the legacy rail, #1986; 403/502 at prepare on the delegation rail;\n // `approval_requests` dropped by #2055), so nothing will ever transition a\n // row out of them. `nextAction` is the field the agent contract says to\n // follow FIRST — emitting `wait_for_user_approval` here would contradict\n // the message beside it and send a compliant agent into a poll loop that\n // cannot terminate. The fail-closed branch is retained; its verdict is stop.\n if (status === 'pending' || status === 'pending_approval') return AgentPaymentNextAction.StopAndTellUser\n // #2262: `approved` closes the #2101 sweep — it was the one branch left\n // emitting a wait, sitting literally between two converted siblings. Same\n // proof as theirs, re-verified rather than inherited: `approved` was an\n // `approval_requests` status (table dropped by #2055), and no write in the\n // repository layer sets `payment_intents.status` to it — every INSERT/UPDATE\n // in `infra/repositories/payment-intents.ts`, `x402-authorizations.ts` and\n // `agent-rekeys.ts` sets `pending_signature`, `submitted`, `confirmed`,\n // `expired` or `failed`. So nothing can mint it, and the wait it returned\n // pointed at a user-execution step on the Safe rail, which has answered 410\n // to everything since #1986. An agent that followed it would wait forever.\n // Three places already said so — `AgentPaymentNextActionDescriptions` and\n // `AgentPaymentPhaseDescriptions` in `types.ts`, and README's next-action\n // table — so the tree contradicted itself here. Fail-closed branch retained;\n // its verdict is stop.\n if (status === 'approved') return AgentPaymentNextAction.StopAndTellUser\n if (status === 'proposed') return AgentPaymentNextAction.StopAndTellUser\n // #2145: `executed` joins its #2101 siblings, fail-closed. It was an\n // `approval_requests` status (table dropped, #2055) and cannot be\n // constructed as a payment_intents.status, so the retry instruction it\n // carried pointed at a state nothing can mint. The reachable producer of\n // retry_original_x402_request is the backend's status projection\n // (funded-but-undelivered on the eip3009 bridge), which arrives via the\n // response's own `next_action` — never through this status fallback.\n if (status === 'executed') return AgentPaymentNextAction.StopAndTellUser\n if (status === 'rejected') return AgentPaymentNextAction.StopAndTellUser\n if (status === 'expired') return AgentPaymentNextAction.RequestAgainIfUserStillWantsIt\n if (status === 'failed') return AgentPaymentNextAction.StopAndTellUser\n return null\n}\n\nfunction messageForState(\n label: string,\n status: string,\n paymentId: string,\n nextAction: PaymentNextAction,\n): string {\n if (status === 'pending' || status === 'pending_approval') {\n // No live Haven rail mints these statuses for a payment: an out-of-policy\n // payment is refused during prepare (403/502 from POST /payments) with\n // nothing written, and the queue table the old text pointed at is gone.\n // The branch is kept fail-closed for a stored row from before the\n // retirement, but the message must not promise an approval that will\n // never arrive — the agent is told to stop, not to poll.\n return `${label} is not payable: it is outside the agent's on-chain budget and no approval is pending (payment_id: ${paymentId}). Ask the user to grant or raise the budget in Haven.`\n }\n if (status === 'approved') {\n // #2262: no live rail mints this status (it belonged to the dropped\n // approval queue), so the message must not promise a payment the user is\n // about to complete. Before this branch existed the generic template below\n // rendered \"<label> is approved; next_action=wait_for_user_to_complete_payment\",\n // which is the instruction, not the documentation, an agent acts on.\n return `This payment carries a retired status (\"approved\") that no live Haven rail produces (payment_id: ${paymentId}). Nothing is waiting to be completed — tell the user to review this payment in Haven.`\n }\n if (status === 'executed') {\n // #2145: no live rail mints this status (it belonged to the dropped\n // approval queue), so the message must not promise a retry.\n return `This payment carries a retired status (\"executed\") that no live Haven rail produces (payment_id: ${paymentId}). Do not retry it — tell the user to review this payment in Haven.`\n }\n if (status === 'rejected') {\n return `The user rejected this payment request (payment_id: ${paymentId}).`\n }\n if (status === 'expired') {\n return `This payment request expired (payment_id: ${paymentId}).`\n }\n return `${label} is ${status}; next_action=${nextAction} (payment_id: ${paymentId}).`\n}\n\nexport function paymentStateFromRaw(\n label: string,\n raw: RawX402AuthorizeResponse | RawSignResponse,\n): PaymentStatusResult | null {\n if (!raw.payment_id || !raw.status) return null\n\n const phase = (raw.phase as PaymentPhase | undefined) ?? phaseForStatus(raw.status)\n const nextAction =\n (raw.next_action as PaymentNextAction | undefined) ?? nextActionForStatus(raw.status)\n if (!phase || !nextAction) return null\n\n const amount = raw.amount ?? raw.requested ?? ''\n const token = raw.token ?? ''\n const message =\n raw.message ??\n raw.error ??\n messageForState(label, raw.status, raw.payment_id, nextAction)\n\n return {\n paymentId: raw.payment_id,\n kind: raw.kind === 'payment_intent' ? 'payment_intent' : 'approval_request',\n rail: raw.rail ?? 'direct',\n status: raw.status === 'pending' ? 'pending_approval' : raw.status,\n phase,\n nextAction,\n amount,\n token,\n resourceUrl: raw.resource_url ?? null,\n merchantAddress: raw.merchant_address ?? raw.merchant_to ?? null,\n txHash: raw.tx_hash ?? null,\n expiresAt: raw.expires_at ?? '',\n chainId: raw.chain_id ?? 0,\n message,\n amountAtomic: raw.amount_atomic ?? raw.x402?.amount_atomic ?? raw.mpp?.amount_atomic ?? null,\n asset: raw.asset ?? raw.x402?.asset ?? raw.mpp?.asset ?? null,\n network: raw.network ?? raw.x402?.network ?? raw.mpp?.network ?? null,\n description: raw.description ?? raw.x402?.description ?? raw.mpp?.description ?? null,\n idempotencyKey: raw.idempotency_key ?? raw.x402?.idempotency_key ?? raw.mpp?.idempotency_key ?? null,\n x402: raw.x402\n ? {\n amountAtomic: raw.x402.amount_atomic ?? raw.amount_atomic ?? null,\n asset: raw.x402.asset ?? raw.asset ?? null,\n network: raw.x402.network ?? raw.network ?? null,\n resourceUrl: raw.x402.resource_url ?? raw.resource_url ?? null,\n merchantAddress: raw.x402.merchant_address ?? raw.merchant_address ?? raw.merchant_to ?? null,\n description: raw.x402.description ?? raw.description ?? null,\n idempotencyKey: raw.x402.idempotency_key ?? raw.idempotency_key ?? null,\n }\n : undefined,\n mpp: raw.mpp\n ? {\n amountAtomic: raw.mpp.amount_atomic ?? raw.amount_atomic ?? null,\n asset: raw.mpp.asset ?? raw.asset ?? null,\n network: raw.mpp.network ?? raw.network ?? null,\n resourceUrl: raw.mpp.resource_url ?? raw.resource_url ?? null,\n merchantAddress: raw.mpp.merchant_address ?? raw.merchant_address ?? raw.merchant_to ?? null,\n description: raw.mpp.description ?? raw.description ?? null,\n idempotencyKey: raw.mpp.idempotency_key ?? raw.idempotency_key ?? null,\n challengeId: raw.mpp.challenge_id ?? raw.challenge_id ?? null,\n }\n : undefined,\n }\n}\n\nexport function throwPaymentStateError(\n label: string,\n raw: RawX402AuthorizeResponse | RawSignResponse,\n): never {\n const statusCode = paymentStateStatusCode(raw.status)\n const state = paymentStateFromRaw(label, raw)\n\n if (state) {\n throw new HavenPaymentStateError(state.message, statusCode, state, raw)\n }\n\n if (raw.status === 'pending_approval') {\n throw new HavenApiError(\n `${label} exceeds the agent's on-chain budget and was declined; no approval is pending and none will arrive (payment_id: ${raw.payment_id}).`,\n statusCode,\n raw,\n )\n }\n\n if (raw.status === 'expired') {\n throw new HavenApiError(\n `${label} expired before it could be completed (payment_id: ${raw.payment_id}).`,\n statusCode,\n raw,\n )\n }\n\n const paymentId = raw.payment_id ? ` (payment_id: ${raw.payment_id})` : ''\n const message = raw.error ?? `${label} ${raw.status}${paymentId}`\n throw new HavenApiError(message, statusCode, raw)\n}\n","import { HavenError } from './types.js'\n\n/**\n * Where the PAID retry goes — and whether it may go there at all (#3097).\n *\n * A merchant's 402 challenge declares `resource.url`. Haven records that\n * declaration as the resource's identity (the binding message, the intent\n * row, the resume checks all compare against it), but the paid request —\n * the one carrying `PAYMENT-SIGNATURE` — must go to the URL the CALLER\n * actually asked for whenever one exists. The declaration is the merchant's\n * word about itself, not an instruction to the client: the Ampersend\n * sandbox declares `http://` for a resource it serves over `https` (live,\n * 2026-09-17; its `http://` answers 308 → https), and a client that adopted\n * it sent the signed header in clear on the first hop.\n *\n * Two rules, both pure, both pinned by tests:\n *\n * - `resolveX402RetryTarget`: the caller's request URL wins; the merchant's\n * `resource.url` is the fallback for callers that only hold the challenge\n * (the hosted pay-from-quote path). The result says which one it chose and\n * whether the two disagree, so a quote can surface the disagreement.\n * - `isSecureX402RetryTarget`: `https` always; `http` only to a target that\n * cannot leave the machine or the test bench — loopback addresses and the\n * RFC 2606/6761 reserved names (`.test`, `.localhost`, `.invalid`,\n * `.example`), which every fixture in this repo uses. A public `http://`\n * target is refused BEFORE a signed header is handed to a transport.\n */\nexport interface X402RetryTarget {\n /** The URL the paid request goes to. */\n url: string\n /** Which input produced it. */\n source: 'request' | 'resource'\n /**\n * True when the merchant's declared `resource.url` is not the caller's URL.\n * Absent (undefined) when nothing was compared — the caller named no URL\n * and the declaration was adopted as-is — so a consumer never reads\n * \"false\" as \"the merchant agrees with what you quoted\".\n */\n resourceUrlDiffersFromRequest?: boolean\n}\n\nexport function resolveX402RetryTarget(input: {\n requestUrl?: string | null\n resourceUrl: string\n}): X402RetryTarget {\n const requestUrl = input.requestUrl?.trim() || undefined\n if (requestUrl) {\n return {\n url: requestUrl,\n source: 'request',\n resourceUrlDiffersFromRequest: requestUrl !== input.resourceUrl,\n }\n }\n return { url: input.resourceUrl, source: 'resource' }\n}\n\nconst LOOPBACK_HOSTS = new Set(['localhost', '::1', '[::1]'])\nconst RESERVED_SUFFIXES = ['.test', '.localhost', '.invalid', '.example']\n// The whole 127/8 block, matched octet by octet. A string-prefix test on the\n// hostname (`startsWith('127.')`) is NOT this: `127.attacker.io` is an ordinary\n// registrable public name whose first label happens to be digits, and it would\n// have passed (haven-reviewer finding on #3112). `URL` already normalises the\n// exotic spellings (`0x7f.0.0.1`, `2130706433`) to dotted decimal before this\n// runs, so dotted decimal is the only form that reaches it.\nconst IPV4_LOOPBACK = /^127(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}$/\n\n/** True when a retry carrying a payment header may be sent to `url`. */\nexport function isSecureX402RetryTarget(url: string): boolean {\n let parsed: URL\n try {\n parsed = new URL(url)\n } catch {\n return false\n }\n if (parsed.protocol === 'https:') return true\n if (parsed.protocol !== 'http:') return false\n const host = parsed.hostname.toLowerCase()\n if (LOOPBACK_HOSTS.has(host) || IPV4_LOOPBACK.test(host)) return true\n return RESERVED_SUFFIXES.some((suffix) => host.endsWith(suffix))\n}\n\nexport const INSECURE_RETRY_TARGET_CODE = 'INSECURE_RETRY_TARGET'\n\n/** Refused before any signed header leaves: the paid retry would travel in clear. */\nexport class HavenInsecureRetryTargetError extends HavenError {\n constructor(public readonly url: string) {\n super(\n `Refusing to send a payment header to ${url}: the paid x402 retry must go to an https URL ` +\n '(or a loopback / reserved test host). The merchant\\'s challenge declared this resource URL; ' +\n 'retry with the https URL you quoted (pass it as `url`), and report a merchant whose ' +\n 'challenge downgrades the scheme.',\n INSECURE_RETRY_TARGET_CODE,\n 400,\n )\n this.name = 'HavenInsecureRetryTargetError'\n }\n}\n\nexport function assertSecureX402RetryTarget(url: string): void {\n if (!isSecureX402RetryTarget(url)) throw new HavenInsecureRetryTargetError(url)\n}\n","import type { X402McpTransport, X402PaymentRequired } from './types.js'\nimport { MerchantTimeoutError } from './types.js'\nimport { decodeBase64Json, encodeBase64Json } from './base64.js'\nimport { X402_PAYMENT_HEADER_NAMES, normalizePaymentRequired, x402PaymentHeaderNamesFor } from './x402.js'\nimport { assertSecureX402RetryTarget } from './x402-retry-target.js'\n\nexport const DEFAULT_MERCHANT_TIMEOUT = 300_000\nexport const MCP_NOTIFICATION_TIMEOUT = 10_000\nexport const MCP_PROTOCOL_VERSION = '2025-06-18'\nexport const MCP_ACCEPT = 'application/json, text/event-stream'\n\nconst MCP_CLIENT_INFO = { name: 'haven-sdk', version: '1' } as const\n\n/**\n * #3118: the official x402 MCP transport profile\n * (x402-foundation/x402 `specs/transports-v2/mcp.md`). A merchant following\n * it never answers HTTP 402: the challenge is a tool RESULT with\n * `isError: true` carrying the `PaymentRequired` object as\n * `structuredContent` (and `JSON.stringify` of it as the text content for\n * clients without structured-content support); the payment travels back in\n * the tools/call request's `params._meta[\"x402/payment\"]` as a JSON object\n * (the same envelope the `PAYMENT-SIGNATURE` header carries base64-encoded);\n * settlement comes back in `result._meta[\"x402/payment-response\"]`.\n *\n * Haven's HTTP-402-over-MCP layering (the Streamable-HTTP status code plus\n * `PAYMENT-REQUIRED` / `PAYMENT-SIGNATURE` / `PAYMENT-RESPONSE` headers) is a\n * valid, distinct integration and is retained unchanged; the profile below is\n * ADDED beside it. Delivery is dual: the header is always sent, and the\n * `_meta` object is added whenever the caller body is a `tools/call` request,\n * so a header-reading merchant and a `_meta`-reading merchant both see the\n * payment and neither has to be told which kind it is.\n */\nexport const MCP_X402_PAYMENT_META_KEY = 'x402/payment'\nexport const MCP_X402_PAYMENT_RESPONSE_META_KEY = 'x402/payment-response'\n/** The HTTP status an in-band (HTTP 200, `isError: true`) payment-required refusal is reported as. */\nexport const X402_RETRY_REJECTED_STATUS = 402\n\n/** The settlement object a profile merchant returns in `result._meta[\"x402/payment-response\"]`. */\nexport interface McpX402SettlementMeta {\n success: boolean\n transaction?: string\n network?: string\n payer?: string\n errorReason?: string\n}\n\n/**\n * #3171: the recovery data a merchant attaches to its unknown-session 404\n * (`-32001`) when it guarantees nothing was settled. Only this exact shape\n * licenses the SDK to re-initialize and resend the same payment header: the\n * guarantee is the merchant's, so it must be stated, never inferred from a\n * bare -32001.\n */\nexport const SESSION_NOT_FOUND_NEXT_ACTION = 'reinitialize_then_retry_same_payment_header'\n\nexport interface SessionNotFoundRecovery {\n reason: string\n settled: false\n next_action: typeof SESSION_NOT_FOUND_NEXT_ACTION\n}\n\nexport interface CapturedMerchantResponse {\n merchant_status: number\n merchant_status_text: string\n merchant_headers: Record<string, string>\n merchant_body: string\n}\n\ntype MerchantFetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>\n\nexport interface McpMerchantTransportOptions {\n merchantTimeout?: number\n fetch?: MerchantFetch\n}\n\n/**\n * Per-client MCP-over-HTTP merchant wire transport.\n *\n * This internal seam owns only protocol framing and bounded delivery. It does\n * not create payment authority: callers pass a public wallet address and an\n * already-signed, exact-context-bound payment header.\n */\nexport class McpMerchantTransport {\n private readonly merchantTimeout: number\n private readonly fetchImpl: MerchantFetch\n private requestId = 0\n\n constructor(options: McpMerchantTransportOptions = {}) {\n this.merchantTimeout = options.merchantTimeout ?? DEFAULT_MERCHANT_TIMEOUT\n // Resolve the global at call time, matching the former client helper and\n // preserving the SDK's established fetch-mocking/polyfill seam.\n this.fetchImpl = options.fetch ?? ((input, init) => globalThis.fetch(input, init))\n }\n\n /** Fetch a merchant with a settlement-sized timeout and caller cancellation. */\n async fetch(url: string, init: RequestInit = {}, timeoutMs = this.merchantTimeout): Promise<Response> {\n const timeoutSignal = AbortSignal.timeout(timeoutMs)\n const signal = init.signal ? AbortSignal.any([init.signal, timeoutSignal]) : timeoutSignal\n try {\n return await this.fetchImpl(url, { ...init, signal })\n } catch (err) {\n if (timeoutSignal.aborted) {\n throw new MerchantTimeoutError(`Merchant request timed out after ${timeoutMs}ms: ${url}`)\n }\n throw err\n }\n }\n\n /**\n * Establish an MCP Streamable-HTTP session. Any handshake failure degrades\n * to `undefined`, allowing the caller to fall back to plain x402.\n */\n async initialize(\n url: string,\n init?: RequestInit,\n wallet?: string,\n ): Promise<string | undefined> {\n try {\n const headers = new Headers(init?.headers)\n headers.set('Content-Type', 'application/json')\n headers.set('Accept', MCP_ACCEPT)\n if (wallet && !headers.has('x402-wallet')) headers.set('x402-wallet', wallet)\n\n const response = await this.fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: ++this.requestId,\n method: 'initialize',\n params: {\n protocolVersion: MCP_PROTOCOL_VERSION,\n capabilities: {},\n clientInfo: MCP_CLIENT_INFO,\n },\n }),\n })\n\n if (!response.ok) return undefined\n\n const sessionId = response.headers.get('mcp-session-id')\n if (!sessionId) return undefined\n\n const message = await this.readMessage(response)\n if (message && 'error' in message) return undefined\n\n await this.notifyInitialized(url, init, sessionId, wallet)\n return sessionId\n } catch {\n return undefined\n }\n }\n\n /** Add the MCP session and response-content negotiation headers. */\n withSessionHeaders(init: RequestInit | undefined, sessionId: string): RequestInit {\n const headers = new Headers(init?.headers)\n headers.set('mcp-session-id', sessionId)\n headers.set('Accept', MCP_ACCEPT)\n return { ...init, headers }\n }\n\n /** Read one JSON-RPC message from a JSON or SSE response without consuming it. */\n async readMessage(response: Response): Promise<Record<string, unknown> | undefined> {\n let text: string\n try {\n text = await response.clone().text()\n } catch {\n return undefined\n }\n\n if ((response.headers.get('content-type') ?? '').includes('text/event-stream')) {\n return selectJsonRpcResult(parseSseJsonRpcMessages(text))\n }\n\n try {\n return JSON.parse(text) as Record<string, unknown>\n } catch {\n return undefined\n }\n }\n\n /**\n * Collapse an MCP SSE response to the JSON-RPC result. Non-SSE and\n * unparseable responses pass through with their original body untouched.\n */\n async surfaceResult(response: Response): Promise<Response> {\n if (!(response.headers.get('content-type') ?? '').includes('text/event-stream')) {\n return response\n }\n\n let text: string\n try {\n text = await response.clone().text()\n } catch {\n return response\n }\n\n const message = selectJsonRpcResult(parseSseJsonRpcMessages(text))\n // #3155 review r3: collapse only a real JSON-RPC result or error. A stream\n // whose frames are none of those (a paid SSE resource that is not MCP)\n // would otherwise be reduced to its LAST frame — returned untouched instead.\n if (!message || !('result' in message || 'error' in message)) return response\n\n const body = 'result' in message ? message.result : message\n const headers = new Headers(response.headers)\n headers.set('content-type', 'application/json')\n headers.delete('content-length')\n headers.delete('mcp-session-id')\n\n return new Response(JSON.stringify(body), {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n }\n\n /** Detect MCP transport from the URL or Coinbase Bazaar extension. */\n async detect(\n url: string,\n paymentRequired: X402PaymentRequired,\n response: Response,\n ): Promise<X402McpTransport | undefined> {\n if (isMcpUrl(url)) return { handshakeRequired: true, source: 'path' }\n if (paymentRequired.extensions?.bazaar != null) {\n return { handshakeRequired: true, source: 'bazaar' }\n }\n if (await responseHasBazaarExtension(response)) {\n return { handshakeRequired: true, source: 'bazaar' }\n }\n return undefined\n }\n\n /** Identify the conventional Streamable-HTTP MCP path without probing it. */\n isMcpUrl(url: string): boolean {\n return isMcpUrl(url)\n }\n\n /** Detect Bazaar metadata without consuming the merchant response. */\n hasBazaarExtension(response: Response): Promise<boolean> {\n return responseHasBazaarExtension(response)\n }\n\n /**\n * Deliver an already-signed x402 header without changing the caller body.\n *\n * #2289: x402 v2 reads `PAYMENT-SIGNATURE`; v1 reads `X-PAYMENT`. Sending\n * only the legacy name meant a strict v2 merchant never saw the header —\n * indistinguishable, from the merchant's side, from sending no header at\n * all, while on the EIP-3009 bridge the funding leg had already moved the\n * money.\n *\n * #2341: WHICH names go on is per-payload, not always both — see\n * `x402PaymentHeaderNamesFor`. Both for EIP-3009; `PAYMENT-SIGNATURE` alone\n * for erc7710, whose header carries a whole delegation chain and answered\n * HTTP 431 when duplicated. The decision is made here rather than by the\n * caller so every path inherits it, and it is read from the payload rather\n * than passed in, because a flag a caller supplies is a flag a caller can\n * get wrong.\n *\n * Always `set`, never `append`, so a stale header on the caller's `init` is\n * replaced rather than added to — a merchant that reads the first of two\n * values would otherwise verify a superseded authorization. The name NOT\n * being sent is deleted for the same reason: on erc7710 a stale `X-PAYMENT`\n * left in place would be a superseded authorization we chose not to\n * overwrite, which is worse than the duplicate this change removes.\n */\n async deliverPayment(\n url: string,\n init: RequestInit | undefined,\n paymentHeader: string,\n ): Promise<Response> {\n // #3097: the ONE seam every paid retry crosses (plain HTTP, MCP, resume).\n // A signed header never leaves for a public http:// target.\n assertSecureX402RetryTarget(url)\n const headers = new Headers(init?.headers)\n const send = x402PaymentHeaderNamesFor(paymentHeader)\n for (const name of X402_PAYMENT_HEADER_NAMES) {\n if (send.includes(name)) headers.set(name, paymentHeader)\n else headers.delete(name)\n }\n // #3118: a `tools/call` body additionally carries the payment in\n // `params._meta[\"x402/payment\"]` (the official MCP profile). Any other\n // body is sent byte-for-byte as the caller gave it.\n return this.fetch(url, withMcpPaymentMeta({ ...init, headers }, paymentHeader))\n }\n\n /**\n * #3171: deliver the payment; if the merchant answers its unknown-session\n * 404 WITH the settled-nothing recovery data, re-initialize once and resend\n * the SAME header on the new session. The merchant's own guarantee (#1578:\n * the session guard runs before its payment gate) is what makes the resend\n * safe — a bare -32001, or any other 404, is returned to the caller\n * untouched (body re-wrapped, since reading it consumed the stream). One\n * recovery only: a second 404 is the answer.\n */\n async deliverPaymentRecoveringSession(\n url: string,\n init: RequestInit | undefined,\n paymentHeader: string,\n reinitialize: () => Promise<string | undefined>,\n ): Promise<Response> {\n const first = await this.deliverPayment(url, init, paymentHeader)\n if (first.status !== 404) return first\n let text: string\n try {\n text = await first.clone().text()\n } catch {\n return first\n }\n if (!sessionNotFoundRecovery(text)) return first\n const sessionId = await reinitialize()\n if (!sessionId) return first\n return this.deliverPayment(url, this.withSessionHeaders(init, sessionId), paymentHeader)\n }\n\n /**\n * #3118: read a native MCP payment-required tool result from a response\n * WITHOUT consuming it — JSON or SSE framed. `undefined` for anything that\n * is not an `isError: true` tool result carrying a valid `PaymentRequired`\n * (structured content first, text fallback second), so an ordinary tool\n * error, a successful result that merely resembles a challenge, or an\n * unparseable body is never mistaken for a payment demand.\n */\n async extractToolResultChallenge(response: Response, init?: RequestInit): Promise<X402PaymentRequired | undefined> {\n const toolResult = await this.readToolResult(response, init)\n return toolResult ? extractMcpPaymentRequired(toolResult) : undefined\n }\n\n /**\n * #3118: the tool RESULT a response carries, read WITHOUT consuming it, or\n * `undefined`. Only a JSON or SSE body is read at all (#3155 review S2):\n * a non-402 answer used to be returned untouched, and buffering an\n * arbitrary body — a streaming or binary paid resource — to look for a\n * challenge would block the caller until the stream ended or the merchant\n * timeout fired. A merchant that speaks JSON-RPC declares one of those two\n * content types.\n */\n async readToolResult(response: Response, init?: RequestInit): Promise<Record<string, unknown> | undefined> {\n // #3155 partner review: a native challenge can only answer a JSON-RPC\n // `tools/call` request, so when the request is known and is not one, the\n // body is not read at all — a plain `haven.fetch()` of a JSON API pays\n // nothing for this probe.\n if (init !== undefined && !isJsonRpcToolsCallBody(init.body)) return undefined\n const contentType = (response.headers.get('content-type') ?? '').toLowerCase()\n if (!contentType.includes('application/json') && !contentType.includes('text/event-stream')) return undefined\n return mcpToolResultOf(await this.readMessage(response))\n }\n\n private async notifyInitialized(\n url: string,\n init: RequestInit | undefined,\n sessionId: string,\n wallet?: string,\n ): Promise<void> {\n try {\n const headers = new Headers(init?.headers)\n headers.set('Content-Type', 'application/json')\n headers.set('Accept', MCP_ACCEPT)\n headers.set('mcp-session-id', sessionId)\n if (wallet && !headers.has('x402-wallet')) headers.set('x402-wallet', wallet)\n\n await this.fetch(\n url,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }),\n },\n MCP_NOTIFICATION_TIMEOUT,\n )\n } catch {\n // The session is established. Notification delivery remains best-effort.\n }\n }\n}\n\n/**\n * #3118: the tool RESULT inside whatever shape a merchant body arrived in —\n * a raw JSON-RPC envelope (`{ jsonrpc, id, result }`), or an already-surfaced\n * result (`surfaceResult` collapses SSE to the bare `result`). `undefined`\n * when the value is neither.\n */\nexport function mcpToolResultOf(value: unknown): Record<string, unknown> | undefined {\n if (!isRecord(value)) return undefined\n if ('jsonrpc' in value) {\n return isRecord(value.result) ? value.result : undefined\n }\n if ('isError' in value || Array.isArray(value.content) || isRecord(value._meta)) return value\n return undefined\n}\n\n/**\n * #3118: the `PaymentRequired` a profile merchant put in an `isError: true`\n * tool result. `structuredContent` is preferred; the first text content item\n * that parses as JSON is the fallback. Both go through\n * `normalizePaymentRequired`, so a challenge with no payable `accepts` entry\n * is not a challenge at all.\n */\nexport function extractMcpPaymentRequired(toolResult: Record<string, unknown>): X402PaymentRequired | undefined {\n if (toolResult.isError !== true) return undefined\n if (isRecord(toolResult.structuredContent)) {\n const parsed = normalizePaymentRequired(toolResult.structuredContent)\n if (parsed) return parsed\n }\n if (Array.isArray(toolResult.content)) {\n for (const item of toolResult.content) {\n if (!isRecord(item) || item.type !== 'text' || typeof item.text !== 'string') continue\n let candidate: unknown\n try {\n candidate = JSON.parse(item.text)\n } catch {\n continue\n }\n const parsed = normalizePaymentRequired(candidate)\n if (parsed) return parsed\n }\n }\n return undefined\n}\n\n/**\n * #3118: the settlement object in `result._meta[\"x402/payment-response\"]`,\n * or `undefined` when the result carries none (or one without a boolean\n * `success`, which is not a settlement statement the SDK will act on).\n */\nexport function mcpSettlementFromToolResult(toolResult: Record<string, unknown>): McpX402SettlementMeta | undefined {\n const meta = toolResult._meta\n if (!isRecord(meta)) return undefined\n const settlement = meta[MCP_X402_PAYMENT_RESPONSE_META_KEY]\n if (!isRecord(settlement) || typeof settlement.success !== 'boolean') return undefined\n return {\n success: settlement.success,\n ...(typeof settlement.transaction === 'string' ? { transaction: settlement.transaction } : {}),\n ...(typeof settlement.network === 'string' ? { network: settlement.network } : {}),\n ...(typeof settlement.payer === 'string' ? { payer: settlement.payer } : {}),\n ...(typeof settlement.errorReason === 'string' ? { errorReason: settlement.errorReason } : {}),\n }\n}\n\n/**\n * #3118: add `params._meta[\"x402/payment\"]` to a `tools/call` request body.\n * The value is the decoded payment envelope (the header is base64 JSON of\n * exactly this object). Unrelated `_meta` keys, `arguments`, the id and the\n * method are preserved. Any body that is not a string-encoded JSON-RPC\n * `tools/call` request — form data, a stream, another method, no body — is\n * returned untouched, as is one whose header does not decode.\n *\n * The `tools/call` body IS re-serialised (`JSON.parse` → `JSON.stringify`),\n * so it is semantically, not byte-, identical: an integer above 2^53 in the\n * id or arguments is rounded by JavaScript's number type, and a caller-set\n * `Content-Length` header would go stale (the runtime recomputes it for a\n * string body). Neither half of the dual delivery is size-bounded here; on\n * erc7710 the decoded envelope is smaller than its base64 header, and only\n * the header half counts against the 16 KB header ceiling (#2341). On erc7710\n * the dual delivery therefore sends the delegation chain twice (header and\n * body) — stated, accepted, and the partner reviewer's to weigh.\n */\nexport function withMcpPaymentMeta(init: RequestInit, paymentHeader: string): RequestInit {\n const request = parseJsonRpcToolsCall(init.body)\n if (!request) return init\n let envelope: unknown\n try {\n envelope = decodeBase64Json<unknown>(paymentHeader)\n } catch {\n return init\n }\n if (!isRecord(envelope)) return init\n const params = request.params\n const existingMeta = isRecord(params._meta) ? params._meta : {}\n return {\n ...init,\n body: JSON.stringify({\n ...request,\n params: { ...params, _meta: { ...existingMeta, [MCP_X402_PAYMENT_META_KEY]: envelope } },\n }),\n }\n}\n\n/**\n * #3118: the `_meta` settlement re-encoded exactly as a `PAYMENT-RESPONSE`\n * header would carry it (base64 JSON), so the evidence report's receipt\n * payload goes through the one existing decoder whichever form arrived.\n */\nexport function encodeMcpSettlementReceipt(settlement: McpX402SettlementMeta): string {\n return encodeBase64Json(settlement)\n}\n\n/** #3155: the request body parsed as a JSON-RPC `tools/call` with an object `params`, else undefined. */\nfunction parseJsonRpcToolsCall(body: unknown): (Record<string, unknown> & { params: Record<string, unknown> }) | undefined {\n if (typeof body !== 'string') return undefined\n let request: unknown\n try {\n request = JSON.parse(body)\n } catch {\n return undefined\n }\n if (!isRecord(request) || request.method !== 'tools/call' || !isRecord(request.params)) return undefined\n return request as Record<string, unknown> & { params: Record<string, unknown> }\n}\n\n/**\n * #3155: whether a request body is a JSON-RPC `tools/call` — the only request a\n * native challenge can answer. Decided boundaries: a `Uint8Array`/`Buffer`\n * body is NOT recognised (the quote path's `snapshotRequestBody` refuses\n * non-string bodies too), and neither is a JSON-RPC batch array, a\n * `resources/read`, or a `tools/call` without an object `params` — a paid\n * request in any of those shapes is returned as an ordinary answer and no\n * payment is created (safe direction; state it, do not widen it silently).\n */\nexport function isJsonRpcToolsCallBody(body: unknown): boolean {\n return parseJsonRpcToolsCall(body) !== undefined\n}\n\n/**\n * #3171: parse a merchant 404 body for the unknown-session recovery data.\n * `undefined` for anything else — a different code, a missing or\n * contradicting `data`, a non-JSON body.\n */\nexport function sessionNotFoundRecovery(body: string): SessionNotFoundRecovery | undefined {\n let parsed: unknown\n try {\n parsed = JSON.parse(body)\n } catch {\n return undefined\n }\n if (!isRecord(parsed) || !isRecord(parsed.error)) return undefined\n if (parsed.error.code !== -32001) return undefined\n const data = parsed.error.data\n if (!isRecord(data)) return undefined\n if (data.settled !== false || data.next_action !== SESSION_NOT_FOUND_NEXT_ACTION) return undefined\n return {\n reason: typeof data.reason === 'string' ? data.reason : 'session_expired',\n settled: false,\n next_action: SESSION_NOT_FOUND_NEXT_ACTION,\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Consume and preserve every diagnostic field of a failed merchant response. */\nexport async function captureMerchantResponse(\n response: Response,\n): Promise<CapturedMerchantResponse> {\n const merchant_body = await response.text().catch(() => '')\n return {\n merchant_status: response.status,\n merchant_status_text: response.statusText,\n merchant_headers: Object.fromEntries(response.headers.entries()),\n merchant_body,\n }\n}\n\nfunction isMcpUrl(url: string): boolean {\n try {\n return new URL(url).pathname.replace(/\\/+$/, '').endsWith('/mcp')\n } catch {\n return /\\/mcp(?:[/?#]|$)/.test(url)\n }\n}\n\nasync function responseHasBazaarExtension(response: Response): Promise<boolean> {\n try {\n const body = (await response.clone().json()) as { extensions?: { bazaar?: unknown } } | null\n return body?.extensions?.bazaar != null\n } catch {\n return false\n }\n}\n\nfunction parseSseJsonRpcMessages(text: string): Array<Record<string, unknown>> {\n const messages: Array<Record<string, unknown>> = []\n let dataLines: string[] = []\n\n const flush = (): void => {\n if (dataLines.length === 0) return\n try {\n messages.push(JSON.parse(dataLines.join('\\n')) as Record<string, unknown>)\n } catch {\n // Ignore keep-alives and non-JSON data frames.\n }\n dataLines = []\n }\n\n for (const line of text.split(/\\r?\\n/)) {\n if (line === '') {\n flush()\n continue\n }\n if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^ /, ''))\n }\n flush()\n\n return messages\n}\n\nfunction selectJsonRpcResult(\n messages: Array<Record<string, unknown>>,\n): Record<string, unknown> | undefined {\n return messages.find((message) => 'result' in message || 'error' in message) ?? messages.at(-1)\n}\n","import { ethers } from 'ethers'\nimport type { RawPaymentParties } from './types.js'\n\n/**\n * Verifiable payment receipts.\n *\n * A self-contained proof bundle for a settled Haven payment that anyone can\n * verify **independently of Haven**. The anchor is the agent delegate's\n * signature over the on-chain transfer hash: recover the signer and confirm it\n * is the agent's delegate, and you have cryptographic proof the agent authorised\n * exactly this transfer — no need to trust Haven's backend. The on-chain\n * `txHash` is the settlement source of truth (verify on any explorer).\n *\n * This lives in the SDK so agents and users can verify receipts client-side\n * with zero Haven trust.\n */\nexport const RECEIPT_VERSION = 'haven-receipt-1'\n\nexport interface PaymentReceipt {\n version: typeof RECEIPT_VERSION\n paymentId: string\n payment: {\n token: string\n tokenAddress: string\n amount: string\n amountSek: string | null\n recipient: string\n /** The payer's smart-account address. */\n account: string\n /**\n * #2960: one party vocabulary for \"who paid\", additive alongside `account`\n * above (which is `parties.treasury_account` only). Optional: a server\n * from before #2960 emits neither. Ignored by `verifyPaymentReceipt`,\n * which reads only `authorization`.\n */\n parties?: RawPaymentParties\n chainId: number\n settledAt: string | null\n resourceUrl: string | null\n }\n /** The agent's cryptographic authorisation — what makes the receipt verifiable. */\n authorization: {\n delegate: string\n signHash: string\n signature: string | null\n }\n onChain: {\n txHash: string | null\n chainId: number\n }\n}\n\nexport type ReceiptVerification =\n | { verified: true; recoveredSigner: string }\n | {\n verified: false\n reason: 'missing_signature' | 'bad_signature' | 'signer_mismatch'\n recoveredSigner?: string\n }\n\n/** Default ECDSA recovery (raw ecrecover over the hash, no message prefix). */\nfunction defaultRecover(hash: string, signature: string): string {\n return ethers.recoverAddress(hash, signature)\n}\n\n/**\n * Verify a receipt independently: recover the signer from the authorisation and\n * confirm it is the agent's delegate. Pure — `recover` is injectable but\n * defaults to standard ECDSA recovery, so this runs anywhere (no Haven backend).\n */\nexport function verifyPaymentReceipt(\n receipt: PaymentReceipt,\n recover: (hash: string, signature: string) => string = defaultRecover,\n): ReceiptVerification {\n const { delegate, signHash, signature } = receipt.authorization\n if (!signature) return { verified: false, reason: 'missing_signature' }\n\n let recovered: string\n try {\n recovered = recover(signHash, signature)\n } catch {\n return { verified: false, reason: 'bad_signature' }\n }\n\n if (recovered.toLowerCase() !== delegate.toLowerCase()) {\n return { verified: false, reason: 'signer_mismatch', recoveredSigner: recovered }\n }\n return { verified: true, recoveredSigner: recovered }\n}\n","import { verifyPaymentReceipt, type PaymentReceipt, type ReceiptVerification } from './receipt.js'\nimport type {\n AgentPaymentWarning,\n HavenAgent,\n HavenAgentAllowanceSummary,\n HavenAgentReadiness,\n HavenAgentSummary,\n HavenAllowanceSummary,\n HavenBalanceCoverage,\n HavenPaymentReceipt,\n PaymentStatusResult,\n PostPurchaseAllowanceSummary,\n RawHavenAgent,\n RawHavenAllowanceSummary,\n RawHavenBalanceCoverage,\n RawHavenPaymentReceiptsResponse,\n HavenPaymentReceiptsPage,\n} from './types.js'\nimport { AgentPaymentWarningCode } from './types.js'\nimport { HavenApiTransport } from './haven-api-transport.js'\nimport { mapPaymentReceipt } from './payment-mappers.js'\nimport { resolveTokenFromAddress } from './x402.js'\n\nexport type PaymentStatusReader = (paymentId: string) => Promise<PaymentStatusResult>\n\nexport interface AccountReadsOptions {\n transport: HavenApiTransport\n getPaymentStatus: PaymentStatusReader\n}\n\nfunction safeBigInt(value: string): bigint {\n try {\n return BigInt(value)\n } catch {\n return 0n\n }\n}\n\nfunction formatAtomicAmount(atomic: bigint, decimals: number): string {\n if (atomic < 0n) return '0.0'\n const value = atomic.toString().padStart(decimals + 1, '0')\n const whole = value.slice(0, value.length - decimals) || '0'\n const fraction = value.slice(value.length - decimals).replace(/0+$/, '') || '0'\n return `${whole}.${fraction}`\n}\n\nfunction deriveReadiness(\n status: string,\n allowances: ReadonlyArray<{ remainingAtomic: string }>,\n): HavenAgentReadiness {\n if (status !== 'active') return 'revoked'\n return allowances.some((allowance) => safeBigInt(allowance.remainingAtomic) > 0n)\n ? 'ready'\n : 'needs_approval'\n}\n\n/**\n * #3128: the ONE function behind every `remainingDisplay` the SDK emits —\n * `HavenAllowance.remainingDisplay` and the bootstrap summary's field are the\n * same call on the same inputs.\n */\nexport function formatRemainingDisplay(tokenAddress: string, tokenSymbol: string, remainingAtomic: string): string {\n const token = resolveTokenFromAddress(tokenAddress)\n return token\n ? `${formatAtomicAmount(safeBigInt(remainingAtomic), token.decimals)} ${tokenSymbol}`\n : `${remainingAtomic} ${tokenSymbol} (atomic; unknown decimals)`\n}\n\n/**\n * Internal read-only account boundary for HavenClient.\n *\n * It owns authenticated account/allowance/receipt reads and intentionally has\n * no signer, merchant delivery, or payment-state mutation capability. Exported\n * from this module for direct tests and composition only; it is not exported by\n * the SDK entrypoint.\n */\nexport class AccountReads {\n private readonly transport: HavenApiTransport\n private readonly getPaymentStatus: PaymentStatusReader\n private agentInFlight: Promise<HavenAgent> | null = null\n\n constructor(options: AccountReadsOptions) {\n this.transport = options.transport\n this.getPaymentStatus = options.getPaymentStatus\n }\n\n async getAgent(): Promise<HavenAgent> {\n if (this.agentInFlight) return this.agentInFlight\n const request = this.fetchAgent()\n this.agentInFlight = request\n request.finally(() => {\n this.agentInFlight = null\n }).catch(() => {})\n return request\n }\n\n async getAgentSummary(): Promise<HavenAgentSummary> {\n const [agent, allowanceSummary] = await Promise.all([this.getAgent(), this.getAllowances()])\n // #3128: every field here is the HavenAllowance's own (or, for the display\n // string, derived by the same function `getAllowances` used), so the two\n // reads cannot disagree for the same fixture.\n const allowances: HavenAgentAllowanceSummary[] = allowanceSummary.allowances.map((allowance) => {\n return {\n id: allowance.id,\n tokenSymbol: allowance.tokenSymbol,\n tokenAddress: allowance.tokenAddress,\n remainingAtomic: allowance.onchain.remaining,\n remainingDisplay: allowance.remainingDisplay,\n configuredAmount: allowance.configuredAmount,\n resetPeriodMin: allowance.resetPeriodMin,\n isResetPending: allowance.onchain.isResetPending,\n }\n })\n const readiness = deriveReadiness(agent.status, allowances)\n return { ...agent, readiness, spend_authority_readiness: readiness, allowances }\n }\n\n async getAllowances(): Promise<HavenAllowanceSummary> {\n const raw = await this.transport.get<RawHavenAllowanceSummary>('/machine-payments/allowances')\n return {\n agentId: raw.agent_id,\n // `account_address` is required on the wire contract, so the declared\n // type stays `string`; a server that omits it is off-contract and the\n // cast is the one place that case is allowed through as `undefined`\n // rather than a fabricated `''` (a present-but-blank address downstream\n // — the hosted MCP output spreads this object, and the sweep uses it as\n // a destination).\n accountAddress: raw.account_address as string,\n delegateAddress: raw.delegate_address,\n chainId: raw.chain_id,\n allowances: raw.allowances.map((allowance) => ({\n id: allowance.id,\n tokenAddress: allowance.token_address,\n tokenSymbol: allowance.token_symbol,\n configuredAmount: allowance.configured_amount,\n resetPeriodMin: allowance.reset_period_min,\n remainingDisplay: formatRemainingDisplay(allowance.token_address, allowance.token_symbol, allowance.onchain.remaining),\n onchain: {\n amount: allowance.onchain.amount,\n spent: allowance.onchain.spent,\n remaining: allowance.onchain.remaining,\n effectiveSpent: allowance.onchain.effective_spent,\n resetTimeMin: allowance.onchain.reset_time_min,\n lastResetMin: allowance.onchain.last_reset_min,\n nonce: allowance.onchain.nonce,\n isResetPending: allowance.onchain.is_reset_pending,\n remainingIsFromChain: allowance.onchain.remaining_is_from_chain,\n },\n })),\n }\n }\n\n /**\n * #3126 — the sufficiency signal behind {@link HavenBalanceCoverage}.\n *\n * Deliberately NOT a balance read: the endpoint answers whether the\n * account HOLDS at least the checked amount, as `covered\n * true/false/null`, and never returns the balance itself. The camelCase\n * mapping is permissive (raw fields flow through; the server owns the\n * wire shape, pinned by the backend's `expectMatchesSpec` assertion), so\n * an older server that has not deployed the endpoint surfaces its 404 as\n * a thrown error rather than a fabricated answer.\n */\n async checkFunds(input: { token: string; amountAtomic: string }): Promise<HavenBalanceCoverage> {\n const query = `token=${encodeURIComponent(input.token)}&amount_atomic=${encodeURIComponent(input.amountAtomic)}`\n const raw = await this.transport.get<RawHavenBalanceCoverage>(\n `/machine-payments/balance-coverage?${query}`,\n )\n return {\n covered: raw.covered,\n ...(raw.coverage_error !== undefined ? { coverageError: raw.coverage_error } : {}),\n chainId: raw.chain_id,\n tokenAddress: raw.token_address,\n tokenSymbol: raw.token_symbol,\n checkedAmountAtomic: raw.checked_amount_atomic,\n budgetRemainingAtomic: raw.budget_remaining_atomic,\n ...(raw.budget_remaining_is_from_chain !== undefined\n ? { budgetRemainingIsFromChain: raw.budget_remaining_is_from_chain }\n : {}),\n }\n }\n\n async getPostPurchaseAllowanceSummary(paymentId: string): Promise<{\n allowance: PostPurchaseAllowanceSummary | null\n warnings: AgentPaymentWarning[]\n payment: PaymentStatusResult | null\n }> {\n const unavailable = (detail: string, payment: PaymentStatusResult | null = null) => ({\n payment,\n allowance: null,\n warnings: [{\n code: AgentPaymentWarningCode.AllowanceCheckUnavailable,\n message: `Could not read the post-purchase allowance/budget for payment ${paymentId} (${detail}). ` +\n 'The payment itself succeeded — the on-chain policy remains the actual spend gate; this ' +\n 'only affects the remaining-budget figure reported here.',\n }],\n })\n const [statusResult, agentResult, allowanceResult] = await Promise.allSettled([\n this.getPaymentStatus(paymentId), this.getAgent(), this.getAllowances(),\n ])\n if (statusResult.status === 'rejected') {\n return unavailable(statusResult.reason instanceof Error ? statusResult.reason.message : String(statusResult.reason))\n }\n const payment = statusResult.value\n if (agentResult.status === 'rejected') {\n return unavailable(agentResult.reason instanceof Error ? agentResult.reason.message : String(agentResult.reason), payment)\n }\n if (allowanceResult.status === 'rejected') {\n return unavailable(allowanceResult.reason instanceof Error ? allowanceResult.reason.message : String(allowanceResult.reason), payment)\n }\n try {\n const tokenAddress = payment.asset ?? payment.x402?.asset ?? null\n if (!tokenAddress) return unavailable('the settled payment does not carry a resolvable token address', payment)\n const match = allowanceResult.value.allowances.find(\n (allowance) => allowance.tokenAddress.toLowerCase() === tokenAddress.toLowerCase(),\n )\n if (!match) return unavailable('no allowance/budget row matches the settled token', payment)\n const token = resolveTokenFromAddress(match.tokenAddress)\n const remainingDisplay = token\n ? `${formatAtomicAmount(safeBigInt(match.onchain.remaining), token.decimals)} ${match.tokenSymbol}`\n : undefined\n const rail = agentResult.value.executionRail\n return {\n payment,\n allowance: {\n rail,\n remaining_atomic: match.onchain.remaining,\n ...(remainingDisplay ? { remaining_display: remainingDisplay } : {}),\n token_symbol: match.tokenSymbol,\n token_address: match.tokenAddress,\n reset_period: match.resetPeriodMin,\n source: rail === 'delegation' ? 'active_delegations' : 'allowance_module',\n },\n warnings: [],\n }\n } catch (error) {\n return unavailable(error instanceof Error ? error.message : String(error))\n }\n }\n\n /** The first page's receipts as a bare array — the pre-#3128 shape, kept for callers that never page. */\n async listReceipts(options: { limit?: number } = {}): Promise<HavenPaymentReceipt[]> {\n return (await this.listReceiptsPage(options)).receipts\n }\n\n /** #3128: one page with `total`, `hasMore` and `nextCursor` — see {@link HavenPaymentReceiptsPage}. */\n async listReceiptsPage(options: { limit?: number; cursor?: string } = {}): Promise<HavenPaymentReceiptsPage> {\n const params = new URLSearchParams()\n if (options.limit) params.set('limit', String(options.limit))\n if (options.cursor) params.set('cursor', options.cursor)\n const query = params.size > 0 ? `?${params.toString()}` : ''\n const raw = await this.transport.get<RawHavenPaymentReceiptsResponse>(`/machine-payments/receipts${query}`)\n return {\n receipts: raw.receipts.map(mapPaymentReceipt),\n total: typeof raw.total === 'number' ? raw.total : null,\n hasMore: typeof raw.has_more === 'boolean' ? raw.has_more : null,\n nextCursor: typeof raw.next_cursor === 'string' ? raw.next_cursor : null,\n }\n }\n\n async getReceipt(paymentId: string): Promise<{ receipt: PaymentReceipt; verification: ReceiptVerification }> {\n const { receipt } = await this.transport.get<{ receipt: PaymentReceipt }>(`/payments/${paymentId}/receipt`)\n return { receipt, verification: verifyPaymentReceipt(receipt) }\n }\n\n private async fetchAgent(): Promise<HavenAgent> {\n const raw = await this.transport.get<RawHavenAgent>('/machine-payments/agent')\n return {\n id: raw.id,\n name: raw.name,\n status: raw.status,\n // See the comment on `getAllowances` above: `account_address` is\n // required on the wire contract, so an omission here is off-contract\n // and comes through as `undefined` rather than a fabricated `''`.\n accountAddress: raw.account_address as string,\n delegateAddress: raw.delegate_address,\n chainId: raw.chain_id,\n executionRail: raw.execution_rail === 'delegation' ? 'delegation' : 'legacy',\n }\n }\n}\n","import { ethers } from 'ethers'\n\nexport function createJsonRpcProvider(url: string): ethers.JsonRpcProvider {\n return new ethers.JsonRpcProvider(url)\n}\n\nexport function createWallet(privateKey: string, provider: ethers.JsonRpcProvider): ethers.Wallet {\n return new ethers.Wallet(privateKey, provider)\n}\n\n/**\n * `runner` is a `ContractRunner`, not a `Signer`: a read-only call such as\n * `balanceOf` only needs a provider, and requiring a signer would have forced\n * the #1521 balance check to construct a wallet it never uses.\n */\nexport function createErc20Contract(\n address: string,\n abi: readonly string[],\n runner: ethers.ContractRunner,\n): ethers.Contract {\n return new ethers.Contract(address, abi as string[], runner)\n}\n","import { createErc20Contract, createJsonRpcProvider, createWallet } from './provider.js'\nimport { sweepUsdcAddress, isSweepableChain, type SweepAuthorization, type SweepPrepareResponse, type SweepSubmitResponse } from './sweep.js'\nimport { DEFAULT_CONFIRMATION_TIMEOUT_MS, HavenApiError, HavenSigningError, type HavenAgent, type SweepConfirmation, type SweepResult } from './types.js'\nimport type { HavenApiTransport } from './haven-api-transport.js'\n\n/** The shape of an ethers v6 `TransactionResponse` this module actually uses. */\ninterface SweepTx {\n hash: string\n wait: (confirmations?: number, timeoutMs?: number) => Promise<{ hash: string } | null>\n}\n\n/**\n * Did a confirmation wait expire, as opposed to fail? (#1756)\n *\n * ethers v6 rejects with `code: 'TIMEOUT'` when the deadline passed and\n * `code: 'CALL_EXCEPTION'` when the transaction mined and reverted. Only the\n * first is \"still in flight\" — collapsing them is the same defect this fix\n * exists to remove, one layer out.\n *\n * The one assumption: the code is read off the error's OWN `code` property.\n * If a future ethers version nests it (e.g. under `info.error.code`) this\n * predicate silently stops recognising timeouts and every expiry throws\n * again. That fails loudly in the tests above — `neverMinesWait()` drives a\n * real `code: 'TIMEOUT'` rejection — so the shape is pinned, not assumed.\n */\nfunction isWaitTimeout(err: unknown): boolean {\n return (err as { code?: unknown } | null)?.code === 'TIMEOUT'\n}\n\n/**\n * Wait for one sweep transfer, bounded (#1756).\n *\n * Before this, both legs called `wait(1)` — which passes CONFIRMATIONS, not a\n * timeout, so it was as unbounded as a bare `wait()` while reading like a\n * deliberate choice. A fee-stuck sweep hung the calling agent forever, with no\n * error and no way to learn the hash it was waiting on.\n *\n * Expiry RETURNS `unconfirmed` rather than throwing. The backend's equivalents\n * (#1722 / #1735 / #1742) can leave a stuck transaction to a durable outbound\n * record and a bump worker; this code runs on the user's machine with no queue\n * behind it, so the CALLER is the only possible owner of a stuck transfer —\n * and throwing would destroy the one thing that owner needs, the tx hash.\n *\n * Everything that is not a timeout still throws, unchanged: a revert is a\n * revert.\n */\nasync function waitForSweepTx(tx: SweepTx): Promise<{ txHash: string; confirmation: SweepConfirmation }> {\n let receipt: { hash: string } | null\n try {\n receipt = await tx.wait(1, DEFAULT_CONFIRMATION_TIMEOUT_MS)\n } catch (err) {\n if (!isWaitTimeout(err)) throw err\n return { txHash: tx.hash, confirmation: 'unconfirmed' }\n }\n // A null receipt is \"no receipt yet\", never \"confirmed\" — the pre-#1756 code\n // substituted the broadcast hash here and reported the transfer as done.\n if (!receipt) return { txHash: tx.hash, confirmation: 'unconfirmed' }\n return { txHash: receipt.hash, confirmation: 'confirmed' }\n}\n\nexport class DelegateSweepApi {\n constructor(private readonly options: { transport: Pick<HavenApiTransport, 'post'>; delegateKey?: string; chainRpcs: Record<number, string>; getAgent: () => Promise<HavenAgent>; buildExplorerUrl: (chainId: number, hash: string) => string }) {}\n async sweepDelegate(): Promise<SweepResult> {\n if (!this.options.delegateKey) throw new HavenSigningError('delegateKey is required for sweepDelegate.')\n const agent = await this.options.getAgent()\n if (!agent.delegateAddress) throw new HavenApiError('Agent has no delegate address.', 422)\n const rpcUrl = this.options.chainRpcs[agent.chainId]\n if (!rpcUrl) throw new HavenApiError(`chainRpcs[${agent.chainId}] must be configured to sweep the delegate wallet.`, 422)\n const provider = createJsonRpcProvider(rpcUrl)\n const wallet = createWallet(this.options.delegateKey, provider)\n const transfers: SweepResult['transfers'] = []\n if (isSweepableChain(agent.chainId)) {\n const contract = createErc20Contract(sweepUsdcAddress(agent.chainId), ['function balanceOf(address) view returns (uint256)', 'function transfer(address to, uint256 amount) returns (bool)'], wallet)\n const balance = await contract.balanceOf(agent.delegateAddress) as bigint\n if (balance > 0n) { const tx = await contract.transfer(agent.accountAddress, balance); const { txHash, confirmation } = await waitForSweepTx(tx as SweepTx); transfers.push({ asset: 'USDC', amount: format(balance, 6), amountAtomic: balance.toString(), txHash, explorerUrl: this.options.buildExplorerUrl(agent.chainId, txHash), confirmation }) }\n }\n // Reached even when the USDC leg came back `unconfirmed`: a stuck ERC-20\n // transfer must not strand the native balance this sweep also exists to\n // recover (#1756). Before the bound, it did — the ETH leg never ran.\n const balance = await provider.getBalance(agent.delegateAddress)\n if (balance > 0n) { const fee = await provider.getFeeData(); const send = balance - ((fee.maxFeePerGas ?? fee.gasPrice ?? 1_000_000n) * 21_000n * 2n); if (send > 0n) { const tx = await wallet.sendTransaction({ to: agent.accountAddress, value: send }); const { txHash, confirmation } = await waitForSweepTx(tx as SweepTx); transfers.push({ asset: 'ETH', amount: format(send, 18), amountAtomic: send.toString(), txHash, explorerUrl: this.options.buildExplorerUrl(agent.chainId, txHash), confirmation }) } }\n return { fromAddress: agent.delegateAddress, toAddress: agent.accountAddress, chainId: agent.chainId, transfers, unconfirmed: transfers.some((t) => t.confirmation === 'unconfirmed') }\n }\n prepareSweep(): Promise<SweepPrepareResponse> { return this.options.transport.post('/machine-payments/sweep/prepare', {}) }\n submitSweep(authorization: SweepAuthorization, signature: string): Promise<SweepSubmitResponse> { return this.options.transport.post('/machine-payments/sweep/submit', { authorization, signature }) }\n}\nfunction format(value: bigint, decimals: number): string { const raw = value.toString().padStart(decimals + 1, '0'); return `${raw.slice(0, -decimals) || '0'}.${raw.slice(-decimals).replace(/0+$/, '') || '0'}` }\n","import {\n AgentPaymentNextAction,\n HavenApiError,\n HavenPaymentStateError,\n} from './types.js'\nimport type {\n PaymentStatusResult,\n X402McpTransport,\n X402PaymentOption,\n X402PaymentRequired,\n X402Quote,\n X402Receipt,\n X402RequestSnapshot,\n X402ResumeState,\n} from './types.js'\nimport {\n buildX402IdempotencyKey,\n isErc7710Option,\n resolveTokenFromAddress,\n selectErc7710PaymentOption,\n selectStandardPaymentOption,\n x402AssetTransferMethod,\n x402AuthorizationAmount,\n} from './x402.js'\nimport { paymentStateStatusCode } from './payment-state.js'\n\n/**\n * Protocol-level x402 shapes and request plumbing, owned by neither\n * settlement scheme (#1618, epic #1613).\n *\n * These are the parts of the x402 lifecycle that do not know how the money\n * moves: quote/receipt/resume shapes, the merchant request snapshot a resume\n * replays, the `x402-wallet` header, and the state checks that decide whether\n * a payment is resumable at all. The EIP-3009 funding leg\n * (`x402-funding-leg.ts`) and the erc7710 no-funding-leg path both build on\n * them, which is why they live here rather than inside either one — a\n * neutral primitive parked in the 3009 module would make the erc7710 module\n * import a funding leg it does not have.\n *\n * Everything here is a free function. There is no state to own: give the same\n * inputs, get the same shape. That is also what makes them cheap to test\n * directly, without constructing a client.\n */\n\nconst CHAIN_EXPLORER_TX: Record<number, string> = {\n 100: 'https://gnosisscan.io/tx',\n 8453: 'https://basescan.org/tx',\n}\n\nexport function buildExplorerUrl(chainId: number | undefined, txHash: string): string {\n const base = CHAIN_EXPLORER_TX[chainId ?? 8453] ?? CHAIN_EXPLORER_TX[8453]\n return `${base}/${txHash}`\n}\n\nexport function explorerUrlOrEmpty(\n chainId: number | undefined,\n txHash: string | null | undefined,\n): string {\n return txHash ? buildExplorerUrl(chainId, txHash) : ''\n}\n\nexport function chainIdFromNetwork(network: string | undefined): number | undefined {\n if (network === 'base') return 8453\n // #1471: canonical in the x402 spec's NetworkSchema, and the backend maps\n // it as of the same change — the #1478 pin test enforces that every copy\n // widens together, which is exactly how this line got here.\n if (network === 'base-sepolia') return 84532\n if (!network?.startsWith('eip155:')) return undefined\n const chainId = Number(network.slice('eip155:'.length))\n return Number.isFinite(chainId) ? chainId : undefined\n}\n\nexport function chainIdOrNull(network: string | undefined): number | null {\n return chainIdFromNetwork(network) ?? null\n}\n\nexport function sameAddress(\n a: string | null | undefined,\n b: string | null | undefined,\n): boolean {\n return Boolean(a && b && a.toLowerCase() === b.toLowerCase())\n}\n\nexport function decimalFromUsdcAtomic(value: string): string {\n const amount = BigInt(value)\n const whole = amount / 1_000_000n\n const fraction = (amount % 1_000_000n).toString().padStart(6, '0').replace(/0+$/, '')\n return fraction ? `${whole}.${fraction}` : whole.toString()\n}\n\nexport function normalizeDecimal(value: string): string {\n if (!value.includes('.')) return value.replace(/^0+(?=\\d)/, '') || '0'\n const [whole, fraction = ''] = value.split('.')\n const normalizedWhole = whole.replace(/^0+(?=\\d)/, '') || '0'\n const normalizedFraction = fraction.replace(/0+$/, '')\n return normalizedFraction ? `${normalizedWhole}.${normalizedFraction}` : normalizedWhole\n}\n\n// ── Payer identity and the merchant-facing wallet header ────────────\n\n/**\n * The address a merchant should see as the payer. Both settlement schemes ask\n * this question; the answer differs only by which one is configured.\n */\nexport function x402PayerAddress(\n delegateAddress: string | undefined,\n x402Wallet: string | undefined,\n): string | undefined {\n return delegateAddress ?? x402Wallet\n}\n\nexport function withX402Wallet(\n init: RequestInit | undefined,\n wallet: string | undefined,\n): RequestInit | undefined {\n if (!wallet) return init\n\n const headers = new Headers(init?.headers)\n if (!headers.has('x402-wallet')) {\n headers.set('x402-wallet', wallet)\n }\n\n return {\n ...init,\n headers,\n }\n}\n\n// ── Request snapshots (what a resume replays) ───────────────────────\n\nexport function snapshotRequestBody(body: BodyInit | null | undefined): string | undefined {\n if (body == null) return undefined\n if (typeof body === 'string') return body\n if (body instanceof URLSearchParams) return body.toString()\n\n throw new HavenApiError(\n 'Quote helpers can only capture resumable request bodies that are strings or URLSearchParams. ' +\n 'For streams, blobs, or binary bodies, preserve the original request yourself and call the matching resume method with fresh init.',\n 400,\n )\n}\n\nexport function snapshotX402Request(url: string, init?: RequestInit): X402RequestSnapshot {\n return {\n url,\n method: init?.method ?? 'GET',\n headers: Array.from(new Headers(init?.headers).entries()),\n body: snapshotRequestBody(init?.body),\n }\n}\n\nexport function requestInitFromSnapshot(request: X402RequestSnapshot): RequestInit {\n return {\n method: request.method,\n headers: request.headers,\n body: request.body,\n }\n}\n\n// ── Quote / receipt / resume shapes ─────────────────────────────────\n\n/**\n * #2054 (review finding) — the shared no-compatible-option refusal, made\n * honest about WHY when the answer is the erc7710 tag.\n *\n * Every EIP-3009 path that re-selects through `selectStandardPaymentOption`\n * (`authorizeX402`, `createX402Intent`, the resume path) used to claim \"Haven\n * supports standard x402 exact payments on Base USDC\" even when the merchant's\n * only Haven-compatible entry was erc7710-tagged — blaming the asset when the\n * limit is the settlement scheme. That message got one hop MORE misleading\n * once `buildX402Quote` started describing erc7710-only merchants: a local or\n * generic-SDK caller can now quote such a merchant successfully and then hit\n * this refusal at pay time, so the refusal has to name the real reason. The\n * base sentence is byte-identical to the pre-#2054 message; the erc7710 clause\n * is appended only when the tag is in fact the reason.\n */\nexport function noCompatiblePaymentOptionError(\n accepts: X402PaymentOption[],\n): HavenApiError {\n const erc7710Only = selectErc7710PaymentOption(accepts) !== null\n // #3116: when the refusal's real reason is a transfer method / payment flow\n // this SDK cannot construct, say so — the same honesty rule #2054 applied\n // to the erc7710 tag. Detected WITHOUT the supported-vocabulary sets, so a\n // future supported entry cannot reclassify a merchant as unsupported.\n const unsupportedOnly =\n !erc7710Only &&\n accepts.some(\n (opt) =>\n opt !== null &&\n typeof opt === 'object' &&\n !isErc7710Option(opt) &&\n (x402AssetTransferMethod(opt) !== null ||\n opt.extra?.paymentFlow !== undefined),\n )\n return new HavenApiError(\n 'No compatible payment option found in x402 requirements. ' +\n 'Haven supports standard x402 exact payments on Base USDC.' +\n (erc7710Only\n ? \" The only Haven-compatible option this merchant advertises is tagged \" +\n \"extra.assetTransferMethod: 'erc7710' (direct settlement), which this EIP-3009 \" +\n 'payment path cannot settle — the limitation is the settlement scheme, not the ' +\n 'asset. Paying this merchant requires a delegation-rail erc7710 flow ' +\n '(settleX402Erc7710, or the hosted MCP purchase tools).'\n : unsupportedOnly\n ? ' Every option this merchant advertises asks for a transfer method or payment ' +\n 'flow Haven cannot construct (for example extra.assetTransferMethod: \\'permit2\\', ' +\n 'or an unrecognized extra.paymentFlow). No payment intent was created and no ' +\n 'funds moved.'\n : ''),\n 400,\n )\n}\n\nexport function buildX402Quote(\n paymentRequired: X402PaymentRequired,\n request: X402RequestSnapshot,\n idempotencyKey?: string,\n mcpTransport?: X402McpTransport,\n): X402Quote {\n // #2054: this used to be standard-only, so a merchant advertising ONLY an\n // erc7710-tagged entry — no untagged fallback — was refused as having \"no\n // compatible payment option\" before scheme selection could ever see the\n // entry Haven actually PREFERS on the delegation rail (#1450). The quote is\n // informational and rail-agnostic, so when no standard entry exists it now\n // DESCRIBES the erc7710 entry instead of throwing, and says which selector\n // produced it via `acceptedScheme`. `selectStandardPaymentOption`'s own\n // erc7710 skip is untouched — it is a #1453 correctness property, and the\n // 3009 settlement paths keep re-selecting through it, so an erc7710\n // described quote can never leak into an EIP-3009 authorization.\n const standard = selectStandardPaymentOption(paymentRequired.accepts)\n const option = standard ?? selectErc7710PaymentOption(paymentRequired.accepts)\n if (!option) {\n throw noCompatiblePaymentOptionError(paymentRequired.accepts)\n }\n\n const token = resolveTokenFromAddress(option.asset, option.network)\n return {\n rail: 'x402',\n idempotencyKey: idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option),\n paymentRequired,\n accepted: option,\n acceptedScheme: standard ? 'standard' : 'erc7710',\n request,\n ...(mcpTransport ? { mcpTransport } : {}),\n resourceUrl: paymentRequired.resource.url,\n // #3097: the merchant's declaration vs the URL the caller quoted. The\n // paid retry goes to the caller's URL; a quote that says the two disagree\n // is how an agent sees a challenge that downgrades the scheme or moves\n // the host before it pays.\n resourceUrlDiffersFromRequest: paymentRequired.resource.url !== request.url,\n description: paymentRequired.resource.description ?? option.description ?? null,\n mimeType: paymentRequired.resource.mimeType ?? option.mimeType ?? null,\n amountAtomic: x402AuthorizationAmount(option),\n amount: decimalFromUsdcAtomic(x402AuthorizationAmount(option)),\n token: token?.symbol ?? 'USDC',\n // #1351: null when the asset is unrecognised on this network — the\n // `token` fallback above is a LABEL, not evidence of 6 decimals, and a\n // human-denominated cap must fail closed rather than convert against a\n // guess. Same resolution as `token`, so the two never disagree.\n decimals: token?.decimals ?? null,\n asset: option.asset,\n network: option.network,\n chainId: chainIdOrNull(option.network),\n merchantAddress: option.payTo,\n maxTimeoutSeconds: option.maxTimeoutSeconds,\n }\n}\n\nexport function buildX402Receipt(input: {\n paymentId: string\n txHash: string\n token: string\n amount: string\n to: string\n resourceUrl: string\n explorerUrl: string\n accepted: X402PaymentOption\n // #1521: absent for a receipt describing an ALREADY-SETTLED payment,\n // which has no live authorization to carry. `X402Receipt.paymentHeader`\n // was already optional; only these builders assumed otherwise.\n paymentHeader: string | undefined\n merchantTo?: string | null\n payer?: string\n chainId?: number\n}): X402Receipt {\n const fundingExplorerUrl = input.explorerUrl || explorerUrlOrEmpty(input.chainId, input.txHash)\n\n return {\n success: true,\n paymentId: input.paymentId,\n txHash: input.txHash,\n token: input.token,\n amount: input.amount,\n to: input.to,\n resourceUrl: input.resourceUrl,\n explorerUrl: input.explorerUrl,\n accepted: input.accepted,\n paymentHeader: input.paymentHeader,\n merchantTo: input.merchantTo ?? input.accepted.payTo,\n payer: input.payer,\n chainId: input.chainId,\n haven: {\n paymentId: input.paymentId,\n fundingTxHash: input.txHash,\n fundingExplorerUrl,\n },\n merchant: {\n payTo: input.merchantTo ?? input.accepted.payTo,\n },\n x402: {\n amount: x402AuthorizationAmount(input.accepted),\n token: input.token,\n network: input.accepted.network,\n asset: input.accepted.asset,\n resource: input.accepted.resource ?? input.resourceUrl,\n },\n }\n}\n\nexport function buildX402ResumeState(input: {\n paymentId: string\n paymentRequired: X402PaymentRequired\n accepted: X402PaymentOption\n idempotencyKey: string\n request?: X402RequestSnapshot\n}): X402ResumeState {\n const token = resolveTokenFromAddress(input.accepted.asset, input.accepted.network)\n return {\n rail: 'x402',\n paymentId: input.paymentId,\n idempotencyKey: input.idempotencyKey,\n paymentRequired: input.paymentRequired,\n accepted: input.accepted,\n url: input.request?.url ?? input.paymentRequired.resource.url,\n request: input.request,\n resourceUrl: input.paymentRequired.resource.url,\n description: input.paymentRequired.resource.description ?? input.accepted.description ?? null,\n amountAtomic: x402AuthorizationAmount(input.accepted),\n amount: decimalFromUsdcAtomic(x402AuthorizationAmount(input.accepted)),\n token: token?.symbol ?? 'USDC',\n asset: input.accepted.asset,\n network: input.accepted.network,\n chainId: chainIdOrNull(input.accepted.network),\n merchantAddress: input.accepted.payTo,\n }\n}\n\nexport function attachX402ResumeState(\n err: unknown,\n paymentRequired: X402PaymentRequired,\n accepted: X402PaymentOption,\n idempotencyKey: string,\n request?: X402RequestSnapshot,\n): void {\n if (!(err instanceof HavenPaymentStateError)) return\n if (err.state.rail !== 'x402') return\n\n err.resumeState = buildX402ResumeState({\n paymentId: err.state.paymentId,\n paymentRequired,\n accepted,\n idempotencyKey,\n request,\n })\n}\n\n// #1328: attachResumeState's 'mpp' branch (buildMppQuote / buildMppResumeState\n// / attachMppResumeState) is retired along with the rest of the MPP-demo\n// client surface — every remaining caller passes rail: 'x402' only, so this\n// is now a direct alias for attachX402ResumeState rather than a dispatcher.\nexport function attachResumeState(\n err: unknown,\n input: {\n rail: 'x402'\n paymentRequired: X402PaymentRequired\n accepted: X402PaymentOption\n idempotencyKey: string\n request?: X402RequestSnapshot\n },\n): void {\n attachX402ResumeState(\n err,\n input.paymentRequired,\n input.accepted,\n input.idempotencyKey,\n input.request,\n )\n}\n\n/**\n * Does this payment's live state actually permit the resume the caller is\n * asking for, and does it describe the SAME purchase they are resuming?\n *\n * Every mismatch below is a 409 rather than a best-effort continue: a resume\n * that quietly retargets a different merchant, amount, network or resource is\n * a payment the user never approved.\n */\nexport function assertCanResumeX402(\n status: PaymentStatusResult,\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n): void {\n if (status.rail !== 'x402') {\n throw new HavenPaymentStateError(\n `Payment ${status.paymentId} is ${status.rail}, not x402.`,\n 409,\n status,\n )\n }\n\n if (status.nextAction !== AgentPaymentNextAction.RetryOriginalX402Request) {\n throw new HavenPaymentStateError(status.message, paymentStateStatusCode(status.status, 409), status)\n }\n\n if (!status.txHash) {\n throw new HavenApiError(\n `x402 payment ${status.paymentId} is ready to retry but has no Haven transaction hash.`,\n 502,\n status,\n status.paymentId,\n )\n }\n\n if (status.resourceUrl && status.resourceUrl !== paymentRequired.resource.url) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved resource URL.',\n 409,\n { status, paymentRequired },\n status.paymentId,\n )\n }\n\n if (status.merchantAddress && !sameAddress(status.merchantAddress, option.payTo)) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved merchant.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n\n const optionChainId = chainIdFromNetwork(option.network)\n if (status.chainId && optionChainId && status.chainId !== optionChainId) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved network.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n\n if (status.token && status.token !== 'USDC') {\n throw new HavenApiError(\n 'x402 resume request does not match the approved token.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n\n const approvedAmount = status.amount ? normalizeDecimal(status.amount) : ''\n const requestedAmount = normalizeDecimal(decimalFromUsdcAtomic(x402AuthorizationAmount(option)))\n if (approvedAmount && approvedAmount !== requestedAmount) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved amount.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n}\n","/**\n * #2914 (naming epic #2906, phase 5 — the CONTRACTION): the compatibility\n * window #2908 opened (read both server-response names, prefer the new;\n * emit both camelCase names; write only the new) closed with the\n * `0.2.0-alpha.0` release reaching `main` on 2026-09-14 and a further\n * promotion on 2026-09-16. The account-vocabulary name is now the ONLY name\n * on every wire shape this module touches; `safe_address` / `safe_id` /\n * `sign_data.components.safe` are no longer read from a server response.\n *\n * `readAccountAddress` and `readAccountId` collapsed to a single field read\n * once the fallback was removed, so they are gone — read `raw.account_address`\n * / `raw.account_id` directly. `accountAddressTwins` is gone too: the SDK's\n * public shapes carry `accountAddress` only, never a `safeAddress` twin.\n *\n * `readX402ReceiptPayer` survives because it still has a real multi-step\n * chain (`payer`, then the top-level account address, then the nested\n * `sign_data.components` twin) once the old names are dropped from it.\n */\n\n/**\n * The x402 receipt's `payer` off a funding-authorization response: the\n * explicit `payer`, then the top-level `account_address`, then\n * `sign_data.components.payer_account`.\n *\n * `components.account` is deliberately NOT in this chain: on the funding\n * shapes it holds the DELEGATE account address, a different address, and\n * reading it here would silently corrupt the receipt's payer.\n */\nexport function readX402ReceiptPayer(raw: {\n payer?: string\n account_address?: string\n sign_data?: { components?: { payer_account?: string; account?: string } }\n}): string | undefined {\n return raw.payer ?? raw.account_address ?? raw.sign_data?.components?.payer_account\n}\n","import { exact } from 'x402/schemes'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport {\n AgentPaymentNextAction,\n HavenApiError,\n HavenSigningError,\n X402AlreadySettledError,\n} from './types.js'\nimport type {\n PaymentStatusResult,\n RawSignResponse,\n RawX402AuthorizeResponse,\n SignData,\n X402PaymentOption,\n X402PaymentRequired,\n X402Receipt,\n} from './types.js'\nimport {\n toStandardPaymentRequirements,\n x402AuthorizationAmount,\n x402V2PaymentEnvelope,\n} from './x402.js'\nimport { paymentStateFromRaw, throwPaymentStateError } from './payment-state.js'\nimport { createErc20Contract, createJsonRpcProvider } from './provider.js'\nimport { decodeBase64Json, encodeBase64Json } from './base64.js'\nimport { readX402ReceiptPayer } from './account-naming.js'\nimport {\n buildX402Receipt,\n chainIdFromNetwork,\n decimalFromUsdcAtomic,\n explorerUrlOrEmpty,\n} from './x402-protocol.js'\n\n/**\n * The EIP-3009 funding-leg x402 lifecycle (#1618, epic #1613).\n *\n * This scheme moves money in TWO hops: Haven funds the agent's delegate EOA\n * from the account, and the delegate then signs a standard EIP-3009\n * authorization the merchant's facilitator settles. Everything peculiar to\n * that shape lives here — funding confirmation, the delegate's fundability\n * check, header minting from the local delegate key, and the receipt cache\n * keyed by the authorization's own expiry.\n *\n * What is NOT here is deliberate: the erc7710 direct-settlement path has no\n * funding leg at all, so it must not reach into this module. Anything both\n * schemes need is a free function in `x402-protocol.ts`.\n *\n * Non-custody is unchanged by the extraction. The delegate key never leaves\n * the caller's process, Haven never signs, and nothing here can widen what\n * the on-chain policy already permits.\n *\n * Internal to `HavenClient`. Exported for direct tests and composition only;\n * it is not part of the SDK's published entrypoint.\n */\n\nexport type PaymentPoster = <T>(path: string, body: Record<string, unknown>) => Promise<T>\nexport type DataSigner = (signData: SignData) => Promise<string>\nexport type AuthorizationStateAssertion = (label: string, raw: RawX402AuthorizeResponse) => void\n\nexport interface X402FundingLegOptions {\n /** The agent's local delegate key. Required to mint an EIP-3009 header. */\n delegateKey: string | undefined\n /** Derived from `delegateKey`; the address the funding leg pays into. */\n delegateAddress: string | undefined\n /** Payer override for clients without a local delegate key. */\n x402Wallet: string | undefined\n /** Chain id → RPC URL. Absent entries make on-chain reads unverifiable, never guessed. */\n chainRpcs: Record<number, string>\n post: PaymentPoster\n signForData: DataSigner\n assertSignableAuthorizationState: AuthorizationStateAssertion\n}\n\nexport class X402FundingLeg {\n private readonly delegateKey: string | undefined\n private readonly delegateAddress: string | undefined\n private readonly x402Wallet: string | undefined\n private readonly chainRpcs: Record<number, string>\n private readonly post: PaymentPoster\n private readonly signForData: DataSigner\n private readonly assertSignableAuthorizationState: AuthorizationStateAssertion\n\n /**\n * Receipts keyed by idempotency key, held only as long as the underlying\n * EIP-3009 authorization is valid. The cache belongs to this module rather\n * than to the facade because its expiry is read out of the authorization\n * header itself — a 3009 artifact.\n */\n private readonly receiptCache = new Map<string, { expiresAt: number; receipt: X402Receipt }>()\n\n constructor(options: X402FundingLegOptions) {\n this.delegateKey = options.delegateKey\n this.delegateAddress = options.delegateAddress\n this.x402Wallet = options.x402Wallet\n this.chainRpcs = options.chainRpcs\n this.post = options.post\n this.signForData = options.signForData\n this.assertSignableAuthorizationState = options.assertSignableAuthorizationState\n }\n\n // ── Receipt cache ────────────────────────────────────────────────\n\n /** A still-valid cached receipt for this key, or undefined. */\n cachedReceipt(idempotencyKey: string): X402Receipt | undefined {\n const cached = this.receiptCache.get(idempotencyKey)\n if (cached && cached.expiresAt > Date.now()) return cached.receipt\n return undefined\n }\n\n cacheReceipt(idempotencyKey: string, paymentHeader: string, receipt: X402Receipt): void {\n const expiresAt = getPaymentHeaderValidBefore(paymentHeader)\n if (expiresAt > Date.now()) {\n this.receiptCache.set(idempotencyKey, { expiresAt, receipt })\n }\n }\n\n // ── Authorization ────────────────────────────────────────────────\n\n async authorize(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n idempotencyKey: string,\n ): Promise<X402Receipt> {\n // 2. Standard x402 settles from an EOA, so the SDK uses the agent-owned\n // delegate EOA for the merchant-facing EIP-3009 authorization. Haven does\n // not control this EOA or its private key.\n //\n // The only automated funding path is a separate transfer from the user's\n // account, redeemed through the agent's budget delegation, signed by the\n // agent key and constrained on-chain by the delegation's caveats. Haven's\n // backend relays that signed top-up; it is not the source of payment\n // authority.\n // #1521: the authorization is minted AFTER the backend's answer is\n // classified, never before. Signing first meant that when the idempotency\n // key resolved to an already-settled payment, a brand-new authorization\n // had already been created against a delegate whose USDC was gone — and\n // it was handed back paired with the FIRST payment's tx_hash. Within one\n // authorize call the header is still created once and reused, which is\n // all the original \"reuse one EIP-3009 nonce\" note ever meant. If funding\n // fails later, the unused authorization simply expires via validBefore.\n const raw = await this.post<RawX402AuthorizeResponse>('/x402', {\n url: paymentRequired.resource.url,\n payTo: this.delegateAddress,\n merchantPayTo: option.payTo,\n amount: x402AuthorizationAmount(option),\n asset: option.asset,\n network: option.network,\n description: paymentRequired.resource.description,\n idempotencyKey,\n // #1360: same explicit funding-leg declaration as createX402Intent —\n // this local-key path derives payTo from the key (never stale), but the\n // declaration keeps both writers of the 3009 shape loud-by-default.\n settlementScheme: 'eip3009',\n })\n\n // The backend can report an ALREADY-EXECUTED payment in two different\n // shapes, and #1521 is reachable through both — the guard is therefore on\n // the meaning, not on one response shape:\n //\n // 1. `success` + `tx_hash` — the delegation rail's confirmed-intent\n // replay (`modules/x402/replay.ts`). Reached only by an idempotency\n // collision; the caller did not ask for THIS payment.\n // 2. `nextAction: retry_original_x402_request` — RETIRED PRODUCER\n // (#2131). This was the legacy rail's approval-queue replay:\n // `modules/x402/legacy-authorize.ts` returned `getAgentPaymentStatus`'s\n // body, which carries no `success` field at all, and that was the\n // DOCUMENTED post-approval retry loop. #1987 deleted that module and\n // #2055 dropped the `approval_requests` table behind it, so nothing\n // emits this value on any rail today (#2145 tracks giving it a live\n // producer). The branch is KEPT fail-closed rather than removed: it\n // costs nothing, and deleting a guard because its input is currently\n // unreachable is how the input comes back unguarded.\n //\n // In both, \"executed\" means the FUNDING leg executed, which is ambiguous:\n //\n // (a) funding confirmed, merchant never paid → the delegate still\n // holds the money and minting a header is correct;\n // (b) funding confirmed, merchant already paid → the delegate is\n // empty and any authorization minted here is unfundable.\n //\n // Only the delegate's on-chain balance separates them. The two shapes\n // differ in what an UNVERIFIABLE balance should mean, and they differ for\n // the same reason the explicit `resumeAuthorizedX402` path does: shape 1\n // is an accident, so \"can't tell\" refuses rather than mint a header we\n // cannot vouch for; shape 2 is the caller following documented steps, so\n // \"can't tell\" proceeds and only a balance verified ABSENT refuses —\n // otherwise every approval resume without a `chainRpcs` entry would break.\n const state = paymentStateFromRaw('x402 payment', raw)\n const executedReplay = raw.success && raw.tx_hash\n ? 'idempotency-collision' as const\n : state?.nextAction === AgentPaymentNextAction.RetryOriginalX402Request\n ? 'approval-resume' as const\n : null\n\n if (executedReplay) {\n const canFund = await this.delegateCanFund(\n raw.chain_id ?? state?.chainId ?? chainIdFromNetwork(option.network),\n option.asset,\n x402AuthorizationAmount(option),\n )\n const refuse = executedReplay === 'idempotency-collision'\n ? canFund !== true\n : canFund === false\n if (refuse) {\n const settledReceipt = state && executedReplay === 'approval-resume'\n ? this.receiptFromStatus(paymentRequired, option, undefined, state)\n : this.receiptFromAuthorization(paymentRequired, option, undefined, raw)\n throw new X402AlreadySettledError(\n canFund === false\n ? 'This x402 payment already settled — the delegate no longer holds the funds to ' +\n 'authorize it again. To buy the same item a second time, pass a distinct ' +\n '`idempotencyKey`; the synthesised key intentionally collapses repeat calls for ' +\n 'the same product within a 5-minute window so a retried request cannot pay twice.'\n : 'This x402 payment already settled, and whether the delegate can still fund a new ' +\n 'authorization could not be verified (no `chainRpcs` entry for this chain). Refusing ' +\n 'rather than issue an authorization that may be unfundable. To buy the same item a ' +\n 'second time, pass a distinct `idempotencyKey`; to finish an interrupted payment, ' +\n 'resume it by `paymentId`.',\n settledReceipt,\n canFund === false ? 'settled' : 'unverifiable',\n )\n }\n }\n\n const paymentHeader = await this.createPaymentHeader(paymentRequired, option)\n\n if (raw.success && raw.tx_hash) {\n const receipt = this.receiptFromAuthorization(paymentRequired, option, paymentHeader, raw)\n this.cacheReceipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n if (state?.nextAction === AgentPaymentNextAction.RetryOriginalX402Request) {\n const receipt = this.receiptFromStatus(paymentRequired, option, paymentHeader, state)\n this.cacheReceipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n this.assertSignableAuthorizationState('x402 payment', raw)\n\n // 3. Sign the hash\n if (!raw.sign_data?.hash) {\n throw new HavenApiError('No sign_hash returned from x402/authorize', 500, raw)\n }\n const sig = await this.signForData(raw.sign_data)\n\n // 4. Submit signature (reuse existing payments/:id/sign endpoint)\n const execResult = await this.post<RawSignResponse>(\n `/payments/${raw.payment_id}/sign`,\n { signature: sig },\n )\n\n if (execResult.status !== 'confirmed') {\n throwPaymentStateError('x402 payment', execResult)\n }\n\n // Wait for ≥1 on-chain confirmation before retrying the merchant so the\n // merchant's balanceOf(delegate) check sees the funded balance.\n await this.waitForFundingTx(\n execResult.tx_hash,\n execResult.chain_id ?? chainIdFromNetwork(option.network),\n )\n\n const receipt = this.receiptFromAuthorization(paymentRequired, option, paymentHeader, raw, execResult)\n this.cacheReceipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n // ── Header minting ───────────────────────────────────────────────\n\n async createPaymentHeader(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n ): Promise<string> {\n if (!this.delegateKey) {\n throw new HavenSigningError('delegateKey is required to sign x402 payment headers.')\n }\n\n const account = privateKeyToAccount(this.delegateKey as `0x${string}`)\n const requirements = toStandardPaymentRequirements(paymentRequired, option)\n\n const header = await exact.evm.createPaymentHeader(\n account,\n paymentRequired.x402Version,\n requirements,\n )\n if (paymentRequired.x402Version < 2) return header\n\n const payment = decodeBase64Json<{ payload: unknown }>(header)\n // #2361: the shared envelope carries the resource/extensions echoes —\n // see `x402V2PaymentEnvelope`'s comment for why they are load-bearing.\n return encodeBase64Json(x402V2PaymentEnvelope(paymentRequired, option, payment.payload))\n }\n\n // ── Receipt mapping ──────────────────────────────────────────────\n\n receiptFromAuthorization(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n // #1521: `undefined` builds the receipt for a payment that already\n // settled. A settled payment has no live authorization to carry, and\n // minting one to fill this slot is precisely the defect that issue names.\n paymentHeader: string | undefined,\n raw: RawX402AuthorizeResponse,\n execResult?: RawSignResponse,\n ): X402Receipt {\n const txHash = execResult?.tx_hash ?? raw.tx_hash ?? ''\n const chainId = execResult?.chain_id ?? raw.chain_id ?? chainIdFromNetwork(option.network)\n const token = execResult?.token ?? raw.token ?? 'USDC'\n const amount = execResult?.amount ?? raw.amount ?? decimalFromUsdcAtomic(x402AuthorizationAmount(option))\n const to = execResult?.to ?? raw.to ?? this.delegateAddress ?? ''\n const explorerUrl = execResult?.explorer_url ?? raw.explorer_url ?? explorerUrlOrEmpty(chainId, txHash)\n const merchantTo = execResult?.merchant_to ?? raw.merchant_to ?? option.payTo\n // `account_address` then `components.payer_account`. NEVER\n // `components.account`: that is the delegate.\n const payer = readX402ReceiptPayer(raw)\n\n return buildX402Receipt({\n paymentId: raw.payment_id,\n txHash,\n token,\n amount,\n to,\n resourceUrl: paymentRequired.resource.url,\n explorerUrl,\n accepted: option,\n paymentHeader,\n merchantTo,\n payer,\n chainId,\n })\n }\n\n receiptFromStatus(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n // See `receiptFromAuthorization` — `undefined` is the settled case.\n paymentHeader: string | undefined,\n status: PaymentStatusResult,\n ): X402Receipt {\n if (!status.txHash) {\n throw new HavenApiError(\n `x402 payment ${status.paymentId} is ready to retry but has no Haven transaction hash.`,\n 502,\n status,\n status.paymentId,\n )\n }\n\n return buildX402Receipt({\n paymentId: status.paymentId,\n txHash: status.txHash,\n token: status.token || 'USDC',\n amount: status.amount || decimalFromUsdcAtomic(x402AuthorizationAmount(option)),\n to: this.delegateAddress ?? '',\n resourceUrl: paymentRequired.resource.url,\n explorerUrl: explorerUrlOrEmpty(status.chainId, status.txHash),\n accepted: option,\n paymentHeader,\n merchantTo: status.merchantAddress ?? option.payTo,\n payer: this.x402Wallet,\n chainId: status.chainId || chainIdFromNetwork(option.network),\n })\n }\n\n // ── On-chain reads ───────────────────────────────────────────────\n\n /**\n * Wait for a funding tx to be mined with ≥1 confirmation before the\n * merchant retry, eliminating the race where the merchant's\n * `balanceOf(delegate)` runs before the funding block propagates.\n *\n * Skipped when `chainRpcs` does not include the chain; in that case Haven's\n * backend has already confirmed on-chain submission and callers accept the\n * small propagation window as a trade-off for not configuring an RPC URL.\n */\n async waitForFundingTx(\n txHash: string | undefined,\n chainId: number | undefined,\n timeoutMs = 30_000,\n ): Promise<void> {\n if (!txHash || !chainId) return\n const rpcUrl = this.chainRpcs[chainId]\n if (!rpcUrl) return\n const provider = createJsonRpcProvider(rpcUrl)\n const onChainReceipt = await provider.waitForTransaction(txHash, 1, timeoutMs)\n if (!onChainReceipt || onChainReceipt.status !== 1) {\n throw new HavenApiError(\n 'Funding tx did not confirm on-chain within the timeout window.',\n 500,\n { txHash, chainId },\n )\n }\n }\n\n /**\n * Can the delegate EOA still fund an authorization for `amountAtomic`?\n *\n * #1521: the only question that separates a legitimate resume (funding\n * confirmed, merchant never paid — the delegate still holds the money) from\n * a replayed settled payment (funding confirmed, merchant paid, delegate\n * spent). The intent's own `status: 'confirmed'` is identical in both.\n *\n * The balance is asked of the CHAIN rather than of Haven's bookkeeping on\n * purpose: the merchant-settlement evidence record is written by this SDK\n * *after* the merchant call, so a client that dies between the two leaves\n * the backend believing the merchant was never paid — the exact case the\n * discriminator has to get right. The chain cannot be behind in that way.\n *\n * Returns `null` — never a guess — when `chainRpcs` has no entry for the\n * chain or the read fails. Callers must treat that as \"unverifiable\", not\n * as \"funded\".\n */\n async delegateCanFund(\n chainId: number | undefined,\n tokenAddress: string,\n amountAtomic: string,\n timeoutMs = 10_000,\n ): Promise<boolean | null> {\n if (!chainId || !this.delegateAddress) return null\n const rpcUrl = this.chainRpcs[chainId]\n if (!rpcUrl) return null\n try {\n const provider = createJsonRpcProvider(rpcUrl)\n const token = createErc20Contract(\n tokenAddress,\n ['function balanceOf(address) view returns (uint256)'] as const,\n provider,\n )\n // Bounded like `waitForFundingTx` above. This sits on a money\n // authorization path with no way for a caller to route around a stall,\n // so an unresponsive RPC must degrade to \"unverifiable\" rather than\n // hang the payment: a slow answer is worth less than a prompt refusal.\n const balance = await Promise.race([\n token.balanceOf(this.delegateAddress) as Promise<bigint>,\n new Promise<null>((resolve) => setTimeout(() => resolve(null), timeoutMs).unref?.()),\n ])\n if (balance === null) return null\n return balance >= BigInt(amountAtomic)\n } catch {\n // An RPC that is down, or an amount that will not parse, tells us\n // nothing about the delegate's balance. Saying so is the whole point of\n // the tri-state — and on the accidental-replay path it fails toward\n // refusing, never toward minting.\n return null\n }\n }\n}\n\n/**\n * The authorization's own `validBefore`, in milliseconds — the only honest\n * expiry for a cached receipt, since the header stops being usable then\n * whatever the SDK believes.\n */\nexport function getPaymentHeaderValidBefore(paymentHeader: string): number {\n try {\n const payment = decodeBase64Json<{ payload?: { authorization?: { validBefore?: string } } }>(\n paymentHeader,\n )\n const payload = payment.payload as { authorization?: { validBefore?: string } }\n const validBeforeSeconds = Number(payload.authorization?.validBefore)\n if (Number.isFinite(validBeforeSeconds)) return validBeforeSeconds * 1000\n } catch {\n // If the header cannot be decoded, skip caching rather than hiding errors.\n }\n\n return 0\n}\n","import {\n HavenApiError,\n HavenSigningError,\n} from './types.js'\nimport type {\n RawX402AuthorizeResponse,\n RawX402SettleResponse,\n SignData,\n X402Erc7710Settlement,\n X402McpCallContext,\n X402PaymentRequired,\n} from './types.js'\nimport {\n selectX402SettlementScheme,\n x402AuthorizationAmount,\n} from './x402.js'\nimport { chainIdForNetwork, type SettlementChildExpectation } from './settlement-child.js'\n\n/**\n * The erc7710 direct-settlement lifecycle (#1619, epic #1613).\n *\n * The defining property of this scheme is an ABSENCE. There is no funding\n * leg: the merchant redeems a delegation chain and pulls from the treasury\n * directly, so the delegate EOA never holds the money, no sweep can strand\n * it, and the #713 reconciliation class does not apply. Nothing in this\n * module checks a delegate balance or waits for a funding transaction,\n * because on this path there is neither — and a test pins that, since the\n * defects this epic exists to prevent (#1510, #1511, #1521) were all a\n * funding-leg assumption leaking into a path that has none.\n *\n * It builds no merchant header either. The backend assembles the MetaMask\n * erc7710 payload in `assembleSettlementPayload`, which is why this module is\n * so much smaller than `x402-funding-leg.ts`.\n *\n * Non-custody: `settle()` signs in-process with the caller's delegate key,\n * while `prepare()`/`submit()` exist precisely so the hosted topology can\n * drive the two halves with the LOCAL signer in between — hosted Haven has no\n * key and must not. Neither half can widen what the delegation already\n * permits; the caveat enforcers decide that on-chain.\n *\n * Internal to `HavenClient`. Exported for direct tests and composition only;\n * it is not part of the SDK's published entrypoint.\n */\n\nexport type PaymentPoster = <T>(path: string, body: Record<string, unknown>) => Promise<T>\n/**\n * Signs a `sign_data` payload. The erc7710 path passes the second argument:\n * what the merchant's own 402 says the settlement child must implement, so\n * the child is verified against something Haven did not produce (#3283).\n */\nexport type DataSigner = (\n signData: SignData,\n settlementExpectation?: SettlementChildExpectation,\n) => Promise<string>\nexport type RailReader = () => Promise<{ executionRail?: string }>\n\nexport interface X402Erc7710Options {\n /** Required only by `settle()`, which signs in-process. */\n delegateKey: string | undefined\n post: PaymentPoster\n signForData: DataSigner\n /** Reads the ACCOUNT's rail — a property no 402 response can carry. */\n getAgent: RailReader\n}\n\nexport class X402Erc7710 {\n private readonly delegateKey: string | undefined\n private readonly post: PaymentPoster\n private readonly signForData: DataSigner\n private readonly getAgent: RailReader\n\n constructor(options: X402Erc7710Options) {\n this.delegateKey = options.delegateKey\n this.post = options.post\n this.signForData = options.signForData\n this.getAgent = options.getAgent\n }\n\n /**\n * Pay a merchant through **erc7710 direct settlement** (#1454, epic #1450).\n *\n * The whole point of this path is what it does NOT do. There is no funding\n * leg: the merchant redeems a delegation chain and pulls from the treasury\n * directly, so the delegate EOA never holds the money, no sweep can strand\n * it, and the #713 reconciliation class does not apply. It is also why this\n * method is SMALLER than the 3009 path — the backend assembles the merchant\n * `X-PAYMENT` header in `assembleSettlementPayload`, so the SDK builds no\n * header locally.\n *\n * authorize (payTo = the MERCHANT) → sign the child → settle → header\n *\n * The caller then retries the merchant with that header. **Nothing has\n * settled when this returns** — that is why it does not return an\n * `X402Receipt`.\n *\n * Requires a delegation-rail account. The backend enforces that at the\n * rail seam — a non-delegation account gets the #1986 retired-rail 410 from\n * `POST /x402/authorize` whatever scheme it asks for (#2245) — and so does\n * this method, before building a request the backend would only reject: an\n * error a client can explain is worth more than a refusal it has to decode.\n *\n * **MCP callers must pass `options.resourceUrl`.** An in-band MCP 402\n * challenge frequently carries no `resource` object at all, so\n * `paymentRequired.resource?.url` is undefined and the backend answers\n * \"Valid url is required\". The QA scenario this path was ported from falls\n * back to the request URL for exactly that reason — the SDK cannot, because\n * it never saw the request. Pass it.\n */\n async settle(\n paymentRequired: X402PaymentRequired,\n options: { resourceUrl?: string } = {},\n ): Promise<X402Erc7710Settlement> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'delegateKey is required for x402 payments. Pass it in the HavenClient config.',\n )\n }\n const prepared = await this.prepare(paymentRequired, options)\n const signature = await this.signForData(\n prepared.signData,\n settlementExpectationFromQuote(prepared.settlement),\n )\n const paymentHeader = await this.submit(prepared.paymentId, signature)\n return { ...prepared.settlement, paymentHeader }\n }\n\n /**\n * The AUTHORIZE half of erc7710 settlement (#1456): select the scheme, build\n * the request, and return the child to be signed — without signing it.\n *\n * Split out because the hosted topology cannot use `settleX402Erc7710()`:\n * that method signs in-process with `delegateKey`, and hosted Haven does not\n * have one and must not. The hosted MCP server drives these two halves with\n * the LOCAL signer in between, so the key stays where it belongs and the\n * request shaping stays in one place rather than being reimplemented.\n */\n async prepare(\n paymentRequired: X402PaymentRequired,\n options: {\n resourceUrl?: string\n /**\n * The account's rail, when the caller has ALREADY read it from\n * `GET /machine-payments/agent` — passing it skips a duplicate fetch\n * (#1456: the hosted tool reads the agent for the delegate address\n * anyway, and #1348 pins that path to exactly one agent round-trip).\n *\n * This is an optimisation, not a trust boundary: omit it and the rail is\n * read here, and either way the backend independently refuses a\n * non-delegation account at the rail seam (the #1986 410; #2245 removed\n * the separate scheme-level 400). A caller that asserted the wrong rail\n * would build a request the backend rejects.\n */\n delegationRail?: boolean\n /**\n * #1547: the merchant MCP-tool call this authorization was quoted\n * against, persisted so the settle leg can rehydrate it by payment_id\n * (#1307) — the same option `createX402Intent` already carries. Without\n * it an erc7710 settle needs merchant_url/tool_name/arguments\n * re-threaded, which the guided catalog path (#1305) exists to remove.\n */\n mcpCallContext?: X402McpCallContext\n /**\n * #2041: replay key for this authorization, exactly as the 3009 path's\n * `createX402Intent` already sends one.\n *\n * The backend has supported full replay dedup on THIS branch all along —\n * `runDelegationAuthorize` looks an existing intent up by key before it\n * ever branches on the funding shape, and the erc7710 insert carries\n * `conflictTarget: 'x402_idempotency_key'`. The dedup was simply never\n * invoked, because this options bag had no way to say the key. A retried\n * call therefore minted a SECOND independently-signable settlement child\n * for the same purchase — a double-authorize hazard on the one scheme\n * whose signed artifact is spend authority rather than a funding step.\n *\n * Omitted, the backend behaves exactly as before (no key, no dedup).\n */\n idempotencyKey?: string\n } = {},\n ): Promise<{\n paymentId: string\n signData: SignData\n settlement: Omit<X402Erc7710Settlement, 'paymentHeader'>\n }> {\n\n // The rail half of the #1450 preference rule is not visible in a 402\n // response — it is a property of the ACCOUNT, so read it rather than let a\n // caller assert it. #1453's selector takes it as input for exactly this\n // reason, and this is the one place that input is sourced from truth.\n const delegationRail =\n options.delegationRail ?? (await this.getAgent()).executionRail === 'delegation'\n\n // Rail first, and BEFORE selection — the two failures have different\n // remedies and the caller needs the one that applies. Checking selection\n // first made a legacy-rail agent at an erc7710-only merchant get \"no\n // compatible payment option\", which is true and useless: the option is\n // there, the account cannot use it. (Found by this method's own tests.)\n if (!delegationRail) {\n throw new HavenApiError(\n 'erc7710 settlement requires a delegation-rail account; this one is not on it. ' +\n 'Use authorizeX402() for the standard EIP-3009 path.',\n 400,\n )\n }\n\n const selection = selectX402SettlementScheme(paymentRequired.accepts, { delegationRail })\n\n if (!selection || selection.scheme !== 'erc7710') {\n // Never silently reroute to the other scheme (#1454 AC). On a delegation\n // rail the only remaining reason is the merchant, so name that.\n throw new HavenApiError(\n 'This merchant does not advertise an erc7710 settlement option ' +\n \"(no accepts[] entry carries extra.assetTransferMethod: 'erc7710'). \" +\n 'Use authorizeX402() for the standard EIP-3009 path.',\n 400,\n )\n }\n\n const option = selection.option\n const merchantPayTo = option.payTo\n const amountAtomic = x402AuthorizationAmount(option)\n\n const raw = await this.post<RawX402AuthorizeResponse>('/x402', {\n url: options.resourceUrl ?? paymentRequired.resource?.url,\n // #2373: the full 402 challenge, persisted verbatim by the backend\n // (#1355) so the settle handoff can echo its resource/extensions into\n // the X-PAYMENT envelope (#2361). This scheme decomposes the challenge\n // into the fields below for AUTHORITY; the stored copy exists for the\n // echo, which cannot be reconstructed from the decomposition — omitting\n // it is how every erc7710 payment failed a merchant that enforces the\n // spec's extensions-echo MUST. Same ≤64KB guard and omission behaviour\n // as the 3009 path (client.ts): an oversized challenge omits the field\n // rather than failing the payment, and the settle echo then omits too.\n ...(new TextEncoder().encode(JSON.stringify(paymentRequired)).length <= 65536\n ? { paymentRequired }\n : {}),\n // payTo = the MERCHANT is what selects direct settlement server-side.\n // The explicit settlementScheme must AGREE with that shape (#1360) —\n // disagreement is a 400 by design, so that a stale delegate address\n // becomes a loud mismatch instead of a silent reroute to the 3009 leg.\n payTo: merchantPayTo,\n settlementScheme: 'erc7710',\n // #2041: sent only when the caller supplied one, so an omitting caller's\n // request body is byte-identical to the pre-#2041 shape.\n ...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}),\n amount: amountAtomic,\n asset: option.asset,\n network: option.network,\n // The v2 header echoes the accepted entry field-for-field, so the quoted\n // timeout must round-trip or the merchant rejects the echo (#1064).\n maxTimeoutSeconds: option.maxTimeoutSeconds,\n // #1058: forward the advertised facilitators verbatim — the child becomes\n // redeemable ONLY by them. `null` here means the merchant advertised none\n // (or an empty array, which the backend 400s on), so the field is OMITTED\n // rather than sent empty. See x402FacilitatorAddresses.\n ...(selection.facilitatorAddresses\n ? { facilitatorAddresses: selection.facilitatorAddresses }\n : {}),\n // #1307/#1547: persisted so the settle leg can rehydrate the merchant\n // call by payment_id on this scheme too, not only on the 3009 bridge.\n ...(options.mcpCallContext ? { mcpCallContext: options.mcpCallContext } : {}),\n })\n\n if (!raw.payment_id) {\n throw new HavenApiError('No payment_id returned from x402/authorize', 500, raw)\n }\n const signData = raw.sign_data\n if (signData?.signature_scheme !== 'eip712_delegation' || !signData.typed_data) {\n // The backend chose a different scheme than the shape asked for. Refuse\n // loudly: signing whatever came back would be exactly the \"silent\n // reroute\" this path exists to make impossible.\n throw new HavenApiError(\n 'x402/authorize did not return an erc7710 settlement child ' +\n `(signature_scheme was ${JSON.stringify(signData?.signature_scheme)}). ` +\n 'Refusing to sign a payload this path did not ask for.',\n 500,\n raw,\n )\n }\n\n return {\n paymentId: raw.payment_id,\n signData,\n settlement: {\n paymentId: raw.payment_id,\n merchantPayTo,\n amountAtomic,\n asset: option.asset,\n network: option.network,\n facilitatorAddresses: selection.facilitatorAddresses,\n },\n }\n }\n\n /**\n * The SETTLE half (#1456): exchange the signed child for the merchant header.\n *\n * The SDK builds no header on this path — the backend assembles the MetaMask\n * erc7710 payload in `assembleSettlementPayload`. Whoever produced the\n * signature (an in-process delegate key, or the local edge signer over the\n * hosted boundary) is irrelevant here.\n */\n async submit(paymentId: string, signature: string): Promise<string> {\n const settled = await this.post<RawX402SettleResponse>(\n `/x402/${paymentId}/settle`,\n { signature },\n )\n if (!settled.payment_header) {\n throw new HavenApiError(\n 'x402 settle returned no payment_header — the merchant cannot be retried.',\n 500,\n settled,\n )\n }\n return settled.payment_header\n }\n}\n\n/**\n * #3283: what the settlement child must implement, taken from the MERCHANT'S\n * 402 option this path selected — payee, exact amount, token, chain and the\n * advertised facilitators — never from the `/x402/authorize` response, so a\n * compromised Haven API cannot restate the expectation to match a child it\n * rewrote. `signForData` adds the agent's own account as the required\n * delegator.\n */\nexport function settlementExpectationFromQuote(\n settlement: Omit<X402Erc7710Settlement, 'paymentHeader'>,\n): SettlementChildExpectation {\n const chainId = chainIdForNetwork(settlement.network)\n if (chainId === undefined) {\n throw new HavenSigningError(\n `Refusing to sign the x402 settlement child: the merchant's network ${JSON.stringify(settlement.network)} ` +\n 'is not one this SDK can verify a settlement child on.',\n )\n }\n return {\n merchantTo: settlement.merchantPayTo,\n amount: settlement.amountAtomic,\n asset: settlement.asset,\n chainId,\n ...(settlement.facilitatorAddresses && settlement.facilitatorAddresses.length > 0\n ? { redeemers: settlement.facilitatorAddresses }\n : {}),\n }\n}\n","import { HavenApiError, HavenPaymentStateError } from './types.js'\nimport type { X402PaymentRequired, X402Receipt } from './types.js'\n\n/**\n * The agent-tool adapter (#1620, epic #1613).\n *\n * `HavenClient.executeTool` exists so an agent framework can hand a tool call\n * straight through; these three functions are the translation layer it needs\n * — a 402 challenge built from flat tool arguments, a receipt flattened to\n * snake_case JSON, and an error rendered as a RESULT rather than thrown.\n *\n * That last one is the reason this is a distinct concern rather than\n * incidental formatting: a tool handler that throws loses the payment state\n * the model needs to decide what to do next, so `toolError` deliberately\n * preserves it (payment_id, phase, next_action) in a shape a model can read.\n *\n * Pure functions over their inputs — no client, no network, no state.\n */\n\nexport function toolX402PaymentRequired(input: {\n url: string\n payTo: string\n amount: string\n asset: string\n network: string\n description?: string\n}): X402PaymentRequired {\n return {\n x402Version: 2,\n resource: { url: input.url, description: input.description },\n accepts: [\n {\n scheme: 'exact',\n network: input.network,\n amount: input.amount,\n asset: input.asset,\n payTo: input.payTo,\n maxTimeoutSeconds: 30,\n },\n ],\n }\n}\n\nexport function x402ToolReceipt(receipt: X402Receipt): Record<string, unknown> {\n return {\n success: true,\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n token: receipt.token,\n amount: receipt.amount,\n to: receipt.to,\n resource_url: receipt.resourceUrl,\n explorer_url: receipt.explorerUrl,\n payment_header: receipt.paymentHeader,\n merchant_to: receipt.merchantTo,\n payer: receipt.payer,\n chain_id: receipt.chainId,\n haven: receipt.haven,\n merchant: receipt.merchant,\n x402: receipt.x402,\n }\n}\n\nexport function toolError(err: unknown): Record<string, unknown> {\n if (err instanceof HavenPaymentStateError) {\n return {\n success: false,\n payment_id: err.state.paymentId,\n kind: err.state.kind,\n rail: err.state.rail,\n status: err.state.status,\n phase: err.state.phase,\n next_action: err.state.nextAction,\n tx_hash: err.state.txHash,\n token: err.state.token,\n amount: err.state.amount,\n resource_url: err.state.resourceUrl,\n merchant_address: err.state.merchantAddress,\n amount_atomic: err.state.amountAtomic,\n asset: err.state.asset,\n network: err.state.network,\n description: err.state.description,\n idempotency_key: err.state.idempotencyKey,\n x402: err.state.x402\n ? {\n amount_atomic: err.state.x402.amountAtomic,\n asset: err.state.x402.asset,\n network: err.state.x402.network,\n resource_url: err.state.x402.resourceUrl,\n merchant_address: err.state.x402.merchantAddress,\n description: err.state.x402.description,\n idempotency_key: err.state.x402.idempotencyKey,\n }\n : undefined,\n mpp: err.state.mpp\n ? {\n amount_atomic: err.state.mpp.amountAtomic,\n asset: err.state.mpp.asset,\n network: err.state.mpp.network,\n resource_url: err.state.mpp.resourceUrl,\n merchant_address: err.state.mpp.merchantAddress,\n description: err.state.mpp.description,\n idempotency_key: err.state.mpp.idempotencyKey,\n challenge_id: err.state.mpp.challengeId,\n }\n : undefined,\n resume_state: err.resumeState,\n expires_at: err.state.expiresAt,\n chain_id: err.state.chainId,\n message: err.state.message,\n error: err.message,\n }\n }\n\n if (err instanceof HavenApiError) {\n return {\n success: false,\n status_code: err.statusCode,\n error: err.message,\n body: err.body,\n }\n }\n\n return {\n success: false,\n error: err instanceof Error ? err.message : String(err),\n }\n}\n","import {\n AgentPaymentNextAction,\n AgentPaymentPhase,\n HavenApiError,\n HavenPaymentStateError,\n HavenZeroSettlementHashError,\n} from './types.js'\nimport type {\n PaymentStatusResult,\n X402PaymentRequired,\n X402Receipt,\n} from './types.js'\nimport {\n captureMerchantResponse,\n McpMerchantTransport,\n} from './mcp-merchant-transport.js'\nimport type { CapturedMerchantResponse } from './mcp-merchant-transport.js'\nimport {\n MCP_X402_PAYMENT_RESPONSE_META_KEY,\n X402_RETRY_REJECTED_STATUS,\n encodeMcpSettlementReceipt,\n extractMcpPaymentRequired,\n mcpSettlementFromToolResult,\n} from './mcp-merchant-transport.js'\nimport { x402PaymentHeaderNamesSent } from './x402.js'\nimport { buildExplorerUrl, x402PayerAddress } from './x402-protocol.js'\nimport { paymentStateStatusCode } from './payment-state.js'\nimport { decodeBase64Json } from './base64.js'\n\n/**\n * Merchant delivery and the evidence trail behind it (#1620, epic #1613).\n *\n * Where `mcp-merchant-transport.ts` (#1616) owns the wire — timeouts,\n * sessions, SSE framing — this module owns what has to be TRUE around a\n * merchant call once a payment exists: which wallet the merchant should see,\n * what the payment's live state permits, and what gets written down\n * afterwards.\n *\n * The reporting is deliberately best-effort and deliberately asymmetric. A\n * merchant that REJECTS a retry after Haven already moved money is a\n * reconciliation event and is recorded as one; a merchant that accepts is\n * evidence, plus its own receipt when it offers one. Neither write may ever\n * change the caller-visible outcome — the resource is already paid for, and\n * an exception thrown from bookkeeping would turn a completed payment into a\n * reported failure. That is why every one of these swallows.\n *\n * Scheme-neutral by construction: it is handed a receipt or a payment id and\n * never asks how the money moved, which is what lets the #1508 no-funding-leg\n * path through the same door as the 3009 path.\n *\n * Internal to `HavenClient`. Exported for direct tests and composition only.\n */\n\n/** #2292: what an agent says a merchant answered to a retry Haven did not make. */\nexport type X402MerchantOutcome = 'accepted' | 'rejected'\n\n/** #2292: what Haven wrote down for such a report. */\nexport interface X402MerchantOutcomeReport {\n paymentId: string\n outcome: X402MerchantOutcome\n /** Haven's own funding tx for this payment — the anchor, never caller-supplied. */\n txHash: string\n /** Haven's own recorded resource URL — likewise never caller-supplied. */\n resourceUrl: string\n recorded: 'reconciliation_event' | 'evidence'\n}\n\nconst MERCHANT_BODY_SNIPPET_LIMIT = 1000\n\n/**\n * Evidence-report retry policy for a RETRYABLE refusal (#2117).\n *\n * The backend already distinguishes two refusals on `POST\n * /machine-payments/evidence` and says so in the status code: `503`\n * (`settlement_unobservable`) means \"the chain could not be read, or the\n * settlement is not mined yet — report it again\", and `409` means \"that is a\n * settled no\". The SDK discarded that distinction in a bare `catch {}`,\n * treating both as best-effort silence — so on erc7710, where the reported hash\n * is the ONLY thing that produces an evidence row, a transaction that simply\n * had not been mined yet at report time meant the payment never reached the\n * user's books at all.\n *\n * Bounded, and terminal on anything that is not a 503: a retry loop against a\n * settled no is just noise, and the total wait has to stay far under any\n * caller's patience because the paid resource is already in hand. Four attempts\n * over ~7s of backoff covers the mine-latency case this exists for without ever\n * becoming a reason a completed payment feels slow.\n */\nconst EVIDENCE_RETRY_DELAYS_MS = [1_000, 2_000, 4_000]\n\n/** The backend's retryable refusal — see `modules/mpp/evidence.ts`. */\nconst EVIDENCE_RETRYABLE_STATUS = 503\n\nexport type PaymentPoster = <T>(path: string, body: Record<string, unknown>) => Promise<T>\nexport type PaymentStatusReader = (paymentId: string) => Promise<PaymentStatusResult>\nexport type AgentReader = () => Promise<{ delegateAddress?: string }>\n\nexport interface MerchantCompletionOptions {\n post: PaymentPoster\n merchantTransport: McpMerchantTransport\n getPaymentStatus: PaymentStatusReader\n getAgent: AgentReader\n delegateAddress: string | undefined\n x402Wallet: string | undefined\n /** Injectable only so tests do not spend the real backoff. */\n sleep?: (ms: number) => Promise<void>\n}\n\nexport class MerchantCompletion {\n private readonly post: PaymentPoster\n private readonly merchantTransport: McpMerchantTransport\n private readonly getPaymentStatus: PaymentStatusReader\n private readonly getAgent: AgentReader\n private readonly delegateAddress: string | undefined\n private readonly x402Wallet: string | undefined\n private readonly sleep: (ms: number) => Promise<void>\n\n constructor(options: MerchantCompletionOptions) {\n this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)))\n this.post = options.post\n this.merchantTransport = options.merchantTransport\n this.getPaymentStatus = options.getPaymentStatus\n this.getAgent = options.getAgent\n this.delegateAddress = options.delegateAddress\n this.x402Wallet = options.x402Wallet\n }\n\n async retryRequest(\n url: string,\n initialInit: RequestInit | undefined,\n paymentRequired: X402PaymentRequired,\n receipt: X402Receipt,\n ): Promise<Response> {\n if (!receipt.accepted) {\n throw new HavenApiError('No accepted x402 option was recorded for payment retry', 500)\n }\n if (!receipt.paymentHeader) {\n throw new HavenApiError('No x402 payment header was returned for payment retry', 500)\n }\n\n // 5. Retry with a merchant-verifiable x402 EIP-3009 payment header.\n // #3171: if the merchant's session is gone (expired, or it restarted\n // between the challenge and this retry) and it SAYS nothing was settled,\n // re-initialize and resend the same header once instead of reporting a\n // 404 as a rejection after funding.\n const retryResponse = await this.merchantTransport.deliverPaymentRecoveringSession(\n url,\n initialInit,\n receipt.paymentHeader,\n () => this.merchantTransport.initialize(url, initialInit),\n )\n\n // #3118: a profile merchant refuses under HTTP 200 with an `isError: true`\n // payment-required tool result or a `_meta[\"x402/payment-response\"]` of\n // `success: false` (#3155 review B2 — the same two signals the hosted\n // completion reads). Either is a rejection after funding exactly like a\n // non-2xx answer; the thrown status is 402 (what the merchant said\n // in-band) while the captured `merchant_status` keeps the real 200.\n // NOT gated on the request body (#3155 review r6): this read runs AFTER\n // the funding leg moved money, and a merchant that mixes dialects (HTTP-402\n // challenge, profile-style refusal on the paid answer) must still be seen.\n // The content-type gate inside readToolResult keeps binary/streaming paid\n // resources unbuffered.\n const toolResult = retryResponse.ok ? await this.merchantTransport.readToolResult(retryResponse) : undefined\n const inBandChallenge = toolResult ? extractMcpPaymentRequired(toolResult) : undefined\n const metaSettlement = toolResult ? mcpSettlementFromToolResult(toolResult) : undefined\n const inBandRejection = inBandChallenge !== undefined || metaSettlement?.success === false\n if (!retryResponse.ok || inBandRejection) {\n const merchant = await captureMerchantResponse(retryResponse)\n await this.recordRetryRejected({\n rail: 'x402',\n paymentId: receipt.paymentId,\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n merchant,\n details: {\n merchant_to: receipt.merchantTo,\n delegate_to: receipt.to,\n },\n })\n\n throw new HavenApiError(\n 'x402 retry failed after Haven funded the delegate wallet; reconciliation may be required.',\n inBandRejection ? X402_RETRY_REJECTED_STATUS : merchant.merchant_status,\n {\n marker: 'x402_retry_rejected_after_funding',\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n resource_url: receipt.resourceUrl,\n merchant_to: receipt.merchantTo,\n delegate_to: receipt.to,\n ...merchant,\n },\n )\n }\n\n // #3155 review S1: the `_meta` settlement is the receipt when there is no\n // header, re-encoded so the one existing decoder reads both forms.\n const headerReceipt = retryResponse.headers.get('PAYMENT-RESPONSE')\n const protocolReceiptHeader = headerReceipt ?? (metaSettlement ? encodeMcpSettlementReceipt(metaSettlement) : undefined)\n const protocolReceiptHeaderName = headerReceipt\n ? 'PAYMENT-RESPONSE'\n : metaSettlement\n ? `_meta.${MCP_X402_PAYMENT_RESPONSE_META_KEY}`\n : undefined\n const merchantSettlement = parseMerchantSettlement(protocolReceiptHeader ?? null)\n if (receipt.merchant && merchantSettlement.settlementTxHash) {\n receipt.merchant.settlementTxHash = merchantSettlement.settlementTxHash\n receipt.merchant.settlementExplorerUrl = buildExplorerUrl(\n receipt.chainId,\n merchantSettlement.settlementTxHash,\n )\n }\n\n await this.reportEvidence({\n paymentId: receipt.paymentId,\n rail: 'x402',\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n merchantStatus: retryResponse.status,\n challengePayload: paymentRequired as unknown as Record<string, unknown>,\n selectedPayment: receipt.accepted as unknown as Record<string, unknown>,\n paymentProofHeaderName: x402PaymentHeaderNamesSent(receipt.paymentHeader),\n paymentProofHeader: receipt.paymentHeader,\n protocolReceiptHeaderName,\n protocolReceiptHeader,\n })\n\n await this.reportMerchantReceipt(receipt.paymentId, retryResponse)\n\n return retryResponse\n }\n\n /**\n * #956: capture the merchant's OWN receipt when the paid response carries\n * one, and report it to Haven so the reporting feed can attach it next to\n * the Haven-generated payment evidence (#498). Two supported signals on the\n * paid response:\n *\n * x-receipt-json: base64-encoded JSON receipt document (inline)\n * x-receipt-url: https URL to the receipt document (reference)\n *\n * Strictly best-effort: absence is the normal case, and no failure here may\n * ever affect the completed payment — the response is already paid for.\n */\n async reportMerchantReceipt(paymentId: string, response: Response): Promise<void> {\n try {\n const inlineB64 = response.headers.get('x-receipt-json')\n const url = response.headers.get('x-receipt-url')\n if (!inlineB64 && !url) return\n\n let body: Record<string, unknown> | null = null\n if (inlineB64) {\n // Mirror the backend's 64KB decoded cap exactly (base64 inflates 4/3)\n // — don't ship what the server will reject.\n if (inlineB64.length > Math.ceil((64 * 1024 * 4) / 3)) return\n const decoded = JSON.parse(Buffer.from(inlineB64, 'base64').toString('utf8')) as unknown\n if (decoded && typeof decoded === 'object') body = { json: decoded }\n } else if (url && url.startsWith('https://') && url.length <= 2048) {\n body = { url }\n }\n if (!body) return\n\n await this.post(`/machine-payments/${paymentId}/merchant-receipt`, body)\n } catch {\n // Best-effort by contract — a malformed header or a capture-endpoint\n // hiccup never surfaces to the caller of a successful payment.\n }\n }\n\n async resolveCompletionContext(input: {\n paymentId: string\n url: string\n /** #1508: see completeX402MerchantCall's option of the same name. */\n noFundingLeg?: boolean\n }): Promise<{\n paymentId: string\n /** Null on a no-funding-leg scheme — there is no Haven-submitted tx. */\n txHash: string | null\n resourceUrl: string\n merchantAddress: string | null\n }> {\n const status = await this.getPaymentStatus(input.paymentId)\n\n if (status.rail !== 'x402') {\n throw new HavenPaymentStateError(\n `Payment ${status.paymentId} is ${status.rail}, not x402.`,\n 409,\n status,\n )\n }\n\n // #1508: BOTH conditions below encode the EIP-3009 lifecycle, where\n // `confirmed` means Haven's funding transaction mined and its hash is the\n // evidence anchor. On a no-funding-leg scheme neither is reachable, and\n // #1456 reused this helper unadapted — so every hosted erc7710 call threw\n // `HavenPaymentStateError(status.message)`, surfacing as \"The payment was\n // submitted and is waiting for confirmation\" AFTER the settlement had\n // already succeeded, with the merchant never contacted.\n //\n // `submitted` is not a transient state to wait out here: it is the CORRECT\n // and final Haven-side state for erc7710 (`modules/x402/settle.ts` — \"The\n // intent flips to 'submitted'; final settlement is observed via the\n // merchant/receipt path\"). The merchant redeems the [child, budget] chain,\n // which is exactly the call this method is about to make.\n const readyForMerchantCompletion = input.noFundingLeg\n ? status.kind === 'payment_intent' && status.status === 'submitted'\n : status.nextAction === AgentPaymentNextAction.RetryOriginalX402Request ||\n (\n status.kind === 'payment_intent' &&\n status.status === 'confirmed' &&\n status.phase === AgentPaymentPhase.PaymentConfirmed &&\n status.nextAction === AgentPaymentNextAction.None\n )\n\n if (!readyForMerchantCompletion) {\n throw new HavenPaymentStateError(status.message, paymentStateStatusCode(status.status, 409), status)\n }\n\n // Deliberately NOT relaxed to \"absent is fine\": on the funding-leg path a\n // missing hash still means the evidence anchor is gone and remains a 502.\n // The no-funding-leg path skips it because there is no such transaction to\n // be missing — not because the check is inconvenient.\n if (!input.noFundingLeg && !status.txHash) {\n throw new HavenApiError(\n `x402 payment ${status.paymentId} is ready for merchant completion but has no Haven transaction hash.`,\n 502,\n status,\n status.paymentId,\n )\n }\n\n const approvedResourceUrl = status.resourceUrl ?? status.x402?.resourceUrl ?? null\n if (approvedResourceUrl && approvedResourceUrl !== input.url) {\n throw new HavenApiError(\n 'x402 merchant completion does not match the approved resource URL.',\n 409,\n { status, url: input.url },\n status.paymentId,\n )\n }\n\n return {\n paymentId: status.paymentId,\n txHash: status.txHash,\n resourceUrl: approvedResourceUrl ?? input.url,\n merchantAddress: status.merchantAddress ?? status.x402?.merchantAddress ?? null,\n }\n }\n\n async resolveWalletForMerchantCall(): Promise<string | undefined> {\n const localWallet = x402PayerAddress(this.delegateAddress, this.x402Wallet)\n if (localWallet) return localWallet\n\n try {\n const agent = await this.getAgent()\n return agent.delegateAddress ?? undefined\n } catch {\n return undefined\n }\n }\n\n // #1328: authorizeMachinePayment / authorizeMppDemoPayment / resumeAuthorizedMpp\n // / resumeMppPayment / fetchWithMachinePayment / retryMppRequest (the\n // MACHINE-PAYMENT-CHALLENGE / mpp_demo client surface) are retired — the\n // backend's POST /machine-payments/authorize refuses unconditionally now,\n // and MACHINE-PAYMENT-CHALLENGE was never produced by any other Haven\n // surface. Use the x402 flow (authorizeX402 / fetch / quoteX402 / payX402Quote)\n // for agent-to-merchant payments.\n\n async recordRetryRejected(input: {\n rail: string\n paymentId: string\n txHash: string\n resourceUrl: string\n merchant: CapturedMerchantResponse\n details?: Record<string, unknown>\n }): Promise<void> {\n try {\n await this.post('/machine-payments/reconciliation-events', {\n paymentId: input.paymentId,\n rail: input.rail,\n eventType: 'merchant_retry_rejected_after_payment',\n txHash: input.txHash,\n reason: `Merchant returned HTTP ${input.merchant.merchant_status} after Haven payment confirmation`,\n details: {\n resource_url: input.resourceUrl,\n retry_status: input.merchant.merchant_status,\n retry_body: input.merchant.merchant_body.slice(0, MERCHANT_BODY_SNIPPET_LIMIT) || null,\n ...input.details,\n },\n })\n } catch {\n // Best-effort durability: preserve the original retry failure for callers.\n }\n }\n\n /**\n * #2292: record what a merchant said to a retry **Haven did not make**.\n *\n * On the plain-HTTP x402 path Haven tells the agent to call the merchant\n * itself — that is the keyless design, not an oversight — so the two writes\n * above were reachable only from `completeX402MerchantCall`, where Haven IS\n * the caller. A manual retry had nowhere to put its outcome, which left\n * `intentStateFor`'s merchant-rejected branch dead on the one flow Haven\n * prescribes and made the 15-minute grace window the only route to\n * `funded_but_unsettled`.\n *\n * Three properties distinguish this from `recordRetryRejected` /\n * `reportEvidence`, and each is deliberate:\n *\n * 1. **It does not swallow.** Those two are bookkeeping hung off a call\n * whose outcome is already decided, so an exception there would turn a\n * completed payment into a reported failure. Here the report IS the\n * caller's request; silently dropping it would recreate the exact\n * unobservability #2292 exists to remove.\n * 2. **The anchor is server-side.** `txHash` and `resourceUrl` come from\n * the payment's own Haven record, never from the reporter — so a report\n * cannot be pointed at a different transaction or a different resource,\n * and it can never CONFIRM an intent (an erc7710 intent has no Haven\n * tx hash and is refused here rather than completed from a supplied one,\n * which is #2092's verified seam and stays its own path).\n * 3. **It is evidence, never authority.** Haven does not and must not check\n * the claim: verifying it would mean calling the merchant, which is the\n * property this whole path exists to preserve. What bounds a false\n * report is scope — the backend routes resolve the payment\n * `WHERE agent_id = $`, so a caller can only ever describe its own\n * payment — plus the fact that nothing financial keys off the claim:\n * the sweep is balance-driven, the intent's status/amount/recipient are\n * untouched, and a false `accepted` runs the server's own on-chain\n * residue check, which re-flags stranded funds independently.\n */\n async reportMerchantOutcome(input: {\n paymentId: string\n outcome: X402MerchantOutcome\n merchantStatus: number\n merchantBody?: string\n }): Promise<X402MerchantOutcomeReport> {\n if (!Number.isInteger(input.merchantStatus) || input.merchantStatus < 100 || input.merchantStatus > 599) {\n throw new HavenApiError(\n `merchant_status must be an integer HTTP status from 100 to 599 (received ${input.merchantStatus}).`,\n 400,\n undefined,\n input.paymentId,\n )\n }\n // A self-contradictory report is refused rather than recorded: this is\n // the one thing about the claim Haven CAN check without contacting the\n // merchant, so it checks it.\n const looksAccepted = input.merchantStatus >= 200 && input.merchantStatus < 300\n if (looksAccepted !== (input.outcome === 'accepted')) {\n throw new HavenApiError(\n `outcome \"${input.outcome}\" contradicts merchant_status ${input.merchantStatus}: ` +\n 'report \"accepted\" only for a 2xx and \"rejected\" only for a non-2xx.',\n 400,\n undefined,\n input.paymentId,\n )\n }\n\n const status = await this.getPaymentStatus(input.paymentId)\n if (status.rail !== 'x402') {\n throw new HavenPaymentStateError(\n `Payment ${status.paymentId} is ${status.rail}, not x402 — there is no merchant retry to report.`,\n 409,\n status,\n )\n }\n if (status.status !== 'confirmed' || !status.txHash) {\n throw new HavenPaymentStateError(\n `Payment ${status.paymentId} has no confirmed Haven funding transaction to anchor a ` +\n `merchant report to (status ${status.status}). ${status.message}`,\n paymentStateStatusCode(status.status, 409),\n status,\n )\n }\n const resourceUrl = status.resourceUrl ?? status.x402?.resourceUrl ?? null\n if (!resourceUrl) {\n throw new HavenApiError(\n `Payment ${status.paymentId} has no recorded resource URL, so a merchant report cannot be stored.`,\n 409,\n status,\n status.paymentId,\n )\n }\n\n const txHash = status.txHash\n if (input.outcome === 'rejected') {\n await this.post('/machine-payments/reconciliation-events', {\n paymentId: status.paymentId,\n rail: 'x402',\n eventType: 'merchant_retry_rejected_after_payment',\n txHash,\n reason: `Agent-reported: merchant returned HTTP ${input.merchantStatus} to a manual retry after Haven payment confirmation`,\n details: {\n resource_url: resourceUrl,\n retry_status: input.merchantStatus,\n retry_body: input.merchantBody?.slice(0, MERCHANT_BODY_SNIPPET_LIMIT) || null,\n reported_by: 'agent_manual_retry',\n },\n })\n return { paymentId: status.paymentId, outcome: 'rejected', txHash, resourceUrl, recorded: 'reconciliation_event' }\n }\n\n await this.post('/machine-payments/evidence', {\n paymentId: status.paymentId,\n rail: 'x402',\n txHash,\n resourceUrl,\n merchantStatus: input.merchantStatus,\n })\n return { paymentId: status.paymentId, outcome: 'accepted', txHash, resourceUrl, recorded: 'evidence' }\n }\n\n async reportEvidence(input: {\n paymentId: string\n rail: string\n txHash: string\n /**\n * #2972: OPTIONAL — `haven_report_settlement_evidence` reports a hash the\n * agent holds out of band, with no fresh merchant HTTP exchange to read a\n * resource URL or status from. Omitting it is safe: the backend only\n * enforces a MATCH (`input.resourceUrl && input.resourceUrl !== resourceUrl`\n * in `modules/mpp/evidence.ts`) when one is supplied, never that one is\n * present. The funding-leg callers above keep passing the one Haven's own\n * record already named.\n */\n resourceUrl?: string\n /** #2972: OPTIONAL for the same reason as `resourceUrl` — see there. */\n merchantStatus?: number\n challengePayload?: Record<string, unknown>\n selectedPayment?: Record<string, unknown>\n paymentProofHeaderName?: string\n paymentProofHeader?: string\n protocolReceiptHeaderName?: string\n protocolReceiptHeader?: string\n }): Promise<EvidenceReportOutcome> {\n const body = {\n paymentId: input.paymentId,\n rail: input.rail,\n txHash: input.txHash,\n resourceUrl: input.resourceUrl,\n merchantStatus: input.merchantStatus,\n challengePayload: input.challengePayload,\n selectedPayment: input.selectedPayment,\n paymentProofHeaderName: input.paymentProofHeaderName,\n paymentProofHeader: input.paymentProofHeader,\n protocolReceiptHeaderName: input.protocolReceiptHeaderName,\n protocolReceiptHeader: input.protocolReceiptHeader,\n protocolReceiptPayload: input.protocolReceiptHeader\n ? parseProtocolReceiptHeader(input.protocolReceiptHeader)\n : undefined,\n }\n\n // Still best-effort in the sense that matters — nothing here may change\n // the caller-visible outcome, because the resource is already paid for and\n // delivered. What changed (#2117) is that a RETRYABLE refusal is no longer\n // swallowed identically to a terminal one. On erc7710 this report is the\n // only thing that produces an evidence row, and therefore the only thing\n // that puts the payment in the user's books.\n //\n // #2970: the RETURN value is now load-bearing too, not just the retry\n // decision. The hosted erc7710 settle/complete gate reads this outcome to\n // decide whether `settled: true` is honest — a caller that only awaited\n // this for its side effect (the local retryRequest path, #1620) is\n // unaffected: the resolved value is simply ignored there.\n for (let attempt = 0; ; attempt += 1) {\n try {\n await this.post('/machine-payments/evidence', body)\n return { outcome: 'confirmed' }\n } catch (err) {\n const statusCode = err instanceof HavenApiError ? err.statusCode : undefined\n const retryable = statusCode === EVIDENCE_RETRYABLE_STATUS\n if (!retryable) {\n return { outcome: 'refused', statusCode: statusCode ?? 0 }\n }\n if (attempt >= EVIDENCE_RETRY_DELAYS_MS.length) {\n return { outcome: 'retryable', statusCode }\n }\n await this.sleep(EVIDENCE_RETRY_DELAYS_MS[attempt])\n }\n }\n }\n\n /**\n * #2972: report the merchant's REAL settlement transaction hash for an\n * erc7710 x402 payment out of band — the remedy #2970's guidance could not\n * name, because no hosted tool accepted a hash. An agent reaches this after\n * `haven_settle_mcp_tool` / `haven_complete_mcp_tool` answered\n * `DELIVERED_UNSETTLED` or `SETTLEMENT_PENDING`, or after\n * `haven_get_payment_status` reports `awaiting_settlement_evidence` — in\n * every one of those cases the agent may be holding the merchant's own\n * `PAYMENT-RESPONSE.transaction` while Haven has nothing.\n *\n * Reuses `reportEvidence` — same backend seam\n * (`POST /machine-payments/evidence` → `observeErc7710Settlement`,\n * fail-closed — see `settlement-observed.ts`), same three-outcome contract.\n * `resourceUrl` and `merchantStatus` are omitted: this call has no fresh\n * merchant HTTP exchange to read either from, and both are optional at the\n * backend (see the parameter doc on `reportEvidence`).\n *\n * The zero hash is refused HERE, client-side, before any network call —\n * never posted. `isZeroSettlementTxHash` is the same recognizer the #2970\n * gate uses, so a caller cannot \"fix\" a missing hash by reporting the demo\n * merchant's own marker and getting a different verdict than the settle\n * path already gave it.\n */\n async reportSettlementEvidence(\n paymentId: string,\n settlementTxHash: string,\n ): Promise<EvidenceReportOutcome> {\n if (isZeroSettlementTxHash(settlementTxHash)) {\n throw new HavenZeroSettlementHashError(paymentId)\n }\n return this.reportEvidence({\n paymentId,\n rail: 'x402',\n txHash: settlementTxHash,\n })\n }\n}\n\n/**\n * #2970: what `reportEvidence` learned about the report it just made.\n *\n * `confirmed` mirrors the backend's 202 (`modules/mpp/evidence.ts`) — the\n * intent is now `confirmed` (or was already, on the funding-leg path) with\n * THIS hash recorded. `retryable` mirrors its 503 (`settlement_unobservable`,\n * exhausted the retry budget above): the chain could not be read, or the\n * transaction is not mined yet — ask again later. `refused` mirrors every\n * terminal refusal (409 `settlement_unverified`, a validation error, an\n * unknown payment id, or a transport failure with no HTTP status at all,\n * reported as `statusCode: 0`) — reporting the same hash again will not\n * change the answer.\n */\nexport type EvidenceReportOutcome =\n | { outcome: 'confirmed' }\n | { outcome: 'retryable'; statusCode: number | undefined }\n | { outcome: 'refused'; statusCode: number }\n\n/**\n * #2970: a hash of the form `0x00…00` is never a real transaction — it is the\n * demo merchant's own \"delivered, not settled\" marker (`ZERO_TX_HASH` in\n * `packages/demo-merchant-mcp/src/x402.ts`), reused rather than invented here\n * so the hosted gate and any other consumer recognise it the same way. Treated\n * as equivalent to \"no hash was reported\": there is nothing on-chain to verify,\n * so asking the backend to look is a wasted round trip that can only ever\n * resolve to a refusal.\n */\nexport function isZeroSettlementTxHash(hash: string | null | undefined): boolean {\n return typeof hash === 'string' && /^0x0+$/i.test(hash)\n}\n\nexport function parseMerchantSettlement(header: string | null): {\n settlementTxHash?: string | null\n} {\n if (!header) return {}\n const parsed = parseProtocolReceiptHeader(header)\n const tx =\n typeof parsed?.transaction === 'string'\n ? parsed.transaction\n : typeof parsed?.txHash === 'string'\n ? parsed.txHash\n : typeof parsed?.tx_hash === 'string'\n ? parsed.tx_hash\n : null\n return { settlementTxHash: tx }\n}\n\n\n/**\n * Digest of a delegation-rail signing payload, or `undefined` when there is\n * none (#1138).\n *\n * Guarded because a payload that cannot be hashed is not a recoverable\n * condition to paper over: the edge signer derives this same digest before\n * signing, so an unhashable payload can never be signed by anyone. Surfacing it\n * as a named Haven error beats letting a raw viem type error escape from the\n * middle of intent construction.\n */\n\nexport function parseProtocolReceiptHeader(value: string): Record<string, unknown> | undefined {\n try {\n return decodeBase64Json<Record<string, unknown>>(value)\n } catch {\n try {\n return JSON.parse(value) as Record<string, unknown>\n } catch {\n return undefined\n }\n }\n}\n","import { hashTypedData } from 'viem'\nimport {\n signHash,\n signUserOpTypedDataForDelegation,\n signSettlementDelegationTypedData,\n addressFromKey,\n verifySignature,\n} from './signer.js'\nimport { assertUserOpTypedDataBinding } from './userop-binding.js'\nimport {\n assertBoundDirectPaymentUserOp,\n assertOwnSettlementChild,\n HavenTypedDataRefusedError,\n type SettlementChildExpectation,\n} from './direct-payment-guard.js'\nimport type { PaymentReceipt, ReceiptVerification } from './receipt.js'\nimport type {\n HavenClientConfig,\n PaymentRequest,\n PaymentIntent,\n PaymentResult,\n PaymentStatusResult,\n PaymentResumeState,\n SignData,\n SweepResult,\n X402AuthorizationOptions,\n RawCreateResponse,\n RawSignResponse,\n RawStatusResponse,\n RawPaymentStatusResult,\n X402PaymentRequired,\n X402PaymentOption,\n X402Intent,\n X402McpTransport,\n X402McpCallContext,\n X402MerchantCallContext,\n RawX402MerchantCallContext,\n X402Quote,\n X402Receipt,\n X402RequestSnapshot,\n X402ResumeState,\n ResumeAuthorizedX402Input,\n ResumeX402PaymentInput,\n RawX402AuthorizeResponse,\n X402Erc7710Settlement,\n HavenAgent,\n HavenAgentSummary,\n HavenAgentAllowanceSummary,\n HavenAllowanceSummary,\n HavenBalanceCoverage,\n PostPurchaseAllowanceSummary,\n HavenPaymentReceipt,\n HavenPaymentReceiptsPage,\n CatalogSubmissionAccepted,\n HavenCatalogEntry,\n HavenCatalogSubmission,\n RawCatalogEntry,\n AgentPaymentWarning,\n} from './types.js'\nimport {\n AgentPaymentNextAction,\n AgentPaymentPhase,\n AgentPaymentRail,\n HavenApiError,\n HavenPaymentStateError,\n X402UnexpectedStatusError,\n X402AlreadySettledError,\n HavenSigningError,\n HavenTimeoutError,\n DEFAULT_CONFIRMATION_TIMEOUT_MS,\n} from './types.js'\nimport {\n buildX402IdempotencyKey,\n parsePaymentRequiredResponse,\n resolveTokenFromAddress,\n selectStandardPaymentOption,\n toStandardPaymentRequirements,\n x402AuthorizationAmount,\n x402PaymentHeaderNamesSent,\n} from './x402.js'\nimport type {\n SweepAuthorization,\n SweepPrepareResponse,\n SweepSubmitResponse,\n} from './sweep.js'\nimport { HavenApiTransport } from './haven-api-transport.js'\nimport type { HavenClientUpdate } from './client-identity.js'\nimport {\n mapPaymentResult,\n mapPaymentStatusResult,\n} from './payment-mappers.js'\nimport {\n paymentStateFromRaw,\n paymentStateStatusCode,\n throwPaymentStateError,\n} from './payment-state.js'\nimport {\n MCP_X402_PAYMENT_RESPONSE_META_KEY,\n McpMerchantTransport,\n encodeMcpSettlementReceipt,\n extractMcpPaymentRequired,\n mcpSettlementFromToolResult,\n mcpToolResultOf,\n} from './mcp-merchant-transport.js'\nimport { AccountReads } from './account-reads.js'\nimport { DelegateSweepApi } from './delegate-sweep.js'\nimport {\n assertCanResumeX402,\n attachResumeState,\n buildExplorerUrl,\n buildX402Quote,\n chainIdFromNetwork,\n chainIdOrNull,\n decimalFromUsdcAtomic,\n explorerUrlOrEmpty,\n noCompatiblePaymentOptionError,\n requestInitFromSnapshot,\n sameAddress,\n snapshotX402Request,\n withX402Wallet,\n x402PayerAddress,\n} from './x402-protocol.js'\nimport { X402FundingLeg } from './x402-funding-leg.js'\nimport { X402Erc7710 } from './x402-erc7710.js'\nimport { toolError, toolX402PaymentRequired, x402ToolReceipt } from './tool-adapter.js'\nimport { MerchantCompletion, isZeroSettlementTxHash, parseMerchantSettlement } from './merchant-completion.js'\nimport type { EvidenceReportOutcome, X402MerchantOutcome, X402MerchantOutcomeReport } from './merchant-completion.js'\n\nconst DEFAULT_POLLING_INTERVAL = 3_000\n\n/** Cap the merchant body persisted to the reconciliation event (the full body is kept on the thrown error). */\nconst MERCHANT_BODY_SNIPPET_LIMIT = 1000\n\n\n/**\n * Digest of a delegation-rail signing payload, or `undefined` when there is\n * none (#1138).\n *\n * Guarded because a payload that cannot be hashed is not a recoverable\n * condition to paper over: the edge signer derives this same digest before\n * signing, so an unhashable payload can never be signed by anyone. Surfacing it\n * as a named Haven error beats letting a raw viem type error escape from the\n * middle of intent construction.\n */\nfunction x402TypedDataDigest(typedData: unknown): string | undefined {\n if (!typedData || typeof typedData !== 'object') return undefined\n try {\n return hashTypedData(typedData as Parameters<typeof hashTypedData>[0])\n } catch (err) {\n throw new HavenSigningError(\n 'The x402 funding intent carried a sign_data.typed_data that is not a valid EIP-712 ' +\n 'payload (needs domain, types, primaryType, message), so its digest cannot be derived ' +\n 'and no signer could accept it. ' +\n `Underlying error: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/** Shared by {@link HavenClient.discoverTools} and {@link HavenClient.getCatalogEntry} (#1306). */\nfunction mapCatalogEntry(entry: RawCatalogEntry): HavenCatalogEntry {\n return {\n id: entry.id,\n name: entry.name,\n description: entry.description,\n category: entry.category,\n resourceUrl: entry.resource_url,\n rail: entry.rail,\n protocol: entry.protocol,\n toolName: entry.tool_name,\n toolArguments: entry.tool_arguments ?? null,\n priceDisplay: entry.price_display,\n priceAtomic: entry.price_atomic,\n asset: entry.asset,\n network: entry.network,\n status: entry.status,\n verifiedAt: entry.verified_at,\n source: entry.source,\n domainVerified: entry.domain_verified,\n verifiedPayable: entry.verified_payable,\n // #3078: absent (older backend) or null (unresolved join) both mean \"no\n // merchant known\" — the public field is then absent, never null.\n ...(entry.merchant\n ? {\n merchant: {\n id: entry.merchant.id,\n slug: entry.merchant.slug,\n name: entry.merchant.name,\n listingStatus: entry.merchant.listing_status,\n isTestMerchant: entry.merchant.is_test_merchant,\n },\n }\n : {}),\n }\n}\n\nexport class HavenClient {\n private readonly delegateKey: string | undefined\n private readonly havenApi: HavenApiTransport\n private readonly accountReads: AccountReads\n private readonly delegateSweep: DelegateSweepApi\n private readonly x402Wallet: string | undefined\n private readonly merchantTransport: McpMerchantTransport\n private readonly confirmationTimeout: number\n private readonly pollingInterval: number\n private readonly chainRpcs: Record<number, string>\n private readonly inFlightX402 = new Map<string, Promise<X402Receipt>>()\n /**\n * The EIP-3009 funding-leg lifecycle (#1618). The facade holds a reference\n * and delegates; it does not reimplement any of it.\n */\n private readonly fundingLeg: X402FundingLeg\n /**\n * The erc7710 direct-settlement lifecycle (#1619). Separate from the funding\n * leg on purpose: this scheme has no funding leg to share.\n */\n private readonly erc7710: X402Erc7710\n /**\n * Merchant delivery and the evidence trail behind it (#1620). Scheme-neutral\n * on purpose — both settlement schemes finish through the same door.\n */\n private readonly merchantCompletion: MerchantCompletion\n /** Delegate address derived from the private key (if provided) */\n readonly delegateAddress: string | undefined\n\n constructor(config: HavenClientConfig) {\n this.delegateKey = config.delegateKey\n this.havenApi = new HavenApiTransport(config)\n this.accountReads = new AccountReads({\n transport: this.havenApi,\n getPaymentStatus: (paymentId) => this.getPaymentStatus(paymentId),\n })\n this.delegateSweep = new DelegateSweepApi({\n transport: this.havenApi,\n delegateKey: config.delegateKey,\n chainRpcs: config.chainRpcs ?? {},\n getAgent: () => this.getAgent(),\n buildExplorerUrl: (chainId, hash) => buildExplorerUrl(chainId, hash),\n })\n this.x402Wallet = config.x402Wallet\n this.merchantTransport = new McpMerchantTransport({ merchantTimeout: config.merchantTimeout })\n // #1756 moved the 90 s literal to `types.ts` so the delegate sweep shares\n // this number rather than choosing a fourth one. Same value, same default.\n this.confirmationTimeout = config.confirmationTimeout ?? DEFAULT_CONFIRMATION_TIMEOUT_MS\n this.pollingInterval = config.pollingInterval ?? DEFAULT_POLLING_INTERVAL\n this.chainRpcs = config.chainRpcs ?? {}\n if (this.delegateKey) {\n this.delegateAddress = addressFromKey(this.delegateKey)\n }\n // Constructed LAST: the funding leg pays into `delegateAddress`, which is\n // only derived on the line above.\n this.fundingLeg = new X402FundingLeg({\n delegateKey: this.delegateKey,\n delegateAddress: this.delegateAddress,\n x402Wallet: this.x402Wallet,\n chainRpcs: this.chainRpcs,\n post: (path, body) => this.post(path, body),\n signForData: (signData) => this.signForData(signData),\n assertSignableAuthorizationState: (label, raw) =>\n this.throwIfNonSignableAuthorizationState(label, raw),\n })\n this.merchantCompletion = new MerchantCompletion({\n post: (path, body) => this.post(path, body),\n merchantTransport: this.merchantTransport,\n getPaymentStatus: (paymentId) => this.getPaymentStatus(paymentId),\n getAgent: () => this.getAgent(),\n delegateAddress: this.delegateAddress,\n x402Wallet: this.x402Wallet,\n })\n this.erc7710 = new X402Erc7710({\n delegateKey: this.delegateKey,\n post: (path, body) => this.post(path, body),\n signForData: (signData, settlementExpectation) =>\n this.signForData(signData, settlementExpectation),\n getAgent: () => this.getAgent(),\n })\n }\n\n /**\n * Run `fn` with extra Haven-API headers scoped to the async work it\n * performs. Used by the MCP server to tag every Haven API request that\n * a single tool dispatch makes with `X-Haven-MCP-Tool: <name>` so the\n * backend can write an audit-log row attributing the call.\n *\n * The headers are held in an `AsyncLocalStorage` so overlapping\n * dispatches do not leak headers into each other's requests. The store\n * inherits across `await` boundaries, so any Haven API call made while\n * `fn` is awaiting will pick up the right headers.\n *\n * Has no effect on outbound merchant requests (x402 / MPP) — those\n * never go through the internal `request<T>` path that reads the\n * context.\n */\n withRequestContext<T>(headers: Record<string, string>, fn: () => Promise<T>): Promise<T> {\n return this.havenApi.withRequestContext(headers, fn)\n }\n\n /**\n * The backend's newest `client_update` hint for this client (#3303): inside\n * a `withRequestContext` dispatch, the one that dispatch's own requests\n * received; outside one, the latest seen. Undefined when the client is\n * current or the backend predates #3303.\n */\n clientUpdate(): HavenClientUpdate | undefined {\n return this.havenApi.clientUpdate()\n }\n\n // ── High-Level API ───────────────────────────────────────────────\n\n /**\n * Send a payment in one call.\n *\n * Creates the intent, signs its `sign_data` (a delegation-rail intent's\n * EIP-712 typed data, after the #3271 UserOp binding check), submits the signature,\n * and polls until confirmed (or throws on failure/timeout).\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async pay(request: PaymentRequest): Promise<PaymentResult> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'Cannot use pay() without a delegateKey. Use createIntent() + submitSignature() for manual signing.',\n )\n }\n\n // Step 1: Create intent\n const intent = await this.createIntent(request)\n\n // Step 2: Sign — through signForData so every rail's typed-data checks\n // (including the #3271 UserOp binding check) run before signing, rather\n // than signing intent.signData.hash directly.\n const signature = await this.signForData(intent.signData)\n\n // Step 3: Submit\n await this.submitSignature(intent.paymentId, signature)\n\n // Step 4: Wait for confirmation\n return this.waitForConfirmation(intent.paymentId)\n }\n\n // ── Step-by-Step API ─────────────────────────────────────────────\n\n /**\n * Step 1: Create a payment intent.\n *\n * Returns the intent with the hash to sign.\n */\n async createIntent(request: PaymentRequest): Promise<PaymentIntent> {\n const raw = await this.post<RawCreateResponse>('/payments', {\n token: request.token,\n amount: request.amount,\n to: request.to,\n ...(request.idempotencyKey ? { idempotency_key: request.idempotencyKey } : {}),\n })\n\n // Haven returns HTTP 202 with this status when the requested amount\n // exceeds the on-chain allowance. The payment is parked for the owner\n // to approve in the dashboard — there's nothing to sign yet, so the SDK\n // surfaces it as an explicit error rather than returning a malformed\n // intent with no signData.\n if (raw.status === 'pending_approval') {\n throwPaymentStateError('Payment', raw)\n }\n\n return {\n paymentId: raw.payment_id,\n status: 'pending_signature',\n expiresAt: raw.expires_at,\n signData: raw.sign_data,\n }\n }\n\n /**\n * Keyless x402 construct.\n *\n * The non-custodial half of an x402 payment: posts the funding request to\n * `/x402` and returns the unsigned funding hash plus the data the caller\n * needs to build and sign the EIP-3009 merchant header itself. Crucially it\n * does **not** sign — neither the funding hash nor the merchant header — so\n * it works without a `delegateKey`. Both delegate signatures happen on the\n * machine that holds the key (the edge); the hosted MCP server relays only.\n *\n * Use this from the hosted, keyless server. The all-in-one `authorizeX402`\n * remains for local clients that hold the key.\n *\n * Throws (via the shared payment-state path) when the amount exceeds the\n * on-chain allowance — there is nothing to sign until the user approves.\n */\n async createX402Intent(\n paymentRequired: X402PaymentRequired,\n options: X402AuthorizationOptions = {},\n ): Promise<X402Intent> {\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n if (!option) {\n throw noCompatiblePaymentOptionError(paymentRequired.accepts)\n }\n\n // The funding transfer tops up the agent's delegate EOA. With no local key\n // we resolve that address from the authenticated agent record rather than\n // deriving it from a private key. #1348: a caller that already fetched the\n // agent in this flow passes delegateAddress and skips the duplicate fetch.\n const fundingTo = options.delegateAddress ?? (await this.getAgent()).delegateAddress\n if (!fundingTo) {\n throw new HavenApiError('Authenticated agent has no delegate address registered.', 502)\n }\n\n const idempotencyKey = options.idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option)\n const raw = await this.post<RawX402AuthorizeResponse>('/x402', {\n url: paymentRequired.resource.url,\n payTo: fundingTo,\n merchantPayTo: option.payTo,\n // #1360: this path ALWAYS means the EIP-3009 funding leg (payTo is the\n // agent's own delegate EOA). Saying so explicitly turns a stale/rotated\n // delegate address into the backend's LOUD shape-mismatch 400 instead\n // of a silent reroute to the erc7710 settlement branch (the #1358\n // review's open-budget misroute). Legacy-rail backends ignore the field.\n settlementScheme: 'eip3009',\n amount: x402AuthorizationAmount(option),\n asset: option.asset,\n network: option.network,\n description: paymentRequired.resource.description,\n idempotencyKey,\n // #1307: persisted so the settle leg can rehydrate it by payment_id.\n ...(options.mcpCallContext ? { mcpCallContext: options.mcpCallContext } : {}),\n // #1355: persisted so the SIGN leg can rehydrate it by payment_id — the\n // local signer's context fetch then carries the 402 PaymentRequired and\n // the agent passes only payment_id. Bounded: the backend rejects >64KB,\n // so an oversized blob is omitted here (signer falls back to the\n // caller-supplied copy) rather than failing the intent.\n ...(new TextEncoder().encode(JSON.stringify(paymentRequired)).length <= 65536\n ? { paymentRequired }\n : {}),\n })\n\n // Anything other than a signable funding intent (pending_approval,\n // expired, already-executed, error) is surfaced through the shared path.\n if (raw.status !== 'pending_signature') {\n throwPaymentStateError('x402 payment', raw)\n }\n if (!raw.sign_data?.hash) {\n throw new HavenApiError('No sign_hash returned from x402/authorize', 500, raw)\n }\n // #946/#1138: a delegation-rail funding intent signs the ACCOUNT's EIP-712\n // typed data, not the bare hash. This path is keyless by construction, so\n // it does not sign either one — it passes the payload through to whoever\n // holds the key (the local signer the connector installs). What it MUST\n // refuse is a scheme it cannot describe faithfully: handing a caller a\n // `hash` for a typed-data intent invites a raw ECDSA signature the account\n // rejects at the bundler, after the intent is claimed.\n if (raw.sign_data.signature_scheme !== undefined && !raw.sign_data.typed_data) {\n throw new HavenSigningError(\n `This account's x402 funding intent declares signature scheme ` +\n `'${raw.sign_data.signature_scheme}' but carried no typed_data to sign. ` +\n 'Refusing to fall back to the bare hash — the account would reject that signature ' +\n 'on-chain. This is a backend contract violation; report it rather than working around it.',\n )\n }\n if (!raw.x402_expected_auth) {\n throw new HavenApiError('No x402 expected-context binding returned from x402/authorize', 500, raw)\n }\n\n return {\n paymentId: raw.payment_id,\n idempotencyKey,\n status: 'pending_signature',\n expiresAt: raw.expires_at,\n signData: raw.sign_data,\n accepted: option,\n resourceUrl: paymentRequired.resource.url,\n merchantTo: raw.merchant_to ?? option.payTo,\n amountAtomic: x402AuthorizationAmount(option),\n asset: option.asset,\n network: option.network,\n expectedAuth: raw.x402_expected_auth,\n payerDelegate: (raw as { payer_delegate?: string }).payer_delegate,\n payerAgentId: (raw as { payer_agent_id?: string }).payer_agent_id,\n // #1138: the digest the delegation-rail expected context commits to.\n // Re-derived locally, exactly like every other context field the edge\n // signer is handed (amount, merchantTo, …) — none of them are trusted\n // because they arrived, they are trusted because the reconstructed\n // message has to match Haven's signature over it. A typed_data altered in\n // transit therefore fails message equality and is refused, and the signer\n // re-derives this digest a second time from the payload it actually signs.\n expectedTypedDataHash: x402TypedDataDigest(raw.sign_data.typed_data),\n fundingTo,\n }\n }\n\n /**\n * Step 2: Sign a hash with the delegate key.\n *\n * Returns the 65-byte signature (0x-prefixed).\n * Requires `delegateKey` to be set in the client config.\n */\n sign(hash: string): string {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'Cannot sign without a delegateKey. Pass the private key in HavenClient config, or sign externally.',\n )\n }\n\n const signature = signHash(this.delegateKey, hash)\n\n // Verify the signature locally before submitting\n if (!verifySignature(hash, signature, this.delegateAddress!)) {\n throw new HavenSigningError(\n 'Local signature verification failed — recovered address does not match delegate key.',\n )\n }\n\n return signature\n }\n\n /**\n * Sign a payment's `sign_data` with the correct scheme for its rail.\n *\n * Dispatching on the server-provided scheme means a caller never has to\n * know which rail an account is on; an unknown scheme — or an absent one,\n * since the legacy AllowanceModule rail retired (#2850) — is a hard error,\n * never a guessed signature. The session rail's 'eip191_userop' is retired\n * (#834) — the backend refuses those intents with HTTP 410 before any\n * sign_data reaches a client, so encountering it here is a hard error too.\n */\n private async signForData(\n signData: {\n hash: string\n signature_scheme?: string\n typed_data?: unknown\n },\n settlementExpectation?: SettlementChildExpectation,\n ): Promise<string> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'Cannot sign without a delegateKey. Pass the private key in HavenClient config, or sign externally.',\n )\n }\n const scheme = signData.signature_scheme\n if (scheme === 'eip191_userop') {\n throw new HavenSigningError(\n \"The session rail is retired — 'eip191_userop' intents can no longer be signed. Re-onboard the account on the delegation rail.\",\n )\n }\n if (scheme === 'eip712_userop') {\n if (!signData.typed_data) {\n throw new HavenSigningError(\n 'sign_data.signature_scheme is eip712_userop but typed_data is missing — refusing to sign the bare hash (the account would reject it).',\n )\n }\n // #3271: refuse before signing unless the typed data recomputes to\n // exactly signData.hash, in the HybridDeleGator domain of its own\n // sender, against the v0.7 EntryPoint — a corrupted typed-data payload\n // used to produce a valid-looking signature over the wrong digest.\n assertUserOpTypedDataBinding(signData.typed_data, signData.hash)\n // #3283 (epic #3284): the binding proves the typed data and hash agree,\n // but the Haven API response supplies both. Sign only the ONE shape a\n // direct payment or funding leg is — this key's own account redeeming a\n // single budget delegation through the DelegationManager — so a\n // compromised API cannot get a self-call or an empty-context\n // redemption (account capture) signed. Same check as `haven_sign`.\n assertBoundDirectPaymentUserOp(\n signData.typed_data as Record<string, unknown>,\n this.delegateAddress!,\n )\n return signUserOpTypedDataForDelegation(this.delegateKey, signData.typed_data as never)\n }\n if (scheme === 'eip712_delegation') {\n // The erc7710 x402 settlement child (#1452, epic #1450). Same guard as\n // eip712_userop above, and for a sharper reason: this signature lets a\n // facilitator pull the exact amount from the treasury. Falling back to\n // the bare hash would produce a signature the DelegationManager rejects\n // at redemption — a failure that surfaces on-chain, after the agent has\n // already told the merchant it paid.\n if (!signData.typed_data) {\n throw new HavenSigningError(\n 'sign_data.signature_scheme is eip712_delegation but typed_data is missing — refusing to sign the bare hash (the settlement would be rejected on redemption).',\n )\n }\n // #3283: this signature lets a facilitator pull from the treasury, so\n // verify the child means what the MERCHANT'S 402 asked for — payee,\n // amount, token, chain, facilitators, a bounded expiry — and that it is\n // a re-delegation of this agent's own budget (delegator = this key's\n // account, never a ROOT grant). Without an expectation there is nothing\n // Haven did not also write to verify it against, so refuse.\n if (!settlementExpectation) {\n throw new HavenTypedDataRefusedError(\n 'Refusing to sign an x402 settlement child without an independent expectation of what ' +\n \"it must pay (the merchant's 402). Pay erc7710 merchants through \" +\n 'settleX402Erc7710(), which supplies it.',\n )\n }\n assertOwnSettlementChild(signData.typed_data, settlementExpectation, this.delegateAddress!)\n return signSettlementDelegationTypedData(this.delegateKey, signData.typed_data as never)\n }\n if (scheme === undefined) {\n // The legacy AllowanceModule rail signed the bare hash when no scheme\n // was present. Every live sign_data emitter sets `signature_scheme` and\n // the backend spec makes it required, so absence is a malformed payload:\n // refuse it loudly rather than silently signing on a guessed scheme\n // (#2850, epic #1440). signHash itself stays live for the EIP-3009 leg.\n throw new HavenSigningError(\n 'sign_data.signature_scheme is required — the legacy AllowanceModule rail that signed the bare hash is retired (#2850). Refusing to guess a signing scheme.',\n )\n }\n throw new HavenSigningError(\n `Unknown sign_data.signature_scheme '${scheme}' — refusing to guess a signing scheme. Update @haven_ai/sdk.`,\n )\n }\n\n /**\n * Step 3: Submit a signature to execute the payment.\n *\n * The signature can come from `client.sign()` or from external signing.\n */\n async submitSignature(\n paymentId: string,\n signature: string,\n ): Promise<{ status: string; txHash?: string }> {\n const raw = await this.post<RawSignResponse>(\n `/payments/${paymentId}/sign`,\n { signature },\n )\n\n return {\n status: raw.status,\n txHash: raw.tx_hash,\n }\n }\n\n /**\n * Get the current status of a payment.\n */\n async getPayment(paymentId: string): Promise<PaymentResult> {\n const raw = await this.get<RawStatusResponse>(`/payments/${paymentId}`)\n return mapPaymentResult(raw, buildExplorerUrl)\n }\n\n /**\n * Get agent-actionable status for a payment intent or approval request.\n *\n * Use this for IDs returned by agent tools and machine-payment/x402 flows.\n * `getPayment()` remains available for payment-intent-only integrations.\n */\n async getPaymentStatus(paymentId: string): Promise<PaymentStatusResult> {\n const raw = await this.get<RawPaymentStatusResult>(`/machine-payments/${paymentId}/status`)\n return mapPaymentStatusResult(raw)\n }\n\n /**\n * Get the agent identity tied to this API key.\n */\n async getAgent(): Promise<HavenAgent> {\n return this.accountReads.getAgent()\n }\n\n /**\n * One-shot \"am I ready?\" bootstrap: identity + live spend authority + a\n * readiness signal, in a single call. Folds {@link getAgent} and\n * {@link getAllowances} together and derives a {@link HavenAgentReadiness}\n * so an agent can answer \"who am I and can I pay right now\" at session start\n * without two round trips and manual assembly.\n */\n async getAgentSummary(): Promise<HavenAgentSummary> {\n return this.accountReads.getAgentSummary()\n }\n\n /**\n * Sweep stranded USDC and ETH from the delegate EOA back to the agent's Haven account.\n *\n * The delegate key held by this client signs and submits the transfer transactions\n * directly — Haven's backend never handles the key or constructs signed txs\n * (CASP/MiCA Red Line #2). Funds always go to the Haven account linked to this agent\n * (`accountAddress` from `getAgent()`).\n *\n * Requires `chainRpcs` to be set for the agent's chain in `HavenClientConfig`.\n */\n async sweepDelegate(): Promise<SweepResult> {\n return this.delegateSweep.sweepDelegate()\n }\n\n /**\n * Hosted (keyless) split-signer sweep — step 1 of 2.\n *\n * Asks the backend to build a gasless EIP-3009 sweep authorization for the\n * delegate's stranded USDC. Returns `nothing_stranded` when the delegate is\n * empty, otherwise an `authorization` + Haven `expected_auth` to hand to the\n * edge signer's `haven_sign_sweep_delegate`. No key is required on this client.\n */\n async prepareSweep(): Promise<SweepPrepareResponse> {\n return this.delegateSweep.prepareSweep()\n }\n\n /**\n * Hosted (keyless) split-signer sweep — step 2 of 2.\n *\n * Relays the delegate-signed authorization. The Haven relayer submits the\n * on-chain `transferWithAuthorization` and pays gas; this client never holds\n * the key.\n */\n async submitSweep(\n authorization: SweepAuthorization,\n signature: string,\n ): Promise<SweepSubmitResponse> {\n return this.delegateSweep.submitSweep(authorization, signature)\n }\n\n /**\n * Get configured and on-chain allowances for the authenticated agent.\n */\n async getAllowances(): Promise<HavenAllowanceSummary> {\n return this.accountReads.getAllowances()\n }\n\n /**\n * #3126 — is the checked amount of the token actually HELD on the\n * agent's own account?\n *\n * This is the companion to {@link getAllowances}, not a variant of it:\n * allowances answer what the agent is PERMITTED to spend this period;\n * this answers whether the account HOLDS funds behind that permission,\n * as a sufficiency signal — `covered: true | false | null` — never as a\n * balance. `covered: null` means the chain read failed: treat it as\n * unverifiable, not as absence (`coverageError` says why). The account's\n * balance itself is deliberately not returned.\n */\n async checkFunds(input: { token: string; amountAtomic: string }): Promise<HavenBalanceCoverage> {\n return this.accountReads.checkFunds(input)\n }\n\n /**\n * `POST /machine-payments/budget-precheck` (#3054): ask Haven to decide —\n * server-side — whether `amountAtomic` of `token` fits the agent's\n * remaining delegation budget, the same compare the guided prepare used to\n * run locally over its allowances read.\n *\n * On insufficiency Haven refuses (403, `delegation_budget_exceeded`) and\n * the refusal reaches the `payment_refusals` ledger with\n * `source: 'hosted_prepare'` — the point of the endpoint. This method\n * surfaces that decision as a thrown {@link HavenApiError}; it does NOT\n * swallow it, because swallowing would turn a decided refusal into the\n * degrade-to-warning path and the ledger row would still land while the\n * purchase proceeded.\n *\n * camelCase body like the route family; the response mirrors the wire\n * (`sufficient`, `remaining_atomic`). `resourceUrl` is the merchant\n * resource being bought — the ledger dedupe window's discriminating\n * column — never this request's own URL.\n */\n async precheckBudget(input: {\n chainId?: number\n token: string\n amountAtomic: string\n merchantTo?: string\n resourceUrl?: string\n }): Promise<{ sufficient: boolean; remaining_atomic: string; remaining_is_from_chain?: boolean }> {\n return this.post<{\n sufficient: boolean\n remaining_atomic: string\n remaining_is_from_chain?: boolean\n }>('/machine-payments/budget-precheck', {\n chainId: input.chainId,\n token: input.token,\n amountAtomic: input.amountAtomic,\n ...(input.merchantTo !== undefined ? { merchantTo: input.merchantTo } : {}),\n ...(input.resourceUrl !== undefined ? { resourceUrl: input.resourceUrl } : {}),\n })\n }\n\n /**\n * Post-purchase allowance/budget summary for a settled payment (#1310).\n *\n * Reuses the EXACT rail-aware read path {@link getAllowances} / #1306's\n * catalog-purchase preflight `allowance` block use — `GET\n * /machine-payments/allowances`, with delegation-rail values coming from\n * the #1090 `deriveDelegationBudgets`-backed enforcer read, never\n * `agent_allowances` — so this can never disagree with\n * {@link getAllowances} for the same fixture. The settled token is\n * resolved from {@link getPaymentStatus} so callers pass only\n * `paymentId`, never a second haven_get_agent-style round trip.\n *\n * NEVER throws: any failed read (status lookup, agent lookup, or the\n * allowance/budget lookup itself) degrades to `{ allowance: null,\n * warnings: [ALLOWANCE_CHECK_UNAVAILABLE] }` rather than converting a\n * successful settlement into a failure — the on-chain policy remains the\n * actual spend gate regardless of whether this report can be produced.\n *\n * Freshness caveat (#1319): the delegation rail's on-chain enforcer read\n * can silently fall back to the optimistic full period budget without\n * throwing when the RPC read itself fails (#1145's fund-safe design,\n * unchanged here). {@link getAllowances}'s `onchain.remainingIsFromChain`\n * now carries that provenance on the wire, and the #1306 catalog-purchase\n * preflight (`haven_prepare_catalog_purchase`) surfaces it as a warning —\n * this summary does not (yet). `remaining_atomic` here reflects the last\n * successful chain read, not a guaranteed-live one, and callers should not\n * phrase it as guaranteed-fresh.\n */\n async getPostPurchaseAllowanceSummary(\n paymentId: string,\n ): Promise<{\n allowance: PostPurchaseAllowanceSummary | null\n warnings: AgentPaymentWarning[]\n payment: PaymentStatusResult | null\n }> {\n return this.accountReads.getPostPurchaseAllowanceSummary(paymentId)\n }\n\n /**\n * `haven_get_payment_status` convenience: fetch status and, for a\n * genuinely SETTLED x402 payment, attach the same post-purchase\n * allowance/budget summary a settle response carries.\n *\n * #1310/#1311 parity: this is the ONE home for logic that was duplicated\n * verbatim in the hosted and local `haven_get_payment_status` handlers —\n * `packages/mcp-server/src/tools/state-direct-recovery.ts` since #2809 (it\n * was `packages/mcp-server/src/tools.ts` when this was written) and\n * `packages/mcp/src/tools.ts` — extracted\n * here because both packages already depend on `@haven_ai/sdk` and call\n * methods on a `HavenClient` instance, so this needed no new dependency\n * edge. `funded_but_unsettled` is deliberately excluded: that phase means\n * the merchant did NOT accept the retry. Every other phase/rail returns\n * the status untouched.\n */\n async getPaymentStatusWithPostPurchaseAllowance(paymentId: string): Promise<\n PaymentStatusResult & {\n allowance?: PostPurchaseAllowanceSummary | null\n warnings?: AgentPaymentWarning[]\n }\n > {\n const status = await this.getPaymentStatus(paymentId)\n if (status.rail === AgentPaymentRail.X402 && status.phase === AgentPaymentPhase.PaymentConfirmed) {\n const { allowance, warnings } = await this.getPostPurchaseAllowanceSummary(paymentId)\n return { ...status, allowance, ...(warnings.length > 0 ? { warnings } : {}) }\n }\n return status\n }\n\n /**\n * Discover payable services from Haven's merchant catalog (epic #1717).\n *\n * Read-only: returns catalog entries (price, rail, protocol) so an agent\n * can choose a service and pay it with the regular payment tools in the\n * same session. Never creates payments or signatures.\n */\n async discoverTools(\n options: {\n category?: string\n search?: string\n rail?: 'x402' | 'mpp'\n /**\n * `'verified'` (epic #1717, #2978) returns entries whose endpoint Haven\n * watched answer a live quote — `verifiedPayable === true` — from\n * EITHER source: an operator-curated row that keeps passing its\n * periodic 402 probe, or a self-submitted row that also passed\n * domain-ownership proof. It is not a provenance filter; `'operator'`\n * still filters on provenance (`source === 'operator'`) regardless of\n * badge state, and `'any'` (the default) returns the merged listing.\n */\n verified?: 'any' | 'verified' | 'operator'\n } = {},\n ): Promise<HavenCatalogEntry[]> {\n const params = new URLSearchParams()\n if (options.category) params.set('category', options.category)\n if (options.search !== undefined) params.set('search', options.search)\n if (options.rail) params.set('rail', options.rail)\n const query = params.size > 0 ? `?${params.toString()}` : ''\n const raw = await this.get<{ entries: RawCatalogEntry[] }>(`/catalog${query}`)\n let entries = raw.entries.map(mapCatalogEntry)\n if (options.verified === 'verified') entries = entries.filter((e) => e.verifiedPayable === true)\n if (options.verified === 'operator') entries = entries.filter((e) => e.source === 'operator')\n return entries\n }\n\n /**\n * Submit a merchant's payable (x402/MCP) endpoint to the Verified Payable\n * Directory (epic #1717, #1716). Queue-only: writes a submission row and\n * returns the id + verify_token. The request path makes no outbound\n * request; domain-ownership proof and the read-only quote probe run later\n * on the leader-locked monitor. Ownership proof is ALWAYS required before\n * any listing — this method cannot skip it. `website` is a honeypot field\n * that bots fill; leave it unset.\n */\n async submitCatalogEntry(\n resourceUrl: string,\n options: { website?: string } = {},\n ): Promise<HavenCatalogSubmission> {\n const accepted = await this.post<CatalogSubmissionAccepted>('/catalog/submit', {\n resource_url: resourceUrl,\n ...(options.website ? { website: options.website } : {}),\n })\n return {\n id: accepted.id,\n verifyToken: accepted.verify_token,\n status: accepted.status,\n }\n }\n\n /**\n * Fetch one submission's coarse status by id (epic #1717, #1716). Public\n * and read-only. While the submission can still prove ownership the\n * response carries the exact well-known / DNS-TXT `instructions`; the\n * verify token is never returned here.\n */\n async getCatalogSubmissionStatus(\n id: string,\n ): Promise<{\n id: string\n status: 'submitted' | 'ownership_verified' | 'verified_payable' | 'failed' | 'delisted'\n instructions?: {\n expires_at: string\n well_known: { url: string; content: string; instruction: string }\n dns_txt: { name: string; value: string; instruction: string }\n } | null\n }> {\n return this.get(`/catalog/submit/${encodeURIComponent(id)}`)\n }\n\n /**\n * Fetch one curated catalog entry by id (#1306).\n *\n * Chain-scoped for free by the backend's SQL when the client is\n * agent-authenticated (#1299): an unknown id and an id curated for a\n * DIFFERENT chain than this agent's both 404 identically — this method does\n * not (and must not) re-filter by chain in JS. Read-only, like\n * {@link discoverTools}.\n */\n async getCatalogEntry(id: string): Promise<HavenCatalogEntry> {\n const raw = await this.get<RawCatalogEntry>(`/catalog/${encodeURIComponent(id)}`)\n return mapCatalogEntry(raw)\n }\n\n /**\n * List recent machine-payment receipts/evidence for bookkeeping.\n */\n async listReceipts(options: { limit?: number } = {}): Promise<HavenPaymentReceipt[]> {\n return this.accountReads.listReceipts(options)\n }\n\n /** #3128: one page of receipts with `total`, `hasMore` and `nextCursor`. */\n async listReceiptsPage(options: { limit?: number; cursor?: string } = {}): Promise<HavenPaymentReceiptsPage> {\n return this.accountReads.listReceiptsPage(options)\n }\n\n /**\n * Fetch the verifiable receipt bundle for a settled payment and verify it\n * locally. The server's own verification is ignored — the receipt is verified\n * here (independently of Haven) by recovering the signer from the\n * authorisation, so the result is trustworthy even if the backend lied.\n */\n async getReceipt(\n paymentId: string,\n ): Promise<{ receipt: PaymentReceipt; verification: ReceiptVerification }> {\n return this.accountReads.getReceipt(paymentId)\n }\n\n /**\n * Rehydrate the x402 resume-state bundle for a payment id (#1328: the MPP\n * resume-state variant retired along with the rest of the mpp_demo surface).\n *\n * The server returns stored protocol context only. The client still signs the\n * merchant proof locally when resumeX402Payment() runs.\n */\n async getResumeState(paymentId: string): Promise<PaymentResumeState> {\n return this.get<PaymentResumeState>(`/payments/${paymentId}/resume_state`)\n }\n\n /**\n * Poll until a payment reaches a terminal status (confirmed, failed, expired).\n */\n async waitForConfirmation(paymentId: string): Promise<PaymentResult> {\n const deadline = Date.now() + this.confirmationTimeout\n\n while (Date.now() < deadline) {\n const result = await this.getPayment(paymentId)\n\n if (result.status === 'confirmed' || result.status === 'failed' || result.status === 'expired') {\n return result\n }\n\n await sleep(this.pollingInterval)\n }\n\n throw new HavenTimeoutError(paymentId)\n }\n\n // ── x402 Protocol Support ────────────────────────────────────────\n\n /**\n * Authorize an x402 payment.\n *\n * Takes the parsed PaymentRequired from a 402 response, selects a compatible\n * option, funds the delegate wallet through Haven, and returns the standard\n * x402 header that the merchant can verify and settle.\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async authorizeX402(\n paymentRequired: X402PaymentRequired,\n options: X402AuthorizationOptions = {},\n ): Promise<X402Receipt> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'delegateKey is required for x402 payments. Pass it in the HavenClient config.',\n )\n }\n if (!this.delegateAddress) {\n throw new HavenSigningError('delegateAddress could not be derived from delegateKey.')\n }\n\n // 1. Select best payment option\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n if (!option) {\n throw noCompatiblePaymentOptionError(paymentRequired.accepts)\n }\n\n const idempotencyKey = options.idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option)\n const cached = this.fundingLeg.cachedReceipt(idempotencyKey)\n if (cached) return cached\n\n const inFlight = this.inFlightX402.get(idempotencyKey)\n if (inFlight) return inFlight\n\n const promise = this.fundingLeg.authorize(paymentRequired, option, idempotencyKey)\n this.inFlightX402.set(idempotencyKey, promise)\n\n try {\n return await promise\n } catch (err) {\n attachResumeState(err, {\n rail: 'x402',\n paymentRequired,\n accepted: option,\n idempotencyKey,\n })\n throw err\n } finally {\n this.inFlightX402.delete(idempotencyKey)\n }\n }\n\n /**\n * Probe a paid endpoint and return its x402 quote without creating a Haven\n * payment or approval request.\n */\n async quoteX402(\n url: string,\n init?: RequestInit,\n options: X402AuthorizationOptions = {},\n ): Promise<X402Quote> {\n const initialInit = withX402Wallet(init, x402PayerAddress(this.delegateAddress, this.x402Wallet))\n const request = snapshotX402Request(url, initialInit)\n const response = await this.merchantTransport.fetch(url, initialInit)\n\n if (response.status !== 402) {\n // #3118: a merchant on the official x402 MCP profile answers HTTP 200\n // with an `isError: true` tool result carrying the challenge. Quote it\n // like a 402. The transport signal is read exactly as for a 402 (path\n // or Bazaar); a stateless merchant that answered a bare `tools/call`\n // with a tool result has shown it needs no session, so nothing is\n // forced — `quoteMcpX402` still pins its own established session.\n const toolResultChallenge = await this.merchantTransport.extractToolResultChallenge(response, initialInit)\n if (toolResultChallenge) {\n const mcpTransport = await this.merchantTransport.detect(url, toolResultChallenge, response)\n return buildX402Quote(toolResultChallenge, request, options.idempotencyKey, mcpTransport)\n }\n // #2979: best-effort JSON body, so a merchant answering with its own\n // machine-readable refusal (e.g. `503 { error: 'merchant_not_ready' }`)\n // is not reduced to a bare status code — `.clone()` because the caller\n // never otherwise reads this response, but cloning before an unread\n // body is a defensive habit, not a requirement here.\n let body: unknown\n try {\n body = await response.clone().json()\n } catch {\n body = undefined\n }\n // #1300: typed, so consumers key on the class instead of message text.\n throw new X402UnexpectedStatusError(\n `Expected an x402 quote response with HTTP 402, got HTTP ${response.status}.`,\n response.status || 400,\n body,\n )\n }\n\n if (response.headers.get('MACHINE-PAYMENT-CHALLENGE')) {\n throw new HavenApiError('quoteX402 only supports standard x402 Payment Required responses.', 400)\n }\n\n const paymentRequired = await parsePaymentRequiredResponse(response)\n const mcpTransport = await this.merchantTransport.detect(url, paymentRequired, response)\n return buildX402Quote(paymentRequired, request, options.idempotencyKey, mcpTransport)\n }\n\n /**\n * Probe an MCP tool for its x402 quote without creating a payment.\n *\n * Unlike the generic {@link quoteX402} helper, this completes the\n * Streamable-HTTP MCP lifecycle before sending the unpaid `tools/call`.\n * Hosted MCP uses this path while remaining keyless: it resolves only the\n * agent's public delegate address for `x402-wallet`; signing remains local.\n * It refuses before the quote when the merchant does not establish a session;\n * callers that need a plain x402 endpoint must use {@link quoteX402}.\n */\n async quoteMcpX402(\n url: string,\n init?: RequestInit,\n options: X402AuthorizationOptions = {},\n ): Promise<X402Quote> {\n const wallet = await this.merchantCompletion.resolveWalletForMerchantCall()\n const sessionId = await this.merchantTransport.initialize(url, init, wallet)\n if (!sessionId) {\n throw new HavenApiError(\n 'The merchant did not establish an MCP session before the x402 quote. No payment was created.',\n 502,\n { mcpSessionNotEstablished: true },\n )\n }\n\n let requestInit = withX402Wallet(init, wallet)\n requestInit = this.merchantTransport.withSessionHeaders(requestInit, sessionId)\n\n const quote = await this.quoteX402(url, requestInit, options)\n // This dedicated helper established an MCP session even when the endpoint\n // uses a custom path and does not advertise Bazaar metadata. Preserve that\n // fact for the later, fresh session used by the paid retry.\n return {\n ...quote,\n mcpTransport: quote.mcpTransport ?? { handshakeRequired: true, source: 'path' },\n }\n }\n\n /**\n * Pay a previously inspected x402 quote and retry the exact captured request.\n */\n async payX402Quote(\n quote: X402Quote,\n options: X402AuthorizationOptions = {},\n ): Promise<Response> {\n const idempotencyKey = options.idempotencyKey ?? quote.idempotencyKey\n\n try {\n const receipt = await this.authorizeX402(quote.paymentRequired, { idempotencyKey })\n return this.merchantCompletion.retryRequest(\n quote.request.url,\n requestInitFromSnapshot(quote.request),\n quote.paymentRequired,\n receipt,\n )\n } catch (err) {\n attachResumeState(err, {\n rail: 'x402',\n paymentRequired: quote.paymentRequired,\n accepted: quote.accepted,\n idempotencyKey,\n request: quote.request,\n })\n throw err\n }\n }\n\n /**\n * Pay a merchant through **erc7710 direct settlement** (#1454, epic #1450).\n *\n * **Nothing has settled when this returns** — that is why it does not return\n * an `X402Receipt`; the caller still has to retry the merchant with the\n * header. **MCP callers must pass `options.resourceUrl`**, because an in-band\n * MCP 402 challenge frequently carries no `resource` object at all.\n *\n * Both caveats, and why this scheme has no funding leg, are explained where\n * the lifecycle lives: `x402-erc7710.ts` (#1619).\n */\n async settleX402Erc7710(\n paymentRequired: X402PaymentRequired,\n options: { resourceUrl?: string } = {},\n ): Promise<X402Erc7710Settlement> {\n return this.erc7710.settle(paymentRequired, options)\n }\n\n /**\n * The AUTHORIZE half of erc7710 settlement (#1456): select the scheme, build\n * the request, and return the child to be signed — without signing it.\n *\n * Split out because the hosted topology cannot use `settleX402Erc7710()`:\n * that method signs in-process with `delegateKey`, and hosted Haven does not\n * have one and must not.\n */\n async prepareX402Erc7710(\n paymentRequired: X402PaymentRequired,\n options: {\n resourceUrl?: string\n /**\n * The account's rail, when the caller has ALREADY read it — passing it\n * skips a duplicate fetch (#1456). An optimisation, not a trust\n * boundary: the backend independently refuses a non-delegation account\n * at the rail seam (the #1986 retired-rail 410, #2245).\n */\n delegationRail?: boolean\n /**\n * #1547: the merchant MCP-tool call this authorization was quoted\n * against, persisted so the settle leg can rehydrate it by payment_id\n * (#1307).\n */\n mcpCallContext?: X402McpCallContext\n /**\n * #2041: replay key, as `createX402Intent` already takes one. Without it\n * a retried authorize mints a second signable settlement child instead\n * of replaying the first.\n */\n idempotencyKey?: string\n } = {},\n ): Promise<{\n paymentId: string\n signData: SignData\n settlement: Omit<X402Erc7710Settlement, 'paymentHeader'>\n }> {\n return this.erc7710.prepare(paymentRequired, options)\n }\n\n /**\n * The SETTLE half (#1456): exchange the signed child for the merchant header.\n *\n * The SDK builds no header on this path — the backend assembles the MetaMask\n * erc7710 payload. Whoever produced the signature (an in-process delegate\n * key, or the local edge signer over the hosted boundary) is irrelevant.\n */\n async submitX402Erc7710(paymentId: string, signature: string): Promise<string> {\n return this.erc7710.submit(paymentId, signature)\n }\n\n async resumeAuthorizedX402(input: ResumeAuthorizedX402Input): Promise<X402Receipt> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'delegateKey is required for x402 payments. Pass it in the HavenClient config.',\n )\n }\n if (!this.delegateAddress) {\n throw new HavenSigningError('delegateAddress could not be derived from delegateKey.')\n }\n\n const option = selectStandardPaymentOption(input.paymentRequired.accepts)\n if (!option) {\n throw noCompatiblePaymentOptionError(input.paymentRequired.accepts)\n }\n\n const idempotencyKey = input.idempotencyKey ?? buildX402IdempotencyKey(input.paymentRequired, option)\n const cached = this.fundingLeg.cachedReceipt(idempotencyKey)\n if (cached) return cached\n\n const status = await this.getPaymentStatus(input.paymentId)\n assertCanResumeX402(status, input.paymentRequired, option)\n\n // #1521: the same fundability question as the authorize path, with the\n // opposite default. Here the caller NAMED this payment, so an\n // unverifiable balance is not grounds to refuse the thing they asked for\n // — only a balance verified ABSENT is, because then the authorization\n // this would mint is known to be unfundable.\n const canFund = await this.fundingLeg.delegateCanFund(\n status.chainId ?? chainIdFromNetwork(option.network),\n option.asset,\n x402AuthorizationAmount(option),\n )\n if (canFund === false) {\n throw new X402AlreadySettledError(\n `x402 payment ${status.paymentId} has already settled — the delegate no longer holds the ` +\n 'funds to authorize it again, so there is nothing left to resume.',\n this.fundingLeg.receiptFromStatus(input.paymentRequired, option, undefined, status),\n 'settled',\n )\n }\n\n const paymentHeader = await this.fundingLeg.createPaymentHeader(input.paymentRequired, option)\n const receipt = this.fundingLeg.receiptFromStatus(input.paymentRequired, option, paymentHeader, status)\n this.fundingLeg.cacheReceipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n async resumeX402Payment(input: ResumeX402PaymentInput | X402ResumeState): Promise<Response> {\n const inputInit = 'init' in input ? input.init : undefined\n const initialInit = withX402Wallet(\n inputInit ?? (input.request ? requestInitFromSnapshot(input.request) : undefined),\n x402PayerAddress(this.delegateAddress, this.x402Wallet),\n )\n let paymentRequired = input.paymentRequired\n const url = input.url ?? input.request?.url\n\n if (!paymentRequired) {\n if (!url) {\n throw new HavenApiError('x402 resume requires the original URL or a captured request snapshot.', 400)\n }\n const response = await this.merchantTransport.fetch(url, initialInit)\n if (response.status !== 402) {\n throw new HavenApiError('Expected the original x402 request to return HTTP 402 before resuming.', 400)\n }\n paymentRequired = await parsePaymentRequiredResponse(response)\n }\n\n const receipt = await this.resumeAuthorizedX402({\n paymentId: input.paymentId,\n paymentRequired,\n idempotencyKey: input.idempotencyKey,\n })\n\n return this.merchantCompletion.retryRequest(url ?? paymentRequired.resource.url, initialInit, paymentRequired, receipt)\n }\n\n /**\n * Fetch wrapper that automatically handles HTTP 402 responses — and, since\n * #3118, a native-MCP payment-required tool result answered under HTTP 200.\n *\n * Works like the standard `fetch()` but intercepts 402 responses (or that\n * tool-result challenge), pays via x402 through Haven, and retries the request.\n *\n * ```ts\n * const response = await haven.fetch('https://paid-api.com/data')\n * const data = await response.json()\n * ```\n *\n * **MCP-over-x402 auto-handshake (issue #315):** when the endpoint is\n * MCP-shaped — the URL path ends in `/mcp`, or the 402 body (or, since\n * #3118, the tool-result challenge) carries a Coinbase Bazaar\n * `extensions.bazaar` block — the SDK runs the MCP\n * `initialize` handshake, threads the resulting `mcp-session-id`,\n * `Accept: application/json, text/event-stream`, and `x402-wallet` headers\n * through every request, and collapses SSE responses to the JSON-RPC\n * `result`. The caller just passes `(url, { body })` and never sees the\n * protocol plumbing. A non-MCP server (handshake error / no session id)\n * falls back to standard x402 behaviour.\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async fetch(\n url: string,\n init?: RequestInit,\n options: X402AuthorizationOptions = {},\n ): Promise<Response> {\n // Signal A: a `/mcp` path is the MCP-over-HTTP convention, so handshake\n // up front — before the probe — so the session id rides on the probe and\n // the retry alike. A non-MCP server yields `undefined` and we fall back.\n let mcpSessionId: string | undefined\n if (this.merchantTransport.isMcpUrl(url)) {\n mcpSessionId = await this.merchantTransport.initialize(url, init)\n }\n\n let requestInit = withX402Wallet(init, x402PayerAddress(this.delegateAddress, this.x402Wallet))\n if (mcpSessionId) requestInit = this.merchantTransport.withSessionHeaders(requestInit, mcpSessionId)\n\n // 1. Make the original request\n const response = await this.merchantTransport.fetch(url, requestInit)\n\n // 2. Not a 402 — return as-is (collapsing SSE for MCP sessions), unless\n // it is a native MCP payment-required tool result (#3118): the\n // official profile signals the challenge in the tool result, not the\n // status code, and it is paid and retried exactly like a 402.\n let paymentRequired: X402PaymentRequired\n // #3118: a tool-result challenge proves the merchant speaks JSON-RPC, so\n // the paid retry's SSE is collapsed even when no session was established\n // (a profile merchant on a plain URL answers without one). A non-402\n // pass-through is still collapsed only under a session: a plain SSE API\n // that never spoke JSON-RPC must come back untouched.\n let nativeChallenge = false\n if (response.status !== 402) {\n const toolResultChallenge = await this.merchantTransport.extractToolResultChallenge(response, requestInit)\n if (!toolResultChallenge) {\n return mcpSessionId ? this.merchantTransport.surfaceResult(response) : response\n }\n paymentRequired = toolResultChallenge\n nativeChallenge = true\n } else {\n // #1328: the legacy MACHINE-PAYMENT-CHALLENGE / mpp_demo auto-handling is\n // retired — a 402 that isn't standard x402 (including a stray\n // MACHINE-PAYMENT-CHALLENGE header from a pre-retirement caller) is\n // returned to the agent unmodified rather than auto-paid.\n\n // 3. Parse x402 payment requirements\n try {\n paymentRequired = await parsePaymentRequiredResponse(response)\n } catch {\n // Not a standard x402 402 response — return it unchanged.\n return response\n }\n }\n\n // Signal B: a Bazaar `extensions.bazaar` block marks an MCP-discoverable\n // resource even without the `/mcp` convention. Handshake now (if we\n // haven't already) so the paid retry carries the session id.\n // #3118: on a tool-result challenge the block sits inside the challenge\n // (`result.structuredContent.extensions.bazaar`), not at the body's top\n // level, so it is read from the parsed challenge as well.\n if (!mcpSessionId && (paymentRequired.extensions?.bazaar != null || (await this.merchantTransport.hasBazaarExtension(response)))) {\n mcpSessionId = await this.merchantTransport.initialize(url, init)\n if (mcpSessionId) requestInit = this.merchantTransport.withSessionHeaders(requestInit, mcpSessionId)\n }\n\n // 4. Pay through Haven\n const request = snapshotX402Request(url, requestInit)\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n const idempotencyKey = options.idempotencyKey ?? (option ? buildX402IdempotencyKey(paymentRequired, option) : undefined)\n let receipt: X402Receipt\n try {\n receipt = await this.authorizeX402(paymentRequired, options)\n } catch (err) {\n if (option && idempotencyKey) {\n attachResumeState(err, {\n rail: 'x402',\n paymentRequired,\n accepted: option,\n idempotencyKey,\n request,\n })\n }\n throw err\n }\n const retryResponse = await this.merchantCompletion.retryRequest(url, requestInit, paymentRequired, receipt)\n return mcpSessionId || nativeChallenge ? this.merchantTransport.surfaceResult(retryResponse) : retryResponse\n }\n\n /**\n * Deliver an already-signed x402 payment header to the merchant and return\n * the merchant's response. Used by the hosted MCP server to complete the\n * merchant leg of an MCP tool payment after the edge signer has built the\n * merchant payment header.\n *\n * Custody note: this never needs the delegate key. It relays a signed,\n * amount/merchant/nonce-bound EIP-3009 authorization the edge signer already\n * produced — the hosted server cannot mint or reuse signing authority.\n *\n * When the URL is MCP-shaped (`/mcp` path) or the quote-time transport context\n * says the merchant was Bazaar-discoverable, runs a fresh `initialize`\n * handshake (the quote-time session is gone once funding confirms; the x402\n * challenge is stateless w.r.t. the MCP session, so a fresh session is\n * accepted), threads the session + wallet headers, sets the x402 payment\n * header under the names that scheme requires (#2341), and\n * collapses an SSE JSON-RPC response to its `result`.\n */\n /**\n * Wait for a payment's account→delegate funding tx to reach ≥1 on-chain\n * confirmation. The hosted x402 completion path MUST call this after funding\n * and before delivering the merchant payment header, so the merchant's\n * balanceOf(delegate) / transferWithAuthorization verification sees the funded\n * balance — otherwise it rejects with \"Payment verification failed\". The\n * SDK's local path already does this (see `X402FundingLeg.authorize`); the hosted\n * split flow regressed when the 5→3 collapse removed the incidental\n * inter-call latency that used to mask it.\n *\n * **NOT a no-op when the funding tx hash is absent** (#1508). The WAIT is\n * skipped without a hash or a chain RPC, but the `GET /payments/:id` read\n * below runs UNCONDITIONALLY — it is how the fallback hash and the chainId\n * are obtained. That distinction is load-bearing: this method must never be\n * called on a scheme with no funding leg, because the read itself fails once\n * the intent reaches a status the backend maps to a non-2xx (`submitted` is a\n * 409), turning a settled payment into a reported error. The previous wording\n * here said \"No-op when the funding tx hash ... is unavailable\", and the\n * hosted erc7710 path was written against that promise — see\n * `deliverMerchantPayment`'s `noFundingLeg` option.\n */\n async ensureFundingConfirmed(paymentId: string, fundingTxHash?: string): Promise<void> {\n const status = await this.getPaymentStatus(paymentId)\n await this.fundingLeg.waitForFundingTx(fundingTxHash ?? status.txHash ?? undefined, status.chainId)\n }\n\n async completeX402MerchantCall(input: {\n url: string\n init?: RequestInit\n paymentId: string\n paymentHeader: string\n mcpTransport?: X402McpTransport\n /**\n * #1508: the payment settles with NO funding leg (erc7710). This method was\n * written for EIP-3009 and encodes that lifecycle in two places — the\n * readiness gate wants `confirmed`, and a Haven funding tx hash is\n * mandatory. Neither is reachable on a scheme where the MERCHANT redeems\n * the delegation chain: the intent sits at `submitted` by design, and there\n * is no Haven-submitted transaction at all. Set this to take the\n * no-funding-leg path through both.\n */\n noFundingLeg?: boolean\n }): Promise<{\n status: number\n ok: boolean\n body: unknown\n settlementTxHash?: string\n /**\n * #2970: what the evidence report (below) learned, when one was made.\n * `undefined` when there was no hash to report at all — no funding tx on\n * the erc7710 branch and no (or a zero) merchant-reported settlement hash.\n * The hosted erc7710 settle/complete gate reads this to decide whether\n * `settled: true` is honest; the 3009 branch's `settled: true` does not\n * need it — see `paid-mcp-completion.ts` for why.\n */\n evidenceOutcome?: EvidenceReportOutcome\n }> {\n const evidenceContext = await this.merchantCompletion.resolveCompletionContext({\n paymentId: input.paymentId,\n url: input.url,\n noFundingLeg: input.noFundingLeg === true,\n })\n // Non-null on the funding-leg path (the gate below throws without it) and\n // always null on erc7710. Bound once so the evidence calls — which require\n // a string — are provably unreachable without one.\n const fundingTxHash = evidenceContext.txHash\n const shouldHandshakeMcp =\n this.merchantTransport.isMcpUrl(input.url) ||\n input.mcpTransport?.handshakeRequired === true\n const x402Wallet = shouldHandshakeMcp ? await this.merchantCompletion.resolveWalletForMerchantCall() : x402PayerAddress(this.delegateAddress, this.x402Wallet)\n let mcpSessionId: string | undefined\n if (shouldHandshakeMcp) {\n mcpSessionId = await this.merchantTransport.initialize(input.url, input.init, x402Wallet)\n }\n\n let requestInit: RequestInit = withX402Wallet(input.init, x402Wallet) ?? {}\n if (mcpSessionId) requestInit = this.merchantTransport.withSessionHeaders(requestInit, mcpSessionId)\n\n // #3171: same session recovery as `retryRequest` — the hosted twin of the\n // local paid retry must not report a settled-nothing 404 as a rejection.\n const response = await this.merchantTransport.deliverPaymentRecoveringSession(\n input.url,\n requestInit,\n input.paymentHeader,\n () => this.merchantTransport.initialize(input.url, input.init, x402Wallet),\n )\n // #3155 review B1: collapse SSE whether or not a session was established —\n // an event-stream answer is MCP framing regardless, and a profile merchant\n // on a plain URL (no session) would otherwise hide its in-band refusal in\n // a raw SSE string. `surfaceResult` passes every non-SSE response through.\n const surfaced = await this.merchantTransport.surfaceResult(response)\n\n const text = await surfaced.text()\n let body: unknown\n try {\n body = text ? JSON.parse(text) : null\n } catch {\n body = text\n }\n\n // #3118: a profile merchant reports settlement in\n // `result._meta[\"x402/payment-response\"]` and a refusal as an\n // `isError: true` tool result — both under HTTP 200. The header form is\n // read first and stays authoritative when present; the `_meta` form is\n // re-encoded as base64 JSON so the evidence report's receipt payload is\n // parsed by the one existing decoder, and its `success: false` (or an\n // in-band payment-required result) is a merchant REJECTION, never a\n // success: the tool's content was withheld and nothing settled.\n const toolResult = mcpToolResultOf(body)\n const inBandChallenge = toolResult ? extractMcpPaymentRequired(toolResult) : undefined\n const metaSettlement = toolResult ? mcpSettlementFromToolResult(toolResult) : undefined\n const headerReceipt = surfaced.headers.get('PAYMENT-RESPONSE') ?? undefined\n const protocolReceiptHeaderName = headerReceipt\n ? 'PAYMENT-RESPONSE'\n : metaSettlement\n ? `_meta.${MCP_X402_PAYMENT_RESPONSE_META_KEY}`\n : undefined\n const protocolReceiptHeader = headerReceipt ?? (metaSettlement ? encodeMcpSettlementReceipt(metaSettlement) : undefined)\n const settlement = parseMerchantSettlement(protocolReceiptHeader ?? null)\n // A JSON-RPC `error` envelope (no `result`) after payment stays `ok` on the\n // HTTP status: it carries no settlement statement, and the two protocol\n // signals above are the only ones that mean \"nothing settled\" (#3155 S4).\n const merchantAccepted = surfaced.ok && inBandChallenge === undefined && metaSettlement?.success !== false\n\n // #2970: declared here (not inside the `else` below) so it survives to\n // the `return` — `undefined` on the refusal branch and whenever there was\n // no hash to report at all.\n let evidenceOutcome: EvidenceReportOutcome | undefined\n\n if (!merchantAccepted) {\n // #1508: both evidence surfaces below require a txHash — the backend\n // answers `400 txHash is required` without one, and these calls swallow\n // failures, so an erc7710 row would vanish silently rather than fail\n // loudly. Skipping deliberately (owner decision 2026-08-17) instead of\n // writing a row that cannot be written: their consumer is funding-leg\n // reconciliation (#713 — stranded delegate balances), and this rail has\n // no funding leg to strand. The merchant receipt below still runs, so the\n // paid call remains recorded.\n if (!input.noFundingLeg && fundingTxHash) {\n await this.merchantCompletion.recordRetryRejected({\n rail: 'x402',\n paymentId: evidenceContext.paymentId,\n txHash: fundingTxHash,\n resourceUrl: evidenceContext.resourceUrl,\n merchant: {\n merchant_status: surfaced.status,\n merchant_status_text: surfaced.statusText,\n merchant_headers: Object.fromEntries(surfaced.headers.entries()),\n merchant_body: text,\n },\n details: {\n merchant_to: evidenceContext.merchantAddress,\n },\n })\n }\n } else {\n // #2092: the evidence anchor is scheme-dependent, and skipping it on\n // erc7710 (#1508) left a whole settlement scheme with no\n // `machine_payment_evidence` row — and therefore invisible to the Fortnox\n // reporting feed, `GET /receipts`, transaction history, and the\n // merchant-receipt capture on the very next line (which 404s without an\n // evidence row). The #1508 reasoning — \"evidence's consumer is\n // funding-leg reconciliation, and this rail has no funding leg\" — was\n // true about #713 and incomplete about everything else evidence feeds.\n //\n // On the funding-leg path the anchor is Haven's funding transaction; on\n // erc7710 it is the MERCHANT's settlement transaction, which the merchant\n // just handed us in `PAYMENT-RESPONSE`. Both are reported through the\n // same call, so the backend and every consumer keep one code path. The\n // backend verifies the erc7710 hash on-chain before it confirms anything\n // (#2092), so reporting it is a claim, not an authority.\n const rawEvidenceTxHash = input.noFundingLeg\n ? (settlement.settlementTxHash ?? undefined)\n : (fundingTxHash ?? undefined)\n // #2970: a zero hash is never a real transaction (see\n // `isZeroSettlementTxHash`) — reporting it can only ever come back\n // refused, at the cost of a real round trip (and, on the retryable\n // path, the SDK's own multi-second backoff). Treat it as no hash at all.\n const evidenceTxHash =\n rawEvidenceTxHash && !isZeroSettlementTxHash(rawEvidenceTxHash) ? rawEvidenceTxHash : undefined\n // #2117: when the merchant returned no settlement transaction there is\n // simply nothing to report, and inventing an anchor client-side is what\n // the backend's on-chain verification exists to prevent. That gap is\n // closed SERVER-side instead, by the passive settlement sweep\n // (`modules/x402/settlement-sweeper.ts`), which finds the settlement by\n // this payment's own intent-unique delegation child. Do not \"fix\" this\n // branch by fabricating a hash.\n if (evidenceTxHash) {\n evidenceOutcome = await this.merchantCompletion.reportEvidence({\n paymentId: evidenceContext.paymentId,\n rail: 'x402',\n txHash: evidenceTxHash,\n resourceUrl: evidenceContext.resourceUrl,\n merchantStatus: surfaced.status,\n paymentProofHeaderName: x402PaymentHeaderNamesSent(input.paymentHeader),\n paymentProofHeader: input.paymentHeader,\n protocolReceiptHeaderName,\n protocolReceiptHeader,\n })\n }\n // #956: the hosted-MCP completion path is a successful paid retry too —\n // capture the merchant's receipt exactly like the local flow does.\n await this.merchantCompletion.reportMerchantReceipt(evidenceContext.paymentId, surfaced)\n }\n\n return {\n status: surfaced.status,\n ok: merchantAccepted,\n body,\n // #3155 review S3: a transaction beside a rejection is not a settlement.\n settlementTxHash: merchantAccepted ? (settlement.settlementTxHash ?? undefined) : undefined,\n evidenceOutcome,\n }\n }\n\n /**\n * #2292: report the outcome of a merchant retry the AGENT performed.\n *\n * The hosted `haven_complete_mcp_tool` / `completeX402MerchantCall` path is\n * for merchants Haven calls itself. On the plain-HTTP x402 path Haven never\n * talks to the merchant, so the outcome of that retry had no way back —\n * see `MerchantCompletion.reportMerchantOutcome` for what is verified about\n * a caller-asserted report and what deliberately is not.\n */\n async reportX402MerchantOutcome(input: {\n paymentId: string\n outcome: X402MerchantOutcome\n merchantStatus: number\n merchantBody?: string\n }): Promise<X402MerchantOutcomeReport> {\n return await this.merchantCompletion.reportMerchantOutcome(input)\n }\n\n /**\n * #2972: report the merchant's real settlement transaction hash for an\n * erc7710 x402 payment — the remedy for `DELIVERED_UNSETTLED` /\n * `SETTLEMENT_PENDING` / `awaiting_settlement_evidence` when the agent\n * holds the hash (`PAYMENT-RESPONSE.transaction`, or a prior settle/\n * complete result's `settlement_tx_hash`) and Haven does not. See\n * `MerchantCompletion.reportSettlementEvidence` for the fail-closed\n * verification this posts into (`observeErc7710Settlement`) and the\n * client-side zero-hash refusal.\n */\n async reportSettlementEvidence(\n paymentId: string,\n settlementTxHash: string,\n ): Promise<EvidenceReportOutcome> {\n return await this.merchantCompletion.reportSettlementEvidence(paymentId, settlementTxHash)\n }\n\n /**\n * GET /x402/:id/merchant-call-context — the settle-leg twin of #1263's\n * sign-context fetch (#1307). Re-serves the stored merchant MCP-tool call\n * context (merchant_url, tool_name, arguments, mcp_transport) recorded at\n * quote time, so `haven_settle_mcp_tool` / `haven_complete_mcp_tool` can\n * omit those fields and let Haven rehydrate them by payment_id instead of\n * the caller re-threading them. Throws `HavenApiError` (404 unknown/foreign\n * payment_id, 409 no stored context, 410 expired) — the caller decides the\n * fallback (re-send the full context explicitly).\n */\n async getX402MerchantCallContext(paymentId: string): Promise<X402MerchantCallContext> {\n const raw = await this.get<RawX402MerchantCallContext>(\n `/x402/${paymentId}/merchant-call-context`,\n )\n return {\n paymentId: raw.payment_id,\n merchantUrl: raw.merchant_url,\n toolName: raw.tool_name,\n arguments: raw.arguments ?? {},\n ...(raw.mcp_transport\n ? {\n mcpTransport: {\n handshakeRequired: raw.mcp_transport.handshake_required,\n source: raw.mcp_transport.source,\n },\n }\n : {}),\n }\n }\n\n /**\n * Wait for a funding tx to be mined with ≥1 confirmation before the\n * merchant retry, eliminating the race where the merchant's\n * `balanceOf(delegate)` runs before the funding block propagates.\n *\n * Skipped when `chainRpcs` does not include the chain; in that case Haven's\n * backend has already confirmed on-chain submission and callers accept the\n * small propagation window as a trade-off for not configuring an RPC URL.\n */\n private throwIfNonSignableAuthorizationState(\n label: string,\n raw: RawX402AuthorizeResponse,\n ): void {\n if (raw.status === 'pending_signature') return\n throwPaymentStateError(label, raw)\n }\n\n // ── Tool Execution (for agent frameworks) ────────────────────────\n\n /**\n * Execute a tool call by name and input.\n *\n * Designed to plug directly into agent tool-call handlers:\n *\n * ```ts\n * if (block.type === 'tool_use') {\n * const result = await haven.executeTool(block.name, block.input)\n * // send result back to the model\n * }\n * ```\n */\n async executeTool(\n toolName: string,\n input: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n if (toolName === 'make_payment') {\n const { token, amount, to } = input as {\n token: string\n amount: string\n to: string\n }\n\n try {\n const result = await this.pay({ token, amount, to })\n return {\n success: result.status === 'confirmed',\n payment_id: result.paymentId,\n status: result.status,\n tx_hash: result.txHash,\n token: result.token,\n amount: result.amount,\n to: result.to,\n explorer_url: result.explorerUrl,\n error: result.errorMessage,\n }\n } catch (err) {\n return toolError(err)\n }\n }\n\n if (toolName === 'authorize_x402_payment') {\n const { url, payTo, amount, asset, network, description, idempotencyKey } = input as {\n url: string\n payTo: string\n amount: string\n asset: string\n network: string\n description?: string\n idempotencyKey?: string\n }\n\n try {\n const receipt = await this.authorizeX402(\n toolX402PaymentRequired({ url, payTo, amount, asset, network, description }),\n { idempotencyKey },\n )\n return x402ToolReceipt(receipt)\n } catch (err) {\n return toolError(err)\n }\n }\n\n if (toolName === 'resume_x402_payment') {\n const { payment_id, url, payTo, amount, asset, network, description, idempotencyKey } = input as {\n payment_id: string\n url: string\n payTo: string\n amount: string\n asset: string\n network: string\n description?: string\n idempotencyKey?: string\n }\n\n try {\n const receipt = await this.resumeAuthorizedX402({\n paymentId: payment_id,\n paymentRequired: toolX402PaymentRequired({ url, payTo, amount, asset, network, description }),\n idempotencyKey,\n })\n return x402ToolReceipt(receipt)\n } catch (err) {\n return toolError(err)\n }\n }\n\n // #1328: the 'authorize_machine_payment' tool (mpp_demo only) is retired\n // along with the rest of the SDK's MPP-demo client surface — an unknown\n // toolName falls through to the Error below, same as any other retired name.\n\n if (toolName === 'get_payment_status') {\n const { payment_id } = input as { payment_id: string }\n const result = await this.getPaymentStatus(payment_id)\n return {\n payment_id: result.paymentId,\n kind: result.kind,\n rail: result.rail,\n status: result.status,\n phase: result.phase,\n next_action: result.nextAction,\n tx_hash: result.txHash,\n token: result.token,\n amount: result.amount,\n resource_url: result.resourceUrl,\n merchant_address: result.merchantAddress,\n amount_atomic: result.amountAtomic,\n asset: result.asset,\n network: result.network,\n description: result.description,\n idempotency_key: result.idempotencyKey,\n x402: result.x402,\n mpp: result.mpp,\n expires_at: result.expiresAt,\n chain_id: result.chainId,\n message: result.message,\n }\n }\n\n if (toolName === 'get_allowances') {\n return { ...await this.getAllowances() }\n }\n\n throw new Error(`Unknown tool: ${toolName}`)\n }\n\n // ── HTTP Helpers ─────────────────────────────────────────────────\n\n private async post<T>(path: string, body: Record<string, unknown>): Promise<T> {\n return this.havenApi.post<T>(path, body)\n }\n\n private async get<T>(path: string): Promise<T> {\n return this.havenApi.get<T>(path)\n }\n\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n","/**\n * Shared semantic descriptions for Haven agent payment tools.\n *\n * Two surfaces in this repo expose Haven as a tool: the Claude / OpenAI\n * function-calling tool definitions in `tools.ts` (used for direct SDK\n * integrations) and the MCP server in `packages/mcp` (used by any MCP-speaking\n * agent runtime). The two surfaces use different tool *names* — the SDK's\n * tools are tuned for tool-calling conventions (`make_payment`,\n * `authorize_x402_payment`); the MCP tools follow the MCP `haven_*` naming\n * (`haven_pay_x402_quote`).\n *\n * The underlying *operations* are the same, so the descriptive prose should\n * live in one place. Both surfaces import from this module and compose their\n * own tool descriptions from these semantic fragments. Drift is caught by\n * tests asserting each consumer's description string contains the shared\n * `summary` from this module.\n */\n\nexport interface ToolDescription {\n /** One-line summary of the operation. Used as the first sentence of every\n * downstream description and as a stable substring for drift tests. */\n summary: string\n /** Natural-language user intents that should make an agent prefer this\n * tool over adjacent tools. Empty or omitted when the summary is enough. */\n selectionGuidance?: string\n /** Concrete behaviour the tool performs end-to-end, including which\n * non-custodial guarantee applies. */\n behavior: string\n /** What the agent should do next on error / declined states.\n * Empty string if not applicable. */\n nextActionGuidance: string\n}\n\n/**\n * Build a single description string from the three fragments. Joined with\n * spaces so consumers can split on the summary substring if they need to.\n */\nexport function composeDescription(d: ToolDescription): string {\n return [d.summary, d.selectionGuidance, d.behavior, d.nextActionGuidance]\n .filter(Boolean)\n .join(' ')\n}\n\nexport const toolDescriptions = {\n quoteX402: {\n summary:\n 'Inspect an HTTP 402 x402 paid resource without creating a Haven payment, signature, approval, or on-chain transaction.',\n behavior:\n 'Probes the merchant directly and parses the 402 response. Pure read-only client behavior — Haven is not contacted.',\n nextActionGuidance:\n 'On success the returned quote is the input to haven_pay_x402_quote. Do not call the merchant again — Haven re-uses the captured request when paying.',\n },\n payX402: {\n summary:\n 'Pay an inspected x402 quote. The delegate key signs locally; Haven only validates and relays signed, on-chain-constrained payment transactions.',\n selectionGuidance:\n 'Do not use this for read-only allowance, budget, spend-limit, remaining-amount, reset-period, or what-can-I-spend questions; use the allowance lookup tool instead.',\n behavior:\n 'Signs the payment locally and returns the merchant response. Settlement is either direct account-to-merchant with no funding leg, or a bridge that first redeems the agent\\'s budget delegation to fund the delegate wallet for an EIP-3009 authorization. A payment outside the on-chain budget is declined before any money moves; nothing is queued for a human to approve later.',\n nextActionGuidance:\n 'Preserve the returned resume_state — it identifies this payment if you need to ask about it later. ' +\n 'This tool performs the merchant retry itself, so do not wait on a signal while the call is in flight. ' +\n 'If the process crashes after this call and a later haven_get_payment_status reports nextAction=retry_original_x402_request, Haven\\'s funding leg confirmed but no merchant response was ever recorded — call the resume tool with the preserved resume_state or payment_id instead of paying again. ' +\n 'If the response carries phase=insufficient_funds and nextAction=fund_account_or_raise_allowance, the payment cannot be retried until the account is funded or the agent budget raised — stop and tell the user the shortfall reported on the response.',\n },\n payX402OneShot: {\n summary:\n 'Fetch an x402 paid HTTP resource in a single call. Handles the full probe -> pay -> retry round trip and returns the merchant response.',\n selectionGuidance:\n 'Prefer this over the quote+pay split when the agent just wants the paid resource and does not need to inspect the price first. If you already have a quote from haven_quote_x402, use haven_pay_x402_quote instead. Do not use for read-only allowance, budget, spend-limit, remaining-amount, reset-period, or what-can-I-spend questions; use the allowance lookup tool instead.',\n behavior:\n 'Calls the URL, parses any HTTP 402 x402 challenge (or, since #3118, a native-MCP payment-required tool result under HTTP 200), signs the payment locally, then retries the original request with the signed payment header (sent under PAYMENT-SIGNATURE, plus the legacy X-PAYMENT on the EIP-3009 path only) and returns the merchant response. Settlement is either direct account-to-merchant with no funding leg, or a bridge that first redeems the agent\\'s budget delegation to fund the delegate wallet for an EIP-3009 authorization. A payment outside the on-chain budget is declined before any money moves; nothing is queued for a human to approve later. If the resource returns a non-402 status with no payment-required tool result, returns it unchanged without contacting Haven.',\n nextActionGuidance:\n 'Preserve the returned resume_state or paymentId — either identifies this payment if you need to ask about it later. ' +\n 'This tool performs the merchant retry itself, so do not wait on a signal while the call is in flight. ' +\n 'If the process crashes after this call and a later haven_get_payment_status reports nextAction=retry_original_x402_request, Haven\\'s funding leg confirmed but no merchant response was ever recorded — call the resume tool with the preserved resume_state or payment_id instead of paying again. ' +\n 'If the response carries phase=insufficient_funds and nextAction=fund_account_or_raise_allowance, the payment cannot be retried until the account is funded or the agent budget raised — stop and tell the user the shortfall reported on the response.',\n },\n resumeX402: {\n summary:\n 'Resume an x402 payment whose Haven-side authorization already succeeded but whose merchant retry did not complete.',\n behavior:\n 'Accepts either resume_state or payment_id, validates the x402 details against the authorized funding, and retries the merchant request with the signed payment header (PAYMENT-SIGNATURE, plus legacy X-PAYMENT on EIP-3009 only; also params._meta on an MCP tools/call body). No new Haven payment is created.',\n nextActionGuidance:\n 'Only call this after haven_get_payment_status reports nextAction=retry_original_x402_request — that means Haven\\'s funding leg confirmed but no merchant response was ever recorded, most often because the process crashed between funding and the merchant retry. ' +\n 'Any other nextAction reports a conflict instead of retrying, so do not call this speculatively. ' +\n 'Do not start a new merchant session and do not pay again — that would pay twice for one resource.',\n },\n // #1328: quoteMpp / payMpp / resumeMpp (the mpp_demo challenge/quote/resume\n // fragments) are retired along with the client surface they described —\n // MACHINE-PAYMENT-CHALLENGE was never produced by anything besides the now\n // deleted `/demo/mpp/*` route. Use the x402 fragments above instead.\n getPaymentStatus: {\n summary:\n 'Fetch structured Haven payment status for agent recovery.',\n behavior:\n 'State: phase, nextAction, rail, amount, merchant, resource, idempotency, message; parties: treasury/delegate/delegateAccount/merchant. awaiting_settlement_evidence: poll once, else unverified.',\n nextActionGuidance: '',\n },\n getResumeState: {\n summary:\n 'Rehydrate stored x402 resume_state by payment_id.',\n behavior:\n 'Returns the x402 context the agent originally received when the payment was authorized, reconstructed from Haven\\'s database. This is context only; signing still happens locally when a resume tool is called.',\n nextActionGuidance: '',\n },\n getAgent: {\n summary:\n 'Return the authenticated agent identity AND its live spend authority in one call: Haven wallet, delegate, chain, raw status, spend_authority_readiness, per-token remaining allowance (atomic + human-readable). The recommended first call in a new session.',\n selectionGuidance:\n 'Use this as the session bootstrap, or to confirm identity together with whether the agent can spend right now. For per-token detail (configured vs spent vs reset window) use haven_get_allowances.',\n behavior:\n 'Reads identity plus the live spend-authority snapshot — the active on-chain budget delegation. spend_authority_readiness (readiness is a deprecated alias, same value) is \"ready\" when at least one token has remaining spend authority, \"needs_approval\" when the agent is active but has none, and \"revoked\" when the credential is not active. It covers hosted identity + on-chain spend authority ONLY — the hosted server cannot see the LOCAL signer, so \"ready\" does not mean the signer can start; verify the signer with a signer tool call or connect --doctor. An over-budget payment is declined before any money moves; there is no approval queue — ask the owner to grant or raise the budget in Haven. allowances[] carries id, tokenAddress, remainingAtomic, remainingDisplay per token. Identity fields: id, name, status, accountAddress, delegateAddress, chainId.',\n nextActionGuidance: '',\n },\n getAllowances: {\n summary:\n 'Return configured and on-chain allowance state for the authenticated agent. On-chain allowance is the real spend gate.',\n selectionGuidance:\n 'Use this when the user asks about allowance, budget, spend limit, remaining amount, remaining allowance, remaining budget, daily limit, reset period, what can I spend, or what the agent can still spend. For whether the account actually HOLDS funds behind the budget use haven_check_funds.',\n behavior:\n 'Returns the per-token spend authority for the account: the active budget delegation (remaining = the period budget, which re-arms natively at the period boundary), each with id, onchain.remaining, remainingDisplay. An over-budget payment is declined before any money moves; nothing queues. Configured amounts from Haven are returned alongside.',\n nextActionGuidance: '',\n },\n // #3126 — the sufficiency signal, deliberately NOT a balance tool. The\n // constrained actor reads a boolean, never the treasury total.\n checkFunds: {\n summary:\n 'Check whether the agent\\'s account actually holds at least the given amount of a token — funds held, not spend permitted.',\n selectionGuidance:\n 'Use this before attempting a payment when it matters whether the money is really there: allowance answers say what you are PERMITTED to spend, never whether the account HOLDS it. For allowance, budget, spend-limit, remaining-budget, reset-period, or what-can-I-spend questions use the allowance lookup tool instead.',\n behavior:\n 'Returns covered: true (the account holds at least the checked amount), false (a live chain read reports less — the budget is backed by an empty account; stop and tell the user funds are missing), or null (the chain read failed — unverifiable, never treat it as absence; coverageError says why). The account balance itself is deliberately not returned: this is a sufficiency signal, not a balance read. budget_remaining_atomic is the permitted figure from the allowance lookup (the SDK spells it budgetRemainingAtomic), named so it can never be confused with holdings.',\n nextActionGuidance:\n 'On covered=false, do not attempt the payment — tell the user the account is short and let them fund it; on covered=null, retry the check shortly or proceed knowing the payment may fail on-chain.',\n },\n listReceipts: {\n summary:\n 'List machine-payment receipts, newest first, by page.',\n selectionGuidance:\n \"This agent's payment evidence, not the wallet's transaction history (sweeps, funding legs, other agents); use the allowance tool instead for remaining allowance or what-can-I-spend questions.\",\n behavior:\n \"Page { receipts, total, hasMore, nextCursor }; hasMore: pass nextCursor as cursor. parties.treasuryAccount is Haven's authoritative payer. protocolReceiptPayload is the merchant's PAYMENT-RESPONSE relayed verbatim: merchant-controlled, unverified, not Haven's record; payer may differ from payerAddress. Proof header values omitted.\",\n nextActionGuidance: '',\n },\n verifyReceipt: {\n summary:\n 'Verify a payment receipt offline — confirm the agent authorised the transfer.',\n selectionGuidance:\n 'Use this to check a receipt you already hold; it needs no network and does not trust Haven. Use the history tool to fetch receipts in the first place.',\n behavior:\n 'Recovers the signer from the receipt authorisation and confirms it matches the agent delegate. Returns verified true/false with the recovered signer or a reason. Pure and local — no backend call.',\n nextActionGuidance: '',\n },\n payMcpTool: {\n summary:\n 'Call a named tool on an MCP merchant that requires an x402 payment, handling the full initialize → pay → retry round trip in one call.',\n selectionGuidance:\n 'Use this when the agent wants to call a specific tool on an MCP merchant (e.g. Soundside, Coinbase Bazaar) and payment is required. ' +\n 'Prefer this over haven_pay_x402 when you know the merchant_url and tool_name — it builds the JSON-RPC envelope internally. ' +\n 'Use haven_pay_x402 for arbitrary HTTP resources. ' +\n 'Do NOT use for read-only allowance or budget questions — use haven_get_allowances.',\n behavior:\n 'Builds the JSON-RPC tools/call envelope, runs the MCP Streamable-HTTP initialize handshake automatically (if the endpoint is MCP-shaped), ' +\n 'pays any HTTP 402 x402 challenge against the agent\\'s on-chain budget delegation, and retries the request, returning the JSON-RPC result (the actual merchant output) on success. ' +\n 'Amounts within the remaining on-chain budget execute automatically; anything outside it is declined before any money moves — follow the response\\'s nextAction when present.',\n nextActionGuidance:\n 'On a decline, report the reason to the user and ask them to raise the budget in Haven — there is no approval queue to wait on. ' +\n 'This tool retries the merchant itself while it runs, so do not wait on a signal mid-call. ' +\n 'If the process crashes after payment, a later haven_get_payment_status call may report nextAction=retry_original_x402_request — resume via haven_resume_x402_payment instead of paying again.',\n },\n discoverTools: {\n summary:\n 'Step 1 of a purchase: discover payable services from Haven\\'s curated merchant catalog — names, prices, the next call.',\n selectionGuidance:\n 'Use this when the user asks what the agent can buy, pay for, or which paid services exist — or when you need a resource URL for a service the user described. ' +\n 'Use verified=verified for entries Haven watched pass a live quote probe (operator-curated or self-submitted) — domain_verified is the only ownership claim; never treat these badges as proof of merchant honesty, quality, or reliability. ' +\n 'Do NOT use for balance, budget, or spend-limit questions — use haven_get_allowances. ' +\n 'Do NOT use to pay — each returned entry names the next tool to call.',\n behavior:\n 'Use each entry\\'s suggested_tool + suggested_arguments first; an entry without them says why. ' +\n 'Read-only lookup against Haven\\'s curated catalog; entries are periodically re-verified against the live merchant and degraded entries are flagged. ' +\n 'Use category for a case-insensitive category filter (for example, VPN or vpn), or search for a product name, category, or description term. ' +\n 'Returns name, description, price, rail, resource URL, tool_name, tool_arguments, the hint, and the provenance badges source/domain_verified/verified_payable. ' +\n 'The catalog price (price_display/price_atomic, marked price_is_indicative) is a last-verified hint, NOT authoritative — the real price comes from the merchant\\'s live 402 at pay time. ' +\n 'Never creates a payment, signature, or approval.',\n nextActionGuidance:\n 'Call suggested_tool with suggested_arguments VERBATIM (no hint: read suggested_tool_omitted_reason). Confirm the price from the live quote or pay result, not the catalog; if the next tool takes a cap, pass the user\\'s cap as max_amount_human in whole tokens (\"no more than 1 USDC\" → max_amount_human: \"1\"), never atomic units by hand.',\n },\n submitCatalogEntry: {\n summary:\n 'Submit a merchant\\'s payable (x402/MCP) endpoint to Haven\\'s Verified Payable Directory for verification and listing.',\n selectionGuidance:\n 'Use this when a merchant or seller asks to be listed in the directory, or when you have discovered a payable endpoint and want it registered. ' +\n 'The submission is queue-only: it books a spot and returns a verify_token. The seller must then prove control of the domain (a well-known line or DNS TXT record); only after that plus a live quote probe does the entry become listed. ' +\n 'Do NOT use to pay — check the returned status with getCatalogSubmissionStatus instead.',\n behavior:\n 'Sends the https resource_url to Haven\\'s public submission endpoint. The request path makes no outbound request to the merchant. ' +\n 'Returns id + verify_token + status; the verify_token is shown exactly once. Ownership proof is always required later and cannot be skipped from the agent side. ' +\n 'The website field is a honeypot for bots — leave it unset.',\n nextActionGuidance:\n 'Give the verify_token and the well-known instructions (from getCatalogSubmissionStatus) to the merchant so they can publish the proof line, then poll the submission status until it reaches verified_payable or failed.',\n },\n sweep_delegate: {\n summary:\n 'Sweep stranded USDC and/or ETH from the delegate wallet back to the originating account.',\n selectionGuidance:\n 'Use this when the user instructs you to recover stranded funds on the delegate wallet, or when a payment status returns nextAction=sweep_stranded_funds. ' +\n 'Do NOT use for normal payments — use haven_pay_x402. ' +\n 'Do NOT use to read balances only — use haven_get_allowances, or haven_check_funds for whether the account holds funds.',\n behavior:\n 'Reads the delegate EOA\\'s on-chain USDC and ETH balances. For each non-zero balance, signs and submits a transfer from the delegate EOA to the originating account (hardcoded destination). ' +\n 'The delegate key signs locally — Haven never sees it and the backend never constructs signed transactions (CASP/MiCA Red Line #2). ' +\n 'Returns tx hashes and recovered amounts. Returns an empty transfers list when nothing is stranded. ' +\n 'Each transfer carries confirmation: \"confirmed\" (a receipt was seen — the funds are in the account) or \"unconfirmed\" ' +\n '(broadcast but not confirmed within 90 seconds — still in the mempool, may still land). The top-level unconfirmed flag is true when any transfer is unconfirmed.',\n nextActionGuidance:\n 'If transfers is non-empty, confirm the amounts with the user. ' +\n 'Report a transfer as recovered ONLY when its confirmation is \"confirmed\". ' +\n 'For an \"unconfirmed\" transfer, tell the user it was submitted but not yet confirmed, give them its txHash and explorerUrl to check, and do not re-run the sweep immediately — a re-run after it lands will simply find nothing stranded.',\n },\n send: {\n summary:\n 'Send ETH or USDC directly from the agent\\'s Haven wallet to a recipient address.',\n selectionGuidance:\n 'Use this for plain transfers — refunding a user, paying a freelancer, topping up a co-agent\\'s wallet, or moving funds between addresses. ' +\n 'Do NOT use for x402 paid endpoints — use haven_pay_x402 instead. ' +\n 'Do NOT use for read-only allowance, budget, or what-can-I-spend questions — use haven_get_allowances. ' +\n 'Do NOT use to check whether funds are held before sending — use haven_check_funds.',\n behavior:\n 'Sends the amount by redeeming the agent\\'s on-chain budget delegation, account to recipient with no funding leg. ' +\n 'Budget, recipient and expiry are enforced on-chain while the transfer is prepared, so a request outside them is declined before any money moves or any signing — never queued for a human to approve. ' +\n 'The agent\\'s signing key signs the account\\'s typed data, refusing any that mismatches the payment\\'s hash; Haven never receives the key.',\n nextActionGuidance:\n 'On a decline, report the reason to the user and ask them to grant or raise the budget in Haven — there is nothing to poll and no approval will arrive. ' +\n 'After a successful send, poll haven_get_payment_status until nextAction=none.',\n },\n reportSettlementEvidence: {\n summary:\n 'Report an erc7710 payment\\'s real settlement transaction hash so Haven can verify it on-chain and confirm the payment.',\n behavior:\n 'Pass payment_id and settlement_tx_hash (0x + 64 hex chars) — from PAYMENT-RESPONSE or a prior settlement_tx_hash. Haven verifies on-chain before confirming; a zero, mismatched, or reverted hash is refused. Your own payments only.',\n nextActionGuidance:\n 'code DELIVERED_UNSETTLED: did not verify, do not retry — poll haven_get_payment_status. code SETTLEMENT_PENDING (retryable:true): not mined or RPC unreachable — report the same hash again shortly.',\n },\n} as const satisfies Record<string, ToolDescription>\n\nexport type SharedToolKey = keyof typeof toolDescriptions\n","/**\n * Pre-built tool definitions for AI agent frameworks.\n *\n * These definitions describe Haven's direct SDK tool-calling surface in the\n * formats expected by Claude (Anthropic) and OpenAI.\n *\n * The agent payment surface used by these tools is shared with the\n * `@haven_ai/mcp` server — both consume `toolDescriptions` from\n * `./tool-descriptions.ts`. Each consumer composes its own user-visible string\n * from the same semantic fragments, so guidance lands in both surfaces at\n * once and a downstream test asserts the shared summary appears in every\n * consumer description.\n *\n * Usage with Claude:\n * const response = await anthropic.messages.create({\n * tools: havenTools.claude(),\n * ...\n * })\n *\n * Usage with OpenAI:\n * const response = await openai.chat.completions.create({\n * tools: havenTools.openai(),\n * ...\n * })\n */\n\nimport { composeDescription, toolDescriptions as sharedDescriptions } from './tool-descriptions.js'\n\n// ── JSON Schema (shared across formats) ──────────────────────────\n\nconst makePaymentSchema = {\n type: 'object' as const,\n properties: {\n token: {\n type: 'string' as const,\n description: 'Token to send. Gnosis Chain: EURe, USDC.e, xDAI. Base: USDC, ETH.',\n },\n amount: {\n type: 'string' as const,\n description: 'Amount to send as a decimal string, e.g. \"5.00\"',\n },\n to: {\n type: 'string' as const,\n description: 'Recipient Ethereum address (0x...)',\n },\n reason: {\n type: 'string' as const,\n description: 'Brief reason for this payment (for audit trail)',\n },\n },\n required: ['token', 'amount', 'to', 'reason'] as const,\n}\n\nconst getPaymentStatusSchema = {\n type: 'object' as const,\n properties: {\n payment_id: {\n type: 'string' as const,\n description: 'The payment ID returned from make_payment',\n },\n },\n required: ['payment_id'] as const,\n}\n\nconst getAllowancesSchema = {\n type: 'object' as const,\n properties: {},\n required: [] as const,\n}\n\nconst authorizeX402Schema = {\n type: 'object' as const,\n properties: {\n url: {\n type: 'string' as const,\n description: 'The URL that returned HTTP 402',\n },\n payTo: {\n type: 'string' as const,\n description: 'Payment recipient address from the 402 response',\n },\n amount: {\n type: 'string' as const,\n description: 'Payment amount in atomic units (e.g. \"1000000\" for 1 USDC)',\n },\n asset: {\n type: 'string' as const,\n description: 'Token contract address from the 402 response',\n },\n network: {\n type: 'string' as const,\n description: 'CAIP-2 chain ID. \"eip155:100\" for Gnosis Chain, \"eip155:8453\" for Base.',\n },\n description: {\n type: 'string' as const,\n description: 'Description of the resource being paid for',\n },\n idempotencyKey: {\n type: 'string' as const,\n description: 'Stable caller-supplied key for this user intent. Reuse it when resuming the same payment.',\n },\n },\n required: ['url', 'payTo', 'amount', 'asset', 'network'] as const,\n}\n\nconst resumeX402Schema = {\n type: 'object' as const,\n properties: {\n payment_id: {\n type: 'string' as const,\n description: 'The payment ID returned by authorize_x402_payment.',\n },\n url: {\n type: 'string' as const,\n description: 'The original URL that returned HTTP 402.',\n },\n payTo: {\n type: 'string' as const,\n description: 'Payment recipient address from the original 402 response.',\n },\n amount: {\n type: 'string' as const,\n description: 'Payment amount in atomic units from the original 402 response.',\n },\n asset: {\n type: 'string' as const,\n description: 'Token contract address from the original 402 response.',\n },\n network: {\n type: 'string' as const,\n description: 'CAIP-2 chain ID or x402 network from the original 402 response.',\n },\n description: {\n type: 'string' as const,\n description: 'Description of the resource being paid for.',\n },\n idempotencyKey: {\n type: 'string' as const,\n description: 'Stable caller-supplied key used for the original authorization.',\n },\n },\n required: ['payment_id', 'url', 'payTo', 'amount', 'asset', 'network'] as const,\n}\n\nconst MAKE_PAYMENT_DESCRIPTION =\n 'Request and sign a payment from the user-controlled account within its on-chain budget. ' +\n 'For read-only allowance, budget, spend-limit, remaining-amount, or reset-period questions, use get_allowances instead of making a payment. ' +\n 'Haven authenticates the agent and relays the signed transaction that redeems the agent budget delegation; it does not hold keys or control funds. ' +\n 'Gnosis Chain tokens: EURe, USDC.e, xDAI. Base tokens: USDC, ETH.'\n\n// Descriptions are composed from the shared semantic source so the SDK and MCP\n// surfaces stay in lockstep. Each constant prepends the shared `summary` (the\n// stable substring tests assert on) and then appends the SDK-specific guidance\n// for tool-calling consumers.\n\nconst GET_STATUS_DESCRIPTION =\n sharedDescriptions.getPaymentStatus.summary + ' ' +\n 'Accepts payment intent IDs. Returns the current status, phase, next_action, transaction hash if available, and payment details.'\n\nconst GET_ALLOWANCES_DESCRIPTION = composeDescription(sharedDescriptions.getAllowances)\n\nconst AUTHORIZE_X402_DESCRIPTION =\n composeDescription(sharedDescriptions.payX402) + ' ' +\n 'In this SDK tool set, the allowance lookup tool is get_allowances. ' +\n 'When a paid API returns x402 payment requirements, use this tool to sign with the agent-owned delegate key; funding, when the scheme needs it, is redeemed from the agent budget delegation and is bounded by it. ' +\n 'Haven relays signed transactions only; the agent key authorizes payment and on-chain limits enforce spend. ' +\n 'A payment outside the on-chain budget is declined before any money moves — report the decline and ask the user to raise the budget in Haven; do not loop retries and do not wait for an approval, because none is queued. Preserve the original merchant/MCP session and x402 details. ' +\n 'On a manual HTTP retry always set PAYMENT-SIGNATURE (x402 v2) to the returned payment_header; a strict v2 merchant reads only that name. Also set X-PAYMENT (v1) on the EIP-3009 funding path for legacy merchants, but NEVER on erc7710 — that header carries a delegation chain and duplicating it is refused with HTTP 431.'\n\n// #2145: the backend now emits nextAction=retry_original_x402_request from\n// GET /payments/:id (agent-payment-status.ts) when the funding leg confirmed\n// but no merchant response was ever recorded — the crash-recovery case, after\n// a 15-minute grace window. This tool's gate requires that exact nextAction,\n// so it is reachable again on purpose; the description tells an agent to gate\n// on the structured field rather than call this speculatively.\nconst RESUME_X402_DESCRIPTION =\n sharedDescriptions.resumeX402.summary + ' ' +\n 'Only call this after get_payment_status reports nextAction=retry_original_x402_request — that means Haven\\'s funding leg confirmed but no merchant response was ever recorded (typically a crash between funding and the merchant retry). ' +\n 'Any other nextAction reports a conflict instead of retrying — do not call this speculatively, and do not pay again.'\n\nconst SWEEP_DELEGATE_DESCRIPTION = composeDescription(sharedDescriptions.sweep_delegate)\n\nconst sweepDelegateSchema = {\n type: 'object' as const,\n properties: {},\n required: [] as readonly string[],\n}\n\n// ── Claude (Anthropic) format ────────────────────────────────────\n\nexport interface ClaudeTool {\n name: string\n description: string\n input_schema: {\n type: 'object'\n properties: Record<string, unknown>\n required: readonly string[]\n }\n}\n\nfunction claudeTools(): ClaudeTool[] {\n return [\n {\n name: 'make_payment',\n description: MAKE_PAYMENT_DESCRIPTION,\n input_schema: makePaymentSchema,\n },\n {\n name: 'get_payment_status',\n description: GET_STATUS_DESCRIPTION,\n input_schema: getPaymentStatusSchema,\n },\n {\n name: 'get_allowances',\n description: GET_ALLOWANCES_DESCRIPTION,\n input_schema: getAllowancesSchema,\n },\n {\n name: 'authorize_x402_payment',\n description: AUTHORIZE_X402_DESCRIPTION,\n input_schema: authorizeX402Schema,\n },\n {\n name: 'resume_x402_payment',\n description: RESUME_X402_DESCRIPTION,\n input_schema: resumeX402Schema,\n },\n {\n name: 'haven_sweep_delegate',\n description: SWEEP_DELEGATE_DESCRIPTION,\n input_schema: sweepDelegateSchema,\n },\n ]\n}\n\n// ── OpenAI format ────────────────────────────────────────────────\n\nexport interface OpenAITool {\n type: 'function'\n function: {\n name: string\n description: string\n parameters: {\n type: 'object'\n properties: Record<string, unknown>\n required: readonly string[]\n }\n }\n}\n\nfunction openaiTools(): OpenAITool[] {\n return [\n {\n type: 'function',\n function: {\n name: 'make_payment',\n description: MAKE_PAYMENT_DESCRIPTION,\n parameters: makePaymentSchema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'get_payment_status',\n description: GET_STATUS_DESCRIPTION,\n parameters: getPaymentStatusSchema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'get_allowances',\n description: GET_ALLOWANCES_DESCRIPTION,\n parameters: getAllowancesSchema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'authorize_x402_payment',\n description: AUTHORIZE_X402_DESCRIPTION,\n parameters: authorizeX402Schema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'resume_x402_payment',\n description: RESUME_X402_DESCRIPTION,\n parameters: resumeX402Schema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'haven_sweep_delegate',\n description: SWEEP_DELEGATE_DESCRIPTION,\n parameters: sweepDelegateSchema,\n },\n },\n ]\n}\n\n// ── Public API ───────────────────────────────────────────────────\n\nexport const havenTools = {\n /** Tool definitions in Anthropic/Claude format */\n claude: claudeTools,\n\n /** Tool definitions in OpenAI function-calling format */\n openai: openaiTools,\n}\n","/**\n * Agent-facing onboarding guidance — canonical copy (#2523, epic #2519).\n *\n * Two exports, one source:\n *\n * 1. **The shared sentences** — the rules an agent must follow when it runs the\n * connector. They appear in the backend's `setup_prompt`\n * (`routes/agent-connection-setups.ts` `buildSetupPrompt`) AND in the runbook\n * below. Before this file they existed once, inline in the route; the runbook\n * would have been a second copy, and a second copy of a rule is how the two\n * drift into contradicting each other in front of an agent that has no way to\n * tell which is current.\n * 2. **`HAVEN_AGENT_RUNBOOK_MD`** — the runbook served as\n * `packages/frontend/public/for-agents.md`, written to the agent whose user\n * has no Haven account yet. `llms-full.txt`'s quickstart addresses the owner;\n * this addresses the agent, and its job is to say which steps are the human's\n * and exactly what to say at each hand-off.\n *\n * The frontend keeps the runbook as a static file rather than importing it:\n * `packages/frontend` has zero `@haven_ai/*` dependencies by design (standalone\n * Vercel deploys), and `public/` is served as-is. A byte-equality test\n * (`src/lib/__tests__/for-agents-runbook.test.ts`) pins the served file to this\n * string, exactly as `agent-skill-bundle.test.ts` pins the skill.\n *\n * Wording constraints, recorded because they are not stylistic (owner\n * constraints 2026-09-04, and `docs/regulatory/casp-risk-guardrails.md`\n * § Product Copy Rules): the human keeps every signature; there is no headless\n * account path; the runbook must never suggest the agent enters the user's\n * password; the owner-signed budget is what authorises a payment, and Haven\n * constructs and relays.\n */\n\n/** Secret hygiene — the one rule that survives every mode and every runtime. */\nexport const AGENT_SECRET_HYGIENE_SENTENCE =\n 'Do not print private keys, API keys, credential file contents, or config secrets in chat or logs.'\n\n/** Where the signing key is made, and what Haven receives instead of it. */\nexport const AGENT_LOCAL_KEY_SENTENCE =\n 'The Haven connector generates the signing key locally and sends Haven only the public signing address plus proof.'\n\n/** Sandboxed environments: the command does not change, the environment does. */\nexport const AGENT_NETWORK_ACCESS_SENTENCE =\n 'Network access is expected: this command downloads the npm package and contacts the Haven API, so if your environment is sandboxed, run it with network access enabled or request network access escalation; that changes the execution environment, not the command, and is not a third command modification.'\n\n/** #2483: `--json` is a SHOULD addressed to agents, not to a human pasting the command. */\nexport const AGENT_JSON_MODE_SENTENCE =\n 'If you are an AI agent running this command yourself rather than a human pasting it, you should append --json: the connector then emits one machine-readable, secret-free result object on stdout with progress on stderr, and returns promptly instead of blocking while it waits for the budget approval.'\n\n/** #2483: one gate at a time — the approval relay comes before anything else. */\nexport const AGENT_APPROVAL_RELAY_JSON_SENTENCE =\n \"When a --json outcome reports approval.required: true, your first action must be to relay the approval instruction to me in your own reply — if the outcome carries approval.url, give me that link; otherwise tell me to return to Haven and approve this agent's budget — before verifying the connection, restarting anything, or any other step. Never build that link yourself: relay the one the outcome gave you or none at all. Any restart the outcome asks for is a separate instruction to give me afterwards, once the approval is done.\"\n\n/** #2486: the prose-mode twin of the sentence above; each mode relays exactly once. */\nexport const AGENT_APPROVAL_RELAY_PROSE_SENTENCE =\n \"If you ran the command without --json, the connector waits for the approval itself and prints its next steps when it finishes: relay the budget-approval instruction to me — the approval link if those steps printed one, otherwise that you need to return to Haven and approve this agent's budget — only if those printed next steps still ask for it. If they report the budget as already approved, there is nothing for me to approve.\"\n\n/**\n * #2551, handed to #2528 by PR #2567 so a third writer would not land on the\n * money-path prompt file for one line.\n *\n * The connector's `wiring_collision` refusal is the THIRD case where the agent\n * owes its user a decision rather than an action of its own — beside\n * `approval.required` and the runtime-refusal retry. Named explicitly because\n * the other two are, and an unnamed relay case is one an agent resolves by\n * guessing: here it would guess `--replace` (silently displacing a working\n * agent) or `--name` (quietly wiring a second one). Both are the user's call.\n */\nexport const AGENT_WIRING_COLLISION_RELAY_SENTENCE =\n 'If the connector refuses with wiring_collision, this machine is already wired to a different agent: relay that refusal to me with the superseded_agent_ids and suggested_name it carries, and let me choose whether to replace the existing wiring or add this agent alongside it. Never pick for me by adding --replace or --name yourself.'\n\n/** #1719: exactly two permitted changes, and the second is bounded by the refusal's own list. */\nexport const AGENT_COMMAND_MODIFICATION_SENTENCE =\n 'Only two changes to the command above are permitted, and no others: appending --json, and — only if the connector refuses because it could not determine the agent runtime — re-running it once with --runtime <name> added, naming the harness you are running in, using one of the values that refusal lists. Never invent a runtime name and never change anything else.'\n\n/**\n * The agent-facing section every published README carries (#2533, A6).\n *\n * ONE string, six copies, one instrument. All five npm READMEs plus the repo\n * README open with dashboard-first instructions, which strand the reader this\n * epic exists for: an agent whose user has no account yet. This is the entry\n * that redirects them, and it is defined here rather than written six times\n * because six hand-maintained copies is exactly the drift #2310 was about —\n * `agent-guidance.test.ts` fails if any copy differs by a byte.\n *\n * TWO links, and the second is not redundant. The path is correct wherever\n * Haven is actually served and needs no host we do not own (#2520's rule); the\n * GitHub URL is the one that resolves for a reader on npmjs.com, who has no\n * origin to resolve a path against. A path alone would be unfollowable in the\n * place these READMEs are most often read; an absolute app host alone would be\n * a host nobody owns. Naming both is the honest answer, and the runbook itself\n * is committed at that path, so the fallback is a real file rather than a\n * promise.\n *\n * Interrogative, not declarative-with-a-question-mark. `llms.txt` states the\n * same idea declaratively because there it is a LINK TITLE in a list; an H2\n * whose job is to catch the right reader and let everyone else skip is a\n * question. The mismatched mood was a haven-design-reviewer finding, fixed\n * while it was cheap: the string is byte-pinned in six files, so the cost of\n * changing it only ever goes up.\n *\n * It says what the agent CANNOT do first. The account and the passkey are the\n * user's, always — stating that up front is what stops an agent trying, and it\n * is the epic invariant no slice may weaken.\n */\nexport const AGENT_README_SECTION_MD = `## Are you an AI agent whose user has no Haven account yet?\n\nRead **\\`/for-agents.md\\`** on the Haven host your user gave you — or\n[the copy in this repository](https://github.com/d-hinders/Haven-AI/blob/dev/packages/frontend/public/for-agents.md)\nif you do not have that host yet.\n\nYour user creates the account and the passkey: those are theirs, they need a\nhuman, and you should never ask for their password. You can do everything else\n— including running the connector command from the setup prompt they paste you,\nand managing the account from the shell with \\`@haven_ai/cli\\`.`\n\n/**\n * The runbook, served at `/for-agents.md`.\n *\n * Every link is a same-origin path (#2520): resolve it against the host the\n * file was fetched from. The npm dist-tags are the placeholder `<channel>`\n * rather than literals — the connector's command and, since #2617, the CLI's\n * login in step 1 — for two reasons that point the same way: a published\n * package must not hard-code one (#2423, guarded by\n * `scripts/release-bump.test.mjs`), and this string is committed as a static\n * file, so baking in a channel `release-bump.mjs` later rewrites would put the\n * served copy out of parity at exactly the moment nobody is reading it. The\n * page tells the agent to run the command its setup prompt hands it, where the\n * tag is real and deployment-correct, and to read the CLI's tag from\n * `/.well-known/haven.json` (`packages.cli.channel`).\n *\n * The budget-approval hand-off is now a LINK when the connector has one, and a\n * tab when it does not — #2528 landed the half of this that was missing.\n * `ConnectOutcome` (`packages/connect/src/runtime.ts`) carries\n * `approval: { required, expires_at, url? }`; `url` is the same-origin\n * `approval_url` the register response returns, so the agent relays a\n * destination instead of \"return to Haven\".\n *\n * The step-5 hand-off is TWO blockquotes, not one with the alternative in\n * brackets. It was the bracket form briefly, to save ~110 bytes against the\n * size ceiling, and haven-design-reviewer was right to push back: this\n * section's own header says \"Send these as your own message\", so every other\n * script in it is paste-ready. A bracketed either/or inside the quote makes\n * the agent perform text surgery on something presented as copyable — and a\n * naive relay ships the raw brackets to the human, which reads as broken\n * rather than as a choice. Two quotes cost bytes and buy back the property\n * the section is built on. Do not re-compress this to save them.\n *\n * `AGENT_WIRING_COLLISION_RELAY_SENTENCE` is deliberately NOT in this page's\n * rule list, though it IS in the setup prompt (#2551 via #2567). This page's\n * list is already a curated subset of the prompt's — it omits the network and\n * local-key sentences and adds the prose-relay one — and a collision can only\n * happen to an agent that is running the connector, which means it is holding\n * the prompt, where the sentence is. Repeating it here would cost every agent\n * that fetches this page bytes for a rule it will be handed at the moment it\n * applies.\n *\n * TWO limits, stated because the copy below depends on both. First, `url` is\n * OPTIONAL and its absence is normal: a backend older than #2528 sends none,\n * and `approval.required: false` carries none because there is nothing to\n * approve — so every sentence here has to work with and without it, which is\n * why they read \"if the outcome carries a link\". Second, the outcome still has\n * NO setup id: #2528 added the link only, and the connector's own status poll\n * (`GET /:setupId/connector-status`) still answers `{ status, approved_budget }`.\n * An agent must not construct an approval URL out of parts — it has the whole\n * one or it has none. `?next=` / `?via=agent` / `?setup=` are the hand-off\n * link shapes from #2522.\n */\nexport const HAVEN_AGENT_RUNBOOK_MD = `# Haven for agents — set your user up to let you pay\n\nYou are an AI agent whose user has no Haven account yet, or has one but has not connected you.\n\n> Links below are paths on this same host: resolve them against the URL you fetched this file from.\n\n## What Haven is, in three sentences\n\nYour user gives you a **budget on their own account** — not their wallet, and not a key to their funds. The budget is a delegation they sign, enforced on-chain: a payment over it, to the wrong recipient, or past its expiry is refused at execution time, not by a dashboard promise. Haven constructs and relays the payments; you get an agent credential and a signing key made on your machine, and your user can revoke the budget without you and without Haven.\n\n## The sequence\n\nFour of the six steps are your user's — each needs a human signature or a human decision. The rest is yours. If they already have a funded account, start at step 3.\n\n1. **HUMAN — create the account.** Name, email, password, then a passkey (Face ID / Touch ID) or a wallet. Never offer to enter any of it: you must not have their password, and the passkey is bound to their device. With a terminal, \\`npx @haven_ai/cli@<channel> login --api <api-url>\\` afterwards gets you a scoped session for steps 3-4 (that flag or \\`HAVEN_API_URL\\`, on the first command — the session then remembers the backend; **the CLI's built-in default is Haven's hosted production backend**, so on any other deployment an omitted flag connects you somewhere real and wrong rather than failing) — they approve a code in the browser, you never hold their password. The \\`<channel>\\` in that command is the tag your deployment names — read it from \\`/.well-known/haven.json\\` (\\`packages.cli.channel\\`), never a tag you pick. Do not hold the process open while you wait: under \\`--json\\`, pass \\`--no-wait\\` to get the link object back at once, then poll it with \\`haven login --poll <device_code>\\` — one round per invocation, exit 3 while it is still pending, 0 once approved. It can set up agents and read the account; it cannot sign, approve a budget, move funds, or rotate any agent's keys.\n2. **HUMAN — fund it.** USDC only, no ETH: Haven sponsors the gas. \\`/.well-known/haven.json\\` names \\`chains.default\\` as the deployment's expected chain, but after login \\`haven wallets funding\\` prints the address, the amount and which chain in one place; confirm that chain before you message your user. Without a CLI session, the dashboard's funding card shows the address and amount and its Receive-funds screen names the chain; never assume one: a testnet deployment and production both call themselves Haven. Before you write that message, read the manifest: \\`environment\\` says whether this deployment is \\`production\\`, and each \\`chains.supported\\` entry says whether that chain is a \\`testnet\\`. Real money is at stake only on a non-testnet chain of a \\`production\\` deployment — tell your user which case theirs is.\n3. **HUMAN — create the agent, set its budget**, and paste you the **setup prompt** it hands back. With a CLI session (step 1) you can do this step yourself: \\`haven agents connect --name <n> --budget <amount> --token USDC --period <minutes>\\` prints the same connector command and approval link; add \\`--run\\` to do step 4 too.\n4. **YOU — run the connector command** in that prompt (below). It makes your signing key locally, registering only the public address.\n5. **HUMAN — approve the budget** with their passkey, in the Haven tab they created the agent in: it advances to the approval step by itself once your run registers.\n6. **YOU — verify, then pay.**\n\n## Budget changes later (second token, raise, revoke)\n\nThe first budget rides the setup above. After the agent exists, a CLI session can construct the LATER changes — a second token, a bigger amount, a recipient pin, a stop — and hand your user a link; the human still signs, every time:\n\n\\`\\`\\`\nhaven budget grant <agentId> --amount <n> --token USDC --period <minutes> [--recipient <address>] [--wait]\nhaven budget revoke <agentId> <delegationHash> [--wait]\n\\`\\`\\`\n\nThe CLI never signs: it prints a dashboard link, your user opens it and signs with their passkey or wallet. \\`--wait\\` polls until the human's signature lands. The hash for \\`revoke\\` is in \\`haven agents show <agentId>\\`.\n\n## Hand-off scripts\n\nSend these as your own message, \\`<host>\\` replaced by the host you fetched this file from. Say what you cannot do, not only what they must.\n\n**Before signup** (step 1):\n\n> I can do everything except the parts that need your signature. Please open \\`<host>/signup?next=/agents&via=agent\\` — name, email, password, then a passkey (Face ID / Touch ID) or a wallet. That is your account's key: I should not have it, and I will never ask for your password. Already have one? \\`<host>/login?next=/agents\\`.\n\n**At the passkey step:**\n\n> The passkey must be made on your own device — it is what keeps the account yours, so nobody, Haven included, can move your funds without you. If this browser cannot, open \\`<host>/onboarding?next=/agents\\` on your phone and finish there.\n\n**At funding** (step 2):\n\n> Your Haven account needs USDC before I can pay for anything — USDC only, no ETH: Haven sponsors the gas. Before you send anything, let me get you the exact address **and network** — \\`haven wallets funding\\` prints both, and the funding card on \\`<host>/dashboard\\` shows the same. Please do not send to an address or a chain I have not confirmed with you; a small amount first is fine.\n\n**At the budget** (step 3):\n\n> On \\`<host>/agents\\`, create an agent for me and set a budget — say 25 USDC per day. That is the limit I cannot exceed. It hands back a setup prompt: paste it to me and I run it here.\n\n**At budget approval** (step 5) — the moment your run reports that approval is required, before anything else. Send the first if your run carried \\`approval.url\\`, the second if it did not.\n\n> Setup is done on my side. Approve the budget here: <approval.url>. Approve it with your passkey; nothing can be spent until you do.\n\n> Setup is done on my side. Go back to the Haven tab where you created the agent — it should now be asking you to approve the budget. Approve it with your passkey; nothing can be spent until you do.\n\n## What you run\n\nThe setup prompt carries a **connector command** shaped like this:\n\n\\`\\`\\`\nnpx -y @haven_ai/connect@<channel> --setup EXAMPLE-SETUP-TOKEN-NOT-REAL --api <api-url> --ack-local-tools\n\\`\\`\\`\n\nRun the prompt's version, not this one: the token is one-time, the API URL is the backend's own, and \\`<channel>\\` is the npm tag your prompt names — never a tag you pick. The rules below come from that prompt, so \"me\" in them is your user, not Haven.\n\n- ${AGENT_JSON_MODE_SENTENCE}\n- ${AGENT_APPROVAL_RELAY_JSON_SENTENCE}\n- ${AGENT_APPROVAL_RELAY_PROSE_SENTENCE}\n- ${AGENT_COMMAND_MODIFICATION_SENTENCE}\n- ${AGENT_SECRET_HYGIENE_SENTENCE}\n\nIf the approval wait times out, nothing is lost — your agent is registered and the budget is still waiting to be approved. Send your user the \\`approval.url\\` your run reported, or, if it carried none, ask them to finish it in that same Haven tab. The outcome carries no setup id, so never assemble an approval link out of parts — relay the whole one it gave you or none at all.\n\n## How to verify\n\nCall \\`haven_get_agent\\`, one of the Haven MCP tools the connector wires into your runtime in step 4. It returns identity plus \\`spend_authority_readiness\\`:\n\n- \\`ready\\` — a budget is live; you can pay.\n- \\`needs_approval\\` — the connector finished, nobody approved yet. Ask your user again, in their Haven tab; there is no queue to wait in.\n- \\`revoked\\` — the credential is not active; ask your user to create a new agent.\n\n\\`ready\\` covers hosted identity and the budget only, not your local signer. Check that with \\`npx -y @haven_ai/connect@<channel> --doctor\\`, the same tag your prompt named — a separate command, so the two-changes rule does not bind it.\n\n## If you cannot open a browser\n\nNothing here needs you to. Steps 1-3 are links: hand your user the full \\`<host>/…\\` URL and ask them to say when it is done. Step 5 is a link only when your run reported one in \\`approval.url\\` — otherwise it is the tab they already have open, as above. Then poll \\`haven_get_agent\\` until it reads \\`ready\\`. Do not route around the sign-in wall — it makes the account theirs, not yours.\n\n## Vocabulary\n\n| Term | What it is |\n|---|---|\n| **setup prompt** | The text the dashboard hands your user to paste to you. Carries the command and its rules. |\n| **connector command** | The \\`npx -y @haven_ai/connect@…\\` line you run. One-time token, one use. |\n| **agent credential** | Your API key (\\`sk_agent_…\\`), written to \\`~/.haven\\`. It identifies you; alone it cannot move money. |\n| **delegate key** | Your signing key, made on this machine and never sent anywhere. |\n| **budget** | The on-chain delegation your user signed. It authorises the payment; Haven constructs and relays it. |\n\nNext: [your agent hit a 402](/402.md) · [everything agent-readable](/llms.txt)\n`\n\n/**\n * The **onboarding prompt** — the whole-onboarding text the dashboard offers a\n * signed-in user to paste to their agent (#2535, epic #2519).\n *\n * ## It is NOT the \"setup prompt\", and the distinction is load-bearing\n *\n * `setup prompt` is one of the four canonical agent-facing terms\n * (`docs/product/copy-guidelines.md` § Agent-facing vocabulary, settled by\n * #2533 and swept by #2576): it names the text the CONNECT MODAL hands back,\n * which carries a one-time setup token and the connector command. This string\n * is a different object with a different lifetime — it exists before any setup\n * does, contains no token and no secret, and is therefore safe to render to a\n * signed-in user who has not created an agent yet. Calling both \"the setup\n * prompt\" would undo the disambiguation those two issues paid for, so this one\n * is the **onboarding prompt** wherever it is named.\n *\n * ## Why a shared export rather than a route\n *\n * The issue offered `GET /agent-connection-setups/agent-prompt` or a static\n * export. The export wins on cost and on the #2523 precedent: no new route, no\n * auth question, and no `owner_cli` allow-list entry — and the allow-list is\n * fail-closed by design, so every entry is a decision. The route would only\n * earn those three if the prompt had to vary per user, and it deliberately does\n * not: it names commands and links, never account state.\n *\n * ## What keeps it from drifting from the setup prompt\n *\n * The two are built from the SAME sentence constants above — this one reuses\n * the approval-relay and secret-hygiene rules verbatim rather than paraphrasing\n * them, which is the whole reason those constants exist. A test asserts that\n * containment, so a reworded copy here fails rather than quietly disagreeing\n * with what `buildSetupPrompt` tells the same agent minutes later.\n *\n * The frontend cannot import this: `packages/frontend` has zero `@haven_ai/*`\n * runtime dependencies by design (standalone Vercel deploys). It keeps a copy\n * in `src/lib/agent-onboarding-prompt.ts`, byte-pinned to this string by\n * `src/lib/__tests__/agent-onboarding-prompt.test.ts`, exactly as the runbook\n * and the skill are pinned.\n *\n * ## The origin placeholder\n *\n * `{{HAVEN_ORIGIN}}` is substituted by the renderer with the host the user is\n * actually signed in to, so dev, preview and production each produce a truthful\n * prompt from one string. It is a placeholder rather than a build-time constant\n * for the same reason `<channel>` is one in the runbook: this text is committed,\n * and a baked host is wrong everywhere except where it was baked.\n *\n * ## Wording constraints (same as the runbook's, and not stylistic)\n *\n * The human keeps every signature; there is no headless account path; it must\n * never suggest the agent enters the user's password; the owner-signed budget\n * is what authorises a payment, and Haven constructs and relays. Every command\n * it names exists at merge time — `haven login` (#2526) and\n * `haven agents connect` (#2527) both landed before this shipped, which is the\n * condition #2535 made blocking.\n */\nexport const AGENT_ONBOARDING_PROMPT = `I have a Haven account and I am signed in at {{HAVEN_ORIGIN}}. Please set up Haven so you can pay for things within a budget I approve.\n\nStart by reading {{HAVEN_ORIGIN}}/for-agents.md — it is written for you and explains which steps are mine.\n\nThen:\n\n1. Run \\`npx @haven_ai/cli@<channel> login\\`. The \\`<channel>\\` in that command is the tag your deployment names — read it from \\`/.well-known/haven.json\\` (\\`packages.cli.channel\\`), never a tag you pick. It prints a link and a code and does not need my password — it must never ask for it. Give me the link straight away and wait for me to approve it in my browser.\n2. Once I have approved, run \\`haven agents connect --name <a name you choose> --budget <amount> --token USDC --period <minutes>\\` with the budget I tell you. If I have not given you one, ask me before running it. Add \\`--run\\` to complete the connection in the same step.\n3. ${AGENT_APPROVAL_RELAY_JSON_SENTENCE}\n4. Once I have approved the budget, verify with the \\`haven_get_agent\\` tool: \\`ready\\` means you can pay, \\`needs_approval\\` means my approval has not landed yet.\n\nTwo things only I can do: approving that budget with my passkey, and funding the account with USDC on Base — no ETH, Haven sponsors the gas. Tell me if either is missing rather than working around it.\n\n${AGENT_SECRET_HYGIENE_SENTENCE}`\n","import {\n AGENT_APPROVAL_RELAY_JSON_SENTENCE,\n AGENT_COMMAND_MODIFICATION_SENTENCE,\n AGENT_SECRET_HYGIENE_SENTENCE,\n AGENT_WIRING_COLLISION_RELAY_SENTENCE,\n} from './agent-guidance.js'\n\n/**\n * The generic Haven payment skill — canonical copy.\n *\n * This SDK file is the single source of truth for the generic, secret-free\n * skill content: no wallet address, no budget numbers, no per-agent values.\n * The agent learns its live budget at runtime via the `haven_get_agent` /\n * `haven_get_allowances` MCP tools, and can read identity + configured budget\n * for fast first-turn orientation from the non-secret `agent.json` the\n * connector writes (see `packages/connect/src/storage.ts`), so the same file\n * works for every user. `packages/connect` imports this directly to\n * auto-install the skill into runtime skills folders.\n *\n * `packages/frontend/src/lib/agent-skill-bundle.ts` keeps a deliberately\n * decoupled inline copy (the download fallback): the frontend does not depend\n * on the SDK, so it can deploy standalone on Vercel without an unpublished\n * export. It is NOT `@haven_ai/*`-free — it takes `@haven_ai/core` with the\n * `\"*\"` workspace pin — and this comment said otherwise until #2537 checked\n * the manifest; the material point is the one that survives, and it is about\n * the SDK specifically. A parity test in that package's test suite imports\n * this canonical string and asserts byte-for-byte equality, so the two copies\n * cannot drift.\n *\n * **The onboarding section (#2537) is COMPOSED, not written here.** Its rule\n * sentences are interpolated from `agent-guidance.ts`, which is also where the\n * backend's setup prompt and the `/for-agents.md` runbook get them: a rule an\n * agent meets twice must be one text, or the two copies drift into\n * contradicting each other in front of a reader with no way to tell which is\n * current. The prose around them is skill-only and lives here.\n *\n * **Those three bullets are quoted in the setup prompt's own voice**, where\n * the USER is speaking: \"me\"/\"I\" are the user, and \"the command above\" is the\n * connector command printed directly above them there — neither of which\n * holds in this file, which addresses the agent throughout and prints no\n * command. Any future user-voice quote here needs the same two-referent\n * gloss, and it must sit BEFORE the quote rather than after: the first draft\n * put it after, and both the reviewer and the design reviewer independently\n * found that an agent reading top-to-bottom meets `relay ... to me` before\n * it learns whose \"me\" that is — on the one instruction the section itself\n * calls the highest-priority one. `AGENT_APPROVAL_RELAY_PROSE_SENTENCE` is a\n * live sibling constant not pulled in here; if it ever is, this applies to it\n * too (design review, #2537).\n */\n\nexport const HAVEN_SKILL_MD = `---\nname: haven-pay\ndescription: Pay for things from the user's Haven wallet within their agent rules, and set Haven up when it is not yet connected. Use when the user asks to send, pay, tip, or transfer crypto; when a request hits an HTTP 402 (x402) paywall; or when they ask to create a Haven account, create an agent, or connect one.\n---\n\n# Haven: pay from a Haven wallet\n\nThis skill lets the agent make payments from the user's Haven wallet through\nthe Haven MCP tools. Every payment is checked against the agent's on-chain\nbudget before money moves; a payment above the remaining budget is declined —\nnothing is paid past the rules the user set.\n\nHosted tools run in the \\`mcp__haven__\\` namespace. Local signing tools run in\nthe \\`mcp__haven-signer__\\` namespace and keep the delegate key on this machine.\nThat namespacing is Claude-family; other runtimes name the servers by their\nown config keys (Codex: \\`haven\\`, \\`haven_signer\\`). Tool results carry the\nexact next step (\\`next_action\\`, \\`next_tool\\`, \\`next_arguments\\`, plus the\nruntime-neutral \\`next_tool_server\\` + \\`next_tool_name\\` + \\`next_tool_server_role\\`\n— the bare tool name on that logical server, whatever your runtime calls it).\nWhen no tool follows, \\`next_tool\\` is absent and \\`next_tool_omitted_reason\\`\nsays why; that is a complete answer.\nFollow those fields first; the prose below is fallback and orientation, not\nthe source of truth.\n\n## When to use this skill\n\n- The user asks to send money, pay someone, tip, donate, or transfer tokens.\n- A request returns HTTP 402 (x402): use the Haven pay tools to settle it,\n then retry the original request.\n\n## Onboarding and setup\n\nYou are in this mode when there is no Haven agent credential on this machine,\nor when your user asks you to create a Haven account, create an agent, or\nconnect one — for themselves or for someone else.\n\n**None of the tools below creates authority.** They spend a budget a human\nalready signed. There is no tool here that opens an account, mints a\ncredential, or approves a budget, so reaching for one of them to \"set Haven\nup\" cannot work; the steps are the ones in this section instead.\n\nStart by reading \\`/for-agents.md\\` on the Haven host — the origin of the\n\\`api_url\\` in your \\`agent.json\\` if you have one, otherwise the host your user\nnames. It is the full runbook: six steps, which four are your user's, and what\nto say at each hand-off.\n\nTwo of those steps you can do yourself, from the shell with \\`@haven_ai/cli\\`\n(installs the \\`haven\\` command):\n\n- \\`haven login\\` — a device-code browser flow. It prints a code and a link\n for your user to approve, so you never see or ask for their password. What\n the session can reach is an allow-list, not your user's full authority: it\n creates and manages agents and reads the account, and it cannot approve a\n budget, rotate a key, change a signer or move money — those are your user's.\n- \\`haven agents connect\\` with \\`--name\\`, \\`--budget\\`, \\`--token\\` and\n \\`--period\\` — creates a connection setup and prints two things: the\n connector command the backend built, and the approval link to give your user.\n Add \\`--run\\` to execute that command here as a child process.\n- \\`haven wallets funding\\` — prints the paste-ready funding instruction: what\n to send, to which address, on which chain. Read the chain from there rather\n than assuming one. \\`--wait\\` polls until the account counts as funded.\n\n**Four steps are your user's, and each one needs a human:** create the account\nand its passkey, fund the wallet, approve every agent's budget, and rotate a\ncredential. You can compose the funding message for them with\n\\`haven wallets funding\\`, but you cannot send the money — that transfer is\ntheirs, from a wallet you have no access to.\n\nRunning the connector command is the step that wires this machine to the new\nagent — the command \\`haven agents connect\\` printed, or the one your user\npasted you from the dashboard. Three rules bind you while you do it, quoted\nunchanged from the setup prompt your user is also holding so the two copies\ncannot drift into contradicting each other. They are written in your user's\nvoice, so read them accordingly: \"me\" and \"I\" below are your user, never\nHaven, and \"the command above\" is that connector command, not anything printed\nin this file. The first rule outranks anything else you were about to do next:\n\n- ${AGENT_APPROVAL_RELAY_JSON_SENTENCE}\n- ${AGENT_COMMAND_MODIFICATION_SENTENCE}\n- ${AGENT_WIRING_COLLISION_RELAY_SENTENCE}\n\n${AGENT_SECRET_HYGIENE_SENTENCE}\n\n## Identity and budget\n\nDo not guess the wallet address, network, or budget.\n\nFor instant orientation at the start of a session, read the non-secret\n\\`agent.json\\` the connector wrote to your Haven credential directory (typically\n\\`~/.haven/agents/<agent-id>/agent.json\\` — if you don't know the agent id, list\n\\`~/.haven/agents/\\` to find the folder). It\nholds your agent id, Haven wallet address, network, and *configured* per-token\nbudget, and contains no keys — the fastest way to answer \"who am I and what may\nI spend\" with no round trip. If that file is absent (some setups don't write\nit), use the tools below instead.\n\nBefore any payment, confirm the *live remaining* budget with the tools —\n\\`agent.json\\` shows the configured budget, not what is left after recent\nspending:\n\n- \\`mcp__haven__haven_get_agent\\` — the recommended first call: identity\n (wallet, network) plus \\`spend_authority_readiness\\` (\\`ready\\` / \\`needs_approval\\` /\n \\`revoked\\`) and live remaining per-token allowance, in one shot. That signal\n covers hosted identity and on-chain spend authority only — it cannot see the\n local signer; the signer is verified by calling any signer tool.\n- \\`mcp__haven__haven_get_allowances\\` — detailed per-token breakdown\n (configured, spent, reset window) when you need more than the summary.\n- \\`mcp__haven__haven_check_funds\\` — whether the account actually HOLDS at\n least a given amount of a token. Allowance answers above say what you are\n permitted to spend; this one says whether the money is really there,\n answered as \\`covered\\` true/false/null — never as a balance. On\n \\`covered: false\\`, stop and tell the user the account is short; on\n \\`covered: null\\` (the chain read failed), treat it as unverifiable rather\n than as absence.\n\nBudgets reset on a period the user chose. If a payment exceeds the remaining\nbudget it is declined before any money moves — tell the user; they can raise\nthe budget in the Haven dashboard, or wait for the period reset.\n\n## Paying\n\n**Catalog purchases — the primary path for MCP merchants:**\n\n1. \\`mcp__haven__haven_discover_tools\\` to find a payable service and its\n \\`catalog_id\\`.\n2. If the user needs the live price before authorizing a cap, call\n \\`mcp__haven__haven_quote_catalog_purchase\\` with \\`catalog_id\\`. It is\n read-only and informational only: it never reserves a price or creates a\n payment. Tell the user its \\`amount\\` / \\`amount_atomic\\`, then choose a cap.\n3. \\`mcp__haven__haven_prepare_catalog_purchase\\` with \\`catalog_id\\` and a\n spending cap. A cap is REQUIRED on this tool and is best practice on every\n paid call below too — it caps what the LIVE merchant quote may charge,\n checked before any funding intent is created. Write it the way the user\n said it: \\`max_amount_human\\` is whole tokens, so \"no more than 1 USDC\" is\n \\`max_amount_human: \"1\"\\`. (\\`max_amount\\` is the atomic-unit form, where\n \"1\" means 0.000001 USDC — do not convert by hand, and never send both.)\n4. Then FOLLOW THE RESPONSE'S GUIDANCE FIELDS: \\`next_action\\`, \\`next_tool\\`,\n and \\`next_arguments\\` name the exact next call — act on those first; the\n prose in this section is fallback and debugging detail. If the catalog\n entry is missing or degraded, the response instead names\n \\`mcp__haven__haven_pay_mcp_tool\\` (merchant URL, tool name, arguments) as\n the manual fallback.\n\n**Signing:** \\`mcp__haven-signer__haven_sign_x402\\` with \\`payment_id\\` ONLY —\nthe local signer fetches the exact signing bytes AND \\`payment_required\\`\nitself, so never relay \\`typed_data\\` or the 402 blob yourself. If the signer\nreports its fetched context carried no \\`payment_required\\` (older backend),\nre-call with \\`payment_required\\` added verbatim. Fallback for an older signer\nor backend: re-run the quote/prepare tool with the SAME \\`idempotency_key\\`\nplus \\`include_signing_payload=true\\`, then pass \\`payload_hash\\`,\n\\`x402_expected\\` (the nested \\`x402.expected\\` object), and\n\\`typed_data\\`/\\`typed_data_b64\\` through unchanged.\n\n**Settle:** \\`mcp__haven__haven_settle_mcp_tool\\` with \\`payment_id\\`,\n\\`signature\\`, and \\`payment_header\\` ONLY — Haven rehydrates the merchant call\ncontext (\\`merchant_url\\`, \\`tool_name\\`, \\`arguments\\`, \\`mcp_transport\\`)\nserver-side from \\`payment_id\\`. Pass those four fields explicitly only as a\nversion-skew fallback when Haven has no stored context for the id — both or\nnone together, never just one. If the settle result carries \\`settled: false\\`,\nfunding has not confirmed — follow the result's guidance fields and check\nstatus later, do not re-pay.\n\nStep-by-step alternative (also key-safe; for an older signer or backend, or\nwhen you already have a merchant URL and tool name instead of a\n\\`catalog_id\\`): if the user needs the live price before choosing a cap, first\ncall \\`mcp__haven__haven_quote_mcp_tool\\` with that merchant URL, tool name,\nand arguments. It is informational only; then call\n\\`mcp__haven__haven_pay_mcp_tool\\` with the same inputs and the explicit cap.\nThe paid call always obtains a fresh quote before it creates any intent. Then\ncontinue \\`mcp__haven__haven_pay_mcp_tool\\` →\n\\`mcp__haven-signer__haven_sign\\` → \\`mcp__haven__haven_submit\\` →\n\\`mcp__haven-signer__haven_x402_sign_header\\` →\n\\`mcp__haven__haven_complete_mcp_tool\\`. Call that last step with\n\\`payment_id\\` and the signer's \\`payment_header\\` ONLY. It does not take\n\\`payment_required\\`: Haven rehydrates the merchant call context\n(\\`merchant_url\\`, \\`tool_name\\`, \\`arguments\\`, \\`mcp_transport\\`) and the\n402 server-side from \\`payment_id\\`, exactly as at settle. Pass that context\nexplicitly only as a version-skew fallback when Haven has no stored context\nfor the id — \\`merchant_url\\` and \\`tool_name\\` both or none together, never\njust one.\nThe returned \\`expires_at\\` is the signing window; if a tool returns\n\\`PAYMENT_WINDOW_EXPIRED\\`, re-run the same quote/prepare tool with the same\n\\`idempotency_key\\`. Do not call the merchant yourself — Haven completes the\nmerchant leg for you.\n\n**Direct transfer / non-MCP paywall:** \\`mcp__haven__haven_pay\\` with\n\\`to\\`, \\`amount\\`, and \\`token\\` for a plain transfer. For an arbitrary,\nnon-MCP x402 paywall: \\`mcp__haven__haven_quote_x402\\` to get a quote, then\n\\`mcp__haven__haven_pay_x402_quote\\` — follow the result's guidance fields\nfirst and sign in the local Haven signer. On THIS path Haven does not talk to\nthe merchant: \\`mcp__haven-signer__haven_sign_x402\\` returns both\n\\`signature\\` and \\`payment_header\\`; relay \\`signature\\` with\n\\`mcp__haven__haven_submit\\`, then retry the paywalled URL yourself with\n\\`payment_header\\`. Do not pass that call's \\`x402_binding\\` to\n\\`mcp__haven-signer__haven_x402_sign_header\\` — the one-shot already spent it\nbuilding the header, so the call can only refuse. Then tell Haven what the\nmerchant answered: \\`mcp__haven__haven_report_x402_outcome\\` with the\n\\`payment_id\\`, \\`outcome\\` (\\`\"accepted\"\\` for a 2xx, else \\`\"rejected\"\\`)\nand the \\`merchant_status\\` you got. Because Haven never contacted that\nmerchant, this is the only way it can learn the purchase failed — without it a\nfailed purchase reads as complete for fifteen minutes. (The SDK's own\n\\`haven_pay_x402\\` tool does perform the merchant retry itself; that tool is\nnot part of the hosted MCP surface.) If the process\ncrashes after payment, a later \\`mcp__haven__haven_get_payment_status\\` call\nmay report \\`nextAction: 'retry_original_x402_request'\\` — only then call\n\\`mcp__haven__haven_resume_x402_payment\\` with the preserved resume state or\npayment id, instead of paying again.\n\n**Catalog tool arguments:** when \\`haven_discover_tools\\` returns\n\\`tool_arguments\\`, pass that object unchanged as the pay tool's\n\\`arguments\\` field (for example\n\\`tool_arguments: { \"tier\": \"50gb\" }\\` -> \\`arguments: { \"tier\": \"50gb\" }\\`).\n\n**Prices:** show the user the live price from a read-only quote or the pay-tool\nresult, never a catalog price. \\`haven_discover_tools\\` prices are indicative\n(\\`price_is_indicative\\`) and can be stale. A read-only quote is informational\nonly and does not reserve a price; the later paid call re-quotes and enforces\nthe cap. The pay-tool result's \\`amount\\` / \\`amount_atomic\\` is the merchant's\nown quoted price for that call — a ceiling the merchant settles at or below —\nso present it as the most the user will pay. It is a price, not an approval:\nthe payment goes through only if it also fits the cap you set and the on-chain\nbudget the user signed, which is enforced on-chain rather than by Haven.\n\n**Status:** \\`mcp__haven__haven_get_payment_status\\` with a \\`payment_id\\` to\ncheck on in-flight payments. Do not poll in a tight loop.\n\n## Declines and stop signals\n\n- A payment outside the agent's rules — above the remaining budget, wrong\n recipient, or expired budget — is declined before any money moves. Nothing\n is queued; tell the user, who can raise the budget in Haven.\n- \\`safe_to_continue: false\\` on a guidance block is a stop signal in\n machine-readable form: stop and involve the user before calling anything\n else for this payment.\n- Never ask the user for private keys. Signing happens only in the local Haven\n signer; the hosted Haven tools never receive the signing key. If a tool\n reports a missing or invalid credential, tell the user to re-run the Haven\n connector command.\n\n## Failure handling\n\nHaven tool failures are shaped like \\`{ success: false, code, message, ... }\\`\nor older \\`{ error, status, details? }\\` responses. A failure carries the same\n\\`next_action\\` / \\`next_tool\\` / \\`next_arguments\\` / \\`next_tool_omitted_reason\\`\nfields a success does; follow them first, then branch on \\`code\\` and surface\n\\`message\\` or \\`error\\` verbatim. Common cases:\n\n- \\`insufficient_funds\\`: the Haven wallet doesn't hold enough of that token.\n Suggest the user add funds in the Haven dashboard.\n- \\`PRICE_EXCEEDS_MAX\\`: the live merchant price exceeded your cap. No funds\n moved; ask the user before retrying with a higher one.\n- \\`AMBIGUOUS_MAX_AMOUNT\\`: you sent both \\`max_amount\\` and\n \\`max_amount_human\\`. Nothing was contacted or spent — re-send with exactly\n one (\\`max_amount_human\\` for a cap the user stated in tokens).\n- \\`MAX_AMOUNT_UNCONVERTIBLE\\`: \\`max_amount_human\\` does not fit this quote's\n asset — unknown decimals, or more decimal places than the asset supports.\n Round the cap, or send an exact atomic \\`max_amount\\`.\n- \\`PAYMENT_WINDOW_EXPIRED\\`: re-run the quote/prepare tool with the same\n \\`idempotency_key\\`, then sign the fresh payload.\n- \\`MERCHANT_NOT_READY\\`: the merchant refused the quote with its own\n \"cannot settle right now\" signal (a 503 \\`merchant_not_ready\\` with a\n \\`reason_code\\`) instead of a 402. No payment was created. Tell the user;\n retry later (the message carries \\`retry_after_s\\` when the merchant gave\n one) — this is not a wrong or broken endpoint.\n- \\`MERCHANT_REJECTED_AFTER_FUNDING\\`: the merchant refused the paid retry.\n On eip3009 (\\`rail\\` not \\`erc7710\\`): Stop-and-sweep — stop retrying the\n merchant and use \\`mcp__haven__haven_sweep_delegate\\` to recover stranded\n delegate funds. On erc7710 there is no funding leg and nothing to sweep:\n follow the message — it says whether the merchant declined to settle\n (re-quote later) or whether to check \\`haven_get_payment_status\\` after\n the payment window first.\n- \\`MERCHANT_UNRESPONSIVE_AFTER_FUNDING\\`: the merchant never answered the paid\n retry. This is NOT proof of rejection — the merchant may still settle late.\n On eip3009 (\\`rail\\` not \\`erc7710\\`), funding confirmed on-chain: Verify-then-sweep,\n never a blind sweep — check \\`mcp__haven__haven_get_payment_status\\`, retry\n \\`mcp__haven__haven_complete_mcp_tool\\` ONCE, and only sweep with\n \\`mcp__haven__haven_sweep_delegate\\` if no settlement appears. On erc7710\n there is no funding leg and nothing to sweep, and\n \\`mcp__haven__haven_complete_mcp_tool\\` has no erc7710 branch (it refuses a\n submitted intent) — do not retry it: the merchant may still redeem the\n settlement authorization within the payment window, so check\n \\`mcp__haven__haven_get_payment_status\\` after that window and re-quote only\n if it shows no settlement.\n- Budget exceeded: tell the user how much remains (from\n \\`mcp__haven__haven_get_allowances\\`) and that they can raise the budget in\n Haven.\n\n## Reporting after a purchase\n\nA settled \\`mcp__haven__haven_settle_mcp_tool\\` response carries\n\\`agent_summary.purchase_summary\\` and the remaining post-purchase allowance\nin \\`allowance\\` — report the product, Haven-derived payment/transaction\nfields, and what is left from those fields directly. \\`result\\` is optional\nraw merchant evidence; never use it to decide whether the purchase was paid.\nDo not call \\`haven_get_agent\\` or \\`haven_get_allowances\\` again just to\nreport a purchase you already made.\n\n## Revoke\n\nIf this agent's credential may have leaked, tell the user to pause or revoke\nthe agent in the Haven dashboard under Agents. New requests stop immediately\nfor that credential.\n`\n\n/** Directory name for the installed skill folder. */\nexport const SKILL_FOLDER_NAME = 'haven-pay'\n\n/**\n * The skill BODY — HAVEN_SKILL_MD with the YAML front-matter stripped.\n *\n * For runtimes whose instruction mechanism is a plain guidance file rather\n * than a skills folder (Codex's global AGENTS.md, #1332), the front-matter is\n * skill-registry metadata with no meaning and would render as a stray table.\n * Derived mechanically from the canonical string above, never maintained by\n * hand — the substance cannot fork per runtime.\n */\nexport const HAVEN_SKILL_BODY_MD = HAVEN_SKILL_MD.replace(/^---\\n[\\s\\S]*?\\n---\\n+/, '')\n","/**\n * #1271 / #1301: bounded same-origin merchant MCP endpoint discovery.\n *\n * An agent handed a BASE merchant URL previously had to hand-probe /, /mcp,\n * /sse, … until something answered 402. The demo merchant (and the #1266\n * contract) serves a machine-readable discovery document at\n * `/.well-known/haven-demo-merchant` (also at `/`) naming `mcp_url`. This\n * helper fetches ONLY those two fixed same-origin paths — no redirects\n * (`redirect: 'error'`), a 5 s timeout, a 64 KB read cap — and accepts the\n * document's `mcp_url` ONLY when it stays on the same origin as the input.\n * Anything else returns null and the caller reports the original probe\n * failure. Discovery finds endpoints; it carries no payment authority and an\n * off-origin `mcp_url` is never even fetched — this must not grow into a\n * general network scanner (SSRF bound, per the issue).\n *\n * Originally hosted-only (mcp-server, #1271). Moved here in #1301 so the\n * local/self-signed MCP package (`@haven_ai/mcp`) can share the EXACT same\n * bounded implementation instead of re-deriving discovery semantics —\n * behavior is byte-identical to the pre-move mcp-server copy; the #1271\n * contract tests in packages/mcp-server/src/tools.test.ts pass unmodified\n * against this moved implementation.\n */\nexport const MERCHANT_DISCOVERY_PATHS = ['/.well-known/haven-demo-merchant', '/'] as const\nexport const DISCOVERY_MAX_BYTES = 64 * 1024\n\nexport async function discoverMerchantMcpUrl(inputUrl: string): Promise<string | null> {\n let input: URL\n try {\n input = new URL(inputUrl)\n } catch {\n return null\n }\n for (const path of MERCHANT_DISCOVERY_PATHS) {\n try {\n const res = await globalThis.fetch(`${input.origin}${path}`, {\n method: 'GET',\n headers: { accept: 'application/json' },\n redirect: 'error',\n signal: AbortSignal.timeout(5_000),\n })\n if (!res.ok) continue\n const contentLength = Number(res.headers.get('content-length') ?? 0)\n if (contentLength > DISCOVERY_MAX_BYTES) continue\n const text = await res.text()\n if (text.length > DISCOVERY_MAX_BYTES) continue\n const doc = JSON.parse(text) as { mcp_url?: unknown }\n if (typeof doc.mcp_url !== 'string') continue\n const resolved = new URL(doc.mcp_url)\n if (resolved.origin !== input.origin) continue\n return resolved.toString()\n } catch {\n continue\n }\n }\n return null\n}\n\n/** Trailing-slash/percent-case echoes compare equal; unparseable never does. */\nexport function sameUrl(a: string, b: string): boolean {\n try {\n const ua = new URL(a)\n const ub = new URL(b)\n return ua.origin === ub.origin && ua.pathname.replace(/\\/+$/, '') === ub.pathname.replace(/\\/+$/, '')\n } catch {\n return false\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/signer.ts","../src/haven-api-transport.ts","../src/payment-mappers.ts","../src/payment-state.ts","../src/x402-retry-target.ts","../src/mcp-merchant-transport.ts","../src/receipt.ts","../src/account-reads.ts","../src/provider.ts","../src/delegate-sweep.ts","../src/x402-protocol.ts","../src/account-naming.ts","../src/x402-funding-leg.ts","../src/x402-erc7710.ts","../src/tool-adapter.ts","../src/merchant-completion.ts","../src/client.ts","../src/tool-descriptions.ts","../src/tools.ts","../src/agent-guidance.ts","../src/skill-content.ts","../src/merchant-discovery.ts"],"names":["buildExplorerUrl","ethers","signHash","payment","balance","receipt","mcpTransport"],"mappings":";;;;;;;;;;AAWO,SAAS,QAAA,CAAS,YAAoB,IAAA,EAAsB;AACjE,EAAA,IAAI;AACF,IAAA,MAAM,UAAA,GAAa,IAAI,MAAA,CAAO,UAAA,CAAW,UAAU,CAAA;AACnD,IAAA,MAAM,GAAA,GAAM,UAAA,CAAW,IAAA,CAAK,IAAI,CAAA;AAChC,IAAA,OAAO,GAAA,CAAI,UAAA;AAAA,EACb,SAAS,GAAA,EAAK;AACZ,IAAA,MAAM,IAAI,iBAAA;AAAA,MACR,wBAAwB,GAAA,YAAe,KAAA,GAAQ,IAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC,CAAA;AAAA,K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js","sourcesContent":["import { ethers } from 'ethers'\nimport { HavenSigningError } from './types.js'\n\n/**\n * Sign a hash using raw ECDSA (no Ethereum message prefix).\n *\n * This matches what the retired Safe AllowanceModule rail's `checkSignature` expected —\n * a direct ecrecover over the hash, NOT the \"\\x19Ethereum Signed Message\" variant.\n *\n * Uses ethers.SigningKey.sign() instead of wallet.signMessage() to avoid the prefix.\n */\nexport function signHash(privateKey: string, hash: string): string {\n try {\n const signingKey = new ethers.SigningKey(privateKey)\n const sig = signingKey.sign(hash)\n return sig.serialized // 0x + r(32) + s(32) + v(1)\n } catch (err) {\n throw new HavenSigningError(\n `Failed to sign hash: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/**\n * Sign a delegation-rail payment (#829).\n *\n * The delegate SMART ACCOUNT validates an EIP-712 signature over the packed\n * UserOperation — signing the bare 4337 hash would be rejected on-chain. The\n * backend sends the exact typed data in `sign_data.typed_data`; we sign it\n * verbatim and never reconstruct it (a second source of truth could drift\n * from the account's own rules).\n */\nexport interface Eip712TypedData {\n domain: Record<string, unknown>\n types: Record<string, unknown>\n primaryType: string\n message: Record<string, unknown>\n}\n\n/**\n * Sign backend-supplied EIP-712 typed data VERBATIM.\n *\n * One implementation for every typed-data scheme on purpose: the\n * `EIP712Domain` removal below is the kind of subtlety that rots when it is\n * copied. Today the backend's payloads do NOT carry `EIP712Domain` in `types`\n * (checked against a real `buildSettlementDelegation` payload — see\n * `__fixtures__/settlement-delegation-payload.json`), so the delete is\n * defensive rather than load-bearing; ethers derives the domain itself and\n * throws if it also finds it in `types`.\n *\n * `label` only shapes the error message. Nothing about the signature depends\n * on which caller asked.\n *\n * A consequence worth stating before someone refactors this (#1452 review):\n * because the two wrappers below differ ONLY in that label, calling the wrong\n * one for a given scheme produces a byte-identical signature and no test can\n * see it. That is safe today — both sign backend-supplied typed data verbatim\n * — but it stops being safe the moment either wrapper does anything the other\n * does not. If you add per-scheme behaviour, split the implementations rather\n * than branching inside this one.\n */\nasync function signTypedDataVerbatim(\n privateKey: string,\n typedData: Eip712TypedData,\n label: string,\n): Promise<string> {\n try {\n const wallet = new ethers.Wallet(privateKey)\n const types = { ...typedData.types }\n delete (types as Record<string, unknown>).EIP712Domain\n return await wallet.signTypedData(\n typedData.domain as never,\n types as never,\n typedData.message as never,\n )\n } catch (err) {\n throw new HavenSigningError(\n `Failed to sign ${label}: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\nexport async function signUserOpTypedDataForDelegation(\n privateKey: string,\n typedData: Eip712TypedData,\n): Promise<string> {\n return signTypedDataVerbatim(privateKey, typedData, 'delegation UserOperation')\n}\n\n/**\n * Sign the erc7710 x402 SETTLEMENT CHILD delegation (#1452, epic #1450).\n *\n * A different object from the UserOperation above, and a materially different\n * authority: this signature is what lets a merchant's facilitator redeem the\n * `[child, budget]` chain and pull the exact amount from the treasury. The\n * child's caveats — exact amount, payee pin, expiry, redeemer pin — are what\n * bound it, and they are enforced ON-CHAIN. Signing it verbatim is therefore\n * not a style preference: a reconstructed payload that differed from what the\n * DelegationManager will hash is the #829 failure, and it fails at redemption\n * rather than here.\n */\nexport async function signSettlementDelegationTypedData(\n privateKey: string,\n typedData: Eip712TypedData,\n): Promise<string> {\n return signTypedDataVerbatim(privateKey, typedData, 'x402 settlement delegation')\n}\n\n/**\n * Derive the Ethereum address from a private key.\n */\nexport function addressFromKey(privateKey: string): string {\n try {\n return new ethers.Wallet(privateKey).address\n } catch (err) {\n throw new HavenSigningError(\n `Invalid private key: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/**\n * Verify that a signature over a hash recovers to the expected address.\n */\nexport function verifySignature(hash: string, signature: string, expectedAddress: string): boolean {\n try {\n const recovered = ethers.recoverAddress(hash, signature)\n return recovered.toLowerCase() === expectedAddress.toLowerCase()\n } catch {\n return false\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { HavenClientConfig } from './types.js'\nimport { HavenApiError } from './types.js'\nimport {\n HAVEN_CLIENT_HEADER,\n SDK_CLIENT_IDENTITY,\n readClientUpdate,\n type HavenClientUpdate,\n} from './client-identity.js'\n\nconst DEFAULT_BASE_URL = 'http://localhost:3001'\nconst DEFAULT_REQUEST_TIMEOUT = 30_000\n\ntype HavenApiTransportConfig = Pick<\n HavenClientConfig,\n 'apiKey' | 'baseUrl' | 'requestTimeout' | 'defaultHeaders' | 'clientIdentity'\n>\n\n/** Headers minus any case-spelling of `X-Haven-Client` (#3303 review, N1). */\nfunction withoutClientHeader(headers: Record<string, string>): Record<string, string> {\n const target = HAVEN_CLIENT_HEADER.toLowerCase()\n return Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== target))\n}\n\n/**\n * Per-dispatch state carried through `AsyncLocalStorage`: the extra headers,\n * and the last `client_update` the backend sent during this dispatch (#3303),\n * so an MCP tool result can surface the hint its own requests received.\n */\ninterface RequestContextStore {\n headers: Record<string, string>\n clientUpdate?: HavenClientUpdate\n}\n\n/**\n * Internal Haven-API JSON transport.\n *\n * This module deliberately does not handle merchant requests. Merchant HTTP\n * has separate headers, timeout semantics, and error types in HavenClient.\n * The class is exported only for internal composition and direct tests; it is\n * not part of the package entrypoint.\n */\nexport class HavenApiTransport {\n private readonly apiKey: string\n private readonly baseUrl: string\n private readonly requestTimeout: number\n private readonly defaultHeaders: Record<string, string>\n private readonly clientIdentity: string\n private readonly requestContext = new AsyncLocalStorage<RequestContextStore>()\n private lastClientUpdate: HavenClientUpdate | undefined\n\n constructor(config: HavenApiTransportConfig) {\n this.apiKey = config.apiKey\n this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '')\n this.requestTimeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT\n this.defaultHeaders = { ...(config.defaultHeaders ?? {}) }\n this.clientIdentity = config.clientIdentity ?? SDK_CLIENT_IDENTITY\n }\n\n /**\n * The newest `client_update` the backend sent (#3303): inside a\n * `withRequestContext` dispatch, the one that dispatch's own requests\n * received; outside one, the latest this transport has seen.\n */\n clientUpdate(): HavenClientUpdate | undefined {\n const store = this.requestContext.getStore()\n return store ? store.clientUpdate : this.lastClientUpdate\n }\n\n private recordClientUpdate(data: unknown): void {\n if (data === null || typeof data !== 'object' || Array.isArray(data)) return\n const hint = readClientUpdate((data as Record<string, unknown>).client_update)\n if (!hint) return\n this.lastClientUpdate = hint\n const store = this.requestContext.getStore()\n if (store) store.clientUpdate = hint\n }\n\n /** Run `fn` with extra headers scoped to its asynchronous Haven API work. */\n withRequestContext<T>(headers: Record<string, string>, fn: () => Promise<T>): Promise<T> {\n return this.requestContext.run({ headers: { ...headers } }, fn)\n }\n\n async post<T>(path: string, body: Record<string, unknown>): Promise<T> {\n return this.request<T>('POST', path, body)\n }\n\n async get<T>(path: string): Promise<T> {\n return this.request<T>('GET', path)\n }\n\n async request<T>(\n method: 'GET' | 'POST',\n path: string,\n body?: Record<string, unknown>,\n ): Promise<T> {\n const url = `${this.baseUrl}${path}`\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), this.requestTimeout)\n\n try {\n const contextHeaders = this.requestContext.getStore()?.headers ?? {}\n const res = await fetch(url, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n ...withoutClientHeader(this.defaultHeaders),\n ...withoutClientHeader(contextHeaders),\n // Last, and any other spelling of it dropped above (fetch would\n // JOIN `x-haven-client` and `X-Haven-Client` into one unparseable\n // value), so neither `defaultHeaders` nor a dispatch context can\n // misname the client; `clientIdentity` is the one way to set it.\n [HAVEN_CLIENT_HEADER]: this.clientIdentity,\n },\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n })\n\n const data = await res.json()\n this.recordClientUpdate(data)\n\n if (!res.ok) {\n const record = data as Record<string, unknown>\n const errorText = typeof record.error === 'string' ? record.error : undefined\n const rawDetails = record.details ?? record.detail\n const detailsText =\n typeof rawDetails === 'string'\n ? rawDetails\n : rawDetails != null\n ? JSON.stringify(rawDetails)\n : undefined\n const message =\n errorText && detailsText\n ? `${errorText}: ${detailsText}`\n : errorText ?? detailsText ?? 'API request failed'\n throw new HavenApiError(message, res.status, data)\n }\n\n return data as T\n } catch (err) {\n if (err instanceof HavenApiError) throw err\n if (err instanceof Error && err.name === 'AbortError') {\n throw new HavenApiError(`Request to ${path} timed out`, 408)\n }\n throw new HavenApiError(\n `Request to ${path} failed: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n )\n } finally {\n clearTimeout(timeout)\n }\n }\n}\n","import type {\n HavenPaymentReceipt,\n PaymentParties,\n PaymentResult,\n PaymentStatus,\n PaymentStatusResult,\n RawHavenPaymentReceipt,\n RawPaymentParties,\n RawPaymentStatusResult,\n RawStatusResponse,\n} from './types.js'\n\n/** #2960: one mapper, reused by every raw shape carrying `parties`. */\nfunction mapParties(raw: RawPaymentParties | undefined): PaymentParties | undefined {\n if (!raw) return undefined\n return {\n treasuryAccount: raw.treasury_account,\n delegate: raw.delegate,\n delegateAccount: raw.delegate_account,\n merchant: raw.merchant,\n }\n}\n\nexport type ExplorerUrlBuilder = (chainId: number | undefined, txHash: string) => string\n\nexport function mapPaymentResult(\n raw: RawStatusResponse,\n buildExplorerUrl: ExplorerUrlBuilder,\n): PaymentResult {\n return {\n paymentId: raw.payment_id,\n status: raw.status as PaymentStatus,\n token: raw.token,\n amount: raw.amount,\n to: raw.to,\n txHash: raw.tx_hash,\n errorMessage: raw.error_message,\n explorerUrl: raw.explorer_url ?? (raw.tx_hash ? buildExplorerUrl(raw.chain_id, raw.tx_hash) : null),\n fee: raw.fee\n ? {\n amount: raw.fee.amount,\n token: raw.fee.token,\n basisPoints: raw.fee.basis_points,\n applied: raw.fee.applied,\n }\n : null,\n createdAt: raw.created_at,\n signedAt: raw.signed_at,\n submittedAt: raw.submitted_at,\n confirmedAt: raw.confirmed_at,\n expiresAt: raw.expires_at,\n }\n}\n\nexport function mapPaymentStatusResult(raw: RawPaymentStatusResult): PaymentStatusResult {\n return {\n paymentId: raw.payment_id,\n kind: raw.kind,\n rail: raw.rail,\n status: raw.status,\n phase: raw.phase,\n nextAction: raw.next_action,\n amount: raw.amount,\n token: raw.token,\n resourceUrl: raw.resource_url,\n merchantAddress: raw.merchant_address,\n payerAddress: raw.payer_address ?? null,\n parties: mapParties(raw.parties),\n txHash: raw.tx_hash,\n expiresAt: raw.expires_at,\n chainId: raw.chain_id,\n message: raw.message,\n fee: raw.fee\n ? {\n amount: raw.fee.amount,\n token: raw.fee.token,\n basisPoints: raw.fee.basis_points,\n applied: raw.fee.applied,\n }\n : null,\n amountAtomic: raw.amount_atomic ?? raw.x402?.amount_atomic ?? null,\n asset: raw.asset ?? raw.x402?.asset ?? null,\n network: raw.network ?? raw.x402?.network ?? null,\n description: raw.description ?? raw.x402?.description ?? null,\n idempotencyKey: raw.idempotency_key ?? raw.x402?.idempotency_key ?? null,\n x402: raw.x402\n ? {\n amountAtomic: raw.x402.amount_atomic ?? raw.amount_atomic ?? null,\n asset: raw.x402.asset ?? raw.asset ?? null,\n network: raw.x402.network ?? raw.network ?? null,\n resourceUrl: raw.x402.resource_url ?? raw.resource_url,\n merchantAddress: raw.x402.merchant_address ?? raw.merchant_address,\n description: raw.x402.description ?? raw.description ?? null,\n idempotencyKey: raw.x402.idempotency_key ?? raw.idempotency_key ?? null,\n }\n : undefined,\n }\n}\n\n/**\n * #3134 (epic #3130, owner decision 1): the receipt surface converges on the\n * TRANSACTION feed's names for the four concepts the two surfaces share —\n * `paymentProofStatus`, `x402MerchantAddress`, `x402ResourceUrl`, `source` —\n * at this mapper only. The backend receipts wire stays snake_case and the\n * transactions wire is frozen, so the survivor is the transaction-side name\n * in every pair; the argument per pair is in `scripts/ci/vocabulary-map.json`.\n *\n * Removed (#3306): the twins `rail`/`proofStatus`/`resourceUrl`/`merchantAddress`,\n * dual-emitted from 0.5.0-alpha.0, once sdk/mcp `latest` and hosted `serverInfo.version` read 0.5.0-alpha.1.\n */\nexport function mapPaymentReceipt(raw: RawHavenPaymentReceipt): HavenPaymentReceipt {\n const receipt: HavenPaymentReceipt = {\n id: raw.id,\n paymentId: raw.payment_id,\n source: raw.rail,\n paymentProofStatus: raw.proof_status,\n txHash: raw.tx_hash,\n fundingTxHash: raw.funding_tx_hash ?? null,\n settlementTxHash: raw.settlement_tx_hash ?? null,\n chainId: raw.chain_id,\n x402ResourceUrl: raw.resource_url,\n x402MerchantAddress: raw.merchant_address,\n payerAddress: raw.payer_address,\n parties: mapParties(raw.parties),\n settlementAddress: raw.settlement_address,\n tokenSymbol: raw.token_symbol,\n tokenAddress: raw.token_address,\n amountRaw: raw.amount_raw,\n amount: raw.amount_human,\n challengeId: raw.challenge_id,\n idempotencyKey: raw.idempotency_key,\n challengePayload: raw.challenge_payload,\n selectedPayment: raw.selected_payment,\n paymentProofHeaderName: raw.payment_proof_header_name,\n protocolReceiptHeaderName: raw.protocol_receipt_header_name,\n protocolReceiptPayload: raw.protocol_receipt_payload,\n merchantStatus: raw.merchant_status,\n confirmedAt: raw.confirmed_at,\n createdAt: raw.created_at,\n updatedAt: raw.updated_at,\n }\n\n if ('payment_intent_id' in raw) {\n receipt.paymentIntentId = raw.payment_intent_id ?? null\n }\n // #3132: carried when the backend states it; the mapper otherwise drops\n // every key it does not name, which is why the declaration is per row.\n if (raw.scope) {\n receipt.scope = { source: raw.scope.source, filter: raw.scope.filter }\n }\n if ('approval_request_id' in raw) {\n receipt.approvalRequestId = raw.approval_request_id ?? null\n }\n\n return receipt\n}\n","import type {\n PaymentNextAction,\n PaymentPhase,\n PaymentStatusResult,\n RawSignResponse,\n RawX402AuthorizeResponse,\n} from './types.js'\nimport {\n AgentPaymentNextAction,\n AgentPaymentPhase,\n HavenApiError,\n HavenPaymentStateError,\n} from './types.js'\n\nconst PAYMENT_STATE_STATUS_CODES: Record<string, number> = {\n pending: 202,\n pending_approval: 202,\n approved: 202,\n proposed: 202,\n executed: 200,\n pending_signature: 409,\n submitted: 409,\n expired: 410,\n failed: 502,\n rejected: 409,\n}\n\nexport function paymentStateStatusCode(status: string, fallback = 502): number {\n return PAYMENT_STATE_STATUS_CODES[status] ?? fallback\n}\n\n// The three retired-queue statuses keep their descriptive phase labels on\n// purpose, and #2262 deliberately did not make `approved` the exception.\n// #2101 and #2145 both converted `nextActionForStatus` only and left every\n// arm of this function alone: `phase` is a descriptive label, `nextAction` is\n// the field the agent contract says to follow FIRST, and all three phases\n// these arms return — `user_approval_required`, `user_execution_required`,\n// `waiting_for_additional_approvals` — already carry the \"Retired wire value:\n// no live rail produces it. Stop and tell the user.\" text in\n// `AgentPaymentPhaseDescriptions` (`types.ts`). Re-pointing one of the three\n// at a different phase would make the status→phase correspondence lie in a\n// new way and would be a third handling of one fact.\nfunction phaseForStatus(status: string): PaymentPhase | null {\n if (status === 'pending_signature') return AgentPaymentPhase.AgentSignatureRequired\n if (status === 'submitted') return AgentPaymentPhase.PaymentSubmitted\n if (status === 'confirmed') return AgentPaymentPhase.PaymentConfirmed\n if (status === 'pending' || status === 'pending_approval') return AgentPaymentPhase.UserApprovalRequired\n if (status === 'approved') return AgentPaymentPhase.UserExecutionRequired\n if (status === 'proposed') return AgentPaymentPhase.WaitingForAdditionalApprovals\n if (status === 'executed') return AgentPaymentPhase.FundingSent\n if (status === 'rejected') return AgentPaymentPhase.Rejected\n if (status === 'expired') return AgentPaymentPhase.Expired\n if (status === 'failed') return AgentPaymentPhase.Failed\n return null\n}\n\nfunction nextActionForStatus(status: string): PaymentNextAction | null {\n if (status === 'pending_signature') return AgentPaymentNextAction.SignAndSubmitPayment\n if (status === 'submitted') return AgentPaymentNextAction.CheckStatusLater\n if (status === 'confirmed') return AgentPaymentNextAction.None\n // #2101: STOP, not wait. No live rail mints these payment statuses (410 on\n // the legacy rail, #1986; 403/502 at prepare on the delegation rail;\n // `approval_requests` dropped by #2055), so nothing will ever transition a\n // row out of them. `nextAction` is the field the agent contract says to\n // follow FIRST — emitting `wait_for_user_approval` here would contradict\n // the message beside it and send a compliant agent into a poll loop that\n // cannot terminate. The fail-closed branch is retained; its verdict is stop.\n if (status === 'pending' || status === 'pending_approval') return AgentPaymentNextAction.StopAndTellUser\n // #2262: `approved` closes the #2101 sweep — it was the one branch left\n // emitting a wait, sitting literally between two converted siblings. Same\n // proof as theirs, re-verified rather than inherited: `approved` was an\n // `approval_requests` status (table dropped by #2055), and no write in the\n // repository layer sets `payment_intents.status` to it — every INSERT/UPDATE\n // in `infra/repositories/payment-intents.ts`, `x402-authorizations.ts` and\n // `agent-rekeys.ts` sets `pending_signature`, `submitted`, `confirmed`,\n // `expired` or `failed`. So nothing can mint it, and the wait it returned\n // pointed at a user-execution step on the Safe rail, which has answered 410\n // to everything since #1986. An agent that followed it would wait forever.\n // Three places already said so — `AgentPaymentNextActionDescriptions` and\n // `AgentPaymentPhaseDescriptions` in `types.ts`, and README's next-action\n // table — so the tree contradicted itself here. Fail-closed branch retained;\n // its verdict is stop.\n if (status === 'approved') return AgentPaymentNextAction.StopAndTellUser\n if (status === 'proposed') return AgentPaymentNextAction.StopAndTellUser\n // #2145: `executed` joins its #2101 siblings, fail-closed. It was an\n // `approval_requests` status (table dropped, #2055) and cannot be\n // constructed as a payment_intents.status, so the retry instruction it\n // carried pointed at a state nothing can mint. The reachable producer of\n // retry_original_x402_request is the backend's status projection\n // (funded-but-undelivered on the eip3009 bridge), which arrives via the\n // response's own `next_action` — never through this status fallback.\n if (status === 'executed') return AgentPaymentNextAction.StopAndTellUser\n if (status === 'rejected') return AgentPaymentNextAction.StopAndTellUser\n if (status === 'expired') return AgentPaymentNextAction.RequestAgainIfUserStillWantsIt\n if (status === 'failed') return AgentPaymentNextAction.StopAndTellUser\n return null\n}\n\nfunction messageForState(\n label: string,\n status: string,\n paymentId: string,\n nextAction: PaymentNextAction,\n): string {\n if (status === 'pending' || status === 'pending_approval') {\n // No live Haven rail mints these statuses for a payment: an out-of-policy\n // payment is refused during prepare (403/502 from POST /payments) with\n // nothing written, and the queue table the old text pointed at is gone.\n // The branch is kept fail-closed for a stored row from before the\n // retirement, but the message must not promise an approval that will\n // never arrive — the agent is told to stop, not to poll.\n return `${label} is not payable: it is outside the agent's on-chain budget and no approval is pending (payment_id: ${paymentId}). Ask the user to grant or raise the budget in Haven.`\n }\n if (status === 'approved') {\n // #2262: no live rail mints this status (it belonged to the dropped\n // approval queue), so the message must not promise a payment the user is\n // about to complete. Before this branch existed the generic template below\n // rendered \"<label> is approved; next_action=wait_for_user_to_complete_payment\",\n // which is the instruction, not the documentation, an agent acts on.\n return `This payment carries a retired status (\"approved\") that no live Haven rail produces (payment_id: ${paymentId}). Nothing is waiting to be completed — tell the user to review this payment in Haven.`\n }\n if (status === 'executed') {\n // #2145: no live rail mints this status (it belonged to the dropped\n // approval queue), so the message must not promise a retry.\n return `This payment carries a retired status (\"executed\") that no live Haven rail produces (payment_id: ${paymentId}). Do not retry it — tell the user to review this payment in Haven.`\n }\n if (status === 'rejected') {\n return `The user rejected this payment request (payment_id: ${paymentId}).`\n }\n if (status === 'expired') {\n return `This payment request expired (payment_id: ${paymentId}).`\n }\n return `${label} is ${status}; next_action=${nextAction} (payment_id: ${paymentId}).`\n}\n\nexport function paymentStateFromRaw(\n label: string,\n raw: RawX402AuthorizeResponse | RawSignResponse,\n): PaymentStatusResult | null {\n if (!raw.payment_id || !raw.status) return null\n\n const phase = (raw.phase as PaymentPhase | undefined) ?? phaseForStatus(raw.status)\n const nextAction =\n (raw.next_action as PaymentNextAction | undefined) ?? nextActionForStatus(raw.status)\n if (!phase || !nextAction) return null\n\n const amount = raw.amount ?? raw.requested ?? ''\n const token = raw.token ?? ''\n const message =\n raw.message ??\n raw.error ??\n messageForState(label, raw.status, raw.payment_id, nextAction)\n\n return {\n paymentId: raw.payment_id,\n kind: raw.kind === 'payment_intent' ? 'payment_intent' : 'approval_request',\n rail: raw.rail ?? 'direct',\n status: raw.status === 'pending' ? 'pending_approval' : raw.status,\n phase,\n nextAction,\n amount,\n token,\n resourceUrl: raw.resource_url ?? null,\n merchantAddress: raw.merchant_address ?? raw.merchant_to ?? null,\n txHash: raw.tx_hash ?? null,\n expiresAt: raw.expires_at ?? '',\n chainId: raw.chain_id ?? 0,\n message,\n amountAtomic: raw.amount_atomic ?? raw.x402?.amount_atomic ?? raw.mpp?.amount_atomic ?? null,\n asset: raw.asset ?? raw.x402?.asset ?? raw.mpp?.asset ?? null,\n network: raw.network ?? raw.x402?.network ?? raw.mpp?.network ?? null,\n description: raw.description ?? raw.x402?.description ?? raw.mpp?.description ?? null,\n idempotencyKey: raw.idempotency_key ?? raw.x402?.idempotency_key ?? raw.mpp?.idempotency_key ?? null,\n x402: raw.x402\n ? {\n amountAtomic: raw.x402.amount_atomic ?? raw.amount_atomic ?? null,\n asset: raw.x402.asset ?? raw.asset ?? null,\n network: raw.x402.network ?? raw.network ?? null,\n resourceUrl: raw.x402.resource_url ?? raw.resource_url ?? null,\n merchantAddress: raw.x402.merchant_address ?? raw.merchant_address ?? raw.merchant_to ?? null,\n description: raw.x402.description ?? raw.description ?? null,\n idempotencyKey: raw.x402.idempotency_key ?? raw.idempotency_key ?? null,\n }\n : undefined,\n mpp: raw.mpp\n ? {\n amountAtomic: raw.mpp.amount_atomic ?? raw.amount_atomic ?? null,\n asset: raw.mpp.asset ?? raw.asset ?? null,\n network: raw.mpp.network ?? raw.network ?? null,\n resourceUrl: raw.mpp.resource_url ?? raw.resource_url ?? null,\n merchantAddress: raw.mpp.merchant_address ?? raw.merchant_address ?? raw.merchant_to ?? null,\n description: raw.mpp.description ?? raw.description ?? null,\n idempotencyKey: raw.mpp.idempotency_key ?? raw.idempotency_key ?? null,\n challengeId: raw.mpp.challenge_id ?? raw.challenge_id ?? null,\n }\n : undefined,\n }\n}\n\nexport function throwPaymentStateError(\n label: string,\n raw: RawX402AuthorizeResponse | RawSignResponse,\n): never {\n const statusCode = paymentStateStatusCode(raw.status)\n const state = paymentStateFromRaw(label, raw)\n\n if (state) {\n throw new HavenPaymentStateError(state.message, statusCode, state, raw)\n }\n\n if (raw.status === 'pending_approval') {\n throw new HavenApiError(\n `${label} exceeds the agent's on-chain budget and was declined; no approval is pending and none will arrive (payment_id: ${raw.payment_id}).`,\n statusCode,\n raw,\n )\n }\n\n if (raw.status === 'expired') {\n throw new HavenApiError(\n `${label} expired before it could be completed (payment_id: ${raw.payment_id}).`,\n statusCode,\n raw,\n )\n }\n\n const paymentId = raw.payment_id ? ` (payment_id: ${raw.payment_id})` : ''\n const message = raw.error ?? `${label} ${raw.status}${paymentId}`\n throw new HavenApiError(message, statusCode, raw)\n}\n","import { HavenError } from './types.js'\n\n/**\n * Where the PAID retry goes — and whether it may go there at all (#3097).\n *\n * A merchant's 402 challenge declares `resource.url`. Haven records that\n * declaration as the resource's identity (the binding message, the intent\n * row, the resume checks all compare against it), but the paid request —\n * the one carrying `PAYMENT-SIGNATURE` — must go to the URL the CALLER\n * actually asked for whenever one exists. The declaration is the merchant's\n * word about itself, not an instruction to the client: the Ampersend\n * sandbox declares `http://` for a resource it serves over `https` (live,\n * 2026-09-17; its `http://` answers 308 → https), and a client that adopted\n * it sent the signed header in clear on the first hop.\n *\n * Two rules, both pure, both pinned by tests:\n *\n * - `resolveX402RetryTarget`: the caller's request URL wins; the merchant's\n * `resource.url` is the fallback for callers that only hold the challenge\n * (the hosted pay-from-quote path). The result says which one it chose and\n * whether the two disagree, so a quote can surface the disagreement.\n * - `isSecureX402RetryTarget`: `https` always; `http` only to a target that\n * cannot leave the machine or the test bench — loopback addresses and the\n * RFC 2606/6761 reserved names (`.test`, `.localhost`, `.invalid`,\n * `.example`), which every fixture in this repo uses. A public `http://`\n * target is refused BEFORE a signed header is handed to a transport.\n */\nexport interface X402RetryTarget {\n /** The URL the paid request goes to. */\n url: string\n /** Which input produced it. */\n source: 'request' | 'resource'\n /**\n * True when the merchant's declared `resource.url` is not the caller's URL.\n * Absent (undefined) when nothing was compared — the caller named no URL\n * and the declaration was adopted as-is — so a consumer never reads\n * \"false\" as \"the merchant agrees with what you quoted\".\n */\n resourceUrlDiffersFromRequest?: boolean\n}\n\nexport function resolveX402RetryTarget(input: {\n requestUrl?: string | null\n resourceUrl: string\n}): X402RetryTarget {\n const requestUrl = input.requestUrl?.trim() || undefined\n if (requestUrl) {\n return {\n url: requestUrl,\n source: 'request',\n resourceUrlDiffersFromRequest: requestUrl !== input.resourceUrl,\n }\n }\n return { url: input.resourceUrl, source: 'resource' }\n}\n\nconst LOOPBACK_HOSTS = new Set(['localhost', '::1', '[::1]'])\nconst RESERVED_SUFFIXES = ['.test', '.localhost', '.invalid', '.example']\n// The whole 127/8 block, matched octet by octet. A string-prefix test on the\n// hostname (`startsWith('127.')`) is NOT this: `127.attacker.io` is an ordinary\n// registrable public name whose first label happens to be digits, and it would\n// have passed (haven-reviewer finding on #3112). `URL` already normalises the\n// exotic spellings (`0x7f.0.0.1`, `2130706433`) to dotted decimal before this\n// runs, so dotted decimal is the only form that reaches it.\nconst IPV4_LOOPBACK = /^127(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}$/\n\n/** True when a retry carrying a payment header may be sent to `url`. */\nexport function isSecureX402RetryTarget(url: string): boolean {\n let parsed: URL\n try {\n parsed = new URL(url)\n } catch {\n return false\n }\n if (parsed.protocol === 'https:') return true\n if (parsed.protocol !== 'http:') return false\n const host = parsed.hostname.toLowerCase()\n if (LOOPBACK_HOSTS.has(host) || IPV4_LOOPBACK.test(host)) return true\n return RESERVED_SUFFIXES.some((suffix) => host.endsWith(suffix))\n}\n\nexport const INSECURE_RETRY_TARGET_CODE = 'INSECURE_RETRY_TARGET'\n\n/** Refused before any signed header leaves: the paid retry would travel in clear. */\nexport class HavenInsecureRetryTargetError extends HavenError {\n constructor(public readonly url: string) {\n super(\n `Refusing to send a payment header to ${url}: the paid x402 retry must go to an https URL ` +\n '(or a loopback / reserved test host). The merchant\\'s challenge declared this resource URL; ' +\n 'retry with the https URL you quoted (pass it as `url`), and report a merchant whose ' +\n 'challenge downgrades the scheme.',\n INSECURE_RETRY_TARGET_CODE,\n 400,\n )\n this.name = 'HavenInsecureRetryTargetError'\n }\n}\n\nexport function assertSecureX402RetryTarget(url: string): void {\n if (!isSecureX402RetryTarget(url)) throw new HavenInsecureRetryTargetError(url)\n}\n","import type { X402McpTransport, X402PaymentRequired } from './types.js'\nimport { MerchantTimeoutError } from './types.js'\nimport { decodeBase64Json, encodeBase64Json } from './base64.js'\nimport { X402_PAYMENT_HEADER_NAMES, normalizePaymentRequired, x402PaymentHeaderNamesFor } from './x402.js'\nimport { assertSecureX402RetryTarget } from './x402-retry-target.js'\n\nexport const DEFAULT_MERCHANT_TIMEOUT = 300_000\nexport const MCP_NOTIFICATION_TIMEOUT = 10_000\nexport const MCP_PROTOCOL_VERSION = '2025-06-18'\nexport const MCP_ACCEPT = 'application/json, text/event-stream'\n\nconst MCP_CLIENT_INFO = { name: 'haven-sdk', version: '1' } as const\n\n/**\n * #3118: the official x402 MCP transport profile\n * (x402-foundation/x402 `specs/transports-v2/mcp.md`). A merchant following\n * it never answers HTTP 402: the challenge is a tool RESULT with\n * `isError: true` carrying the `PaymentRequired` object as\n * `structuredContent` (and `JSON.stringify` of it as the text content for\n * clients without structured-content support); the payment travels back in\n * the tools/call request's `params._meta[\"x402/payment\"]` as a JSON object\n * (the same envelope the `PAYMENT-SIGNATURE` header carries base64-encoded);\n * settlement comes back in `result._meta[\"x402/payment-response\"]`.\n *\n * Haven's HTTP-402-over-MCP layering (the Streamable-HTTP status code plus\n * `PAYMENT-REQUIRED` / `PAYMENT-SIGNATURE` / `PAYMENT-RESPONSE` headers) is a\n * valid, distinct integration and is retained unchanged; the profile below is\n * ADDED beside it. Delivery is dual: the header is always sent, and the\n * `_meta` object is added whenever the caller body is a `tools/call` request,\n * so a header-reading merchant and a `_meta`-reading merchant both see the\n * payment and neither has to be told which kind it is.\n */\nexport const MCP_X402_PAYMENT_META_KEY = 'x402/payment'\nexport const MCP_X402_PAYMENT_RESPONSE_META_KEY = 'x402/payment-response'\n/** The HTTP status an in-band (HTTP 200, `isError: true`) payment-required refusal is reported as. */\nexport const X402_RETRY_REJECTED_STATUS = 402\n\n/** The settlement object a profile merchant returns in `result._meta[\"x402/payment-response\"]`. */\nexport interface McpX402SettlementMeta {\n success: boolean\n transaction?: string\n network?: string\n payer?: string\n errorReason?: string\n}\n\n/**\n * #3171: the recovery data a merchant attaches to its unknown-session 404\n * (`-32001`) when it guarantees nothing was settled. Only this exact shape\n * licenses the SDK to re-initialize and resend the same payment header: the\n * guarantee is the merchant's, so it must be stated, never inferred from a\n * bare -32001.\n */\nexport const SESSION_NOT_FOUND_NEXT_ACTION = 'reinitialize_then_retry_same_payment_header'\n\nexport interface SessionNotFoundRecovery {\n reason: string\n settled: false\n next_action: typeof SESSION_NOT_FOUND_NEXT_ACTION\n}\n\nexport interface CapturedMerchantResponse {\n merchant_status: number\n merchant_status_text: string\n merchant_headers: Record<string, string>\n merchant_body: string\n}\n\ntype MerchantFetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>\n\nexport interface McpMerchantTransportOptions {\n merchantTimeout?: number\n fetch?: MerchantFetch\n}\n\n/**\n * Per-client MCP-over-HTTP merchant wire transport.\n *\n * This internal seam owns only protocol framing and bounded delivery. It does\n * not create payment authority: callers pass a public wallet address and an\n * already-signed, exact-context-bound payment header.\n */\nexport class McpMerchantTransport {\n private readonly merchantTimeout: number\n private readonly fetchImpl: MerchantFetch\n private requestId = 0\n\n constructor(options: McpMerchantTransportOptions = {}) {\n this.merchantTimeout = options.merchantTimeout ?? DEFAULT_MERCHANT_TIMEOUT\n // Resolve the global at call time, matching the former client helper and\n // preserving the SDK's established fetch-mocking/polyfill seam.\n this.fetchImpl = options.fetch ?? ((input, init) => globalThis.fetch(input, init))\n }\n\n /** Fetch a merchant with a settlement-sized timeout and caller cancellation. */\n async fetch(url: string, init: RequestInit = {}, timeoutMs = this.merchantTimeout): Promise<Response> {\n const timeoutSignal = AbortSignal.timeout(timeoutMs)\n const signal = init.signal ? AbortSignal.any([init.signal, timeoutSignal]) : timeoutSignal\n try {\n return await this.fetchImpl(url, { ...init, signal })\n } catch (err) {\n if (timeoutSignal.aborted) {\n throw new MerchantTimeoutError(`Merchant request timed out after ${timeoutMs}ms: ${url}`)\n }\n throw err\n }\n }\n\n /**\n * Establish an MCP Streamable-HTTP session. Any handshake failure degrades\n * to `undefined`, allowing the caller to fall back to plain x402.\n */\n async initialize(\n url: string,\n init?: RequestInit,\n wallet?: string,\n ): Promise<string | undefined> {\n try {\n const headers = new Headers(init?.headers)\n headers.set('Content-Type', 'application/json')\n headers.set('Accept', MCP_ACCEPT)\n if (wallet && !headers.has('x402-wallet')) headers.set('x402-wallet', wallet)\n\n const response = await this.fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: ++this.requestId,\n method: 'initialize',\n params: {\n protocolVersion: MCP_PROTOCOL_VERSION,\n capabilities: {},\n clientInfo: MCP_CLIENT_INFO,\n },\n }),\n })\n\n if (!response.ok) return undefined\n\n const sessionId = response.headers.get('mcp-session-id')\n if (!sessionId) return undefined\n\n const message = await this.readMessage(response)\n if (message && 'error' in message) return undefined\n\n await this.notifyInitialized(url, init, sessionId, wallet)\n return sessionId\n } catch {\n return undefined\n }\n }\n\n /** Add the MCP session and response-content negotiation headers. */\n withSessionHeaders(init: RequestInit | undefined, sessionId: string): RequestInit {\n const headers = new Headers(init?.headers)\n headers.set('mcp-session-id', sessionId)\n headers.set('Accept', MCP_ACCEPT)\n return { ...init, headers }\n }\n\n /** Read one JSON-RPC message from a JSON or SSE response without consuming it. */\n async readMessage(response: Response): Promise<Record<string, unknown> | undefined> {\n let text: string\n try {\n text = await response.clone().text()\n } catch {\n return undefined\n }\n\n if ((response.headers.get('content-type') ?? '').includes('text/event-stream')) {\n return selectJsonRpcResult(parseSseJsonRpcMessages(text))\n }\n\n try {\n return JSON.parse(text) as Record<string, unknown>\n } catch {\n return undefined\n }\n }\n\n /**\n * Collapse an MCP SSE response to the JSON-RPC result. Non-SSE and\n * unparseable responses pass through with their original body untouched.\n */\n async surfaceResult(response: Response): Promise<Response> {\n if (!(response.headers.get('content-type') ?? '').includes('text/event-stream')) {\n return response\n }\n\n let text: string\n try {\n text = await response.clone().text()\n } catch {\n return response\n }\n\n const message = selectJsonRpcResult(parseSseJsonRpcMessages(text))\n // #3155 review r3: collapse only a real JSON-RPC result or error. A stream\n // whose frames are none of those (a paid SSE resource that is not MCP)\n // would otherwise be reduced to its LAST frame — returned untouched instead.\n if (!message || !('result' in message || 'error' in message)) return response\n\n const body = 'result' in message ? message.result : message\n const headers = new Headers(response.headers)\n headers.set('content-type', 'application/json')\n headers.delete('content-length')\n headers.delete('mcp-session-id')\n\n return new Response(JSON.stringify(body), {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n }\n\n /** Detect MCP transport from the URL or Coinbase Bazaar extension. */\n async detect(\n url: string,\n paymentRequired: X402PaymentRequired,\n response: Response,\n ): Promise<X402McpTransport | undefined> {\n if (isMcpUrl(url)) return { handshakeRequired: true, source: 'path' }\n if (paymentRequired.extensions?.bazaar != null) {\n return { handshakeRequired: true, source: 'bazaar' }\n }\n if (await responseHasBazaarExtension(response)) {\n return { handshakeRequired: true, source: 'bazaar' }\n }\n return undefined\n }\n\n /** Identify the conventional Streamable-HTTP MCP path without probing it. */\n isMcpUrl(url: string): boolean {\n return isMcpUrl(url)\n }\n\n /** Detect Bazaar metadata without consuming the merchant response. */\n hasBazaarExtension(response: Response): Promise<boolean> {\n return responseHasBazaarExtension(response)\n }\n\n /**\n * Deliver an already-signed x402 header without changing the caller body.\n *\n * #2289: x402 v2 reads `PAYMENT-SIGNATURE`; v1 reads `X-PAYMENT`. Sending\n * only the legacy name meant a strict v2 merchant never saw the header —\n * indistinguishable, from the merchant's side, from sending no header at\n * all, while on the EIP-3009 bridge the funding leg had already moved the\n * money.\n *\n * #2341: WHICH names go on is per-payload, not always both — see\n * `x402PaymentHeaderNamesFor`. Both for EIP-3009; `PAYMENT-SIGNATURE` alone\n * for erc7710, whose header carries a whole delegation chain and answered\n * HTTP 431 when duplicated. The decision is made here rather than by the\n * caller so every path inherits it, and it is read from the payload rather\n * than passed in, because a flag a caller supplies is a flag a caller can\n * get wrong.\n *\n * Always `set`, never `append`, so a stale header on the caller's `init` is\n * replaced rather than added to — a merchant that reads the first of two\n * values would otherwise verify a superseded authorization. The name NOT\n * being sent is deleted for the same reason: on erc7710 a stale `X-PAYMENT`\n * left in place would be a superseded authorization we chose not to\n * overwrite, which is worse than the duplicate this change removes.\n */\n async deliverPayment(\n url: string,\n init: RequestInit | undefined,\n paymentHeader: string,\n ): Promise<Response> {\n // #3097: the ONE seam every paid retry crosses (plain HTTP, MCP, resume).\n // A signed header never leaves for a public http:// target.\n assertSecureX402RetryTarget(url)\n const headers = new Headers(init?.headers)\n const send = x402PaymentHeaderNamesFor(paymentHeader)\n for (const name of X402_PAYMENT_HEADER_NAMES) {\n if (send.includes(name)) headers.set(name, paymentHeader)\n else headers.delete(name)\n }\n // #3118: a `tools/call` body additionally carries the payment in\n // `params._meta[\"x402/payment\"]` (the official MCP profile). Any other\n // body is sent byte-for-byte as the caller gave it.\n return this.fetch(url, withMcpPaymentMeta({ ...init, headers }, paymentHeader))\n }\n\n /**\n * #3171: deliver the payment; if the merchant answers its unknown-session\n * 404 WITH the settled-nothing recovery data, re-initialize once and resend\n * the SAME header on the new session. The merchant's own guarantee (#1578:\n * the session guard runs before its payment gate) is what makes the resend\n * safe — a bare -32001, or any other 404, is returned to the caller\n * untouched (body re-wrapped, since reading it consumed the stream). One\n * recovery only: a second 404 is the answer.\n */\n async deliverPaymentRecoveringSession(\n url: string,\n init: RequestInit | undefined,\n paymentHeader: string,\n reinitialize: () => Promise<string | undefined>,\n ): Promise<Response> {\n const first = await this.deliverPayment(url, init, paymentHeader)\n if (first.status !== 404) return first\n let text: string\n try {\n text = await first.clone().text()\n } catch {\n return first\n }\n if (!sessionNotFoundRecovery(text)) return first\n const sessionId = await reinitialize()\n if (!sessionId) return first\n return this.deliverPayment(url, this.withSessionHeaders(init, sessionId), paymentHeader)\n }\n\n /**\n * #3118: read a native MCP payment-required tool result from a response\n * WITHOUT consuming it — JSON or SSE framed. `undefined` for anything that\n * is not an `isError: true` tool result carrying a valid `PaymentRequired`\n * (structured content first, text fallback second), so an ordinary tool\n * error, a successful result that merely resembles a challenge, or an\n * unparseable body is never mistaken for a payment demand.\n */\n async extractToolResultChallenge(response: Response, init?: RequestInit): Promise<X402PaymentRequired | undefined> {\n const toolResult = await this.readToolResult(response, init)\n return toolResult ? extractMcpPaymentRequired(toolResult) : undefined\n }\n\n /**\n * #3118: the tool RESULT a response carries, read WITHOUT consuming it, or\n * `undefined`. Only a JSON or SSE body is read at all (#3155 review S2):\n * a non-402 answer used to be returned untouched, and buffering an\n * arbitrary body — a streaming or binary paid resource — to look for a\n * challenge would block the caller until the stream ended or the merchant\n * timeout fired. A merchant that speaks JSON-RPC declares one of those two\n * content types.\n */\n async readToolResult(response: Response, init?: RequestInit): Promise<Record<string, unknown> | undefined> {\n // #3155 partner review: a native challenge can only answer a JSON-RPC\n // `tools/call` request, so when the request is known and is not one, the\n // body is not read at all — a plain `haven.fetch()` of a JSON API pays\n // nothing for this probe.\n if (init !== undefined && !isJsonRpcToolsCallBody(init.body)) return undefined\n const contentType = (response.headers.get('content-type') ?? '').toLowerCase()\n if (!contentType.includes('application/json') && !contentType.includes('text/event-stream')) return undefined\n return mcpToolResultOf(await this.readMessage(response))\n }\n\n private async notifyInitialized(\n url: string,\n init: RequestInit | undefined,\n sessionId: string,\n wallet?: string,\n ): Promise<void> {\n try {\n const headers = new Headers(init?.headers)\n headers.set('Content-Type', 'application/json')\n headers.set('Accept', MCP_ACCEPT)\n headers.set('mcp-session-id', sessionId)\n if (wallet && !headers.has('x402-wallet')) headers.set('x402-wallet', wallet)\n\n await this.fetch(\n url,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }),\n },\n MCP_NOTIFICATION_TIMEOUT,\n )\n } catch {\n // The session is established. Notification delivery remains best-effort.\n }\n }\n}\n\n/**\n * #3118: the tool RESULT inside whatever shape a merchant body arrived in —\n * a raw JSON-RPC envelope (`{ jsonrpc, id, result }`), or an already-surfaced\n * result (`surfaceResult` collapses SSE to the bare `result`). `undefined`\n * when the value is neither.\n */\nexport function mcpToolResultOf(value: unknown): Record<string, unknown> | undefined {\n if (!isRecord(value)) return undefined\n if ('jsonrpc' in value) {\n return isRecord(value.result) ? value.result : undefined\n }\n if ('isError' in value || Array.isArray(value.content) || isRecord(value._meta)) return value\n return undefined\n}\n\n/**\n * #3118: the `PaymentRequired` a profile merchant put in an `isError: true`\n * tool result. `structuredContent` is preferred; the first text content item\n * that parses as JSON is the fallback. Both go through\n * `normalizePaymentRequired`, so a challenge with no payable `accepts` entry\n * is not a challenge at all.\n */\nexport function extractMcpPaymentRequired(toolResult: Record<string, unknown>): X402PaymentRequired | undefined {\n if (toolResult.isError !== true) return undefined\n if (isRecord(toolResult.structuredContent)) {\n const parsed = normalizePaymentRequired(toolResult.structuredContent)\n if (parsed) return parsed\n }\n if (Array.isArray(toolResult.content)) {\n for (const item of toolResult.content) {\n if (!isRecord(item) || item.type !== 'text' || typeof item.text !== 'string') continue\n let candidate: unknown\n try {\n candidate = JSON.parse(item.text)\n } catch {\n continue\n }\n const parsed = normalizePaymentRequired(candidate)\n if (parsed) return parsed\n }\n }\n return undefined\n}\n\n/**\n * #3118: the settlement object in `result._meta[\"x402/payment-response\"]`,\n * or `undefined` when the result carries none (or one without a boolean\n * `success`, which is not a settlement statement the SDK will act on).\n */\nexport function mcpSettlementFromToolResult(toolResult: Record<string, unknown>): McpX402SettlementMeta | undefined {\n const meta = toolResult._meta\n if (!isRecord(meta)) return undefined\n const settlement = meta[MCP_X402_PAYMENT_RESPONSE_META_KEY]\n if (!isRecord(settlement) || typeof settlement.success !== 'boolean') return undefined\n return {\n success: settlement.success,\n ...(typeof settlement.transaction === 'string' ? { transaction: settlement.transaction } : {}),\n ...(typeof settlement.network === 'string' ? { network: settlement.network } : {}),\n ...(typeof settlement.payer === 'string' ? { payer: settlement.payer } : {}),\n ...(typeof settlement.errorReason === 'string' ? { errorReason: settlement.errorReason } : {}),\n }\n}\n\n/**\n * #3118: add `params._meta[\"x402/payment\"]` to a `tools/call` request body.\n * The value is the decoded payment envelope (the header is base64 JSON of\n * exactly this object). Unrelated `_meta` keys, `arguments`, the id and the\n * method are preserved. Any body that is not a string-encoded JSON-RPC\n * `tools/call` request — form data, a stream, another method, no body — is\n * returned untouched, as is one whose header does not decode.\n *\n * The `tools/call` body IS re-serialised (`JSON.parse` → `JSON.stringify`),\n * so it is semantically, not byte-, identical: an integer above 2^53 in the\n * id or arguments is rounded by JavaScript's number type, and a caller-set\n * `Content-Length` header would go stale (the runtime recomputes it for a\n * string body). Neither half of the dual delivery is size-bounded here; on\n * erc7710 the decoded envelope is smaller than its base64 header, and only\n * the header half counts against the 16 KB header ceiling (#2341). On erc7710\n * the dual delivery therefore sends the delegation chain twice (header and\n * body) — stated, accepted, and the partner reviewer's to weigh.\n */\nexport function withMcpPaymentMeta(init: RequestInit, paymentHeader: string): RequestInit {\n const request = parseJsonRpcToolsCall(init.body)\n if (!request) return init\n let envelope: unknown\n try {\n envelope = decodeBase64Json<unknown>(paymentHeader)\n } catch {\n return init\n }\n if (!isRecord(envelope)) return init\n const params = request.params\n const existingMeta = isRecord(params._meta) ? params._meta : {}\n return {\n ...init,\n body: JSON.stringify({\n ...request,\n params: { ...params, _meta: { ...existingMeta, [MCP_X402_PAYMENT_META_KEY]: envelope } },\n }),\n }\n}\n\n/**\n * #3118: the `_meta` settlement re-encoded exactly as a `PAYMENT-RESPONSE`\n * header would carry it (base64 JSON), so the evidence report's receipt\n * payload goes through the one existing decoder whichever form arrived.\n */\nexport function encodeMcpSettlementReceipt(settlement: McpX402SettlementMeta): string {\n return encodeBase64Json(settlement)\n}\n\n/** #3155: the request body parsed as a JSON-RPC `tools/call` with an object `params`, else undefined. */\nfunction parseJsonRpcToolsCall(body: unknown): (Record<string, unknown> & { params: Record<string, unknown> }) | undefined {\n if (typeof body !== 'string') return undefined\n let request: unknown\n try {\n request = JSON.parse(body)\n } catch {\n return undefined\n }\n if (!isRecord(request) || request.method !== 'tools/call' || !isRecord(request.params)) return undefined\n return request as Record<string, unknown> & { params: Record<string, unknown> }\n}\n\n/**\n * #3155: whether a request body is a JSON-RPC `tools/call` — the only request a\n * native challenge can answer. Decided boundaries: a `Uint8Array`/`Buffer`\n * body is NOT recognised (the quote path's `snapshotRequestBody` refuses\n * non-string bodies too), and neither is a JSON-RPC batch array, a\n * `resources/read`, or a `tools/call` without an object `params` — a paid\n * request in any of those shapes is returned as an ordinary answer and no\n * payment is created (safe direction; state it, do not widen it silently).\n */\nexport function isJsonRpcToolsCallBody(body: unknown): boolean {\n return parseJsonRpcToolsCall(body) !== undefined\n}\n\n/**\n * #3171: parse a merchant 404 body for the unknown-session recovery data.\n * `undefined` for anything else — a different code, a missing or\n * contradicting `data`, a non-JSON body.\n */\nexport function sessionNotFoundRecovery(body: string): SessionNotFoundRecovery | undefined {\n let parsed: unknown\n try {\n parsed = JSON.parse(body)\n } catch {\n return undefined\n }\n if (!isRecord(parsed) || !isRecord(parsed.error)) return undefined\n if (parsed.error.code !== -32001) return undefined\n const data = parsed.error.data\n if (!isRecord(data)) return undefined\n if (data.settled !== false || data.next_action !== SESSION_NOT_FOUND_NEXT_ACTION) return undefined\n return {\n reason: typeof data.reason === 'string' ? data.reason : 'session_expired',\n settled: false,\n next_action: SESSION_NOT_FOUND_NEXT_ACTION,\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Consume and preserve every diagnostic field of a failed merchant response. */\nexport async function captureMerchantResponse(\n response: Response,\n): Promise<CapturedMerchantResponse> {\n const merchant_body = await response.text().catch(() => '')\n return {\n merchant_status: response.status,\n merchant_status_text: response.statusText,\n merchant_headers: Object.fromEntries(response.headers.entries()),\n merchant_body,\n }\n}\n\nfunction isMcpUrl(url: string): boolean {\n try {\n return new URL(url).pathname.replace(/\\/+$/, '').endsWith('/mcp')\n } catch {\n return /\\/mcp(?:[/?#]|$)/.test(url)\n }\n}\n\nasync function responseHasBazaarExtension(response: Response): Promise<boolean> {\n try {\n const body = (await response.clone().json()) as { extensions?: { bazaar?: unknown } } | null\n return body?.extensions?.bazaar != null\n } catch {\n return false\n }\n}\n\nfunction parseSseJsonRpcMessages(text: string): Array<Record<string, unknown>> {\n const messages: Array<Record<string, unknown>> = []\n let dataLines: string[] = []\n\n const flush = (): void => {\n if (dataLines.length === 0) return\n try {\n messages.push(JSON.parse(dataLines.join('\\n')) as Record<string, unknown>)\n } catch {\n // Ignore keep-alives and non-JSON data frames.\n }\n dataLines = []\n }\n\n for (const line of text.split(/\\r?\\n/)) {\n if (line === '') {\n flush()\n continue\n }\n if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^ /, ''))\n }\n flush()\n\n return messages\n}\n\nfunction selectJsonRpcResult(\n messages: Array<Record<string, unknown>>,\n): Record<string, unknown> | undefined {\n return messages.find((message) => 'result' in message || 'error' in message) ?? messages.at(-1)\n}\n","import { ethers } from 'ethers'\nimport type { RawPaymentParties } from './types.js'\n\n/**\n * Verifiable payment receipts.\n *\n * A self-contained proof bundle for a settled Haven payment that anyone can\n * verify **independently of Haven**. The anchor is the agent delegate's\n * signature over the on-chain transfer hash: recover the signer and confirm it\n * is the agent's delegate, and you have cryptographic proof the agent authorised\n * exactly this transfer — no need to trust Haven's backend. The on-chain\n * `txHash` is the settlement source of truth (verify on any explorer).\n *\n * This lives in the SDK so agents and users can verify receipts client-side\n * with zero Haven trust.\n */\nexport const RECEIPT_VERSION = 'haven-receipt-1'\n\nexport interface PaymentReceipt {\n version: typeof RECEIPT_VERSION\n paymentId: string\n payment: {\n token: string\n tokenAddress: string\n amount: string\n amountSek: string | null\n recipient: string\n /** The payer's smart-account address. */\n account: string\n /**\n * #2960: one party vocabulary for \"who paid\", additive alongside `account`\n * above (which is `parties.treasury_account` only). Optional: a server\n * from before #2960 emits neither. Ignored by `verifyPaymentReceipt`,\n * which reads only `authorization`.\n */\n parties?: RawPaymentParties\n chainId: number\n settledAt: string | null\n resourceUrl: string | null\n }\n /** The agent's cryptographic authorisation — what makes the receipt verifiable. */\n authorization: {\n delegate: string\n signHash: string\n signature: string | null\n }\n onChain: {\n txHash: string | null\n chainId: number\n }\n}\n\nexport type ReceiptVerification =\n | { verified: true; recoveredSigner: string }\n | {\n verified: false\n reason: 'missing_signature' | 'bad_signature' | 'signer_mismatch'\n recoveredSigner?: string\n }\n\n/** Default ECDSA recovery (raw ecrecover over the hash, no message prefix). */\nfunction defaultRecover(hash: string, signature: string): string {\n return ethers.recoverAddress(hash, signature)\n}\n\n/**\n * Verify a receipt independently: recover the signer from the authorisation and\n * confirm it is the agent's delegate. Pure — `recover` is injectable but\n * defaults to standard ECDSA recovery, so this runs anywhere (no Haven backend).\n */\nexport function verifyPaymentReceipt(\n receipt: PaymentReceipt,\n recover: (hash: string, signature: string) => string = defaultRecover,\n): ReceiptVerification {\n const { delegate, signHash, signature } = receipt.authorization\n if (!signature) return { verified: false, reason: 'missing_signature' }\n\n let recovered: string\n try {\n recovered = recover(signHash, signature)\n } catch {\n return { verified: false, reason: 'bad_signature' }\n }\n\n if (recovered.toLowerCase() !== delegate.toLowerCase()) {\n return { verified: false, reason: 'signer_mismatch', recoveredSigner: recovered }\n }\n return { verified: true, recoveredSigner: recovered }\n}\n","import { verifyPaymentReceipt, type PaymentReceipt, type ReceiptVerification } from './receipt.js'\nimport type {\n AgentPaymentWarning,\n HavenAgent,\n HavenAgentAllowanceSummary,\n HavenAgentReadiness,\n HavenAgentSummary,\n HavenAllowanceSummary,\n HavenBalanceCoverage,\n HavenPaymentReceipt,\n HavenTaskBudget,\n HavenTaskBudgetSummary,\n PaymentStatusResult,\n PostPurchaseAllowanceSummary,\n RawHavenAgent,\n RawHavenAllowanceSummary,\n RawHavenBalanceCoverage,\n RawHavenPaymentReceiptsResponse,\n RawTaskBudget,\n HavenPaymentReceiptsPage,\n} from './types.js'\nimport { AgentPaymentWarningCode } from './types.js'\nimport { HavenApiTransport } from './haven-api-transport.js'\nimport { mapPaymentReceipt } from './payment-mappers.js'\nimport { resolveTokenFromAddress } from './x402.js'\n\nexport type PaymentStatusReader = (paymentId: string) => Promise<PaymentStatusResult>\n\nexport interface AccountReadsOptions {\n transport: HavenApiTransport\n getPaymentStatus: PaymentStatusReader\n}\n\nfunction safeBigInt(value: string): bigint {\n try {\n return BigInt(value)\n } catch {\n return 0n\n }\n}\n\nfunction formatAtomicAmount(atomic: bigint, decimals: number): string {\n if (atomic < 0n) return '0.0'\n const value = atomic.toString().padStart(decimals + 1, '0')\n const whole = value.slice(0, value.length - decimals) || '0'\n const fraction = value.slice(value.length - decimals).replace(/0+$/, '') || '0'\n return `${whole}.${fraction}`\n}\n\nfunction deriveReadiness(\n status: string,\n allowances: ReadonlyArray<{ remainingAtomic: string }>,\n): HavenAgentReadiness {\n if (status !== 'active') return 'revoked'\n return allowances.some((allowance) => safeBigInt(allowance.remainingAtomic) > 0n)\n ? 'ready'\n : 'needs_approval'\n}\n\n/**\n * #3128: the ONE function behind every `remainingDisplay` the SDK emits —\n * `HavenAllowance.remainingDisplay` and the bootstrap summary's field are the\n * same call on the same inputs.\n */\nexport function formatRemainingDisplay(tokenAddress: string, tokenSymbol: string, remainingAtomic: string): string {\n const token = resolveTokenFromAddress(tokenAddress)\n return token\n ? `${formatAtomicAmount(safeBigInt(remainingAtomic), token.decimals)} ${tokenSymbol}`\n : `${remainingAtomic} ${tokenSymbol} (atomic; unknown decimals)`\n}\n\n/** #3329: `RawTaskBudget` (snake_case wire) → `HavenTaskBudget` (camelCase). */\nexport function mapTaskBudget(raw: RawTaskBudget): HavenTaskBudget {\n return {\n id: raw.id,\n agentId: raw.agent_id,\n chainId: raw.chain_id,\n tokenAddress: raw.token_address,\n recipientAddress: raw.recipient_address,\n parentDelegationHash: raw.parent_delegation_hash,\n delegationHash: raw.delegation_hash,\n label: raw.label,\n maxAtomic: raw.max_atomic,\n status: raw.status,\n expiresAt: raw.expires_at,\n isExpired: raw.is_expired,\n createdAt: raw.created_at,\n openedAt: raw.opened_at,\n closedAt: raw.closed_at,\n closeTxHash: raw.close_tx_hash,\n }\n}\n\n/** #3329: `HavenTaskBudget` → the condensed row `getAgentSummary()` carries. */\nfunction summarizeTaskBudget(taskBudget: HavenTaskBudget): HavenTaskBudgetSummary {\n const token = resolveTokenFromAddress(taskBudget.tokenAddress)\n const maxDisplay = token\n ? `${formatAtomicAmount(safeBigInt(taskBudget.maxAtomic), token.decimals)} ${token.symbol}`\n : `${taskBudget.maxAtomic} (atomic; unknown decimals)`\n return {\n id: taskBudget.id,\n label: taskBudget.label,\n tokenAddress: taskBudget.tokenAddress,\n maxAtomic: taskBudget.maxAtomic,\n maxDisplay,\n recipientAddress: taskBudget.recipientAddress,\n expiresAt: taskBudget.expiresAt,\n }\n}\n\n/**\n * Internal read-only account boundary for HavenClient.\n *\n * It owns authenticated account/allowance/receipt reads and intentionally has\n * no signer, merchant delivery, or payment-state mutation capability. Exported\n * from this module for direct tests and composition only; it is not exported by\n * the SDK entrypoint.\n */\nexport class AccountReads {\n private readonly transport: HavenApiTransport\n private readonly getPaymentStatus: PaymentStatusReader\n private agentInFlight: Promise<HavenAgent> | null = null\n\n constructor(options: AccountReadsOptions) {\n this.transport = options.transport\n this.getPaymentStatus = options.getPaymentStatus\n }\n\n async getAgent(): Promise<HavenAgent> {\n if (this.agentInFlight) return this.agentInFlight\n const request = this.fetchAgent()\n this.agentInFlight = request\n request.finally(() => {\n this.agentInFlight = null\n }).catch(() => {})\n return request\n }\n\n async getAgentSummary(): Promise<HavenAgentSummary> {\n const [agent, allowanceSummary, taskBudgets] = await Promise.all([\n this.getAgent(),\n this.getAllowances(),\n this.listOpenTaskBudgetsSummary(),\n ])\n // #3128: every field here is the HavenAllowance's own (or, for the display\n // string, derived by the same function `getAllowances` used), so the two\n // reads cannot disagree for the same fixture.\n const allowances: HavenAgentAllowanceSummary[] = allowanceSummary.allowances.map((allowance) => {\n return {\n id: allowance.id,\n tokenSymbol: allowance.tokenSymbol,\n tokenAddress: allowance.tokenAddress,\n remainingAtomic: allowance.onchain.remaining,\n remainingDisplay: allowance.remainingDisplay,\n configuredAmount: allowance.configuredAmount,\n resetPeriodMin: allowance.resetPeriodMin,\n isResetPending: allowance.onchain.isResetPending,\n }\n })\n const readiness = deriveReadiness(agent.status, allowances)\n return { ...agent, readiness, spend_authority_readiness: readiness, allowances, taskBudgets }\n }\n\n /**\n * #3329: `GET /task-budgets?status=open`, mapped to the condensed summary\n * row `getAgentSummary()` carries. Fails SOFT per the #3093 rule (default\n * every array wire key to `[]` so an absent/malformed key degrades instead\n * of taking the route down): a 404 (a backend that predates #3329's\n * route), ANY other transport error, an undefined/null body, or a missing\n * or non-array `task_budgets` key all return `[]` rather than throwing —\n * `getAgentSummary`'s identity + readiness + allowances fields are what\n * callers depend on, and this read must never be why the whole summary\n * fails.\n */\n private async listOpenTaskBudgetsSummary(): Promise<HavenTaskBudgetSummary[]> {\n try {\n const raw = await this.transport.get<{ task_budgets?: RawTaskBudget[] } | null | undefined>(\n '/task-budgets?status=open',\n )\n const rows = raw?.task_budgets\n if (!Array.isArray(rows)) return []\n return rows.map((row) => summarizeTaskBudget(mapTaskBudget(row)))\n } catch {\n // #3093: any transport failure (404, network error, malformed body) —\n // never let it fail the agent summary this feeds.\n return []\n }\n }\n\n async getAllowances(): Promise<HavenAllowanceSummary> {\n const raw = await this.transport.get<RawHavenAllowanceSummary>('/machine-payments/allowances')\n return {\n agentId: raw.agent_id,\n // `account_address` is required on the wire contract, so the declared\n // type stays `string`; a server that omits it is off-contract and the\n // cast is the one place that case is allowed through as `undefined`\n // rather than a fabricated `''` (a present-but-blank address downstream\n // — the hosted MCP output spreads this object, and the sweep uses it as\n // a destination).\n accountAddress: raw.account_address as string,\n delegateAddress: raw.delegate_address,\n chainId: raw.chain_id,\n allowances: raw.allowances.map((allowance) => ({\n id: allowance.id,\n tokenAddress: allowance.token_address,\n tokenSymbol: allowance.token_symbol,\n configuredAmount: allowance.configured_amount,\n resetPeriodMin: allowance.reset_period_min,\n remainingDisplay: formatRemainingDisplay(allowance.token_address, allowance.token_symbol, allowance.onchain.remaining),\n onchain: {\n amount: allowance.onchain.amount,\n spent: allowance.onchain.spent,\n remaining: allowance.onchain.remaining,\n effectiveSpent: allowance.onchain.effective_spent,\n resetTimeMin: allowance.onchain.reset_time_min,\n lastResetMin: allowance.onchain.last_reset_min,\n nonce: allowance.onchain.nonce,\n isResetPending: allowance.onchain.is_reset_pending,\n remainingIsFromChain: allowance.onchain.remaining_is_from_chain,\n },\n })),\n }\n }\n\n /**\n * #3126 — the sufficiency signal behind {@link HavenBalanceCoverage}.\n *\n * Deliberately NOT a balance read: the endpoint answers whether the\n * account HOLDS at least the checked amount, as `covered\n * true/false/null`, and never returns the balance itself. The camelCase\n * mapping is permissive (raw fields flow through; the server owns the\n * wire shape, pinned by the backend's `expectMatchesSpec` assertion), so\n * an older server that has not deployed the endpoint surfaces its 404 as\n * a thrown error rather than a fabricated answer.\n */\n async checkFunds(input: { token: string; amountAtomic: string }): Promise<HavenBalanceCoverage> {\n const query = `token=${encodeURIComponent(input.token)}&amount_atomic=${encodeURIComponent(input.amountAtomic)}`\n const raw = await this.transport.get<RawHavenBalanceCoverage>(\n `/machine-payments/balance-coverage?${query}`,\n )\n return {\n covered: raw.covered,\n ...(raw.coverage_error !== undefined ? { coverageError: raw.coverage_error } : {}),\n chainId: raw.chain_id,\n tokenAddress: raw.token_address,\n tokenSymbol: raw.token_symbol,\n checkedAmountAtomic: raw.checked_amount_atomic,\n budgetRemainingAtomic: raw.budget_remaining_atomic,\n ...(raw.budget_remaining_is_from_chain !== undefined\n ? { budgetRemainingIsFromChain: raw.budget_remaining_is_from_chain }\n : {}),\n }\n }\n\n async getPostPurchaseAllowanceSummary(paymentId: string): Promise<{\n allowance: PostPurchaseAllowanceSummary | null\n warnings: AgentPaymentWarning[]\n payment: PaymentStatusResult | null\n }> {\n const unavailable = (detail: string, payment: PaymentStatusResult | null = null) => ({\n payment,\n allowance: null,\n warnings: [{\n code: AgentPaymentWarningCode.AllowanceCheckUnavailable,\n message: `Could not read the post-purchase allowance/budget for payment ${paymentId} (${detail}). ` +\n 'The payment itself succeeded — the on-chain policy remains the actual spend gate; this ' +\n 'only affects the remaining-budget figure reported here.',\n }],\n })\n const [statusResult, agentResult, allowanceResult] = await Promise.allSettled([\n this.getPaymentStatus(paymentId), this.getAgent(), this.getAllowances(),\n ])\n if (statusResult.status === 'rejected') {\n return unavailable(statusResult.reason instanceof Error ? statusResult.reason.message : String(statusResult.reason))\n }\n const payment = statusResult.value\n if (agentResult.status === 'rejected') {\n return unavailable(agentResult.reason instanceof Error ? agentResult.reason.message : String(agentResult.reason), payment)\n }\n if (allowanceResult.status === 'rejected') {\n return unavailable(allowanceResult.reason instanceof Error ? allowanceResult.reason.message : String(allowanceResult.reason), payment)\n }\n try {\n const tokenAddress = payment.asset ?? payment.x402?.asset ?? null\n if (!tokenAddress) return unavailable('the settled payment does not carry a resolvable token address', payment)\n const match = allowanceResult.value.allowances.find(\n (allowance) => allowance.tokenAddress.toLowerCase() === tokenAddress.toLowerCase(),\n )\n if (!match) return unavailable('no allowance/budget row matches the settled token', payment)\n const token = resolveTokenFromAddress(match.tokenAddress)\n const remainingDisplay = token\n ? `${formatAtomicAmount(safeBigInt(match.onchain.remaining), token.decimals)} ${match.tokenSymbol}`\n : undefined\n const rail = agentResult.value.executionRail\n return {\n payment,\n allowance: {\n rail,\n remaining_atomic: match.onchain.remaining,\n ...(remainingDisplay ? { remaining_display: remainingDisplay } : {}),\n token_symbol: match.tokenSymbol,\n token_address: match.tokenAddress,\n reset_period: match.resetPeriodMin,\n source: rail === 'delegation' ? 'active_delegations' : 'allowance_module',\n },\n warnings: [],\n }\n } catch (error) {\n return unavailable(error instanceof Error ? error.message : String(error))\n }\n }\n\n /** The first page's receipts as a bare array — the pre-#3128 shape, kept for callers that never page. */\n async listReceipts(options: { limit?: number } = {}): Promise<HavenPaymentReceipt[]> {\n return (await this.listReceiptsPage(options)).receipts\n }\n\n /** #3128: one page with `total`, `hasMore` and `nextCursor` — see {@link HavenPaymentReceiptsPage}. */\n async listReceiptsPage(options: { limit?: number; cursor?: string } = {}): Promise<HavenPaymentReceiptsPage> {\n const params = new URLSearchParams()\n if (options.limit) params.set('limit', String(options.limit))\n if (options.cursor) params.set('cursor', options.cursor)\n const query = params.size > 0 ? `?${params.toString()}` : ''\n const raw = await this.transport.get<RawHavenPaymentReceiptsResponse>(`/machine-payments/receipts${query}`)\n return {\n receipts: raw.receipts.map(mapPaymentReceipt),\n total: typeof raw.total === 'number' ? raw.total : null,\n hasMore: typeof raw.has_more === 'boolean' ? raw.has_more : null,\n nextCursor: typeof raw.next_cursor === 'string' ? raw.next_cursor : null,\n }\n }\n\n async getReceipt(paymentId: string): Promise<{ receipt: PaymentReceipt; verification: ReceiptVerification }> {\n const { receipt } = await this.transport.get<{ receipt: PaymentReceipt }>(`/payments/${paymentId}/receipt`)\n return { receipt, verification: verifyPaymentReceipt(receipt) }\n }\n\n private async fetchAgent(): Promise<HavenAgent> {\n const raw = await this.transport.get<RawHavenAgent>('/machine-payments/agent')\n return {\n id: raw.id,\n name: raw.name,\n status: raw.status,\n // See the comment on `getAllowances` above: `account_address` is\n // required on the wire contract, so an omission here is off-contract\n // and comes through as `undefined` rather than a fabricated `''`.\n accountAddress: raw.account_address as string,\n delegateAddress: raw.delegate_address,\n chainId: raw.chain_id,\n executionRail: raw.execution_rail === 'delegation' ? 'delegation' : 'legacy',\n }\n }\n}\n","import { ethers } from 'ethers'\n\nexport function createJsonRpcProvider(url: string): ethers.JsonRpcProvider {\n return new ethers.JsonRpcProvider(url)\n}\n\nexport function createWallet(privateKey: string, provider: ethers.JsonRpcProvider): ethers.Wallet {\n return new ethers.Wallet(privateKey, provider)\n}\n\n/**\n * `runner` is a `ContractRunner`, not a `Signer`: a read-only call such as\n * `balanceOf` only needs a provider, and requiring a signer would have forced\n * the #1521 balance check to construct a wallet it never uses.\n */\nexport function createErc20Contract(\n address: string,\n abi: readonly string[],\n runner: ethers.ContractRunner,\n): ethers.Contract {\n return new ethers.Contract(address, abi as string[], runner)\n}\n","import { createErc20Contract, createJsonRpcProvider, createWallet } from './provider.js'\nimport { sweepUsdcAddress, isSweepableChain, type SweepAuthorization, type SweepPrepareResponse, type SweepSubmitResponse } from './sweep.js'\nimport { DEFAULT_CONFIRMATION_TIMEOUT_MS, HavenApiError, HavenSigningError, type HavenAgent, type SweepConfirmation, type SweepResult } from './types.js'\nimport type { HavenApiTransport } from './haven-api-transport.js'\n\n/** The shape of an ethers v6 `TransactionResponse` this module actually uses. */\ninterface SweepTx {\n hash: string\n wait: (confirmations?: number, timeoutMs?: number) => Promise<{ hash: string } | null>\n}\n\n/**\n * Did a confirmation wait expire, as opposed to fail? (#1756)\n *\n * ethers v6 rejects with `code: 'TIMEOUT'` when the deadline passed and\n * `code: 'CALL_EXCEPTION'` when the transaction mined and reverted. Only the\n * first is \"still in flight\" — collapsing them is the same defect this fix\n * exists to remove, one layer out.\n *\n * The one assumption: the code is read off the error's OWN `code` property.\n * If a future ethers version nests it (e.g. under `info.error.code`) this\n * predicate silently stops recognising timeouts and every expiry throws\n * again. That fails loudly in the tests above — `neverMinesWait()` drives a\n * real `code: 'TIMEOUT'` rejection — so the shape is pinned, not assumed.\n */\nfunction isWaitTimeout(err: unknown): boolean {\n return (err as { code?: unknown } | null)?.code === 'TIMEOUT'\n}\n\n/**\n * Wait for one sweep transfer, bounded (#1756).\n *\n * Before this, both legs called `wait(1)` — which passes CONFIRMATIONS, not a\n * timeout, so it was as unbounded as a bare `wait()` while reading like a\n * deliberate choice. A fee-stuck sweep hung the calling agent forever, with no\n * error and no way to learn the hash it was waiting on.\n *\n * Expiry RETURNS `unconfirmed` rather than throwing. The backend's equivalents\n * (#1722 / #1735 / #1742) can leave a stuck transaction to a durable outbound\n * record and a bump worker; this code runs on the user's machine with no queue\n * behind it, so the CALLER is the only possible owner of a stuck transfer —\n * and throwing would destroy the one thing that owner needs, the tx hash.\n *\n * Everything that is not a timeout still throws, unchanged: a revert is a\n * revert.\n */\nasync function waitForSweepTx(tx: SweepTx): Promise<{ txHash: string; confirmation: SweepConfirmation }> {\n let receipt: { hash: string } | null\n try {\n receipt = await tx.wait(1, DEFAULT_CONFIRMATION_TIMEOUT_MS)\n } catch (err) {\n if (!isWaitTimeout(err)) throw err\n return { txHash: tx.hash, confirmation: 'unconfirmed' }\n }\n // A null receipt is \"no receipt yet\", never \"confirmed\" — the pre-#1756 code\n // substituted the broadcast hash here and reported the transfer as done.\n if (!receipt) return { txHash: tx.hash, confirmation: 'unconfirmed' }\n return { txHash: receipt.hash, confirmation: 'confirmed' }\n}\n\nexport class DelegateSweepApi {\n constructor(private readonly options: { transport: Pick<HavenApiTransport, 'post'>; delegateKey?: string; chainRpcs: Record<number, string>; getAgent: () => Promise<HavenAgent>; buildExplorerUrl: (chainId: number, hash: string) => string }) {}\n async sweepDelegate(): Promise<SweepResult> {\n if (!this.options.delegateKey) throw new HavenSigningError('delegateKey is required for sweepDelegate.')\n const agent = await this.options.getAgent()\n if (!agent.delegateAddress) throw new HavenApiError('Agent has no delegate address.', 422)\n const rpcUrl = this.options.chainRpcs[agent.chainId]\n if (!rpcUrl) throw new HavenApiError(`chainRpcs[${agent.chainId}] must be configured to sweep the delegate wallet.`, 422)\n const provider = createJsonRpcProvider(rpcUrl)\n const wallet = createWallet(this.options.delegateKey, provider)\n const transfers: SweepResult['transfers'] = []\n if (isSweepableChain(agent.chainId)) {\n const contract = createErc20Contract(sweepUsdcAddress(agent.chainId), ['function balanceOf(address) view returns (uint256)', 'function transfer(address to, uint256 amount) returns (bool)'], wallet)\n const balance = await contract.balanceOf(agent.delegateAddress) as bigint\n if (balance > 0n) { const tx = await contract.transfer(agent.accountAddress, balance); const { txHash, confirmation } = await waitForSweepTx(tx as SweepTx); transfers.push({ asset: 'USDC', amount: format(balance, 6), amountAtomic: balance.toString(), txHash, explorerUrl: this.options.buildExplorerUrl(agent.chainId, txHash), confirmation }) }\n }\n // Reached even when the USDC leg came back `unconfirmed`: a stuck ERC-20\n // transfer must not strand the native balance this sweep also exists to\n // recover (#1756). Before the bound, it did — the ETH leg never ran.\n const balance = await provider.getBalance(agent.delegateAddress)\n if (balance > 0n) { const fee = await provider.getFeeData(); const send = balance - ((fee.maxFeePerGas ?? fee.gasPrice ?? 1_000_000n) * 21_000n * 2n); if (send > 0n) { const tx = await wallet.sendTransaction({ to: agent.accountAddress, value: send }); const { txHash, confirmation } = await waitForSweepTx(tx as SweepTx); transfers.push({ asset: 'ETH', amount: format(send, 18), amountAtomic: send.toString(), txHash, explorerUrl: this.options.buildExplorerUrl(agent.chainId, txHash), confirmation }) } }\n return { fromAddress: agent.delegateAddress, toAddress: agent.accountAddress, chainId: agent.chainId, transfers, unconfirmed: transfers.some((t) => t.confirmation === 'unconfirmed') }\n }\n prepareSweep(): Promise<SweepPrepareResponse> { return this.options.transport.post('/machine-payments/sweep/prepare', {}) }\n submitSweep(authorization: SweepAuthorization, signature: string): Promise<SweepSubmitResponse> { return this.options.transport.post('/machine-payments/sweep/submit', { authorization, signature }) }\n}\nfunction format(value: bigint, decimals: number): string { const raw = value.toString().padStart(decimals + 1, '0'); return `${raw.slice(0, -decimals) || '0'}.${raw.slice(-decimals).replace(/0+$/, '') || '0'}` }\n","import {\n AgentPaymentNextAction,\n HavenApiError,\n HavenPaymentStateError,\n} from './types.js'\nimport type {\n PaymentStatusResult,\n X402McpTransport,\n X402PaymentOption,\n X402PaymentRequired,\n X402Quote,\n X402Receipt,\n X402RequestSnapshot,\n X402ResumeState,\n} from './types.js'\nimport {\n buildX402IdempotencyKey,\n isErc7710Option,\n resolveTokenFromAddress,\n selectErc7710PaymentOption,\n selectStandardPaymentOption,\n x402AssetTransferMethod,\n x402AuthorizationAmount,\n} from './x402.js'\nimport { paymentStateStatusCode } from './payment-state.js'\n\n/**\n * Protocol-level x402 shapes and request plumbing, owned by neither\n * settlement scheme (#1618, epic #1613).\n *\n * These are the parts of the x402 lifecycle that do not know how the money\n * moves: quote/receipt/resume shapes, the merchant request snapshot a resume\n * replays, the `x402-wallet` header, and the state checks that decide whether\n * a payment is resumable at all. The EIP-3009 funding leg\n * (`x402-funding-leg.ts`) and the erc7710 no-funding-leg path both build on\n * them, which is why they live here rather than inside either one — a\n * neutral primitive parked in the 3009 module would make the erc7710 module\n * import a funding leg it does not have.\n *\n * Everything here is a free function. There is no state to own: give the same\n * inputs, get the same shape. That is also what makes them cheap to test\n * directly, without constructing a client.\n */\n\nconst CHAIN_EXPLORER_TX: Record<number, string> = {\n 100: 'https://gnosisscan.io/tx',\n 8453: 'https://basescan.org/tx',\n}\n\nexport function buildExplorerUrl(chainId: number | undefined, txHash: string): string {\n const base = CHAIN_EXPLORER_TX[chainId ?? 8453] ?? CHAIN_EXPLORER_TX[8453]\n return `${base}/${txHash}`\n}\n\nexport function explorerUrlOrEmpty(\n chainId: number | undefined,\n txHash: string | null | undefined,\n): string {\n return txHash ? buildExplorerUrl(chainId, txHash) : ''\n}\n\nexport function chainIdFromNetwork(network: string | undefined): number | undefined {\n if (network === 'base') return 8453\n // #1471: canonical in the x402 spec's NetworkSchema, and the backend maps\n // it as of the same change — the #1478 pin test enforces that every copy\n // widens together, which is exactly how this line got here.\n if (network === 'base-sepolia') return 84532\n if (!network?.startsWith('eip155:')) return undefined\n const chainId = Number(network.slice('eip155:'.length))\n return Number.isFinite(chainId) ? chainId : undefined\n}\n\nexport function chainIdOrNull(network: string | undefined): number | null {\n return chainIdFromNetwork(network) ?? null\n}\n\nexport function sameAddress(\n a: string | null | undefined,\n b: string | null | undefined,\n): boolean {\n return Boolean(a && b && a.toLowerCase() === b.toLowerCase())\n}\n\nexport function decimalFromUsdcAtomic(value: string): string {\n const amount = BigInt(value)\n const whole = amount / 1_000_000n\n const fraction = (amount % 1_000_000n).toString().padStart(6, '0').replace(/0+$/, '')\n return fraction ? `${whole}.${fraction}` : whole.toString()\n}\n\nexport function normalizeDecimal(value: string): string {\n if (!value.includes('.')) return value.replace(/^0+(?=\\d)/, '') || '0'\n const [whole, fraction = ''] = value.split('.')\n const normalizedWhole = whole.replace(/^0+(?=\\d)/, '') || '0'\n const normalizedFraction = fraction.replace(/0+$/, '')\n return normalizedFraction ? `${normalizedWhole}.${normalizedFraction}` : normalizedWhole\n}\n\n// ── Payer identity and the merchant-facing wallet header ────────────\n\n/**\n * The address a merchant should see as the payer. Both settlement schemes ask\n * this question; the answer differs only by which one is configured.\n */\nexport function x402PayerAddress(\n delegateAddress: string | undefined,\n x402Wallet: string | undefined,\n): string | undefined {\n return delegateAddress ?? x402Wallet\n}\n\nexport function withX402Wallet(\n init: RequestInit | undefined,\n wallet: string | undefined,\n): RequestInit | undefined {\n if (!wallet) return init\n\n const headers = new Headers(init?.headers)\n if (!headers.has('x402-wallet')) {\n headers.set('x402-wallet', wallet)\n }\n\n return {\n ...init,\n headers,\n }\n}\n\n// ── Request snapshots (what a resume replays) ───────────────────────\n\nexport function snapshotRequestBody(body: BodyInit | null | undefined): string | undefined {\n if (body == null) return undefined\n if (typeof body === 'string') return body\n if (body instanceof URLSearchParams) return body.toString()\n\n throw new HavenApiError(\n 'Quote helpers can only capture resumable request bodies that are strings or URLSearchParams. ' +\n 'For streams, blobs, or binary bodies, preserve the original request yourself and call the matching resume method with fresh init.',\n 400,\n )\n}\n\nexport function snapshotX402Request(url: string, init?: RequestInit): X402RequestSnapshot {\n return {\n url,\n method: init?.method ?? 'GET',\n headers: Array.from(new Headers(init?.headers).entries()),\n body: snapshotRequestBody(init?.body),\n }\n}\n\nexport function requestInitFromSnapshot(request: X402RequestSnapshot): RequestInit {\n return {\n method: request.method,\n headers: request.headers,\n body: request.body,\n }\n}\n\n// ── Quote / receipt / resume shapes ─────────────────────────────────\n\n/**\n * #2054 (review finding) — the shared no-compatible-option refusal, made\n * honest about WHY when the answer is the erc7710 tag.\n *\n * Every EIP-3009 path that re-selects through `selectStandardPaymentOption`\n * (`authorizeX402`, `createX402Intent`, the resume path) used to claim \"Haven\n * supports standard x402 exact payments on Base USDC\" even when the merchant's\n * only Haven-compatible entry was erc7710-tagged — blaming the asset when the\n * limit is the settlement scheme. That message got one hop MORE misleading\n * once `buildX402Quote` started describing erc7710-only merchants: a local or\n * generic-SDK caller can now quote such a merchant successfully and then hit\n * this refusal at pay time, so the refusal has to name the real reason. The\n * base sentence is byte-identical to the pre-#2054 message; the erc7710 clause\n * is appended only when the tag is in fact the reason.\n */\nexport function noCompatiblePaymentOptionError(\n accepts: X402PaymentOption[],\n): HavenApiError {\n const erc7710Only = selectErc7710PaymentOption(accepts) !== null\n // #3116: when the refusal's real reason is a transfer method / payment flow\n // this SDK cannot construct, say so — the same honesty rule #2054 applied\n // to the erc7710 tag. Detected WITHOUT the supported-vocabulary sets, so a\n // future supported entry cannot reclassify a merchant as unsupported.\n const unsupportedOnly =\n !erc7710Only &&\n accepts.some(\n (opt) =>\n opt !== null &&\n typeof opt === 'object' &&\n !isErc7710Option(opt) &&\n (x402AssetTransferMethod(opt) !== null ||\n opt.extra?.paymentFlow !== undefined),\n )\n return new HavenApiError(\n 'No compatible payment option found in x402 requirements. ' +\n 'Haven supports standard x402 exact payments on Base USDC.' +\n (erc7710Only\n ? \" The only Haven-compatible option this merchant advertises is tagged \" +\n \"extra.assetTransferMethod: 'erc7710' (direct settlement), which this EIP-3009 \" +\n 'payment path cannot settle — the limitation is the settlement scheme, not the ' +\n 'asset. Paying this merchant requires a delegation-rail erc7710 flow ' +\n '(settleX402Erc7710, or the hosted MCP purchase tools).'\n : unsupportedOnly\n ? ' Every option this merchant advertises asks for a transfer method or payment ' +\n 'flow Haven cannot construct (for example extra.assetTransferMethod: \\'permit2\\', ' +\n 'or an unrecognized extra.paymentFlow). No payment intent was created and no ' +\n 'funds moved.'\n : ''),\n 400,\n )\n}\n\nexport function buildX402Quote(\n paymentRequired: X402PaymentRequired,\n request: X402RequestSnapshot,\n idempotencyKey?: string,\n mcpTransport?: X402McpTransport,\n): X402Quote {\n // #2054: this used to be standard-only, so a merchant advertising ONLY an\n // erc7710-tagged entry — no untagged fallback — was refused as having \"no\n // compatible payment option\" before scheme selection could ever see the\n // entry Haven actually PREFERS on the delegation rail (#1450). The quote is\n // informational and rail-agnostic, so when no standard entry exists it now\n // DESCRIBES the erc7710 entry instead of throwing, and says which selector\n // produced it via `acceptedScheme`. `selectStandardPaymentOption`'s own\n // erc7710 skip is untouched — it is a #1453 correctness property, and the\n // 3009 settlement paths keep re-selecting through it, so an erc7710\n // described quote can never leak into an EIP-3009 authorization.\n const standard = selectStandardPaymentOption(paymentRequired.accepts)\n const option = standard ?? selectErc7710PaymentOption(paymentRequired.accepts)\n if (!option) {\n throw noCompatiblePaymentOptionError(paymentRequired.accepts)\n }\n\n const token = resolveTokenFromAddress(option.asset, option.network)\n return {\n rail: 'x402',\n idempotencyKey: idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option),\n paymentRequired,\n accepted: option,\n acceptedScheme: standard ? 'standard' : 'erc7710',\n request,\n ...(mcpTransport ? { mcpTransport } : {}),\n resourceUrl: paymentRequired.resource.url,\n // #3097: the merchant's declaration vs the URL the caller quoted. The\n // paid retry goes to the caller's URL; a quote that says the two disagree\n // is how an agent sees a challenge that downgrades the scheme or moves\n // the host before it pays.\n resourceUrlDiffersFromRequest: paymentRequired.resource.url !== request.url,\n description: paymentRequired.resource.description ?? option.description ?? null,\n mimeType: paymentRequired.resource.mimeType ?? option.mimeType ?? null,\n amountAtomic: x402AuthorizationAmount(option),\n amount: decimalFromUsdcAtomic(x402AuthorizationAmount(option)),\n token: token?.symbol ?? 'USDC',\n // #1351: null when the asset is unrecognised on this network — the\n // `token` fallback above is a LABEL, not evidence of 6 decimals, and a\n // human-denominated cap must fail closed rather than convert against a\n // guess. Same resolution as `token`, so the two never disagree.\n decimals: token?.decimals ?? null,\n asset: option.asset,\n network: option.network,\n chainId: chainIdOrNull(option.network),\n merchantAddress: option.payTo,\n maxTimeoutSeconds: option.maxTimeoutSeconds,\n }\n}\n\nexport function buildX402Receipt(input: {\n paymentId: string\n txHash: string\n token: string\n amount: string\n to: string\n resourceUrl: string\n explorerUrl: string\n accepted: X402PaymentOption\n // #1521: absent for a receipt describing an ALREADY-SETTLED payment,\n // which has no live authorization to carry. `X402Receipt.paymentHeader`\n // was already optional; only these builders assumed otherwise.\n paymentHeader: string | undefined\n merchantTo?: string | null\n payer?: string\n chainId?: number\n}): X402Receipt {\n const fundingExplorerUrl = input.explorerUrl || explorerUrlOrEmpty(input.chainId, input.txHash)\n\n return {\n success: true,\n paymentId: input.paymentId,\n txHash: input.txHash,\n token: input.token,\n amount: input.amount,\n to: input.to,\n resourceUrl: input.resourceUrl,\n explorerUrl: input.explorerUrl,\n accepted: input.accepted,\n paymentHeader: input.paymentHeader,\n merchantTo: input.merchantTo ?? input.accepted.payTo,\n payer: input.payer,\n chainId: input.chainId,\n haven: {\n paymentId: input.paymentId,\n fundingTxHash: input.txHash,\n fundingExplorerUrl,\n },\n merchant: {\n payTo: input.merchantTo ?? input.accepted.payTo,\n },\n x402: {\n amount: x402AuthorizationAmount(input.accepted),\n token: input.token,\n network: input.accepted.network,\n asset: input.accepted.asset,\n resource: input.accepted.resource ?? input.resourceUrl,\n },\n }\n}\n\nexport function buildX402ResumeState(input: {\n paymentId: string\n paymentRequired: X402PaymentRequired\n accepted: X402PaymentOption\n idempotencyKey: string\n request?: X402RequestSnapshot\n}): X402ResumeState {\n const token = resolveTokenFromAddress(input.accepted.asset, input.accepted.network)\n return {\n rail: 'x402',\n paymentId: input.paymentId,\n idempotencyKey: input.idempotencyKey,\n paymentRequired: input.paymentRequired,\n accepted: input.accepted,\n url: input.request?.url ?? input.paymentRequired.resource.url,\n request: input.request,\n resourceUrl: input.paymentRequired.resource.url,\n description: input.paymentRequired.resource.description ?? input.accepted.description ?? null,\n amountAtomic: x402AuthorizationAmount(input.accepted),\n amount: decimalFromUsdcAtomic(x402AuthorizationAmount(input.accepted)),\n token: token?.symbol ?? 'USDC',\n asset: input.accepted.asset,\n network: input.accepted.network,\n chainId: chainIdOrNull(input.accepted.network),\n merchantAddress: input.accepted.payTo,\n }\n}\n\nexport function attachX402ResumeState(\n err: unknown,\n paymentRequired: X402PaymentRequired,\n accepted: X402PaymentOption,\n idempotencyKey: string,\n request?: X402RequestSnapshot,\n): void {\n if (!(err instanceof HavenPaymentStateError)) return\n if (err.state.rail !== 'x402') return\n\n err.resumeState = buildX402ResumeState({\n paymentId: err.state.paymentId,\n paymentRequired,\n accepted,\n idempotencyKey,\n request,\n })\n}\n\n// #1328: attachResumeState's 'mpp' branch (buildMppQuote / buildMppResumeState\n// / attachMppResumeState) is retired along with the rest of the MPP-demo\n// client surface — every remaining caller passes rail: 'x402' only, so this\n// is now a direct alias for attachX402ResumeState rather than a dispatcher.\nexport function attachResumeState(\n err: unknown,\n input: {\n rail: 'x402'\n paymentRequired: X402PaymentRequired\n accepted: X402PaymentOption\n idempotencyKey: string\n request?: X402RequestSnapshot\n },\n): void {\n attachX402ResumeState(\n err,\n input.paymentRequired,\n input.accepted,\n input.idempotencyKey,\n input.request,\n )\n}\n\n/**\n * Does this payment's live state actually permit the resume the caller is\n * asking for, and does it describe the SAME purchase they are resuming?\n *\n * Every mismatch below is a 409 rather than a best-effort continue: a resume\n * that quietly retargets a different merchant, amount, network or resource is\n * a payment the user never approved.\n */\nexport function assertCanResumeX402(\n status: PaymentStatusResult,\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n): void {\n if (status.rail !== 'x402') {\n throw new HavenPaymentStateError(\n `Payment ${status.paymentId} is ${status.rail}, not x402.`,\n 409,\n status,\n )\n }\n\n if (status.nextAction !== AgentPaymentNextAction.RetryOriginalX402Request) {\n throw new HavenPaymentStateError(status.message, paymentStateStatusCode(status.status, 409), status)\n }\n\n if (!status.txHash) {\n throw new HavenApiError(\n `x402 payment ${status.paymentId} is ready to retry but has no Haven transaction hash.`,\n 502,\n status,\n status.paymentId,\n )\n }\n\n if (status.resourceUrl && status.resourceUrl !== paymentRequired.resource.url) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved resource URL.',\n 409,\n { status, paymentRequired },\n status.paymentId,\n )\n }\n\n if (status.merchantAddress && !sameAddress(status.merchantAddress, option.payTo)) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved merchant.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n\n const optionChainId = chainIdFromNetwork(option.network)\n if (status.chainId && optionChainId && status.chainId !== optionChainId) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved network.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n\n if (status.token && status.token !== 'USDC') {\n throw new HavenApiError(\n 'x402 resume request does not match the approved token.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n\n const approvedAmount = status.amount ? normalizeDecimal(status.amount) : ''\n const requestedAmount = normalizeDecimal(decimalFromUsdcAtomic(x402AuthorizationAmount(option)))\n if (approvedAmount && approvedAmount !== requestedAmount) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved amount.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n}\n","/**\n * #2914 (naming epic #2906, phase 5 — the CONTRACTION): the compatibility\n * window #2908 opened (read both server-response names, prefer the new;\n * emit both camelCase names; write only the new) closed with the\n * `0.2.0-alpha.0` release reaching `main` on 2026-09-14 and a further\n * promotion on 2026-09-16. The account-vocabulary name is now the ONLY name\n * on every wire shape this module touches; `safe_address` / `safe_id` /\n * `sign_data.components.safe` are no longer read from a server response.\n *\n * `readAccountAddress` and `readAccountId` collapsed to a single field read\n * once the fallback was removed, so they are gone — read `raw.account_address`\n * / `raw.account_id` directly. `accountAddressTwins` is gone too: the SDK's\n * public shapes carry `accountAddress` only, never a `safeAddress` twin.\n *\n * `readX402ReceiptPayer` survives because it still has a real multi-step\n * chain (`payer`, then the top-level account address, then the nested\n * `sign_data.components` twin) once the old names are dropped from it.\n */\n\n/**\n * The x402 receipt's `payer` off a funding-authorization response: the\n * explicit `payer`, then the top-level `account_address`, then\n * `sign_data.components.payer_account`.\n *\n * `components.account` is deliberately NOT in this chain: on the funding\n * shapes it holds the DELEGATE account address, a different address, and\n * reading it here would silently corrupt the receipt's payer.\n */\nexport function readX402ReceiptPayer(raw: {\n payer?: string\n account_address?: string\n sign_data?: { components?: { payer_account?: string; account?: string } }\n}): string | undefined {\n return raw.payer ?? raw.account_address ?? raw.sign_data?.components?.payer_account\n}\n","import { exact } from 'x402/schemes'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport {\n AgentPaymentNextAction,\n HavenApiError,\n HavenSigningError,\n X402AlreadySettledError,\n} from './types.js'\nimport type {\n PaymentStatusResult,\n RawSignResponse,\n RawX402AuthorizeResponse,\n SignData,\n X402PaymentOption,\n X402PaymentRequired,\n X402Receipt,\n} from './types.js'\nimport {\n toStandardPaymentRequirements,\n x402AuthorizationAmount,\n x402V2PaymentEnvelope,\n} from './x402.js'\nimport { paymentStateFromRaw, throwPaymentStateError } from './payment-state.js'\nimport { createErc20Contract, createJsonRpcProvider } from './provider.js'\nimport { decodeBase64Json, encodeBase64Json } from './base64.js'\nimport { readX402ReceiptPayer } from './account-naming.js'\nimport {\n buildX402Receipt,\n chainIdFromNetwork,\n decimalFromUsdcAtomic,\n explorerUrlOrEmpty,\n} from './x402-protocol.js'\n\n/**\n * The EIP-3009 funding-leg x402 lifecycle (#1618, epic #1613).\n *\n * This scheme moves money in TWO hops: Haven funds the agent's delegate EOA\n * from the account, and the delegate then signs a standard EIP-3009\n * authorization the merchant's facilitator settles. Everything peculiar to\n * that shape lives here — funding confirmation, the delegate's fundability\n * check, header minting from the local delegate key, and the receipt cache\n * keyed by the authorization's own expiry.\n *\n * What is NOT here is deliberate: the erc7710 direct-settlement path has no\n * funding leg at all, so it must not reach into this module. Anything both\n * schemes need is a free function in `x402-protocol.ts`.\n *\n * Non-custody is unchanged by the extraction. The delegate key never leaves\n * the caller's process, Haven never signs, and nothing here can widen what\n * the on-chain policy already permits.\n *\n * Internal to `HavenClient`. Exported for direct tests and composition only;\n * it is not part of the SDK's published entrypoint.\n */\n\nexport type PaymentPoster = <T>(path: string, body: Record<string, unknown>) => Promise<T>\n/**\n * #3375 (epic #3284): what a funding leg must pay, from the 402 option the\n * caller is paying — never from the `/x402` response. The signer pins the\n * leg's single execution to `transfer(<own delegate EOA>, amount)` of `asset`.\n */\nexport interface FundingLegExpectation {\n asset: string\n amount: string\n}\nexport type DataSigner = (signData: SignData, fundingExpectation: FundingLegExpectation) => Promise<string>\nexport type AuthorizationStateAssertion = (label: string, raw: RawX402AuthorizeResponse) => void\n\nexport interface X402FundingLegOptions {\n /** The agent's local delegate key. Required to mint an EIP-3009 header. */\n delegateKey: string | undefined\n /** Derived from `delegateKey`; the address the funding leg pays into. */\n delegateAddress: string | undefined\n /** Payer override for clients without a local delegate key. */\n x402Wallet: string | undefined\n /** Chain id → RPC URL. Absent entries make on-chain reads unverifiable, never guessed. */\n chainRpcs: Record<number, string>\n post: PaymentPoster\n signForData: DataSigner\n assertSignableAuthorizationState: AuthorizationStateAssertion\n}\n\nexport class X402FundingLeg {\n private readonly delegateKey: string | undefined\n private readonly delegateAddress: string | undefined\n private readonly x402Wallet: string | undefined\n private readonly chainRpcs: Record<number, string>\n private readonly post: PaymentPoster\n private readonly signForData: DataSigner\n private readonly assertSignableAuthorizationState: AuthorizationStateAssertion\n\n /**\n * Receipts keyed by idempotency key, held only as long as the underlying\n * EIP-3009 authorization is valid. The cache belongs to this module rather\n * than to the facade because its expiry is read out of the authorization\n * header itself — a 3009 artifact.\n */\n private readonly receiptCache = new Map<string, { expiresAt: number; receipt: X402Receipt }>()\n\n constructor(options: X402FundingLegOptions) {\n this.delegateKey = options.delegateKey\n this.delegateAddress = options.delegateAddress\n this.x402Wallet = options.x402Wallet\n this.chainRpcs = options.chainRpcs\n this.post = options.post\n this.signForData = options.signForData\n this.assertSignableAuthorizationState = options.assertSignableAuthorizationState\n }\n\n // ── Receipt cache ────────────────────────────────────────────────\n\n /** A still-valid cached receipt for this key, or undefined. */\n cachedReceipt(idempotencyKey: string): X402Receipt | undefined {\n const cached = this.receiptCache.get(idempotencyKey)\n if (cached && cached.expiresAt > Date.now()) return cached.receipt\n return undefined\n }\n\n cacheReceipt(idempotencyKey: string, paymentHeader: string, receipt: X402Receipt): void {\n const expiresAt = getPaymentHeaderValidBefore(paymentHeader)\n if (expiresAt > Date.now()) {\n this.receiptCache.set(idempotencyKey, { expiresAt, receipt })\n }\n }\n\n // ── Authorization ────────────────────────────────────────────────\n\n async authorize(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n idempotencyKey: string,\n taskBudgetId?: string,\n ): Promise<X402Receipt> {\n // 2. Standard x402 settles from an EOA, so the SDK uses the agent-owned\n // delegate EOA for the merchant-facing EIP-3009 authorization. Haven does\n // not control this EOA or its private key.\n //\n // The only automated funding path is a separate transfer from the user's\n // account, redeemed through the agent's budget delegation, signed by the\n // agent key and constrained on-chain by the delegation's caveats. Haven's\n // backend relays that signed top-up; it is not the source of payment\n // authority.\n // #1521: the authorization is minted AFTER the backend's answer is\n // classified, never before. Signing first meant that when the idempotency\n // key resolved to an already-settled payment, a brand-new authorization\n // had already been created against a delegate whose USDC was gone — and\n // it was handed back paired with the FIRST payment's tx_hash. Within one\n // authorize call the header is still created once and reused, which is\n // all the original \"reuse one EIP-3009 nonce\" note ever meant. If funding\n // fails later, the unused authorization simply expires via validBefore.\n const raw = await this.post<RawX402AuthorizeResponse>('/x402', {\n url: paymentRequired.resource.url,\n payTo: this.delegateAddress,\n merchantPayTo: option.payTo,\n amount: x402AuthorizationAmount(option),\n asset: option.asset,\n network: option.network,\n description: paymentRequired.resource.description,\n idempotencyKey,\n // #1360: same explicit funding-leg declaration as createX402Intent —\n // this local-key path derives payTo from the key (never stale), but the\n // declaration keeps both writers of the 3009 shape loud-by-default.\n settlementScheme: 'eip3009',\n // #3329: `/x402` bodies are camelCase (`X402AuthorizeRequest`) — do not\n // switch this to `task_budget_id`, which is only the `POST /payments` key.\n ...(taskBudgetId ? { taskBudgetId } : {}),\n })\n\n // The backend can report an ALREADY-EXECUTED payment in two different\n // shapes, and #1521 is reachable through both — the guard is therefore on\n // the meaning, not on one response shape:\n //\n // 1. `success` + `tx_hash` — the delegation rail's confirmed-intent\n // replay (`modules/x402/replay.ts`). Reached only by an idempotency\n // collision; the caller did not ask for THIS payment.\n // 2. `nextAction: retry_original_x402_request` — RETIRED PRODUCER\n // (#2131). This was the legacy rail's approval-queue replay:\n // `modules/x402/legacy-authorize.ts` returned `getAgentPaymentStatus`'s\n // body, which carries no `success` field at all, and that was the\n // DOCUMENTED post-approval retry loop. #1987 deleted that module and\n // #2055 dropped the `approval_requests` table behind it, so nothing\n // emits this value on any rail today (#2145 tracks giving it a live\n // producer). The branch is KEPT fail-closed rather than removed: it\n // costs nothing, and deleting a guard because its input is currently\n // unreachable is how the input comes back unguarded.\n //\n // In both, \"executed\" means the FUNDING leg executed, which is ambiguous:\n //\n // (a) funding confirmed, merchant never paid → the delegate still\n // holds the money and minting a header is correct;\n // (b) funding confirmed, merchant already paid → the delegate is\n // empty and any authorization minted here is unfundable.\n //\n // Only the delegate's on-chain balance separates them. The two shapes\n // differ in what an UNVERIFIABLE balance should mean, and they differ for\n // the same reason the explicit `resumeAuthorizedX402` path does: shape 1\n // is an accident, so \"can't tell\" refuses rather than mint a header we\n // cannot vouch for; shape 2 is the caller following documented steps, so\n // \"can't tell\" proceeds and only a balance verified ABSENT refuses —\n // otherwise every approval resume without a `chainRpcs` entry would break.\n const state = paymentStateFromRaw('x402 payment', raw)\n const executedReplay = raw.success && raw.tx_hash\n ? 'idempotency-collision' as const\n : state?.nextAction === AgentPaymentNextAction.RetryOriginalX402Request\n ? 'approval-resume' as const\n : null\n\n if (executedReplay) {\n const canFund = await this.delegateCanFund(\n raw.chain_id ?? state?.chainId ?? chainIdFromNetwork(option.network),\n option.asset,\n x402AuthorizationAmount(option),\n )\n const refuse = executedReplay === 'idempotency-collision'\n ? canFund !== true\n : canFund === false\n if (refuse) {\n const settledReceipt = state && executedReplay === 'approval-resume'\n ? this.receiptFromStatus(paymentRequired, option, undefined, state)\n : this.receiptFromAuthorization(paymentRequired, option, undefined, raw)\n throw new X402AlreadySettledError(\n canFund === false\n ? 'This x402 payment already settled — the delegate no longer holds the funds to ' +\n 'authorize it again. To buy the same item a second time, pass a distinct ' +\n '`idempotencyKey`; the synthesised key intentionally collapses repeat calls for ' +\n 'the same product within a 5-minute window so a retried request cannot pay twice.'\n : 'This x402 payment already settled, and whether the delegate can still fund a new ' +\n 'authorization could not be verified (no `chainRpcs` entry for this chain). Refusing ' +\n 'rather than issue an authorization that may be unfundable. To buy the same item a ' +\n 'second time, pass a distinct `idempotencyKey`; to finish an interrupted payment, ' +\n 'resume it by `paymentId`.',\n settledReceipt,\n canFund === false ? 'settled' : 'unverifiable',\n )\n }\n }\n\n const paymentHeader = await this.createPaymentHeader(paymentRequired, option)\n\n if (raw.success && raw.tx_hash) {\n const receipt = this.receiptFromAuthorization(paymentRequired, option, paymentHeader, raw)\n this.cacheReceipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n if (state?.nextAction === AgentPaymentNextAction.RetryOriginalX402Request) {\n const receipt = this.receiptFromStatus(paymentRequired, option, paymentHeader, state)\n this.cacheReceipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n this.assertSignableAuthorizationState('x402 payment', raw)\n\n // 3. Sign the hash\n if (!raw.sign_data?.hash) {\n throw new HavenApiError('No sign_hash returned from x402/authorize', 500, raw)\n }\n // #3375: the recipient pin's asset and amount come from the option this\n // call is paying, the same values sent in the `/x402` body above — never\n // from the response, which a compromised Haven writes.\n const sig = await this.signForData(raw.sign_data, {\n asset: option.asset,\n amount: x402AuthorizationAmount(option),\n })\n\n // 4. Submit signature (reuse existing payments/:id/sign endpoint)\n const execResult = await this.post<RawSignResponse>(\n `/payments/${raw.payment_id}/sign`,\n { signature: sig },\n )\n\n if (execResult.status !== 'confirmed') {\n throwPaymentStateError('x402 payment', execResult)\n }\n\n // Wait for ≥1 on-chain confirmation before retrying the merchant so the\n // merchant's balanceOf(delegate) check sees the funded balance.\n await this.waitForFundingTx(\n execResult.tx_hash,\n execResult.chain_id ?? chainIdFromNetwork(option.network),\n )\n\n const receipt = this.receiptFromAuthorization(paymentRequired, option, paymentHeader, raw, execResult)\n this.cacheReceipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n // ── Header minting ───────────────────────────────────────────────\n\n async createPaymentHeader(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n ): Promise<string> {\n if (!this.delegateKey) {\n throw new HavenSigningError('delegateKey is required to sign x402 payment headers.')\n }\n\n const account = privateKeyToAccount(this.delegateKey as `0x${string}`)\n const requirements = toStandardPaymentRequirements(paymentRequired, option)\n\n const header = await exact.evm.createPaymentHeader(\n account,\n paymentRequired.x402Version,\n requirements,\n )\n if (paymentRequired.x402Version < 2) return header\n\n const payment = decodeBase64Json<{ payload: unknown }>(header)\n // #2361: the shared envelope carries the resource/extensions echoes —\n // see `x402V2PaymentEnvelope`'s comment for why they are load-bearing.\n return encodeBase64Json(x402V2PaymentEnvelope(paymentRequired, option, payment.payload))\n }\n\n // ── Receipt mapping ──────────────────────────────────────────────\n\n receiptFromAuthorization(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n // #1521: `undefined` builds the receipt for a payment that already\n // settled. A settled payment has no live authorization to carry, and\n // minting one to fill this slot is precisely the defect that issue names.\n paymentHeader: string | undefined,\n raw: RawX402AuthorizeResponse,\n execResult?: RawSignResponse,\n ): X402Receipt {\n const txHash = execResult?.tx_hash ?? raw.tx_hash ?? ''\n const chainId = execResult?.chain_id ?? raw.chain_id ?? chainIdFromNetwork(option.network)\n const token = execResult?.token ?? raw.token ?? 'USDC'\n const amount = execResult?.amount ?? raw.amount ?? decimalFromUsdcAtomic(x402AuthorizationAmount(option))\n const to = execResult?.to ?? raw.to ?? this.delegateAddress ?? ''\n const explorerUrl = execResult?.explorer_url ?? raw.explorer_url ?? explorerUrlOrEmpty(chainId, txHash)\n const merchantTo = execResult?.merchant_to ?? raw.merchant_to ?? option.payTo\n // `account_address` then `components.payer_account`. NEVER\n // `components.account`: that is the delegate.\n const payer = readX402ReceiptPayer(raw)\n\n return buildX402Receipt({\n paymentId: raw.payment_id,\n txHash,\n token,\n amount,\n to,\n resourceUrl: paymentRequired.resource.url,\n explorerUrl,\n accepted: option,\n paymentHeader,\n merchantTo,\n payer,\n chainId,\n })\n }\n\n receiptFromStatus(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n // See `receiptFromAuthorization` — `undefined` is the settled case.\n paymentHeader: string | undefined,\n status: PaymentStatusResult,\n ): X402Receipt {\n if (!status.txHash) {\n throw new HavenApiError(\n `x402 payment ${status.paymentId} is ready to retry but has no Haven transaction hash.`,\n 502,\n status,\n status.paymentId,\n )\n }\n\n return buildX402Receipt({\n paymentId: status.paymentId,\n txHash: status.txHash,\n token: status.token || 'USDC',\n amount: status.amount || decimalFromUsdcAtomic(x402AuthorizationAmount(option)),\n to: this.delegateAddress ?? '',\n resourceUrl: paymentRequired.resource.url,\n explorerUrl: explorerUrlOrEmpty(status.chainId, status.txHash),\n accepted: option,\n paymentHeader,\n merchantTo: status.merchantAddress ?? option.payTo,\n payer: this.x402Wallet,\n chainId: status.chainId || chainIdFromNetwork(option.network),\n })\n }\n\n // ── On-chain reads ───────────────────────────────────────────────\n\n /**\n * Wait for a funding tx to be mined with ≥1 confirmation before the\n * merchant retry, eliminating the race where the merchant's\n * `balanceOf(delegate)` runs before the funding block propagates.\n *\n * Skipped when `chainRpcs` does not include the chain; in that case Haven's\n * backend has already confirmed on-chain submission and callers accept the\n * small propagation window as a trade-off for not configuring an RPC URL.\n */\n async waitForFundingTx(\n txHash: string | undefined,\n chainId: number | undefined,\n timeoutMs = 30_000,\n ): Promise<void> {\n if (!txHash || !chainId) return\n const rpcUrl = this.chainRpcs[chainId]\n if (!rpcUrl) return\n const provider = createJsonRpcProvider(rpcUrl)\n const onChainReceipt = await provider.waitForTransaction(txHash, 1, timeoutMs)\n if (!onChainReceipt || onChainReceipt.status !== 1) {\n throw new HavenApiError(\n 'Funding tx did not confirm on-chain within the timeout window.',\n 500,\n { txHash, chainId },\n )\n }\n }\n\n /**\n * Can the delegate EOA still fund an authorization for `amountAtomic`?\n *\n * #1521: the only question that separates a legitimate resume (funding\n * confirmed, merchant never paid — the delegate still holds the money) from\n * a replayed settled payment (funding confirmed, merchant paid, delegate\n * spent). The intent's own `status: 'confirmed'` is identical in both.\n *\n * The balance is asked of the CHAIN rather than of Haven's bookkeeping on\n * purpose: the merchant-settlement evidence record is written by this SDK\n * *after* the merchant call, so a client that dies between the two leaves\n * the backend believing the merchant was never paid — the exact case the\n * discriminator has to get right. The chain cannot be behind in that way.\n *\n * Returns `null` — never a guess — when `chainRpcs` has no entry for the\n * chain or the read fails. Callers must treat that as \"unverifiable\", not\n * as \"funded\".\n */\n async delegateCanFund(\n chainId: number | undefined,\n tokenAddress: string,\n amountAtomic: string,\n timeoutMs = 10_000,\n ): Promise<boolean | null> {\n if (!chainId || !this.delegateAddress) return null\n const rpcUrl = this.chainRpcs[chainId]\n if (!rpcUrl) return null\n try {\n const provider = createJsonRpcProvider(rpcUrl)\n const token = createErc20Contract(\n tokenAddress,\n ['function balanceOf(address) view returns (uint256)'] as const,\n provider,\n )\n // Bounded like `waitForFundingTx` above. This sits on a money\n // authorization path with no way for a caller to route around a stall,\n // so an unresponsive RPC must degrade to \"unverifiable\" rather than\n // hang the payment: a slow answer is worth less than a prompt refusal.\n const balance = await Promise.race([\n token.balanceOf(this.delegateAddress) as Promise<bigint>,\n new Promise<null>((resolve) => setTimeout(() => resolve(null), timeoutMs).unref?.()),\n ])\n if (balance === null) return null\n return balance >= BigInt(amountAtomic)\n } catch {\n // An RPC that is down, or an amount that will not parse, tells us\n // nothing about the delegate's balance. Saying so is the whole point of\n // the tri-state — and on the accidental-replay path it fails toward\n // refusing, never toward minting.\n return null\n }\n }\n}\n\n/**\n * The authorization's own `validBefore`, in milliseconds — the only honest\n * expiry for a cached receipt, since the header stops being usable then\n * whatever the SDK believes.\n */\nexport function getPaymentHeaderValidBefore(paymentHeader: string): number {\n try {\n const payment = decodeBase64Json<{ payload?: { authorization?: { validBefore?: string } } }>(\n paymentHeader,\n )\n const payload = payment.payload as { authorization?: { validBefore?: string } }\n const validBeforeSeconds = Number(payload.authorization?.validBefore)\n if (Number.isFinite(validBeforeSeconds)) return validBeforeSeconds * 1000\n } catch {\n // If the header cannot be decoded, skip caching rather than hiding errors.\n }\n\n return 0\n}\n","import {\n HavenApiError,\n HavenSigningError,\n} from './types.js'\nimport type {\n RawX402AuthorizeResponse,\n RawX402SettleResponse,\n SignData,\n X402Erc7710Settlement,\n X402McpCallContext,\n X402PaymentRequired,\n} from './types.js'\nimport {\n selectX402SettlementScheme,\n x402AuthorizationAmount,\n} from './x402.js'\nimport { chainIdForNetwork, type SettlementChildExpectation } from './settlement-child.js'\n\n/**\n * The erc7710 direct-settlement lifecycle (#1619, epic #1613).\n *\n * The defining property of this scheme is an ABSENCE. There is no funding\n * leg: the merchant redeems a delegation chain and pulls from the treasury\n * directly, so the delegate EOA never holds the money, no sweep can strand\n * it, and the #713 reconciliation class does not apply. Nothing in this\n * module checks a delegate balance or waits for a funding transaction,\n * because on this path there is neither — and a test pins that, since the\n * defects this epic exists to prevent (#1510, #1511, #1521) were all a\n * funding-leg assumption leaking into a path that has none.\n *\n * It builds no merchant header either. The backend assembles the MetaMask\n * erc7710 payload in `assembleSettlementPayload`, which is why this module is\n * so much smaller than `x402-funding-leg.ts`.\n *\n * Non-custody: `settle()` signs in-process with the caller's delegate key,\n * while `prepare()`/`submit()` exist precisely so the hosted topology can\n * drive the two halves with the LOCAL signer in between — hosted Haven has no\n * key and must not. Neither half can widen what the delegation already\n * permits; the caveat enforcers decide that on-chain.\n *\n * Internal to `HavenClient`. Exported for direct tests and composition only;\n * it is not part of the SDK's published entrypoint.\n */\n\nexport type PaymentPoster = <T>(path: string, body: Record<string, unknown>) => Promise<T>\n/**\n * Signs a `sign_data` payload. The erc7710 path passes the second argument:\n * what the merchant's own 402 says the settlement child must implement, so\n * the child is verified against something Haven did not produce (#3283).\n */\nexport type DataSigner = (\n signData: SignData,\n settlementExpectation?: SettlementChildExpectation,\n) => Promise<string>\nexport type RailReader = () => Promise<{ executionRail?: string }>\n\nexport interface X402Erc7710Options {\n /** Required only by `settle()`, which signs in-process. */\n delegateKey: string | undefined\n post: PaymentPoster\n signForData: DataSigner\n /** Reads the ACCOUNT's rail — a property no 402 response can carry. */\n getAgent: RailReader\n}\n\nexport class X402Erc7710 {\n private readonly delegateKey: string | undefined\n private readonly post: PaymentPoster\n private readonly signForData: DataSigner\n private readonly getAgent: RailReader\n\n constructor(options: X402Erc7710Options) {\n this.delegateKey = options.delegateKey\n this.post = options.post\n this.signForData = options.signForData\n this.getAgent = options.getAgent\n }\n\n /**\n * Pay a merchant through **erc7710 direct settlement** (#1454, epic #1450).\n *\n * The whole point of this path is what it does NOT do. There is no funding\n * leg: the merchant redeems a delegation chain and pulls from the treasury\n * directly, so the delegate EOA never holds the money, no sweep can strand\n * it, and the #713 reconciliation class does not apply. It is also why this\n * method is SMALLER than the 3009 path — the backend assembles the merchant\n * `X-PAYMENT` header in `assembleSettlementPayload`, so the SDK builds no\n * header locally.\n *\n * authorize (payTo = the MERCHANT) → sign the child → settle → header\n *\n * The caller then retries the merchant with that header. **Nothing has\n * settled when this returns** — that is why it does not return an\n * `X402Receipt`.\n *\n * Requires a delegation-rail account. The backend enforces that at the\n * rail seam — a non-delegation account gets the #1986 retired-rail 410 from\n * `POST /x402/authorize` whatever scheme it asks for (#2245) — and so does\n * this method, before building a request the backend would only reject: an\n * error a client can explain is worth more than a refusal it has to decode.\n *\n * **MCP callers must pass `options.resourceUrl`.** An in-band MCP 402\n * challenge frequently carries no `resource` object at all, so\n * `paymentRequired.resource?.url` is undefined and the backend answers\n * \"Valid url is required\". The QA scenario this path was ported from falls\n * back to the request URL for exactly that reason — the SDK cannot, because\n * it never saw the request. Pass it.\n */\n async settle(\n paymentRequired: X402PaymentRequired,\n options: { resourceUrl?: string } = {},\n ): Promise<X402Erc7710Settlement> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'delegateKey is required for x402 payments. Pass it in the HavenClient config.',\n )\n }\n const prepared = await this.prepare(paymentRequired, options)\n const signature = await this.signForData(\n prepared.signData,\n settlementExpectationFromQuote(prepared.settlement),\n )\n const paymentHeader = await this.submit(prepared.paymentId, signature)\n return { ...prepared.settlement, paymentHeader }\n }\n\n /**\n * The AUTHORIZE half of erc7710 settlement (#1456): select the scheme, build\n * the request, and return the child to be signed — without signing it.\n *\n * Split out because the hosted topology cannot use `settleX402Erc7710()`:\n * that method signs in-process with `delegateKey`, and hosted Haven does not\n * have one and must not. The hosted MCP server drives these two halves with\n * the LOCAL signer in between, so the key stays where it belongs and the\n * request shaping stays in one place rather than being reimplemented.\n */\n async prepare(\n paymentRequired: X402PaymentRequired,\n options: {\n resourceUrl?: string\n /**\n * The account's rail, when the caller has ALREADY read it from\n * `GET /machine-payments/agent` — passing it skips a duplicate fetch\n * (#1456: the hosted tool reads the agent for the delegate address\n * anyway, and #1348 pins that path to exactly one agent round-trip).\n *\n * This is an optimisation, not a trust boundary: omit it and the rail is\n * read here, and either way the backend independently refuses a\n * non-delegation account at the rail seam (the #1986 410; #2245 removed\n * the separate scheme-level 400). A caller that asserted the wrong rail\n * would build a request the backend rejects.\n */\n delegationRail?: boolean\n /**\n * #1547: the merchant MCP-tool call this authorization was quoted\n * against, persisted so the settle leg can rehydrate it by payment_id\n * (#1307) — the same option `createX402Intent` already carries. Without\n * it an erc7710 settle needs merchant_url/tool_name/arguments\n * re-threaded, which the guided catalog path (#1305) exists to remove.\n */\n mcpCallContext?: X402McpCallContext\n /**\n * #2041: replay key for this authorization, exactly as the 3009 path's\n * `createX402Intent` already sends one.\n *\n * The backend has supported full replay dedup on THIS branch all along —\n * `runDelegationAuthorize` looks an existing intent up by key before it\n * ever branches on the funding shape, and the erc7710 insert carries\n * `conflictTarget: 'x402_idempotency_key'`. The dedup was simply never\n * invoked, because this options bag had no way to say the key. A retried\n * call therefore minted a SECOND independently-signable settlement child\n * for the same purchase — a double-authorize hazard on the one scheme\n * whose signed artifact is spend authority rather than a funding step.\n *\n * Omitted, the backend behaves exactly as before (no key, no dedup).\n */\n idempotencyKey?: string\n /**\n * #3329: build the settlement child under this open task budget's own\n * child delegation instead of the agent's budget delegation directly —\n * `[settlement, task, budget]`.\n */\n taskBudgetId?: string\n } = {},\n ): Promise<{\n paymentId: string\n signData: SignData\n settlement: Omit<X402Erc7710Settlement, 'paymentHeader'>\n }> {\n\n // The rail half of the #1450 preference rule is not visible in a 402\n // response — it is a property of the ACCOUNT, so read it rather than let a\n // caller assert it. #1453's selector takes it as input for exactly this\n // reason, and this is the one place that input is sourced from truth.\n const delegationRail =\n options.delegationRail ?? (await this.getAgent()).executionRail === 'delegation'\n\n // Rail first, and BEFORE selection — the two failures have different\n // remedies and the caller needs the one that applies. Checking selection\n // first made a legacy-rail agent at an erc7710-only merchant get \"no\n // compatible payment option\", which is true and useless: the option is\n // there, the account cannot use it. (Found by this method's own tests.)\n if (!delegationRail) {\n throw new HavenApiError(\n 'erc7710 settlement requires a delegation-rail account; this one is not on it. ' +\n 'Use authorizeX402() for the standard EIP-3009 path.',\n 400,\n )\n }\n\n const selection = selectX402SettlementScheme(paymentRequired.accepts, { delegationRail })\n\n if (!selection || selection.scheme !== 'erc7710') {\n // Never silently reroute to the other scheme (#1454 AC). On a delegation\n // rail the only remaining reason is the merchant, so name that.\n throw new HavenApiError(\n 'This merchant does not advertise an erc7710 settlement option ' +\n \"(no accepts[] entry carries extra.assetTransferMethod: 'erc7710'). \" +\n 'Use authorizeX402() for the standard EIP-3009 path.',\n 400,\n )\n }\n\n const option = selection.option\n const merchantPayTo = option.payTo\n const amountAtomic = x402AuthorizationAmount(option)\n\n const raw = await this.post<RawX402AuthorizeResponse>('/x402', {\n url: options.resourceUrl ?? paymentRequired.resource?.url,\n // #2373: the full 402 challenge, persisted verbatim by the backend\n // (#1355) so the settle handoff can echo its resource/extensions into\n // the X-PAYMENT envelope (#2361). This scheme decomposes the challenge\n // into the fields below for AUTHORITY; the stored copy exists for the\n // echo, which cannot be reconstructed from the decomposition — omitting\n // it is how every erc7710 payment failed a merchant that enforces the\n // spec's extensions-echo MUST. Same ≤64KB guard and omission behaviour\n // as the 3009 path (client.ts): an oversized challenge omits the field\n // rather than failing the payment, and the settle echo then omits too.\n ...(new TextEncoder().encode(JSON.stringify(paymentRequired)).length <= 65536\n ? { paymentRequired }\n : {}),\n // payTo = the MERCHANT is what selects direct settlement server-side.\n // The explicit settlementScheme must AGREE with that shape (#1360) —\n // disagreement is a 400 by design, so that a stale delegate address\n // becomes a loud mismatch instead of a silent reroute to the 3009 leg.\n payTo: merchantPayTo,\n settlementScheme: 'erc7710',\n // #2041: sent only when the caller supplied one, so an omitting caller's\n // request body is byte-identical to the pre-#2041 shape.\n ...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}),\n amount: amountAtomic,\n asset: option.asset,\n network: option.network,\n // The v2 header echoes the accepted entry field-for-field, so the quoted\n // timeout must round-trip or the merchant rejects the echo (#1064).\n maxTimeoutSeconds: option.maxTimeoutSeconds,\n // #1058: forward the advertised facilitators verbatim — the child becomes\n // redeemable ONLY by them. `null` here means the merchant advertised none\n // (or an empty array, which the backend 400s on), so the field is OMITTED\n // rather than sent empty. See x402FacilitatorAddresses.\n ...(selection.facilitatorAddresses\n ? { facilitatorAddresses: selection.facilitatorAddresses }\n : {}),\n // #1307/#1547: persisted so the settle leg can rehydrate the merchant\n // call by payment_id on this scheme too, not only on the 3009 bridge.\n ...(options.mcpCallContext ? { mcpCallContext: options.mcpCallContext } : {}),\n // #3329: `/x402` bodies are camelCase (`X402AuthorizeRequest`) — do not\n // switch this to `task_budget_id`, which is only the `POST /payments` key.\n ...(options.taskBudgetId ? { taskBudgetId: options.taskBudgetId } : {}),\n })\n\n if (!raw.payment_id) {\n throw new HavenApiError('No payment_id returned from x402/authorize', 500, raw)\n }\n const signData = raw.sign_data\n if (signData?.signature_scheme !== 'eip712_delegation' || !signData.typed_data) {\n // The backend chose a different scheme than the shape asked for. Refuse\n // loudly: signing whatever came back would be exactly the \"silent\n // reroute\" this path exists to make impossible.\n throw new HavenApiError(\n 'x402/authorize did not return an erc7710 settlement child ' +\n `(signature_scheme was ${JSON.stringify(signData?.signature_scheme)}). ` +\n 'Refusing to sign a payload this path did not ask for.',\n 500,\n raw,\n )\n }\n\n return {\n paymentId: raw.payment_id,\n signData,\n settlement: {\n paymentId: raw.payment_id,\n merchantPayTo,\n amountAtomic,\n asset: option.asset,\n network: option.network,\n facilitatorAddresses: selection.facilitatorAddresses,\n },\n }\n }\n\n /**\n * The SETTLE half (#1456): exchange the signed child for the merchant header.\n *\n * The SDK builds no header on this path — the backend assembles the MetaMask\n * erc7710 payload in `assembleSettlementPayload`. Whoever produced the\n * signature (an in-process delegate key, or the local edge signer over the\n * hosted boundary) is irrelevant here.\n */\n async submit(paymentId: string, signature: string): Promise<string> {\n const settled = await this.post<RawX402SettleResponse>(\n `/x402/${paymentId}/settle`,\n { signature },\n )\n if (!settled.payment_header) {\n throw new HavenApiError(\n 'x402 settle returned no payment_header — the merchant cannot be retried.',\n 500,\n settled,\n )\n }\n return settled.payment_header\n }\n}\n\n/**\n * #3283: what the settlement child must implement, taken from the MERCHANT'S\n * 402 option this path selected — payee, exact amount, token, chain and the\n * advertised facilitators — never from the `/x402/authorize` response, so a\n * compromised Haven API cannot restate the expectation to match a child it\n * rewrote. `signForData` adds the agent's own account as the required\n * delegator.\n */\nexport function settlementExpectationFromQuote(\n settlement: Omit<X402Erc7710Settlement, 'paymentHeader'>,\n): SettlementChildExpectation {\n const chainId = chainIdForNetwork(settlement.network)\n if (chainId === undefined) {\n throw new HavenSigningError(\n `Refusing to sign the x402 settlement child: the merchant's network ${JSON.stringify(settlement.network)} ` +\n 'is not one this SDK can verify a settlement child on.',\n )\n }\n return {\n merchantTo: settlement.merchantPayTo,\n amount: settlement.amountAtomic,\n asset: settlement.asset,\n chainId,\n ...(settlement.facilitatorAddresses && settlement.facilitatorAddresses.length > 0\n ? { redeemers: settlement.facilitatorAddresses }\n : {}),\n }\n}\n","import { HavenApiError, HavenPaymentStateError } from './types.js'\nimport type { X402PaymentRequired, X402Receipt } from './types.js'\n\n/**\n * The agent-tool adapter (#1620, epic #1613).\n *\n * `HavenClient.executeTool` exists so an agent framework can hand a tool call\n * straight through; these three functions are the translation layer it needs\n * — a 402 challenge built from flat tool arguments, a receipt flattened to\n * snake_case JSON, and an error rendered as a RESULT rather than thrown.\n *\n * That last one is the reason this is a distinct concern rather than\n * incidental formatting: a tool handler that throws loses the payment state\n * the model needs to decide what to do next, so `toolError` deliberately\n * preserves it (payment_id, phase, next_action) in a shape a model can read.\n *\n * Pure functions over their inputs — no client, no network, no state.\n */\n\nexport function toolX402PaymentRequired(input: {\n url: string\n payTo: string\n amount: string\n asset: string\n network: string\n description?: string\n}): X402PaymentRequired {\n return {\n x402Version: 2,\n resource: { url: input.url, description: input.description },\n accepts: [\n {\n scheme: 'exact',\n network: input.network,\n amount: input.amount,\n asset: input.asset,\n payTo: input.payTo,\n maxTimeoutSeconds: 30,\n },\n ],\n }\n}\n\nexport function x402ToolReceipt(receipt: X402Receipt): Record<string, unknown> {\n return {\n success: true,\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n token: receipt.token,\n amount: receipt.amount,\n to: receipt.to,\n resource_url: receipt.resourceUrl,\n explorer_url: receipt.explorerUrl,\n payment_header: receipt.paymentHeader,\n merchant_to: receipt.merchantTo,\n payer: receipt.payer,\n chain_id: receipt.chainId,\n haven: receipt.haven,\n merchant: receipt.merchant,\n x402: receipt.x402,\n }\n}\n\nexport function toolError(err: unknown): Record<string, unknown> {\n if (err instanceof HavenPaymentStateError) {\n return {\n success: false,\n payment_id: err.state.paymentId,\n kind: err.state.kind,\n rail: err.state.rail,\n status: err.state.status,\n phase: err.state.phase,\n next_action: err.state.nextAction,\n tx_hash: err.state.txHash,\n token: err.state.token,\n amount: err.state.amount,\n resource_url: err.state.resourceUrl,\n merchant_address: err.state.merchantAddress,\n amount_atomic: err.state.amountAtomic,\n asset: err.state.asset,\n network: err.state.network,\n description: err.state.description,\n idempotency_key: err.state.idempotencyKey,\n x402: err.state.x402\n ? {\n amount_atomic: err.state.x402.amountAtomic,\n asset: err.state.x402.asset,\n network: err.state.x402.network,\n resource_url: err.state.x402.resourceUrl,\n merchant_address: err.state.x402.merchantAddress,\n description: err.state.x402.description,\n idempotency_key: err.state.x402.idempotencyKey,\n }\n : undefined,\n mpp: err.state.mpp\n ? {\n amount_atomic: err.state.mpp.amountAtomic,\n asset: err.state.mpp.asset,\n network: err.state.mpp.network,\n resource_url: err.state.mpp.resourceUrl,\n merchant_address: err.state.mpp.merchantAddress,\n description: err.state.mpp.description,\n idempotency_key: err.state.mpp.idempotencyKey,\n challenge_id: err.state.mpp.challengeId,\n }\n : undefined,\n resume_state: err.resumeState,\n expires_at: err.state.expiresAt,\n chain_id: err.state.chainId,\n message: err.state.message,\n error: err.message,\n }\n }\n\n if (err instanceof HavenApiError) {\n return {\n success: false,\n status_code: err.statusCode,\n error: err.message,\n body: err.body,\n }\n }\n\n return {\n success: false,\n error: err instanceof Error ? err.message : String(err),\n }\n}\n","import {\n AgentPaymentNextAction,\n AgentPaymentPhase,\n HavenApiError,\n HavenPaymentStateError,\n HavenZeroSettlementHashError,\n} from './types.js'\nimport type {\n PaymentStatusResult,\n X402PaymentRequired,\n X402Receipt,\n} from './types.js'\nimport {\n captureMerchantResponse,\n McpMerchantTransport,\n} from './mcp-merchant-transport.js'\nimport type { CapturedMerchantResponse } from './mcp-merchant-transport.js'\nimport {\n MCP_X402_PAYMENT_RESPONSE_META_KEY,\n X402_RETRY_REJECTED_STATUS,\n encodeMcpSettlementReceipt,\n extractMcpPaymentRequired,\n mcpSettlementFromToolResult,\n} from './mcp-merchant-transport.js'\nimport { x402PaymentHeaderNamesSent } from './x402.js'\nimport { buildExplorerUrl, x402PayerAddress } from './x402-protocol.js'\nimport { paymentStateStatusCode } from './payment-state.js'\nimport { decodeBase64Json } from './base64.js'\n\n/**\n * Merchant delivery and the evidence trail behind it (#1620, epic #1613).\n *\n * Where `mcp-merchant-transport.ts` (#1616) owns the wire — timeouts,\n * sessions, SSE framing — this module owns what has to be TRUE around a\n * merchant call once a payment exists: which wallet the merchant should see,\n * what the payment's live state permits, and what gets written down\n * afterwards.\n *\n * The reporting is deliberately best-effort and deliberately asymmetric. A\n * merchant that REJECTS a retry after Haven already moved money is a\n * reconciliation event and is recorded as one; a merchant that accepts is\n * evidence, plus its own receipt when it offers one. Neither write may ever\n * change the caller-visible outcome — the resource is already paid for, and\n * an exception thrown from bookkeeping would turn a completed payment into a\n * reported failure. That is why every one of these swallows.\n *\n * Scheme-neutral by construction: it is handed a receipt or a payment id and\n * never asks how the money moved, which is what lets the #1508 no-funding-leg\n * path through the same door as the 3009 path.\n *\n * Internal to `HavenClient`. Exported for direct tests and composition only.\n */\n\n/** #2292: what an agent says a merchant answered to a retry Haven did not make. */\nexport type X402MerchantOutcome = 'accepted' | 'rejected'\n\n/** #2292: what Haven wrote down for such a report. */\nexport interface X402MerchantOutcomeReport {\n paymentId: string\n outcome: X402MerchantOutcome\n /** Haven's own funding tx for this payment — the anchor, never caller-supplied. */\n txHash: string\n /** Haven's own recorded resource URL — likewise never caller-supplied. */\n resourceUrl: string\n recorded: 'reconciliation_event' | 'evidence'\n}\n\nconst MERCHANT_BODY_SNIPPET_LIMIT = 1000\n\n/**\n * Evidence-report retry policy for a RETRYABLE refusal (#2117).\n *\n * The backend already distinguishes two refusals on `POST\n * /machine-payments/evidence` and says so in the status code: `503`\n * (`settlement_unobservable`) means \"the chain could not be read, or the\n * settlement is not mined yet — report it again\", and `409` means \"that is a\n * settled no\". The SDK discarded that distinction in a bare `catch {}`,\n * treating both as best-effort silence — so on erc7710, where the reported hash\n * is the ONLY thing that produces an evidence row, a transaction that simply\n * had not been mined yet at report time meant the payment never reached the\n * user's books at all.\n *\n * Bounded, and terminal on anything that is not a 503: a retry loop against a\n * settled no is just noise, and the total wait has to stay far under any\n * caller's patience because the paid resource is already in hand. Four attempts\n * over ~7s of backoff covers the mine-latency case this exists for without ever\n * becoming a reason a completed payment feels slow.\n */\nconst EVIDENCE_RETRY_DELAYS_MS = [1_000, 2_000, 4_000]\n\n/** The backend's retryable refusal — see `modules/mpp/evidence.ts`. */\nconst EVIDENCE_RETRYABLE_STATUS = 503\n\nexport type PaymentPoster = <T>(path: string, body: Record<string, unknown>) => Promise<T>\nexport type PaymentStatusReader = (paymentId: string) => Promise<PaymentStatusResult>\nexport type AgentReader = () => Promise<{ delegateAddress?: string }>\n\nexport interface MerchantCompletionOptions {\n post: PaymentPoster\n merchantTransport: McpMerchantTransport\n getPaymentStatus: PaymentStatusReader\n getAgent: AgentReader\n delegateAddress: string | undefined\n x402Wallet: string | undefined\n /** Injectable only so tests do not spend the real backoff. */\n sleep?: (ms: number) => Promise<void>\n}\n\nexport class MerchantCompletion {\n private readonly post: PaymentPoster\n private readonly merchantTransport: McpMerchantTransport\n private readonly getPaymentStatus: PaymentStatusReader\n private readonly getAgent: AgentReader\n private readonly delegateAddress: string | undefined\n private readonly x402Wallet: string | undefined\n private readonly sleep: (ms: number) => Promise<void>\n\n constructor(options: MerchantCompletionOptions) {\n this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)))\n this.post = options.post\n this.merchantTransport = options.merchantTransport\n this.getPaymentStatus = options.getPaymentStatus\n this.getAgent = options.getAgent\n this.delegateAddress = options.delegateAddress\n this.x402Wallet = options.x402Wallet\n }\n\n async retryRequest(\n url: string,\n initialInit: RequestInit | undefined,\n paymentRequired: X402PaymentRequired,\n receipt: X402Receipt,\n ): Promise<Response> {\n if (!receipt.accepted) {\n throw new HavenApiError('No accepted x402 option was recorded for payment retry', 500)\n }\n if (!receipt.paymentHeader) {\n throw new HavenApiError('No x402 payment header was returned for payment retry', 500)\n }\n\n // 5. Retry with a merchant-verifiable x402 EIP-3009 payment header.\n // #3171: if the merchant's session is gone (expired, or it restarted\n // between the challenge and this retry) and it SAYS nothing was settled,\n // re-initialize and resend the same header once instead of reporting a\n // 404 as a rejection after funding.\n const retryResponse = await this.merchantTransport.deliverPaymentRecoveringSession(\n url,\n initialInit,\n receipt.paymentHeader,\n () => this.merchantTransport.initialize(url, initialInit),\n )\n\n // #3118: a profile merchant refuses under HTTP 200 with an `isError: true`\n // payment-required tool result or a `_meta[\"x402/payment-response\"]` of\n // `success: false` (#3155 review B2 — the same two signals the hosted\n // completion reads). Either is a rejection after funding exactly like a\n // non-2xx answer; the thrown status is 402 (what the merchant said\n // in-band) while the captured `merchant_status` keeps the real 200.\n // NOT gated on the request body (#3155 review r6): this read runs AFTER\n // the funding leg moved money, and a merchant that mixes dialects (HTTP-402\n // challenge, profile-style refusal on the paid answer) must still be seen.\n // The content-type gate inside readToolResult keeps binary/streaming paid\n // resources unbuffered.\n const toolResult = retryResponse.ok ? await this.merchantTransport.readToolResult(retryResponse) : undefined\n const inBandChallenge = toolResult ? extractMcpPaymentRequired(toolResult) : undefined\n const metaSettlement = toolResult ? mcpSettlementFromToolResult(toolResult) : undefined\n const inBandRejection = inBandChallenge !== undefined || metaSettlement?.success === false\n if (!retryResponse.ok || inBandRejection) {\n const merchant = await captureMerchantResponse(retryResponse)\n await this.recordRetryRejected({\n rail: 'x402',\n paymentId: receipt.paymentId,\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n merchant,\n details: {\n merchant_to: receipt.merchantTo,\n delegate_to: receipt.to,\n },\n })\n\n throw new HavenApiError(\n 'x402 retry failed after Haven funded the delegate wallet; reconciliation may be required.',\n inBandRejection ? X402_RETRY_REJECTED_STATUS : merchant.merchant_status,\n {\n marker: 'x402_retry_rejected_after_funding',\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n resource_url: receipt.resourceUrl,\n merchant_to: receipt.merchantTo,\n delegate_to: receipt.to,\n ...merchant,\n },\n )\n }\n\n // #3155 review S1: the `_meta` settlement is the receipt when there is no\n // header, re-encoded so the one existing decoder reads both forms.\n const headerReceipt = retryResponse.headers.get('PAYMENT-RESPONSE')\n const protocolReceiptHeader = headerReceipt ?? (metaSettlement ? encodeMcpSettlementReceipt(metaSettlement) : undefined)\n const protocolReceiptHeaderName = headerReceipt\n ? 'PAYMENT-RESPONSE'\n : metaSettlement\n ? `_meta.${MCP_X402_PAYMENT_RESPONSE_META_KEY}`\n : undefined\n const merchantSettlement = parseMerchantSettlement(protocolReceiptHeader ?? null)\n if (receipt.merchant && merchantSettlement.settlementTxHash) {\n receipt.merchant.settlementTxHash = merchantSettlement.settlementTxHash\n receipt.merchant.settlementExplorerUrl = buildExplorerUrl(\n receipt.chainId,\n merchantSettlement.settlementTxHash,\n )\n }\n\n await this.reportEvidence({\n paymentId: receipt.paymentId,\n rail: 'x402',\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n merchantStatus: retryResponse.status,\n challengePayload: paymentRequired as unknown as Record<string, unknown>,\n selectedPayment: receipt.accepted as unknown as Record<string, unknown>,\n paymentProofHeaderName: x402PaymentHeaderNamesSent(receipt.paymentHeader),\n paymentProofHeader: receipt.paymentHeader,\n protocolReceiptHeaderName,\n protocolReceiptHeader,\n })\n\n await this.reportMerchantReceipt(receipt.paymentId, retryResponse)\n\n return retryResponse\n }\n\n /**\n * #956: capture the merchant's OWN receipt when the paid response carries\n * one, and report it to Haven so the reporting feed can attach it next to\n * the Haven-generated payment evidence (#498). Two supported signals on the\n * paid response:\n *\n * x-receipt-json: base64-encoded JSON receipt document (inline)\n * x-receipt-url: https URL to the receipt document (reference)\n *\n * Strictly best-effort: absence is the normal case, and no failure here may\n * ever affect the completed payment — the response is already paid for.\n */\n async reportMerchantReceipt(paymentId: string, response: Response): Promise<void> {\n try {\n const inlineB64 = response.headers.get('x-receipt-json')\n const url = response.headers.get('x-receipt-url')\n if (!inlineB64 && !url) return\n\n let body: Record<string, unknown> | null = null\n if (inlineB64) {\n // Mirror the backend's 64KB decoded cap exactly (base64 inflates 4/3)\n // — don't ship what the server will reject.\n if (inlineB64.length > Math.ceil((64 * 1024 * 4) / 3)) return\n const decoded = JSON.parse(Buffer.from(inlineB64, 'base64').toString('utf8')) as unknown\n if (decoded && typeof decoded === 'object') body = { json: decoded }\n } else if (url && url.startsWith('https://') && url.length <= 2048) {\n body = { url }\n }\n if (!body) return\n\n await this.post(`/machine-payments/${paymentId}/merchant-receipt`, body)\n } catch {\n // Best-effort by contract — a malformed header or a capture-endpoint\n // hiccup never surfaces to the caller of a successful payment.\n }\n }\n\n async resolveCompletionContext(input: {\n paymentId: string\n url: string\n /** #1508: see completeX402MerchantCall's option of the same name. */\n noFundingLeg?: boolean\n }): Promise<{\n paymentId: string\n /** Null on a no-funding-leg scheme — there is no Haven-submitted tx. */\n txHash: string | null\n resourceUrl: string\n merchantAddress: string | null\n }> {\n const status = await this.getPaymentStatus(input.paymentId)\n\n if (status.rail !== 'x402') {\n throw new HavenPaymentStateError(\n `Payment ${status.paymentId} is ${status.rail}, not x402.`,\n 409,\n status,\n )\n }\n\n // #1508: BOTH conditions below encode the EIP-3009 lifecycle, where\n // `confirmed` means Haven's funding transaction mined and its hash is the\n // evidence anchor. On a no-funding-leg scheme neither is reachable, and\n // #1456 reused this helper unadapted — so every hosted erc7710 call threw\n // `HavenPaymentStateError(status.message)`, surfacing as \"The payment was\n // submitted and is waiting for confirmation\" AFTER the settlement had\n // already succeeded, with the merchant never contacted.\n //\n // `submitted` is not a transient state to wait out here: it is the CORRECT\n // and final Haven-side state for erc7710 (`modules/x402/settle.ts` — \"The\n // intent flips to 'submitted'; final settlement is observed via the\n // merchant/receipt path\"). The merchant redeems the [child, budget] chain,\n // which is exactly the call this method is about to make.\n const readyForMerchantCompletion = input.noFundingLeg\n ? status.kind === 'payment_intent' && status.status === 'submitted'\n : status.nextAction === AgentPaymentNextAction.RetryOriginalX402Request ||\n (\n status.kind === 'payment_intent' &&\n status.status === 'confirmed' &&\n status.phase === AgentPaymentPhase.PaymentConfirmed &&\n status.nextAction === AgentPaymentNextAction.None\n )\n\n if (!readyForMerchantCompletion) {\n throw new HavenPaymentStateError(status.message, paymentStateStatusCode(status.status, 409), status)\n }\n\n // Deliberately NOT relaxed to \"absent is fine\": on the funding-leg path a\n // missing hash still means the evidence anchor is gone and remains a 502.\n // The no-funding-leg path skips it because there is no such transaction to\n // be missing — not because the check is inconvenient.\n if (!input.noFundingLeg && !status.txHash) {\n throw new HavenApiError(\n `x402 payment ${status.paymentId} is ready for merchant completion but has no Haven transaction hash.`,\n 502,\n status,\n status.paymentId,\n )\n }\n\n const approvedResourceUrl = status.resourceUrl ?? status.x402?.resourceUrl ?? null\n if (approvedResourceUrl && approvedResourceUrl !== input.url) {\n throw new HavenApiError(\n 'x402 merchant completion does not match the approved resource URL.',\n 409,\n { status, url: input.url },\n status.paymentId,\n )\n }\n\n return {\n paymentId: status.paymentId,\n txHash: status.txHash,\n resourceUrl: approvedResourceUrl ?? input.url,\n merchantAddress: status.merchantAddress ?? status.x402?.merchantAddress ?? null,\n }\n }\n\n async resolveWalletForMerchantCall(): Promise<string | undefined> {\n const localWallet = x402PayerAddress(this.delegateAddress, this.x402Wallet)\n if (localWallet) return localWallet\n\n try {\n const agent = await this.getAgent()\n return agent.delegateAddress ?? undefined\n } catch {\n return undefined\n }\n }\n\n // #1328: authorizeMachinePayment / authorizeMppDemoPayment / resumeAuthorizedMpp\n // / resumeMppPayment / fetchWithMachinePayment / retryMppRequest (the\n // MACHINE-PAYMENT-CHALLENGE / mpp_demo client surface) are retired — the\n // backend's POST /machine-payments/authorize refuses unconditionally now,\n // and MACHINE-PAYMENT-CHALLENGE was never produced by any other Haven\n // surface. Use the x402 flow (authorizeX402 / fetch / quoteX402 / payX402Quote)\n // for agent-to-merchant payments.\n\n async recordRetryRejected(input: {\n rail: string\n paymentId: string\n txHash: string\n resourceUrl: string\n merchant: CapturedMerchantResponse\n details?: Record<string, unknown>\n }): Promise<void> {\n try {\n await this.post('/machine-payments/reconciliation-events', {\n paymentId: input.paymentId,\n rail: input.rail,\n eventType: 'merchant_retry_rejected_after_payment',\n txHash: input.txHash,\n reason: `Merchant returned HTTP ${input.merchant.merchant_status} after Haven payment confirmation`,\n details: {\n resource_url: input.resourceUrl,\n retry_status: input.merchant.merchant_status,\n retry_body: input.merchant.merchant_body.slice(0, MERCHANT_BODY_SNIPPET_LIMIT) || null,\n ...input.details,\n },\n })\n } catch {\n // Best-effort durability: preserve the original retry failure for callers.\n }\n }\n\n /**\n * #2292: record what a merchant said to a retry **Haven did not make**.\n *\n * On the plain-HTTP x402 path Haven tells the agent to call the merchant\n * itself — that is the keyless design, not an oversight — so the two writes\n * above were reachable only from `completeX402MerchantCall`, where Haven IS\n * the caller. A manual retry had nowhere to put its outcome, which left\n * `intentStateFor`'s merchant-rejected branch dead on the one flow Haven\n * prescribes and made the 15-minute grace window the only route to\n * `funded_but_unsettled`.\n *\n * Three properties distinguish this from `recordRetryRejected` /\n * `reportEvidence`, and each is deliberate:\n *\n * 1. **It does not swallow.** Those two are bookkeeping hung off a call\n * whose outcome is already decided, so an exception there would turn a\n * completed payment into a reported failure. Here the report IS the\n * caller's request; silently dropping it would recreate the exact\n * unobservability #2292 exists to remove.\n * 2. **The anchor is server-side.** `txHash` and `resourceUrl` come from\n * the payment's own Haven record, never from the reporter — so a report\n * cannot be pointed at a different transaction or a different resource,\n * and it can never CONFIRM an intent (an erc7710 intent has no Haven\n * tx hash and is refused here rather than completed from a supplied one,\n * which is #2092's verified seam and stays its own path).\n * 3. **It is evidence, never authority.** Haven does not and must not check\n * the claim: verifying it would mean calling the merchant, which is the\n * property this whole path exists to preserve. What bounds a false\n * report is scope — the backend routes resolve the payment\n * `WHERE agent_id = $`, so a caller can only ever describe its own\n * payment — plus the fact that nothing financial keys off the claim:\n * the sweep is balance-driven, the intent's status/amount/recipient are\n * untouched, and a false `accepted` runs the server's own on-chain\n * residue check, which re-flags stranded funds independently.\n */\n async reportMerchantOutcome(input: {\n paymentId: string\n outcome: X402MerchantOutcome\n merchantStatus: number\n merchantBody?: string\n }): Promise<X402MerchantOutcomeReport> {\n if (!Number.isInteger(input.merchantStatus) || input.merchantStatus < 100 || input.merchantStatus > 599) {\n throw new HavenApiError(\n `merchant_status must be an integer HTTP status from 100 to 599 (received ${input.merchantStatus}).`,\n 400,\n undefined,\n input.paymentId,\n )\n }\n // A self-contradictory report is refused rather than recorded: this is\n // the one thing about the claim Haven CAN check without contacting the\n // merchant, so it checks it.\n const looksAccepted = input.merchantStatus >= 200 && input.merchantStatus < 300\n if (looksAccepted !== (input.outcome === 'accepted')) {\n throw new HavenApiError(\n `outcome \"${input.outcome}\" contradicts merchant_status ${input.merchantStatus}: ` +\n 'report \"accepted\" only for a 2xx and \"rejected\" only for a non-2xx.',\n 400,\n undefined,\n input.paymentId,\n )\n }\n\n const status = await this.getPaymentStatus(input.paymentId)\n if (status.rail !== 'x402') {\n throw new HavenPaymentStateError(\n `Payment ${status.paymentId} is ${status.rail}, not x402 — there is no merchant retry to report.`,\n 409,\n status,\n )\n }\n if (status.status !== 'confirmed' || !status.txHash) {\n throw new HavenPaymentStateError(\n `Payment ${status.paymentId} has no confirmed Haven funding transaction to anchor a ` +\n `merchant report to (status ${status.status}). ${status.message}`,\n paymentStateStatusCode(status.status, 409),\n status,\n )\n }\n const resourceUrl = status.resourceUrl ?? status.x402?.resourceUrl ?? null\n if (!resourceUrl) {\n throw new HavenApiError(\n `Payment ${status.paymentId} has no recorded resource URL, so a merchant report cannot be stored.`,\n 409,\n status,\n status.paymentId,\n )\n }\n\n const txHash = status.txHash\n if (input.outcome === 'rejected') {\n await this.post('/machine-payments/reconciliation-events', {\n paymentId: status.paymentId,\n rail: 'x402',\n eventType: 'merchant_retry_rejected_after_payment',\n txHash,\n reason: `Agent-reported: merchant returned HTTP ${input.merchantStatus} to a manual retry after Haven payment confirmation`,\n details: {\n resource_url: resourceUrl,\n retry_status: input.merchantStatus,\n retry_body: input.merchantBody?.slice(0, MERCHANT_BODY_SNIPPET_LIMIT) || null,\n reported_by: 'agent_manual_retry',\n },\n })\n return { paymentId: status.paymentId, outcome: 'rejected', txHash, resourceUrl, recorded: 'reconciliation_event' }\n }\n\n await this.post('/machine-payments/evidence', {\n paymentId: status.paymentId,\n rail: 'x402',\n txHash,\n resourceUrl,\n merchantStatus: input.merchantStatus,\n })\n return { paymentId: status.paymentId, outcome: 'accepted', txHash, resourceUrl, recorded: 'evidence' }\n }\n\n async reportEvidence(input: {\n paymentId: string\n rail: string\n txHash: string\n /**\n * #2972: OPTIONAL — `haven_report_settlement_evidence` reports a hash the\n * agent holds out of band, with no fresh merchant HTTP exchange to read a\n * resource URL or status from. Omitting it is safe: the backend only\n * enforces a MATCH (`input.resourceUrl && input.resourceUrl !== resourceUrl`\n * in `modules/mpp/evidence.ts`) when one is supplied, never that one is\n * present. The funding-leg callers above keep passing the one Haven's own\n * record already named.\n */\n resourceUrl?: string\n /** #2972: OPTIONAL for the same reason as `resourceUrl` — see there. */\n merchantStatus?: number\n challengePayload?: Record<string, unknown>\n selectedPayment?: Record<string, unknown>\n paymentProofHeaderName?: string\n paymentProofHeader?: string\n protocolReceiptHeaderName?: string\n protocolReceiptHeader?: string\n }): Promise<EvidenceReportOutcome> {\n const body = {\n paymentId: input.paymentId,\n rail: input.rail,\n txHash: input.txHash,\n resourceUrl: input.resourceUrl,\n merchantStatus: input.merchantStatus,\n challengePayload: input.challengePayload,\n selectedPayment: input.selectedPayment,\n paymentProofHeaderName: input.paymentProofHeaderName,\n paymentProofHeader: input.paymentProofHeader,\n protocolReceiptHeaderName: input.protocolReceiptHeaderName,\n protocolReceiptHeader: input.protocolReceiptHeader,\n protocolReceiptPayload: input.protocolReceiptHeader\n ? parseProtocolReceiptHeader(input.protocolReceiptHeader)\n : undefined,\n }\n\n // Still best-effort in the sense that matters — nothing here may change\n // the caller-visible outcome, because the resource is already paid for and\n // delivered. What changed (#2117) is that a RETRYABLE refusal is no longer\n // swallowed identically to a terminal one. On erc7710 this report is the\n // only thing that produces an evidence row, and therefore the only thing\n // that puts the payment in the user's books.\n //\n // #2970: the RETURN value is now load-bearing too, not just the retry\n // decision. The hosted erc7710 settle/complete gate reads this outcome to\n // decide whether `settled: true` is honest — a caller that only awaited\n // this for its side effect (the local retryRequest path, #1620) is\n // unaffected: the resolved value is simply ignored there.\n for (let attempt = 0; ; attempt += 1) {\n try {\n await this.post('/machine-payments/evidence', body)\n return { outcome: 'confirmed' }\n } catch (err) {\n const statusCode = err instanceof HavenApiError ? err.statusCode : undefined\n const retryable = statusCode === EVIDENCE_RETRYABLE_STATUS\n if (!retryable) {\n return { outcome: 'refused', statusCode: statusCode ?? 0 }\n }\n if (attempt >= EVIDENCE_RETRY_DELAYS_MS.length) {\n return { outcome: 'retryable', statusCode }\n }\n await this.sleep(EVIDENCE_RETRY_DELAYS_MS[attempt])\n }\n }\n }\n\n /**\n * #2972: report the merchant's REAL settlement transaction hash for an\n * erc7710 x402 payment out of band — the remedy #2970's guidance could not\n * name, because no hosted tool accepted a hash. An agent reaches this after\n * `haven_settle_mcp_tool` / `haven_complete_mcp_tool` answered\n * `DELIVERED_UNSETTLED` or `SETTLEMENT_PENDING`, or after\n * `haven_get_payment_status` reports `awaiting_settlement_evidence` — in\n * every one of those cases the agent may be holding the merchant's own\n * `PAYMENT-RESPONSE.transaction` while Haven has nothing.\n *\n * Reuses `reportEvidence` — same backend seam\n * (`POST /machine-payments/evidence` → `observeErc7710Settlement`,\n * fail-closed — see `settlement-observed.ts`), same three-outcome contract.\n * `resourceUrl` and `merchantStatus` are omitted: this call has no fresh\n * merchant HTTP exchange to read either from, and both are optional at the\n * backend (see the parameter doc on `reportEvidence`).\n *\n * The zero hash is refused HERE, client-side, before any network call —\n * never posted. `isZeroSettlementTxHash` is the same recognizer the #2970\n * gate uses, so a caller cannot \"fix\" a missing hash by reporting the demo\n * merchant's own marker and getting a different verdict than the settle\n * path already gave it.\n */\n async reportSettlementEvidence(\n paymentId: string,\n settlementTxHash: string,\n ): Promise<EvidenceReportOutcome> {\n if (isZeroSettlementTxHash(settlementTxHash)) {\n throw new HavenZeroSettlementHashError(paymentId)\n }\n return this.reportEvidence({\n paymentId,\n rail: 'x402',\n txHash: settlementTxHash,\n })\n }\n}\n\n/**\n * #2970: what `reportEvidence` learned about the report it just made.\n *\n * `confirmed` mirrors the backend's 202 (`modules/mpp/evidence.ts`) — the\n * intent is now `confirmed` (or was already, on the funding-leg path) with\n * THIS hash recorded. `retryable` mirrors its 503 (`settlement_unobservable`,\n * exhausted the retry budget above): the chain could not be read, or the\n * transaction is not mined yet — ask again later. `refused` mirrors every\n * terminal refusal (409 `settlement_unverified`, a validation error, an\n * unknown payment id, or a transport failure with no HTTP status at all,\n * reported as `statusCode: 0`) — reporting the same hash again will not\n * change the answer.\n */\nexport type EvidenceReportOutcome =\n | { outcome: 'confirmed' }\n | { outcome: 'retryable'; statusCode: number | undefined }\n | { outcome: 'refused'; statusCode: number }\n\n/**\n * #2970: a hash of the form `0x00…00` is never a real transaction — it is the\n * demo merchant's own \"delivered, not settled\" marker (`ZERO_TX_HASH` in\n * `packages/demo-merchant-mcp/src/x402.ts`), reused rather than invented here\n * so the hosted gate and any other consumer recognise it the same way. Treated\n * as equivalent to \"no hash was reported\": there is nothing on-chain to verify,\n * so asking the backend to look is a wasted round trip that can only ever\n * resolve to a refusal.\n */\nexport function isZeroSettlementTxHash(hash: string | null | undefined): boolean {\n return typeof hash === 'string' && /^0x0+$/i.test(hash)\n}\n\nexport function parseMerchantSettlement(header: string | null): {\n settlementTxHash?: string | null\n} {\n if (!header) return {}\n const parsed = parseProtocolReceiptHeader(header)\n const tx =\n typeof parsed?.transaction === 'string'\n ? parsed.transaction\n : typeof parsed?.txHash === 'string'\n ? parsed.txHash\n : typeof parsed?.tx_hash === 'string'\n ? parsed.tx_hash\n : null\n return { settlementTxHash: tx }\n}\n\n\n/**\n * Digest of a delegation-rail signing payload, or `undefined` when there is\n * none (#1138).\n *\n * Guarded because a payload that cannot be hashed is not a recoverable\n * condition to paper over: the edge signer derives this same digest before\n * signing, so an unhashable payload can never be signed by anyone. Surfacing it\n * as a named Haven error beats letting a raw viem type error escape from the\n * middle of intent construction.\n */\n\nexport function parseProtocolReceiptHeader(value: string): Record<string, unknown> | undefined {\n try {\n return decodeBase64Json<Record<string, unknown>>(value)\n } catch {\n try {\n return JSON.parse(value) as Record<string, unknown>\n } catch {\n return undefined\n }\n }\n}\n","import { hashTypedData } from 'viem'\nimport {\n signHash,\n signUserOpTypedDataForDelegation,\n signSettlementDelegationTypedData,\n addressFromKey,\n verifySignature,\n} from './signer.js'\nimport { assertUserOpTypedDataBinding } from './userop-binding.js'\nimport {\n assertBoundDirectPaymentUserOp,\n assertFundingLegPaysDelegate,\n assertOwnSettlementChild,\n HavenTypedDataRefusedError,\n type SettlementChildExpectation,\n} from './direct-payment-guard.js'\nimport type { PaymentReceipt, ReceiptVerification } from './receipt.js'\nimport type {\n HavenClientConfig,\n PaymentRequest,\n PaymentIntent,\n PaymentResult,\n PaymentStatusResult,\n PaymentResumeState,\n SignData,\n SweepResult,\n X402AuthorizationOptions,\n RawCreateResponse,\n RawSignResponse,\n RawStatusResponse,\n RawPaymentStatusResult,\n X402PaymentRequired,\n X402PaymentOption,\n X402Intent,\n X402McpTransport,\n X402McpCallContext,\n X402MerchantCallContext,\n RawX402MerchantCallContext,\n X402Quote,\n X402Receipt,\n X402RequestSnapshot,\n X402ResumeState,\n ResumeAuthorizedX402Input,\n ResumeX402PaymentInput,\n RawX402AuthorizeResponse,\n X402Erc7710Settlement,\n HavenAgent,\n HavenAgentSummary,\n HavenAgentAllowanceSummary,\n HavenAllowanceSummary,\n HavenBalanceCoverage,\n PostPurchaseAllowanceSummary,\n HavenPaymentReceipt,\n HavenPaymentReceiptsPage,\n CatalogSubmissionAccepted,\n HavenCatalogEntry,\n HavenCatalogSubmission,\n RawCatalogEntry,\n AgentPaymentWarning,\n HavenTaskBudget,\n RawTaskBudget,\n OpenTaskBudgetResult,\n CloseTaskBudgetResult,\n SubmitTaskBudgetResult,\n TaskBudgetSignContext,\n TaskBudgetOpenSignContext,\n TaskBudgetCloseSignContext,\n HavenTaskBudgetSignData,\n HavenTaskBudgetStatus,\n RawOpenTaskBudgetResponse,\n RawSubmitTaskBudgetResponse,\n RawCloseTaskBudgetResponse,\n RawTaskBudgetSignContext,\n} from './types.js'\nimport {\n AgentPaymentNextAction,\n AgentPaymentPhase,\n AgentPaymentRail,\n HavenApiError,\n HavenPaymentStateError,\n X402UnexpectedStatusError,\n X402AlreadySettledError,\n HavenSigningError,\n HavenTimeoutError,\n DEFAULT_CONFIRMATION_TIMEOUT_MS,\n} from './types.js'\nimport {\n buildX402IdempotencyKey,\n parsePaymentRequiredResponse,\n resolveTokenFromAddress,\n selectStandardPaymentOption,\n toStandardPaymentRequirements,\n x402AuthorizationAmount,\n x402PaymentHeaderNamesSent,\n} from './x402.js'\nimport type {\n SweepAuthorization,\n SweepPrepareResponse,\n SweepSubmitResponse,\n} from './sweep.js'\nimport { HavenApiTransport } from './haven-api-transport.js'\nimport type { HavenClientUpdate } from './client-identity.js'\nimport {\n mapPaymentResult,\n mapPaymentStatusResult,\n} from './payment-mappers.js'\nimport {\n paymentStateFromRaw,\n paymentStateStatusCode,\n throwPaymentStateError,\n} from './payment-state.js'\nimport {\n MCP_X402_PAYMENT_RESPONSE_META_KEY,\n McpMerchantTransport,\n encodeMcpSettlementReceipt,\n extractMcpPaymentRequired,\n mcpSettlementFromToolResult,\n mcpToolResultOf,\n} from './mcp-merchant-transport.js'\nimport { AccountReads, mapTaskBudget } from './account-reads.js'\nimport { DelegateSweepApi } from './delegate-sweep.js'\nimport {\n assertCanResumeX402,\n attachResumeState,\n buildExplorerUrl,\n buildX402Quote,\n chainIdFromNetwork,\n chainIdOrNull,\n decimalFromUsdcAtomic,\n explorerUrlOrEmpty,\n noCompatiblePaymentOptionError,\n requestInitFromSnapshot,\n sameAddress,\n snapshotX402Request,\n withX402Wallet,\n x402PayerAddress,\n} from './x402-protocol.js'\nimport { X402FundingLeg, type FundingLegExpectation } from './x402-funding-leg.js'\nimport { X402Erc7710 } from './x402-erc7710.js'\nimport { toolError, toolX402PaymentRequired, x402ToolReceipt } from './tool-adapter.js'\nimport { MerchantCompletion, isZeroSettlementTxHash, parseMerchantSettlement } from './merchant-completion.js'\nimport type { EvidenceReportOutcome, X402MerchantOutcome, X402MerchantOutcomeReport } from './merchant-completion.js'\n\nconst DEFAULT_POLLING_INTERVAL = 3_000\n\n/** Cap the merchant body persisted to the reconciliation event (the full body is kept on the thrown error). */\nconst MERCHANT_BODY_SNIPPET_LIMIT = 1000\n\n\n/**\n * Digest of a delegation-rail signing payload, or `undefined` when there is\n * none (#1138).\n *\n * Guarded because a payload that cannot be hashed is not a recoverable\n * condition to paper over: the edge signer derives this same digest before\n * signing, so an unhashable payload can never be signed by anyone. Surfacing it\n * as a named Haven error beats letting a raw viem type error escape from the\n * middle of intent construction.\n */\nfunction x402TypedDataDigest(typedData: unknown): string | undefined {\n if (!typedData || typeof typedData !== 'object') return undefined\n try {\n return hashTypedData(typedData as Parameters<typeof hashTypedData>[0])\n } catch (err) {\n throw new HavenSigningError(\n 'The x402 funding intent carried a sign_data.typed_data that is not a valid EIP-712 ' +\n 'payload (needs domain, types, primaryType, message), so its digest cannot be derived ' +\n 'and no signer could accept it. ' +\n `Underlying error: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/** Shared by {@link HavenClient.discoverTools} and {@link HavenClient.getCatalogEntry} (#1306). */\nfunction mapCatalogEntry(entry: RawCatalogEntry): HavenCatalogEntry {\n return {\n id: entry.id,\n name: entry.name,\n description: entry.description,\n category: entry.category,\n resourceUrl: entry.resource_url,\n rail: entry.rail,\n protocol: entry.protocol,\n toolName: entry.tool_name,\n toolArguments: entry.tool_arguments ?? null,\n priceDisplay: entry.price_display,\n priceAtomic: entry.price_atomic,\n asset: entry.asset,\n network: entry.network,\n status: entry.status,\n verifiedAt: entry.verified_at,\n source: entry.source,\n domainVerified: entry.domain_verified,\n verifiedPayable: entry.verified_payable,\n // #3078: absent (older backend) or null (unresolved join) both mean \"no\n // merchant known\" — the public field is then absent, never null.\n ...(entry.merchant\n ? {\n merchant: {\n id: entry.merchant.id,\n slug: entry.merchant.slug,\n name: entry.merchant.name,\n listingStatus: entry.merchant.listing_status,\n isTestMerchant: entry.merchant.is_test_merchant,\n },\n }\n : {}),\n }\n}\n\nexport class HavenClient {\n private readonly delegateKey: string | undefined\n private readonly havenApi: HavenApiTransport\n private readonly accountReads: AccountReads\n private readonly delegateSweep: DelegateSweepApi\n private readonly x402Wallet: string | undefined\n private readonly merchantTransport: McpMerchantTransport\n private readonly confirmationTimeout: number\n private readonly pollingInterval: number\n private readonly chainRpcs: Record<number, string>\n private readonly inFlightX402 = new Map<string, Promise<X402Receipt>>()\n /**\n * The EIP-3009 funding-leg lifecycle (#1618). The facade holds a reference\n * and delegates; it does not reimplement any of it.\n */\n private readonly fundingLeg: X402FundingLeg\n /**\n * The erc7710 direct-settlement lifecycle (#1619). Separate from the funding\n * leg on purpose: this scheme has no funding leg to share.\n */\n private readonly erc7710: X402Erc7710\n /**\n * Merchant delivery and the evidence trail behind it (#1620). Scheme-neutral\n * on purpose — both settlement schemes finish through the same door.\n */\n private readonly merchantCompletion: MerchantCompletion\n /** Delegate address derived from the private key (if provided) */\n readonly delegateAddress: string | undefined\n\n constructor(config: HavenClientConfig) {\n this.delegateKey = config.delegateKey\n this.havenApi = new HavenApiTransport(config)\n this.accountReads = new AccountReads({\n transport: this.havenApi,\n getPaymentStatus: (paymentId) => this.getPaymentStatus(paymentId),\n })\n this.delegateSweep = new DelegateSweepApi({\n transport: this.havenApi,\n delegateKey: config.delegateKey,\n chainRpcs: config.chainRpcs ?? {},\n getAgent: () => this.getAgent(),\n buildExplorerUrl: (chainId, hash) => buildExplorerUrl(chainId, hash),\n })\n this.x402Wallet = config.x402Wallet\n this.merchantTransport = new McpMerchantTransport({ merchantTimeout: config.merchantTimeout })\n // #1756 moved the 90 s literal to `types.ts` so the delegate sweep shares\n // this number rather than choosing a fourth one. Same value, same default.\n this.confirmationTimeout = config.confirmationTimeout ?? DEFAULT_CONFIRMATION_TIMEOUT_MS\n this.pollingInterval = config.pollingInterval ?? DEFAULT_POLLING_INTERVAL\n this.chainRpcs = config.chainRpcs ?? {}\n if (this.delegateKey) {\n this.delegateAddress = addressFromKey(this.delegateKey)\n }\n // Constructed LAST: the funding leg pays into `delegateAddress`, which is\n // only derived on the line above.\n this.fundingLeg = new X402FundingLeg({\n delegateKey: this.delegateKey,\n delegateAddress: this.delegateAddress,\n x402Wallet: this.x402Wallet,\n chainRpcs: this.chainRpcs,\n post: (path, body) => this.post(path, body),\n signForData: (signData, fundingExpectation) => this.signForData(signData, undefined, fundingExpectation),\n assertSignableAuthorizationState: (label, raw) =>\n this.throwIfNonSignableAuthorizationState(label, raw),\n })\n this.merchantCompletion = new MerchantCompletion({\n post: (path, body) => this.post(path, body),\n merchantTransport: this.merchantTransport,\n getPaymentStatus: (paymentId) => this.getPaymentStatus(paymentId),\n getAgent: () => this.getAgent(),\n delegateAddress: this.delegateAddress,\n x402Wallet: this.x402Wallet,\n })\n this.erc7710 = new X402Erc7710({\n delegateKey: this.delegateKey,\n post: (path, body) => this.post(path, body),\n signForData: (signData, settlementExpectation) =>\n this.signForData(signData, settlementExpectation),\n getAgent: () => this.getAgent(),\n })\n }\n\n /**\n * Run `fn` with extra Haven-API headers scoped to the async work it\n * performs. Used by the MCP server to tag every Haven API request that\n * a single tool dispatch makes with `X-Haven-MCP-Tool: <name>` so the\n * backend can write an audit-log row attributing the call.\n *\n * The headers are held in an `AsyncLocalStorage` so overlapping\n * dispatches do not leak headers into each other's requests. The store\n * inherits across `await` boundaries, so any Haven API call made while\n * `fn` is awaiting will pick up the right headers.\n *\n * Has no effect on outbound merchant requests (x402 / MPP) — those\n * never go through the internal `request<T>` path that reads the\n * context.\n */\n withRequestContext<T>(headers: Record<string, string>, fn: () => Promise<T>): Promise<T> {\n return this.havenApi.withRequestContext(headers, fn)\n }\n\n /**\n * The backend's newest `client_update` hint for this client (#3303): inside\n * a `withRequestContext` dispatch, the one that dispatch's own requests\n * received; outside one, the latest seen. Undefined when the client is\n * current or the backend predates #3303.\n */\n clientUpdate(): HavenClientUpdate | undefined {\n return this.havenApi.clientUpdate()\n }\n\n // ── High-Level API ───────────────────────────────────────────────\n\n /**\n * Send a payment in one call.\n *\n * Creates the intent, signs its `sign_data` (a delegation-rail intent's\n * EIP-712 typed data, after the #3271 UserOp binding check), submits the signature,\n * and polls until confirmed (or throws on failure/timeout).\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async pay(request: PaymentRequest): Promise<PaymentResult> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'Cannot use pay() without a delegateKey. Use createIntent() + submitSignature() for manual signing.',\n )\n }\n\n // Step 1: Create intent\n const intent = await this.createIntent(request)\n\n // Step 2: Sign — through signForData so every rail's typed-data checks\n // (including the #3271 UserOp binding check) run before signing, rather\n // than signing intent.signData.hash directly.\n const signature = await this.signForData(intent.signData)\n\n // Step 3: Submit\n await this.submitSignature(intent.paymentId, signature)\n\n // Step 4: Wait for confirmation\n return this.waitForConfirmation(intent.paymentId)\n }\n\n // ── Step-by-Step API ─────────────────────────────────────────────\n\n /**\n * Step 1: Create a payment intent.\n *\n * Returns the intent with the hash to sign.\n */\n async createIntent(request: PaymentRequest): Promise<PaymentIntent> {\n const raw = await this.post<RawCreateResponse>('/payments', {\n token: request.token,\n amount: request.amount,\n to: request.to,\n ...(request.idempotencyKey ? { idempotency_key: request.idempotencyKey } : {}),\n ...(request.taskBudgetId ? { task_budget_id: request.taskBudgetId } : {}),\n })\n\n // Haven returns HTTP 202 with this status when the requested amount\n // exceeds the on-chain allowance. The payment is parked for the owner\n // to approve in the dashboard — there's nothing to sign yet, so the SDK\n // surfaces it as an explicit error rather than returning a malformed\n // intent with no signData.\n if (raw.status === 'pending_approval') {\n throwPaymentStateError('Payment', raw)\n }\n\n return {\n paymentId: raw.payment_id,\n status: 'pending_signature',\n expiresAt: raw.expires_at,\n signData: raw.sign_data,\n }\n }\n\n /**\n * Keyless x402 construct.\n *\n * The non-custodial half of an x402 payment: posts the funding request to\n * `/x402` and returns the unsigned funding hash plus the data the caller\n * needs to build and sign the EIP-3009 merchant header itself. Crucially it\n * does **not** sign — neither the funding hash nor the merchant header — so\n * it works without a `delegateKey`. Both delegate signatures happen on the\n * machine that holds the key (the edge); the hosted MCP server relays only.\n *\n * Use this from the hosted, keyless server. The all-in-one `authorizeX402`\n * remains for local clients that hold the key.\n *\n * Throws (via the shared payment-state path) when the amount exceeds the\n * on-chain allowance — there is nothing to sign until the user approves.\n */\n async createX402Intent(\n paymentRequired: X402PaymentRequired,\n options: X402AuthorizationOptions = {},\n ): Promise<X402Intent> {\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n if (!option) {\n throw noCompatiblePaymentOptionError(paymentRequired.accepts)\n }\n\n // The funding transfer tops up the agent's delegate EOA. With no local key\n // we resolve that address from the authenticated agent record rather than\n // deriving it from a private key. #1348: a caller that already fetched the\n // agent in this flow passes delegateAddress and skips the duplicate fetch.\n const fundingTo = options.delegateAddress ?? (await this.getAgent()).delegateAddress\n if (!fundingTo) {\n throw new HavenApiError('Authenticated agent has no delegate address registered.', 502)\n }\n\n const idempotencyKey = options.idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option)\n const raw = await this.post<RawX402AuthorizeResponse>('/x402', {\n url: paymentRequired.resource.url,\n payTo: fundingTo,\n merchantPayTo: option.payTo,\n // #1360: this path ALWAYS means the EIP-3009 funding leg (payTo is the\n // agent's own delegate EOA). Saying so explicitly turns a stale/rotated\n // delegate address into the backend's LOUD shape-mismatch 400 instead\n // of a silent reroute to the erc7710 settlement branch (the #1358\n // review's open-budget misroute). Legacy-rail backends ignore the field.\n settlementScheme: 'eip3009',\n amount: x402AuthorizationAmount(option),\n asset: option.asset,\n network: option.network,\n description: paymentRequired.resource.description,\n idempotencyKey,\n // #1307: persisted so the settle leg can rehydrate it by payment_id.\n ...(options.mcpCallContext ? { mcpCallContext: options.mcpCallContext } : {}),\n // #1355: persisted so the SIGN leg can rehydrate it by payment_id — the\n // local signer's context fetch then carries the 402 PaymentRequired and\n // the agent passes only payment_id. Bounded: the backend rejects >64KB,\n // so an oversized blob is omitted here (signer falls back to the\n // caller-supplied copy) rather than failing the intent.\n ...(new TextEncoder().encode(JSON.stringify(paymentRequired)).length <= 65536\n ? { paymentRequired }\n : {}),\n // #3329: `/x402` bodies are camelCase (`X402AuthorizeRequest`), unlike\n // `POST /payments`'s snake_case `task_budget_id` above — the two\n // surfaces use different conventions, so this key is NOT `task_budget_id`.\n ...(options.taskBudgetId ? { taskBudgetId: options.taskBudgetId } : {}),\n })\n\n // Anything other than a signable funding intent (pending_approval,\n // expired, already-executed, error) is surfaced through the shared path.\n if (raw.status !== 'pending_signature') {\n throwPaymentStateError('x402 payment', raw)\n }\n if (!raw.sign_data?.hash) {\n throw new HavenApiError('No sign_hash returned from x402/authorize', 500, raw)\n }\n // #946/#1138: a delegation-rail funding intent signs the ACCOUNT's EIP-712\n // typed data, not the bare hash. This path is keyless by construction, so\n // it does not sign either one — it passes the payload through to whoever\n // holds the key (the local signer the connector installs). What it MUST\n // refuse is a scheme it cannot describe faithfully: handing a caller a\n // `hash` for a typed-data intent invites a raw ECDSA signature the account\n // rejects at the bundler, after the intent is claimed.\n if (raw.sign_data.signature_scheme !== undefined && !raw.sign_data.typed_data) {\n throw new HavenSigningError(\n `This account's x402 funding intent declares signature scheme ` +\n `'${raw.sign_data.signature_scheme}' but carried no typed_data to sign. ` +\n 'Refusing to fall back to the bare hash — the account would reject that signature ' +\n 'on-chain. This is a backend contract violation; report it rather than working around it.',\n )\n }\n if (!raw.x402_expected_auth) {\n throw new HavenApiError('No x402 expected-context binding returned from x402/authorize', 500, raw)\n }\n\n return {\n paymentId: raw.payment_id,\n idempotencyKey,\n status: 'pending_signature',\n expiresAt: raw.expires_at,\n signData: raw.sign_data,\n accepted: option,\n resourceUrl: paymentRequired.resource.url,\n merchantTo: raw.merchant_to ?? option.payTo,\n amountAtomic: x402AuthorizationAmount(option),\n asset: option.asset,\n network: option.network,\n expectedAuth: raw.x402_expected_auth,\n payerDelegate: (raw as { payer_delegate?: string }).payer_delegate,\n payerAgentId: (raw as { payer_agent_id?: string }).payer_agent_id,\n // #1138: the digest the delegation-rail expected context commits to.\n // Re-derived locally, exactly like every other context field the edge\n // signer is handed (amount, merchantTo, …) — none of them are trusted\n // because they arrived, they are trusted because the reconstructed\n // message has to match Haven's signature over it. A typed_data altered in\n // transit therefore fails message equality and is refused, and the signer\n // re-derives this digest a second time from the payload it actually signs.\n expectedTypedDataHash: x402TypedDataDigest(raw.sign_data.typed_data),\n fundingTo,\n }\n }\n\n /**\n * Step 2: Sign a hash with the delegate key.\n *\n * Returns the 65-byte signature (0x-prefixed).\n * Requires `delegateKey` to be set in the client config.\n */\n sign(hash: string): string {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'Cannot sign without a delegateKey. Pass the private key in HavenClient config, or sign externally.',\n )\n }\n\n const signature = signHash(this.delegateKey, hash)\n\n // Verify the signature locally before submitting\n if (!verifySignature(hash, signature, this.delegateAddress!)) {\n throw new HavenSigningError(\n 'Local signature verification failed — recovered address does not match delegate key.',\n )\n }\n\n return signature\n }\n\n /**\n * Sign a payment's `sign_data` with the correct scheme for its rail.\n *\n * Dispatching on the server-provided scheme means a caller never has to\n * know which rail an account is on; an unknown scheme — or an absent one,\n * since the legacy AllowanceModule rail retired (#2850) — is a hard error,\n * never a guessed signature. The session rail's 'eip191_userop' is retired\n * (#834) — the backend refuses those intents with HTTP 410 before any\n * sign_data reaches a client, so encountering it here is a hard error too.\n */\n private async signForData(\n signData: {\n hash: string\n signature_scheme?: string\n typed_data?: unknown\n },\n settlementExpectation?: SettlementChildExpectation,\n fundingExpectation?: FundingLegExpectation,\n ): Promise<string> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'Cannot sign without a delegateKey. Pass the private key in HavenClient config, or sign externally.',\n )\n }\n const scheme = signData.signature_scheme\n if (scheme === 'eip191_userop') {\n throw new HavenSigningError(\n \"The session rail is retired — 'eip191_userop' intents can no longer be signed. Re-onboard the account on the delegation rail.\",\n )\n }\n if (scheme === 'eip712_userop') {\n if (!signData.typed_data) {\n throw new HavenSigningError(\n 'sign_data.signature_scheme is eip712_userop but typed_data is missing — refusing to sign the bare hash (the account would reject it).',\n )\n }\n // #3271: refuse before signing unless the typed data recomputes to\n // exactly signData.hash, in the HybridDeleGator domain of its own\n // sender, against the v0.7 EntryPoint — a corrupted typed-data payload\n // used to produce a valid-looking signature over the wrong digest.\n assertUserOpTypedDataBinding(signData.typed_data, signData.hash)\n // #3283 (epic #3284): the binding proves the typed data and hash agree,\n // but the Haven API response supplies both. Sign only the shapes a\n // direct payment or funding leg is — this key's own account redeeming\n // its budget delegation directly, or a self-delegated task-budget\n // child redeemed under it — through the DelegationManager, so a\n // compromised API cannot get a self-call or an empty-context\n // redemption (account capture) signed. Same check as `haven_sign`.\n assertBoundDirectPaymentUserOp(\n signData.typed_data as Record<string, unknown>,\n this.delegateAddress!,\n )\n // #3375 (epic #3284): an x402 funding leg is also pinned to WHERE it\n // pays — the quoted amount of the quoted token into this key's own\n // delegate EOA, the signer's #3281 check. The address is local and the\n // asset/amount come from the 402 option, so a compromised Haven cannot\n // redirect the leg. `pay()` passes no expectation: a direct payment's\n // recipient is the caller's intent, bounded by the budget's caveats.\n if (fundingExpectation) {\n assertFundingLegPaysDelegate(signData.typed_data as Record<string, unknown>, {\n delegateAddress: this.delegateAddress!,\n asset: fundingExpectation.asset,\n amount: fundingExpectation.amount,\n })\n }\n return signUserOpTypedDataForDelegation(this.delegateKey, signData.typed_data as never)\n }\n if (scheme === 'eip712_delegation') {\n // The erc7710 x402 settlement child (#1452, epic #1450). Same guard as\n // eip712_userop above, and for a sharper reason: this signature lets a\n // facilitator pull the exact amount from the treasury. Falling back to\n // the bare hash would produce a signature the DelegationManager rejects\n // at redemption — a failure that surfaces on-chain, after the agent has\n // already told the merchant it paid.\n if (!signData.typed_data) {\n throw new HavenSigningError(\n 'sign_data.signature_scheme is eip712_delegation but typed_data is missing — refusing to sign the bare hash (the settlement would be rejected on redemption).',\n )\n }\n // #3283: this signature lets a facilitator pull from the treasury, so\n // verify the child means what the MERCHANT'S 402 asked for — payee,\n // amount, token, chain, facilitators, a bounded expiry — and that it is\n // a re-delegation of this agent's own budget (delegator = this key's\n // account, never a ROOT grant). Without an expectation there is nothing\n // Haven did not also write to verify it against, so refuse.\n if (!settlementExpectation) {\n throw new HavenTypedDataRefusedError(\n 'Refusing to sign an x402 settlement child without an independent expectation of what ' +\n \"it must pay (the merchant's 402). Pay erc7710 merchants through \" +\n 'settleX402Erc7710(), which supplies it.',\n )\n }\n assertOwnSettlementChild(signData.typed_data, settlementExpectation, this.delegateAddress!)\n return signSettlementDelegationTypedData(this.delegateKey, signData.typed_data as never)\n }\n if (scheme === undefined) {\n // The legacy AllowanceModule rail signed the bare hash when no scheme\n // was present. Every live sign_data emitter sets `signature_scheme` and\n // the backend spec makes it required, so absence is a malformed payload:\n // refuse it loudly rather than silently signing on a guessed scheme\n // (#2850, epic #1440). signHash itself stays live for the EIP-3009 leg.\n throw new HavenSigningError(\n 'sign_data.signature_scheme is required — the legacy AllowanceModule rail that signed the bare hash is retired (#2850). Refusing to guess a signing scheme.',\n )\n }\n throw new HavenSigningError(\n `Unknown sign_data.signature_scheme '${scheme}' — refusing to guess a signing scheme. Update @haven_ai/sdk.`,\n )\n }\n\n /**\n * Step 3: Submit a signature to execute the payment.\n *\n * The signature can come from `client.sign()` or from external signing.\n */\n async submitSignature(\n paymentId: string,\n signature: string,\n ): Promise<{ status: string; txHash?: string }> {\n const raw = await this.post<RawSignResponse>(\n `/payments/${paymentId}/sign`,\n { signature },\n )\n\n return {\n status: raw.status,\n txHash: raw.tx_hash,\n }\n }\n\n /**\n * Get the current status of a payment.\n */\n async getPayment(paymentId: string): Promise<PaymentResult> {\n const raw = await this.get<RawStatusResponse>(`/payments/${paymentId}`)\n return mapPaymentResult(raw, buildExplorerUrl)\n }\n\n /**\n * Get agent-actionable status for a payment intent or approval request.\n *\n * Use this for IDs returned by agent tools and machine-payment/x402 flows.\n * `getPayment()` remains available for payment-intent-only integrations.\n */\n async getPaymentStatus(paymentId: string): Promise<PaymentStatusResult> {\n const raw = await this.get<RawPaymentStatusResult>(`/machine-payments/${paymentId}/status`)\n return mapPaymentStatusResult(raw)\n }\n\n /**\n * Get the agent identity tied to this API key.\n */\n async getAgent(): Promise<HavenAgent> {\n return this.accountReads.getAgent()\n }\n\n /**\n * One-shot \"am I ready?\" bootstrap: identity + live spend authority + a\n * readiness signal, in a single call. Folds {@link getAgent} and\n * {@link getAllowances} together and derives a {@link HavenAgentReadiness}\n * so an agent can answer \"who am I and can I pay right now\" at session start\n * without two round trips and manual assembly.\n */\n async getAgentSummary(): Promise<HavenAgentSummary> {\n return this.accountReads.getAgentSummary()\n }\n\n /**\n * Sweep stranded USDC and ETH from the delegate EOA back to the agent's Haven account.\n *\n * The delegate key held by this client signs and submits the transfer transactions\n * directly — Haven's backend never handles the key or constructs signed txs\n * (CASP/MiCA Red Line #2). Funds always go to the Haven account linked to this agent\n * (`accountAddress` from `getAgent()`).\n *\n * Requires `chainRpcs` to be set for the agent's chain in `HavenClientConfig`.\n */\n async sweepDelegate(): Promise<SweepResult> {\n return this.delegateSweep.sweepDelegate()\n }\n\n /**\n * Hosted (keyless) split-signer sweep — step 1 of 2.\n *\n * Asks the backend to build a gasless EIP-3009 sweep authorization for the\n * delegate's stranded USDC. Returns `nothing_stranded` when the delegate is\n * empty, otherwise an `authorization` + Haven `expected_auth` to hand to the\n * edge signer's `haven_sign_sweep_delegate`. No key is required on this client.\n */\n async prepareSweep(): Promise<SweepPrepareResponse> {\n return this.delegateSweep.prepareSweep()\n }\n\n /**\n * Hosted (keyless) split-signer sweep — step 2 of 2.\n *\n * Relays the delegate-signed authorization. The Haven relayer submits the\n * on-chain `transferWithAuthorization` and pays gas; this client never holds\n * the key.\n */\n async submitSweep(\n authorization: SweepAuthorization,\n signature: string,\n ): Promise<SweepSubmitResponse> {\n return this.delegateSweep.submitSweep(authorization, signature)\n }\n\n /**\n * Get configured and on-chain allowances for the authenticated agent.\n */\n async getAllowances(): Promise<HavenAllowanceSummary> {\n return this.accountReads.getAllowances()\n }\n\n /**\n * #3126 — is the checked amount of the token actually HELD on the\n * agent's own account?\n *\n * This is the companion to {@link getAllowances}, not a variant of it:\n * allowances answer what the agent is PERMITTED to spend this period;\n * this answers whether the account HOLDS funds behind that permission,\n * as a sufficiency signal — `covered: true | false | null` — never as a\n * balance. `covered: null` means the chain read failed: treat it as\n * unverifiable, not as absence (`coverageError` says why). The account's\n * balance itself is deliberately not returned.\n */\n async checkFunds(input: { token: string; amountAtomic: string }): Promise<HavenBalanceCoverage> {\n return this.accountReads.checkFunds(input)\n }\n\n /**\n * `POST /machine-payments/budget-precheck` (#3054): ask Haven to decide —\n * server-side — whether `amountAtomic` of `token` fits the agent's\n * remaining delegation budget, the same compare the guided prepare used to\n * run locally over its allowances read.\n *\n * On insufficiency Haven refuses (403, `delegation_budget_exceeded`) and\n * the refusal reaches the `payment_refusals` ledger with\n * `source: 'hosted_prepare'` — the point of the endpoint. This method\n * surfaces that decision as a thrown {@link HavenApiError}; it does NOT\n * swallow it, because swallowing would turn a decided refusal into the\n * degrade-to-warning path and the ledger row would still land while the\n * purchase proceeded.\n *\n * camelCase body like the route family; the response mirrors the wire\n * (`sufficient`, `remaining_atomic`). `resourceUrl` is the merchant\n * resource being bought — the ledger dedupe window's discriminating\n * column — never this request's own URL.\n */\n async precheckBudget(input: {\n chainId?: number\n token: string\n amountAtomic: string\n merchantTo?: string\n resourceUrl?: string\n }): Promise<{ sufficient: boolean; remaining_atomic: string; remaining_is_from_chain?: boolean }> {\n return this.post<{\n sufficient: boolean\n remaining_atomic: string\n remaining_is_from_chain?: boolean\n }>('/machine-payments/budget-precheck', {\n chainId: input.chainId,\n token: input.token,\n amountAtomic: input.amountAtomic,\n ...(input.merchantTo !== undefined ? { merchantTo: input.merchantTo } : {}),\n ...(input.resourceUrl !== undefined ? { resourceUrl: input.resourceUrl } : {}),\n })\n }\n\n /**\n * Post-purchase allowance/budget summary for a settled payment (#1310).\n *\n * Reuses the EXACT rail-aware read path {@link getAllowances} / #1306's\n * catalog-purchase preflight `allowance` block use — `GET\n * /machine-payments/allowances`, with delegation-rail values coming from\n * the #1090 `deriveDelegationBudgets`-backed enforcer read, never\n * `agent_allowances` — so this can never disagree with\n * {@link getAllowances} for the same fixture. The settled token is\n * resolved from {@link getPaymentStatus} so callers pass only\n * `paymentId`, never a second haven_get_agent-style round trip.\n *\n * NEVER throws: any failed read (status lookup, agent lookup, or the\n * allowance/budget lookup itself) degrades to `{ allowance: null,\n * warnings: [ALLOWANCE_CHECK_UNAVAILABLE] }` rather than converting a\n * successful settlement into a failure — the on-chain policy remains the\n * actual spend gate regardless of whether this report can be produced.\n *\n * Freshness caveat (#1319): the delegation rail's on-chain enforcer read\n * can silently fall back to the optimistic full period budget without\n * throwing when the RPC read itself fails (#1145's fund-safe design,\n * unchanged here). {@link getAllowances}'s `onchain.remainingIsFromChain`\n * now carries that provenance on the wire, and the #1306 catalog-purchase\n * preflight (`haven_prepare_catalog_purchase`) surfaces it as a warning —\n * this summary does not (yet). `remaining_atomic` here reflects the last\n * successful chain read, not a guaranteed-live one, and callers should not\n * phrase it as guaranteed-fresh.\n */\n async getPostPurchaseAllowanceSummary(\n paymentId: string,\n ): Promise<{\n allowance: PostPurchaseAllowanceSummary | null\n warnings: AgentPaymentWarning[]\n payment: PaymentStatusResult | null\n }> {\n return this.accountReads.getPostPurchaseAllowanceSummary(paymentId)\n }\n\n /**\n * `haven_get_payment_status` convenience: fetch status and, for a\n * genuinely SETTLED x402 payment, attach the same post-purchase\n * allowance/budget summary a settle response carries.\n *\n * #1310/#1311 parity: this is the ONE home for logic that was duplicated\n * verbatim in the hosted and local `haven_get_payment_status` handlers —\n * `packages/mcp-server/src/tools/state-direct-recovery.ts` since #2809 (it\n * was `packages/mcp-server/src/tools.ts` when this was written) and\n * `packages/mcp/src/tools.ts` — extracted\n * here because both packages already depend on `@haven_ai/sdk` and call\n * methods on a `HavenClient` instance, so this needed no new dependency\n * edge. `funded_but_unsettled` is deliberately excluded: that phase means\n * the merchant did NOT accept the retry. Every other phase/rail returns\n * the status untouched.\n */\n async getPaymentStatusWithPostPurchaseAllowance(paymentId: string): Promise<\n PaymentStatusResult & {\n allowance?: PostPurchaseAllowanceSummary | null\n warnings?: AgentPaymentWarning[]\n }\n > {\n const status = await this.getPaymentStatus(paymentId)\n if (status.rail === AgentPaymentRail.X402 && status.phase === AgentPaymentPhase.PaymentConfirmed) {\n const { allowance, warnings } = await this.getPostPurchaseAllowanceSummary(paymentId)\n return { ...status, allowance, ...(warnings.length > 0 ? { warnings } : {}) }\n }\n return status\n }\n\n /**\n * Discover payable services from Haven's merchant catalog (epic #1717).\n *\n * Read-only: returns catalog entries (price, rail, protocol) so an agent\n * can choose a service and pay it with the regular payment tools in the\n * same session. Never creates payments or signatures.\n */\n async discoverTools(\n options: {\n category?: string\n search?: string\n rail?: 'x402' | 'mpp'\n /**\n * `'verified'` (epic #1717, #2978) returns entries whose endpoint Haven\n * watched answer a live quote — `verifiedPayable === true` — from\n * EITHER source: an operator-curated row that keeps passing its\n * periodic 402 probe, or a self-submitted row that also passed\n * domain-ownership proof. It is not a provenance filter; `'operator'`\n * still filters on provenance (`source === 'operator'`) regardless of\n * badge state, and `'any'` (the default) returns the merged listing.\n */\n verified?: 'any' | 'verified' | 'operator'\n } = {},\n ): Promise<HavenCatalogEntry[]> {\n const params = new URLSearchParams()\n if (options.category) params.set('category', options.category)\n if (options.search !== undefined) params.set('search', options.search)\n if (options.rail) params.set('rail', options.rail)\n const query = params.size > 0 ? `?${params.toString()}` : ''\n const raw = await this.get<{ entries: RawCatalogEntry[] }>(`/catalog${query}`)\n let entries = raw.entries.map(mapCatalogEntry)\n if (options.verified === 'verified') entries = entries.filter((e) => e.verifiedPayable === true)\n if (options.verified === 'operator') entries = entries.filter((e) => e.source === 'operator')\n return entries\n }\n\n /**\n * Submit a merchant's payable (x402/MCP) endpoint to the Verified Payable\n * Directory (epic #1717, #1716). Queue-only: writes a submission row and\n * returns the id + verify_token. The request path makes no outbound\n * request; domain-ownership proof and the read-only quote probe run later\n * on the leader-locked monitor. Ownership proof is ALWAYS required before\n * any listing — this method cannot skip it. `website` is a honeypot field\n * that bots fill; leave it unset.\n */\n async submitCatalogEntry(\n resourceUrl: string,\n options: { website?: string } = {},\n ): Promise<HavenCatalogSubmission> {\n const accepted = await this.post<CatalogSubmissionAccepted>('/catalog/submit', {\n resource_url: resourceUrl,\n ...(options.website ? { website: options.website } : {}),\n })\n return {\n id: accepted.id,\n verifyToken: accepted.verify_token,\n status: accepted.status,\n }\n }\n\n /**\n * Fetch one submission's coarse status by id (epic #1717, #1716). Public\n * and read-only. While the submission can still prove ownership the\n * response carries the exact well-known / DNS-TXT `instructions`; the\n * verify token is never returned here.\n */\n async getCatalogSubmissionStatus(\n id: string,\n ): Promise<{\n id: string\n status: 'submitted' | 'ownership_verified' | 'verified_payable' | 'failed' | 'delisted'\n instructions?: {\n expires_at: string\n well_known: { url: string; content: string; instruction: string }\n dns_txt: { name: string; value: string; instruction: string }\n } | null\n }> {\n return this.get(`/catalog/submit/${encodeURIComponent(id)}`)\n }\n\n /**\n * Fetch one curated catalog entry by id (#1306).\n *\n * Chain-scoped for free by the backend's SQL when the client is\n * agent-authenticated (#1299): an unknown id and an id curated for a\n * DIFFERENT chain than this agent's both 404 identically — this method does\n * not (and must not) re-filter by chain in JS. Read-only, like\n * {@link discoverTools}.\n */\n async getCatalogEntry(id: string): Promise<HavenCatalogEntry> {\n const raw = await this.get<RawCatalogEntry>(`/catalog/${encodeURIComponent(id)}`)\n return mapCatalogEntry(raw)\n }\n\n /**\n * List recent machine-payment receipts/evidence for bookkeeping.\n */\n async listReceipts(options: { limit?: number } = {}): Promise<HavenPaymentReceipt[]> {\n return this.accountReads.listReceipts(options)\n }\n\n /** #3128: one page of receipts with `total`, `hasMore` and `nextCursor`. */\n async listReceiptsPage(options: { limit?: number; cursor?: string } = {}): Promise<HavenPaymentReceiptsPage> {\n return this.accountReads.listReceiptsPage(options)\n }\n\n /**\n * Fetch the verifiable receipt bundle for a settled payment and verify it\n * locally. The server's own verification is ignored — the receipt is verified\n * here (independently of Haven) by recovering the signer from the\n * authorisation, so the result is trustworthy even if the backend lied.\n */\n async getReceipt(\n paymentId: string,\n ): Promise<{ receipt: PaymentReceipt; verification: ReceiptVerification }> {\n return this.accountReads.getReceipt(paymentId)\n }\n\n // ── Task Budgets (#3329) ────────────────────────────────────────────\n\n /**\n * Open a task budget: a self-delegated, time-boxed slice of the agent's own\n * budget delegation. Returns the pending row plus the child delegation's\n * `sign_data` — sign it (via `signForData` / `haven_sign` with\n * `task_budget_id`) and pass the signature to `submitTaskBudget` to make it\n * OPEN. Nothing is on-chain until then.\n */\n async openTaskBudget(request: {\n tokenAddress?: string\n maxAmountAtomic: string\n ttlSeconds: number\n recipientAddress?: string\n label?: string\n }): Promise<OpenTaskBudgetResult> {\n const raw = await this.post<RawOpenTaskBudgetResponse>('/task-budgets', {\n ...(request.tokenAddress ? { token_address: request.tokenAddress } : {}),\n max_amount_atomic: request.maxAmountAtomic,\n ttl_seconds: request.ttlSeconds,\n ...(request.recipientAddress ? { recipient_address: request.recipientAddress } : {}),\n ...(request.label ? { label: request.label } : {}),\n })\n return {\n taskBudget: mapTaskBudget(raw.task_budget),\n signData: raw.sign_data,\n nextAction: raw.next_action,\n instructions: raw.instructions,\n }\n }\n\n /** Read one task budget by id. */\n async getTaskBudget(id: string): Promise<HavenTaskBudget> {\n const raw = await this.get<{ task_budget: RawTaskBudget }>(`/task-budgets/${encodeURIComponent(id)}`)\n return mapTaskBudget(raw.task_budget)\n }\n\n /** List this agent's task budgets — `status: 'open'` (default; unexpired only) or `'all'`. */\n async listTaskBudgets(options: { status?: 'open' | 'all' } = {}): Promise<HavenTaskBudget[]> {\n const query = options.status ? `?status=${encodeURIComponent(options.status)}` : ''\n const raw = await this.get<{ task_budgets: RawTaskBudget[] }>(`/task-budgets${query}`)\n return raw.task_budgets.map(mapTaskBudget)\n }\n\n /**\n * The exact signing payload for a pending (purpose `open`) or closing\n * (purpose `close`) task budget — the `task_budget_id` counterpart of\n * `getResumeState` / the payment sign-context reads. `haven_sign` with\n * `task_budget_id` fetches this itself; call it directly only for manual\n * signing.\n */\n async getTaskBudgetSignContext(id: string): Promise<TaskBudgetSignContext> {\n const raw = await this.get<RawTaskBudgetSignContext>(`/task-budgets/${encodeURIComponent(id)}/sign-context`)\n if (raw.purpose === 'close') {\n return {\n taskBudgetId: raw.task_budget_id,\n purpose: 'close',\n taskSignContextVersion: raw.task_sign_context_version,\n typedData: raw.typed_data,\n userOperation: raw.user_operation as Record<string, unknown>,\n userOpHash: raw.user_op_hash as string,\n expected: raw.expected as TaskBudgetCloseSignContext['expected'],\n }\n }\n return {\n taskBudgetId: raw.task_budget_id,\n purpose: 'open',\n taskSignContextVersion: raw.task_sign_context_version,\n typedData: raw.typed_data,\n expected: raw.expected as TaskBudgetOpenSignContext['expected'],\n }\n }\n\n /** Submit a signature for a pending (open) or closing task budget. */\n async submitTaskBudget(id: string, signature: string): Promise<SubmitTaskBudgetResult> {\n const raw = await this.post<RawSubmitTaskBudgetResponse>(\n `/task-budgets/${encodeURIComponent(id)}/submit`,\n { signature },\n )\n return {\n taskBudget: mapTaskBudget(raw.task_budget),\n status: raw.status,\n ...(raw.close_tx_hash ? { closeTxHash: raw.close_tx_hash } : {}),\n }\n }\n\n /**\n * Close a task budget early. A `pending` or already-expired `open` budget\n * closes immediately (nothing was ever signed or is on-chain). A live\n * `open` budget returns `sign_data` for an on-chain `disableDelegation`\n * UserOp — sign it (`haven_sign` with `task_budget_id`) and call\n * `submitTaskBudget`.\n */\n async closeTaskBudget(id: string): Promise<CloseTaskBudgetResult> {\n const raw = await this.post<RawCloseTaskBudgetResponse>(`/task-budgets/${encodeURIComponent(id)}/close`, {})\n return {\n taskBudget: mapTaskBudget(raw.task_budget),\n status: raw.status,\n ...(raw.sign_data ? { signData: raw.sign_data } : {}),\n ...(raw.next_action ? { nextAction: raw.next_action } : {}),\n }\n }\n\n /**\n * Rehydrate the x402 resume-state bundle for a payment id (#1328: the MPP\n * resume-state variant retired along with the rest of the mpp_demo surface).\n *\n * The server returns stored protocol context only. The client still signs the\n * merchant proof locally when resumeX402Payment() runs.\n */\n async getResumeState(paymentId: string): Promise<PaymentResumeState> {\n return this.get<PaymentResumeState>(`/payments/${paymentId}/resume_state`)\n }\n\n /**\n * Poll until a payment reaches a terminal status (confirmed, failed, expired).\n */\n async waitForConfirmation(paymentId: string): Promise<PaymentResult> {\n const deadline = Date.now() + this.confirmationTimeout\n\n while (Date.now() < deadline) {\n const result = await this.getPayment(paymentId)\n\n if (result.status === 'confirmed' || result.status === 'failed' || result.status === 'expired') {\n return result\n }\n\n await sleep(this.pollingInterval)\n }\n\n throw new HavenTimeoutError(paymentId)\n }\n\n // ── x402 Protocol Support ────────────────────────────────────────\n\n /**\n * Authorize an x402 payment.\n *\n * Takes the parsed PaymentRequired from a 402 response, selects a compatible\n * option, funds the delegate wallet through Haven, and returns the standard\n * x402 header that the merchant can verify and settle.\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async authorizeX402(\n paymentRequired: X402PaymentRequired,\n options: X402AuthorizationOptions = {},\n ): Promise<X402Receipt> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'delegateKey is required for x402 payments. Pass it in the HavenClient config.',\n )\n }\n if (!this.delegateAddress) {\n throw new HavenSigningError('delegateAddress could not be derived from delegateKey.')\n }\n\n // 1. Select best payment option\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n if (!option) {\n throw noCompatiblePaymentOptionError(paymentRequired.accepts)\n }\n\n const idempotencyKey = options.idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option)\n const cached = this.fundingLeg.cachedReceipt(idempotencyKey)\n if (cached) return cached\n\n const inFlight = this.inFlightX402.get(idempotencyKey)\n if (inFlight) return inFlight\n\n const promise = this.fundingLeg.authorize(paymentRequired, option, idempotencyKey, options.taskBudgetId)\n this.inFlightX402.set(idempotencyKey, promise)\n\n try {\n return await promise\n } catch (err) {\n attachResumeState(err, {\n rail: 'x402',\n paymentRequired,\n accepted: option,\n idempotencyKey,\n })\n throw err\n } finally {\n this.inFlightX402.delete(idempotencyKey)\n }\n }\n\n /**\n * Probe a paid endpoint and return its x402 quote without creating a Haven\n * payment or approval request.\n */\n async quoteX402(\n url: string,\n init?: RequestInit,\n options: X402AuthorizationOptions = {},\n ): Promise<X402Quote> {\n const initialInit = withX402Wallet(init, x402PayerAddress(this.delegateAddress, this.x402Wallet))\n const request = snapshotX402Request(url, initialInit)\n const response = await this.merchantTransport.fetch(url, initialInit)\n\n if (response.status !== 402) {\n // #3118: a merchant on the official x402 MCP profile answers HTTP 200\n // with an `isError: true` tool result carrying the challenge. Quote it\n // like a 402. The transport signal is read exactly as for a 402 (path\n // or Bazaar); a stateless merchant that answered a bare `tools/call`\n // with a tool result has shown it needs no session, so nothing is\n // forced — `quoteMcpX402` still pins its own established session.\n const toolResultChallenge = await this.merchantTransport.extractToolResultChallenge(response, initialInit)\n if (toolResultChallenge) {\n const mcpTransport = await this.merchantTransport.detect(url, toolResultChallenge, response)\n return buildX402Quote(toolResultChallenge, request, options.idempotencyKey, mcpTransport)\n }\n // #2979: best-effort JSON body, so a merchant answering with its own\n // machine-readable refusal (e.g. `503 { error: 'merchant_not_ready' }`)\n // is not reduced to a bare status code — `.clone()` because the caller\n // never otherwise reads this response, but cloning before an unread\n // body is a defensive habit, not a requirement here.\n let body: unknown\n try {\n body = await response.clone().json()\n } catch {\n body = undefined\n }\n // #1300: typed, so consumers key on the class instead of message text.\n throw new X402UnexpectedStatusError(\n `Expected an x402 quote response with HTTP 402, got HTTP ${response.status}.`,\n response.status || 400,\n body,\n )\n }\n\n if (response.headers.get('MACHINE-PAYMENT-CHALLENGE')) {\n throw new HavenApiError('quoteX402 only supports standard x402 Payment Required responses.', 400)\n }\n\n const paymentRequired = await parsePaymentRequiredResponse(response)\n const mcpTransport = await this.merchantTransport.detect(url, paymentRequired, response)\n return buildX402Quote(paymentRequired, request, options.idempotencyKey, mcpTransport)\n }\n\n /**\n * Probe an MCP tool for its x402 quote without creating a payment.\n *\n * Unlike the generic {@link quoteX402} helper, this completes the\n * Streamable-HTTP MCP lifecycle before sending the unpaid `tools/call`.\n * Hosted MCP uses this path while remaining keyless: it resolves only the\n * agent's public delegate address for `x402-wallet`; signing remains local.\n * It refuses before the quote when the merchant does not establish a session;\n * callers that need a plain x402 endpoint must use {@link quoteX402}.\n */\n async quoteMcpX402(\n url: string,\n init?: RequestInit,\n options: X402AuthorizationOptions = {},\n ): Promise<X402Quote> {\n const wallet = await this.merchantCompletion.resolveWalletForMerchantCall()\n const sessionId = await this.merchantTransport.initialize(url, init, wallet)\n if (!sessionId) {\n throw new HavenApiError(\n 'The merchant did not establish an MCP session before the x402 quote. No payment was created.',\n 502,\n { mcpSessionNotEstablished: true },\n )\n }\n\n let requestInit = withX402Wallet(init, wallet)\n requestInit = this.merchantTransport.withSessionHeaders(requestInit, sessionId)\n\n const quote = await this.quoteX402(url, requestInit, options)\n // This dedicated helper established an MCP session even when the endpoint\n // uses a custom path and does not advertise Bazaar metadata. Preserve that\n // fact for the later, fresh session used by the paid retry.\n return {\n ...quote,\n mcpTransport: quote.mcpTransport ?? { handshakeRequired: true, source: 'path' },\n }\n }\n\n /**\n * Pay a previously inspected x402 quote and retry the exact captured request.\n */\n async payX402Quote(\n quote: X402Quote,\n options: X402AuthorizationOptions = {},\n ): Promise<Response> {\n const idempotencyKey = options.idempotencyKey ?? quote.idempotencyKey\n\n try {\n // #3378: forward every authorization option (taskBudgetId included —\n // #3329's task budgets were silently dropped here), with the quote's\n // own idempotency key as the default.\n const receipt = await this.authorizeX402(quote.paymentRequired, { ...options, idempotencyKey })\n return this.merchantCompletion.retryRequest(\n quote.request.url,\n requestInitFromSnapshot(quote.request),\n quote.paymentRequired,\n receipt,\n )\n } catch (err) {\n attachResumeState(err, {\n rail: 'x402',\n paymentRequired: quote.paymentRequired,\n accepted: quote.accepted,\n idempotencyKey,\n request: quote.request,\n })\n throw err\n }\n }\n\n /**\n * Pay a merchant through **erc7710 direct settlement** (#1454, epic #1450).\n *\n * **Nothing has settled when this returns** — that is why it does not return\n * an `X402Receipt`; the caller still has to retry the merchant with the\n * header. **MCP callers must pass `options.resourceUrl`**, because an in-band\n * MCP 402 challenge frequently carries no `resource` object at all.\n *\n * Both caveats, and why this scheme has no funding leg, are explained where\n * the lifecycle lives: `x402-erc7710.ts` (#1619).\n */\n async settleX402Erc7710(\n paymentRequired: X402PaymentRequired,\n options: { resourceUrl?: string } = {},\n ): Promise<X402Erc7710Settlement> {\n return this.erc7710.settle(paymentRequired, options)\n }\n\n /**\n * The AUTHORIZE half of erc7710 settlement (#1456): select the scheme, build\n * the request, and return the child to be signed — without signing it.\n *\n * Split out because the hosted topology cannot use `settleX402Erc7710()`:\n * that method signs in-process with `delegateKey`, and hosted Haven does not\n * have one and must not.\n */\n async prepareX402Erc7710(\n paymentRequired: X402PaymentRequired,\n options: {\n resourceUrl?: string\n /**\n * The account's rail, when the caller has ALREADY read it — passing it\n * skips a duplicate fetch (#1456). An optimisation, not a trust\n * boundary: the backend independently refuses a non-delegation account\n * at the rail seam (the #1986 retired-rail 410, #2245).\n */\n delegationRail?: boolean\n /**\n * #1547: the merchant MCP-tool call this authorization was quoted\n * against, persisted so the settle leg can rehydrate it by payment_id\n * (#1307).\n */\n mcpCallContext?: X402McpCallContext\n /**\n * #2041: replay key, as `createX402Intent` already takes one. Without it\n * a retried authorize mints a second signable settlement child instead\n * of replaying the first.\n */\n idempotencyKey?: string\n /**\n * #3329: build the settlement child under this open task budget's own\n * child delegation instead of the agent's budget delegation directly —\n * `[settlement, task, budget]`.\n */\n taskBudgetId?: string\n } = {},\n ): Promise<{\n paymentId: string\n signData: SignData\n settlement: Omit<X402Erc7710Settlement, 'paymentHeader'>\n }> {\n return this.erc7710.prepare(paymentRequired, options)\n }\n\n /**\n * The SETTLE half (#1456): exchange the signed child for the merchant header.\n *\n * The SDK builds no header on this path — the backend assembles the MetaMask\n * erc7710 payload. Whoever produced the signature (an in-process delegate\n * key, or the local edge signer over the hosted boundary) is irrelevant.\n */\n async submitX402Erc7710(paymentId: string, signature: string): Promise<string> {\n return this.erc7710.submit(paymentId, signature)\n }\n\n async resumeAuthorizedX402(input: ResumeAuthorizedX402Input): Promise<X402Receipt> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'delegateKey is required for x402 payments. Pass it in the HavenClient config.',\n )\n }\n if (!this.delegateAddress) {\n throw new HavenSigningError('delegateAddress could not be derived from delegateKey.')\n }\n\n const option = selectStandardPaymentOption(input.paymentRequired.accepts)\n if (!option) {\n throw noCompatiblePaymentOptionError(input.paymentRequired.accepts)\n }\n\n const idempotencyKey = input.idempotencyKey ?? buildX402IdempotencyKey(input.paymentRequired, option)\n const cached = this.fundingLeg.cachedReceipt(idempotencyKey)\n if (cached) return cached\n\n const status = await this.getPaymentStatus(input.paymentId)\n assertCanResumeX402(status, input.paymentRequired, option)\n\n // #1521: the same fundability question as the authorize path, with the\n // opposite default. Here the caller NAMED this payment, so an\n // unverifiable balance is not grounds to refuse the thing they asked for\n // — only a balance verified ABSENT is, because then the authorization\n // this would mint is known to be unfundable.\n const canFund = await this.fundingLeg.delegateCanFund(\n status.chainId ?? chainIdFromNetwork(option.network),\n option.asset,\n x402AuthorizationAmount(option),\n )\n if (canFund === false) {\n throw new X402AlreadySettledError(\n `x402 payment ${status.paymentId} has already settled — the delegate no longer holds the ` +\n 'funds to authorize it again, so there is nothing left to resume.',\n this.fundingLeg.receiptFromStatus(input.paymentRequired, option, undefined, status),\n 'settled',\n )\n }\n\n const paymentHeader = await this.fundingLeg.createPaymentHeader(input.paymentRequired, option)\n const receipt = this.fundingLeg.receiptFromStatus(input.paymentRequired, option, paymentHeader, status)\n this.fundingLeg.cacheReceipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n async resumeX402Payment(input: ResumeX402PaymentInput | X402ResumeState): Promise<Response> {\n const inputInit = 'init' in input ? input.init : undefined\n const initialInit = withX402Wallet(\n inputInit ?? (input.request ? requestInitFromSnapshot(input.request) : undefined),\n x402PayerAddress(this.delegateAddress, this.x402Wallet),\n )\n let paymentRequired = input.paymentRequired\n const url = input.url ?? input.request?.url\n\n if (!paymentRequired) {\n if (!url) {\n throw new HavenApiError('x402 resume requires the original URL or a captured request snapshot.', 400)\n }\n const response = await this.merchantTransport.fetch(url, initialInit)\n if (response.status !== 402) {\n throw new HavenApiError('Expected the original x402 request to return HTTP 402 before resuming.', 400)\n }\n paymentRequired = await parsePaymentRequiredResponse(response)\n }\n\n const receipt = await this.resumeAuthorizedX402({\n paymentId: input.paymentId,\n paymentRequired,\n idempotencyKey: input.idempotencyKey,\n })\n\n return this.merchantCompletion.retryRequest(url ?? paymentRequired.resource.url, initialInit, paymentRequired, receipt)\n }\n\n /**\n * Fetch wrapper that automatically handles HTTP 402 responses — and, since\n * #3118, a native-MCP payment-required tool result answered under HTTP 200.\n *\n * Works like the standard `fetch()` but intercepts 402 responses (or that\n * tool-result challenge), pays via x402 through Haven, and retries the request.\n *\n * ```ts\n * const response = await haven.fetch('https://paid-api.com/data')\n * const data = await response.json()\n * ```\n *\n * **MCP-over-x402 auto-handshake (issue #315):** when the endpoint is\n * MCP-shaped — the URL path ends in `/mcp`, or the 402 body (or, since\n * #3118, the tool-result challenge) carries a Coinbase Bazaar\n * `extensions.bazaar` block — the SDK runs the MCP\n * `initialize` handshake, threads the resulting `mcp-session-id`,\n * `Accept: application/json, text/event-stream`, and `x402-wallet` headers\n * through every request, and collapses SSE responses to the JSON-RPC\n * `result`. The caller just passes `(url, { body })` and never sees the\n * protocol plumbing. A non-MCP server (handshake error / no session id)\n * falls back to standard x402 behaviour.\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async fetch(\n url: string,\n init?: RequestInit,\n options: X402AuthorizationOptions = {},\n ): Promise<Response> {\n // Signal A: a `/mcp` path is the MCP-over-HTTP convention, so handshake\n // up front — before the probe — so the session id rides on the probe and\n // the retry alike. A non-MCP server yields `undefined` and we fall back.\n let mcpSessionId: string | undefined\n if (this.merchantTransport.isMcpUrl(url)) {\n mcpSessionId = await this.merchantTransport.initialize(url, init)\n }\n\n let requestInit = withX402Wallet(init, x402PayerAddress(this.delegateAddress, this.x402Wallet))\n if (mcpSessionId) requestInit = this.merchantTransport.withSessionHeaders(requestInit, mcpSessionId)\n\n // 1. Make the original request\n const response = await this.merchantTransport.fetch(url, requestInit)\n\n // 2. Not a 402 — return as-is (collapsing SSE for MCP sessions), unless\n // it is a native MCP payment-required tool result (#3118): the\n // official profile signals the challenge in the tool result, not the\n // status code, and it is paid and retried exactly like a 402.\n let paymentRequired: X402PaymentRequired\n // #3118: a tool-result challenge proves the merchant speaks JSON-RPC, so\n // the paid retry's SSE is collapsed even when no session was established\n // (a profile merchant on a plain URL answers without one). A non-402\n // pass-through is still collapsed only under a session: a plain SSE API\n // that never spoke JSON-RPC must come back untouched.\n let nativeChallenge = false\n if (response.status !== 402) {\n const toolResultChallenge = await this.merchantTransport.extractToolResultChallenge(response, requestInit)\n if (!toolResultChallenge) {\n return mcpSessionId ? this.merchantTransport.surfaceResult(response) : response\n }\n paymentRequired = toolResultChallenge\n nativeChallenge = true\n } else {\n // #1328: the legacy MACHINE-PAYMENT-CHALLENGE / mpp_demo auto-handling is\n // retired — a 402 that isn't standard x402 (including a stray\n // MACHINE-PAYMENT-CHALLENGE header from a pre-retirement caller) is\n // returned to the agent unmodified rather than auto-paid.\n\n // 3. Parse x402 payment requirements\n try {\n paymentRequired = await parsePaymentRequiredResponse(response)\n } catch {\n // Not a standard x402 402 response — return it unchanged.\n return response\n }\n }\n\n // Signal B: a Bazaar `extensions.bazaar` block marks an MCP-discoverable\n // resource even without the `/mcp` convention. Handshake now (if we\n // haven't already) so the paid retry carries the session id.\n // #3118: on a tool-result challenge the block sits inside the challenge\n // (`result.structuredContent.extensions.bazaar`), not at the body's top\n // level, so it is read from the parsed challenge as well.\n if (!mcpSessionId && (paymentRequired.extensions?.bazaar != null || (await this.merchantTransport.hasBazaarExtension(response)))) {\n mcpSessionId = await this.merchantTransport.initialize(url, init)\n if (mcpSessionId) requestInit = this.merchantTransport.withSessionHeaders(requestInit, mcpSessionId)\n }\n\n // 4. Pay through Haven\n const request = snapshotX402Request(url, requestInit)\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n const idempotencyKey = options.idempotencyKey ?? (option ? buildX402IdempotencyKey(paymentRequired, option) : undefined)\n let receipt: X402Receipt\n try {\n receipt = await this.authorizeX402(paymentRequired, options)\n } catch (err) {\n if (option && idempotencyKey) {\n attachResumeState(err, {\n rail: 'x402',\n paymentRequired,\n accepted: option,\n idempotencyKey,\n request,\n })\n }\n throw err\n }\n const retryResponse = await this.merchantCompletion.retryRequest(url, requestInit, paymentRequired, receipt)\n return mcpSessionId || nativeChallenge ? this.merchantTransport.surfaceResult(retryResponse) : retryResponse\n }\n\n /**\n * Deliver an already-signed x402 payment header to the merchant and return\n * the merchant's response. Used by the hosted MCP server to complete the\n * merchant leg of an MCP tool payment after the edge signer has built the\n * merchant payment header.\n *\n * Custody note: this never needs the delegate key. It relays a signed,\n * amount/merchant/nonce-bound EIP-3009 authorization the edge signer already\n * produced — the hosted server cannot mint or reuse signing authority.\n *\n * When the URL is MCP-shaped (`/mcp` path) or the quote-time transport context\n * says the merchant was Bazaar-discoverable, runs a fresh `initialize`\n * handshake (the quote-time session is gone once funding confirms; the x402\n * challenge is stateless w.r.t. the MCP session, so a fresh session is\n * accepted), threads the session + wallet headers, sets the x402 payment\n * header under the names that scheme requires (#2341), and\n * collapses an SSE JSON-RPC response to its `result`.\n */\n /**\n * Wait for a payment's account→delegate funding tx to reach ≥1 on-chain\n * confirmation. The hosted x402 completion path MUST call this after funding\n * and before delivering the merchant payment header, so the merchant's\n * balanceOf(delegate) / transferWithAuthorization verification sees the funded\n * balance — otherwise it rejects with \"Payment verification failed\". The\n * SDK's local path already does this (see `X402FundingLeg.authorize`); the hosted\n * split flow regressed when the 5→3 collapse removed the incidental\n * inter-call latency that used to mask it.\n *\n * **NOT a no-op when the funding tx hash is absent** (#1508). The WAIT is\n * skipped without a hash or a chain RPC, but the `GET /payments/:id` read\n * below runs UNCONDITIONALLY — it is how the fallback hash and the chainId\n * are obtained. That distinction is load-bearing: this method must never be\n * called on a scheme with no funding leg, because the read itself fails once\n * the intent reaches a status the backend maps to a non-2xx (`submitted` is a\n * 409), turning a settled payment into a reported error. The previous wording\n * here said \"No-op when the funding tx hash ... is unavailable\", and the\n * hosted erc7710 path was written against that promise — see\n * `deliverMerchantPayment`'s `noFundingLeg` option.\n */\n async ensureFundingConfirmed(paymentId: string, fundingTxHash?: string): Promise<void> {\n const status = await this.getPaymentStatus(paymentId)\n await this.fundingLeg.waitForFundingTx(fundingTxHash ?? status.txHash ?? undefined, status.chainId)\n }\n\n async completeX402MerchantCall(input: {\n url: string\n init?: RequestInit\n paymentId: string\n paymentHeader: string\n mcpTransport?: X402McpTransport\n /**\n * #1508: the payment settles with NO funding leg (erc7710). This method was\n * written for EIP-3009 and encodes that lifecycle in two places — the\n * readiness gate wants `confirmed`, and a Haven funding tx hash is\n * mandatory. Neither is reachable on a scheme where the MERCHANT redeems\n * the delegation chain: the intent sits at `submitted` by design, and there\n * is no Haven-submitted transaction at all. Set this to take the\n * no-funding-leg path through both.\n */\n noFundingLeg?: boolean\n }): Promise<{\n status: number\n ok: boolean\n body: unknown\n settlementTxHash?: string\n /**\n * #2970: what the evidence report (below) learned, when one was made.\n * `undefined` when there was no hash to report at all — no funding tx on\n * the erc7710 branch and no (or a zero) merchant-reported settlement hash.\n * The hosted erc7710 settle/complete gate reads this to decide whether\n * `settled: true` is honest; the 3009 branch's `settled: true` does not\n * need it — see `paid-mcp-completion.ts` for why.\n */\n evidenceOutcome?: EvidenceReportOutcome\n }> {\n const evidenceContext = await this.merchantCompletion.resolveCompletionContext({\n paymentId: input.paymentId,\n url: input.url,\n noFundingLeg: input.noFundingLeg === true,\n })\n // Non-null on the funding-leg path (the gate below throws without it) and\n // always null on erc7710. Bound once so the evidence calls — which require\n // a string — are provably unreachable without one.\n const fundingTxHash = evidenceContext.txHash\n const shouldHandshakeMcp =\n this.merchantTransport.isMcpUrl(input.url) ||\n input.mcpTransport?.handshakeRequired === true\n const x402Wallet = shouldHandshakeMcp ? await this.merchantCompletion.resolveWalletForMerchantCall() : x402PayerAddress(this.delegateAddress, this.x402Wallet)\n let mcpSessionId: string | undefined\n if (shouldHandshakeMcp) {\n mcpSessionId = await this.merchantTransport.initialize(input.url, input.init, x402Wallet)\n }\n\n let requestInit: RequestInit = withX402Wallet(input.init, x402Wallet) ?? {}\n if (mcpSessionId) requestInit = this.merchantTransport.withSessionHeaders(requestInit, mcpSessionId)\n\n // #3171: same session recovery as `retryRequest` — the hosted twin of the\n // local paid retry must not report a settled-nothing 404 as a rejection.\n const response = await this.merchantTransport.deliverPaymentRecoveringSession(\n input.url,\n requestInit,\n input.paymentHeader,\n () => this.merchantTransport.initialize(input.url, input.init, x402Wallet),\n )\n // #3155 review B1: collapse SSE whether or not a session was established —\n // an event-stream answer is MCP framing regardless, and a profile merchant\n // on a plain URL (no session) would otherwise hide its in-band refusal in\n // a raw SSE string. `surfaceResult` passes every non-SSE response through.\n const surfaced = await this.merchantTransport.surfaceResult(response)\n\n const text = await surfaced.text()\n let body: unknown\n try {\n body = text ? JSON.parse(text) : null\n } catch {\n body = text\n }\n\n // #3118: a profile merchant reports settlement in\n // `result._meta[\"x402/payment-response\"]` and a refusal as an\n // `isError: true` tool result — both under HTTP 200. The header form is\n // read first and stays authoritative when present; the `_meta` form is\n // re-encoded as base64 JSON so the evidence report's receipt payload is\n // parsed by the one existing decoder, and its `success: false` (or an\n // in-band payment-required result) is a merchant REJECTION, never a\n // success: the tool's content was withheld and nothing settled.\n const toolResult = mcpToolResultOf(body)\n const inBandChallenge = toolResult ? extractMcpPaymentRequired(toolResult) : undefined\n const metaSettlement = toolResult ? mcpSettlementFromToolResult(toolResult) : undefined\n const headerReceipt = surfaced.headers.get('PAYMENT-RESPONSE') ?? undefined\n const protocolReceiptHeaderName = headerReceipt\n ? 'PAYMENT-RESPONSE'\n : metaSettlement\n ? `_meta.${MCP_X402_PAYMENT_RESPONSE_META_KEY}`\n : undefined\n const protocolReceiptHeader = headerReceipt ?? (metaSettlement ? encodeMcpSettlementReceipt(metaSettlement) : undefined)\n const settlement = parseMerchantSettlement(protocolReceiptHeader ?? null)\n // A JSON-RPC `error` envelope (no `result`) after payment stays `ok` on the\n // HTTP status: it carries no settlement statement, and the two protocol\n // signals above are the only ones that mean \"nothing settled\" (#3155 S4).\n const merchantAccepted = surfaced.ok && inBandChallenge === undefined && metaSettlement?.success !== false\n\n // #2970: declared here (not inside the `else` below) so it survives to\n // the `return` — `undefined` on the refusal branch and whenever there was\n // no hash to report at all.\n let evidenceOutcome: EvidenceReportOutcome | undefined\n\n if (!merchantAccepted) {\n // #1508: both evidence surfaces below require a txHash — the backend\n // answers `400 txHash is required` without one, and these calls swallow\n // failures, so an erc7710 row would vanish silently rather than fail\n // loudly. Skipping deliberately (owner decision 2026-08-17) instead of\n // writing a row that cannot be written: their consumer is funding-leg\n // reconciliation (#713 — stranded delegate balances), and this rail has\n // no funding leg to strand. The merchant receipt below still runs, so the\n // paid call remains recorded.\n if (!input.noFundingLeg && fundingTxHash) {\n await this.merchantCompletion.recordRetryRejected({\n rail: 'x402',\n paymentId: evidenceContext.paymentId,\n txHash: fundingTxHash,\n resourceUrl: evidenceContext.resourceUrl,\n merchant: {\n merchant_status: surfaced.status,\n merchant_status_text: surfaced.statusText,\n merchant_headers: Object.fromEntries(surfaced.headers.entries()),\n merchant_body: text,\n },\n details: {\n merchant_to: evidenceContext.merchantAddress,\n },\n })\n }\n } else {\n // #2092: the evidence anchor is scheme-dependent, and skipping it on\n // erc7710 (#1508) left a whole settlement scheme with no\n // `machine_payment_evidence` row — and therefore invisible to the Fortnox\n // reporting feed, `GET /receipts`, transaction history, and the\n // merchant-receipt capture on the very next line (which 404s without an\n // evidence row). The #1508 reasoning — \"evidence's consumer is\n // funding-leg reconciliation, and this rail has no funding leg\" — was\n // true about #713 and incomplete about everything else evidence feeds.\n //\n // On the funding-leg path the anchor is Haven's funding transaction; on\n // erc7710 it is the MERCHANT's settlement transaction, which the merchant\n // just handed us in `PAYMENT-RESPONSE`. Both are reported through the\n // same call, so the backend and every consumer keep one code path. The\n // backend verifies the erc7710 hash on-chain before it confirms anything\n // (#2092), so reporting it is a claim, not an authority.\n const rawEvidenceTxHash = input.noFundingLeg\n ? (settlement.settlementTxHash ?? undefined)\n : (fundingTxHash ?? undefined)\n // #2970: a zero hash is never a real transaction (see\n // `isZeroSettlementTxHash`) — reporting it can only ever come back\n // refused, at the cost of a real round trip (and, on the retryable\n // path, the SDK's own multi-second backoff). Treat it as no hash at all.\n const evidenceTxHash =\n rawEvidenceTxHash && !isZeroSettlementTxHash(rawEvidenceTxHash) ? rawEvidenceTxHash : undefined\n // #2117: when the merchant returned no settlement transaction there is\n // simply nothing to report, and inventing an anchor client-side is what\n // the backend's on-chain verification exists to prevent. That gap is\n // closed SERVER-side instead, by the passive settlement sweep\n // (`modules/x402/settlement-sweeper.ts`), which finds the settlement by\n // this payment's own intent-unique delegation child. Do not \"fix\" this\n // branch by fabricating a hash.\n if (evidenceTxHash) {\n evidenceOutcome = await this.merchantCompletion.reportEvidence({\n paymentId: evidenceContext.paymentId,\n rail: 'x402',\n txHash: evidenceTxHash,\n resourceUrl: evidenceContext.resourceUrl,\n merchantStatus: surfaced.status,\n paymentProofHeaderName: x402PaymentHeaderNamesSent(input.paymentHeader),\n paymentProofHeader: input.paymentHeader,\n protocolReceiptHeaderName,\n protocolReceiptHeader,\n })\n }\n // #956: the hosted-MCP completion path is a successful paid retry too —\n // capture the merchant's receipt exactly like the local flow does.\n await this.merchantCompletion.reportMerchantReceipt(evidenceContext.paymentId, surfaced)\n }\n\n return {\n status: surfaced.status,\n ok: merchantAccepted,\n body,\n // #3155 review S3: a transaction beside a rejection is not a settlement.\n settlementTxHash: merchantAccepted ? (settlement.settlementTxHash ?? undefined) : undefined,\n evidenceOutcome,\n }\n }\n\n /**\n * #2292: report the outcome of a merchant retry the AGENT performed.\n *\n * The hosted `haven_complete_mcp_tool` / `completeX402MerchantCall` path is\n * for merchants Haven calls itself. On the plain-HTTP x402 path Haven never\n * talks to the merchant, so the outcome of that retry had no way back —\n * see `MerchantCompletion.reportMerchantOutcome` for what is verified about\n * a caller-asserted report and what deliberately is not.\n */\n async reportX402MerchantOutcome(input: {\n paymentId: string\n outcome: X402MerchantOutcome\n merchantStatus: number\n merchantBody?: string\n }): Promise<X402MerchantOutcomeReport> {\n return await this.merchantCompletion.reportMerchantOutcome(input)\n }\n\n /**\n * #2972: report the merchant's real settlement transaction hash for an\n * erc7710 x402 payment — the remedy for `DELIVERED_UNSETTLED` /\n * `SETTLEMENT_PENDING` / `awaiting_settlement_evidence` when the agent\n * holds the hash (`PAYMENT-RESPONSE.transaction`, or a prior settle/\n * complete result's `settlement_tx_hash`) and Haven does not. See\n * `MerchantCompletion.reportSettlementEvidence` for the fail-closed\n * verification this posts into (`observeErc7710Settlement`) and the\n * client-side zero-hash refusal.\n */\n async reportSettlementEvidence(\n paymentId: string,\n settlementTxHash: string,\n ): Promise<EvidenceReportOutcome> {\n return await this.merchantCompletion.reportSettlementEvidence(paymentId, settlementTxHash)\n }\n\n /**\n * GET /x402/:id/merchant-call-context — the settle-leg twin of #1263's\n * sign-context fetch (#1307). Re-serves the stored merchant MCP-tool call\n * context (merchant_url, tool_name, arguments, mcp_transport) recorded at\n * quote time, so `haven_settle_mcp_tool` / `haven_complete_mcp_tool` can\n * omit those fields and let Haven rehydrate them by payment_id instead of\n * the caller re-threading them. Throws `HavenApiError` (404 unknown/foreign\n * payment_id, 409 no stored context, 410 expired) — the caller decides the\n * fallback (re-send the full context explicitly).\n */\n async getX402MerchantCallContext(paymentId: string): Promise<X402MerchantCallContext> {\n const raw = await this.get<RawX402MerchantCallContext>(\n `/x402/${paymentId}/merchant-call-context`,\n )\n return {\n paymentId: raw.payment_id,\n merchantUrl: raw.merchant_url,\n toolName: raw.tool_name,\n arguments: raw.arguments ?? {},\n ...(raw.mcp_transport\n ? {\n mcpTransport: {\n handshakeRequired: raw.mcp_transport.handshake_required,\n source: raw.mcp_transport.source,\n },\n }\n : {}),\n }\n }\n\n /**\n * Wait for a funding tx to be mined with ≥1 confirmation before the\n * merchant retry, eliminating the race where the merchant's\n * `balanceOf(delegate)` runs before the funding block propagates.\n *\n * Skipped when `chainRpcs` does not include the chain; in that case Haven's\n * backend has already confirmed on-chain submission and callers accept the\n * small propagation window as a trade-off for not configuring an RPC URL.\n */\n private throwIfNonSignableAuthorizationState(\n label: string,\n raw: RawX402AuthorizeResponse,\n ): void {\n if (raw.status === 'pending_signature') return\n throwPaymentStateError(label, raw)\n }\n\n // ── Tool Execution (for agent frameworks) ────────────────────────\n\n /**\n * Execute a tool call by name and input.\n *\n * Designed to plug directly into agent tool-call handlers:\n *\n * ```ts\n * if (block.type === 'tool_use') {\n * const result = await haven.executeTool(block.name, block.input)\n * // send result back to the model\n * }\n * ```\n */\n async executeTool(\n toolName: string,\n input: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n if (toolName === 'make_payment') {\n const { token, amount, to } = input as {\n token: string\n amount: string\n to: string\n }\n\n try {\n const result = await this.pay({ token, amount, to })\n return {\n success: result.status === 'confirmed',\n payment_id: result.paymentId,\n status: result.status,\n tx_hash: result.txHash,\n token: result.token,\n amount: result.amount,\n to: result.to,\n explorer_url: result.explorerUrl,\n error: result.errorMessage,\n }\n } catch (err) {\n return toolError(err)\n }\n }\n\n if (toolName === 'authorize_x402_payment') {\n const { url, payTo, amount, asset, network, description, idempotencyKey } = input as {\n url: string\n payTo: string\n amount: string\n asset: string\n network: string\n description?: string\n idempotencyKey?: string\n }\n\n try {\n const receipt = await this.authorizeX402(\n toolX402PaymentRequired({ url, payTo, amount, asset, network, description }),\n { idempotencyKey },\n )\n return x402ToolReceipt(receipt)\n } catch (err) {\n return toolError(err)\n }\n }\n\n if (toolName === 'resume_x402_payment') {\n const { payment_id, url, payTo, amount, asset, network, description, idempotencyKey } = input as {\n payment_id: string\n url: string\n payTo: string\n amount: string\n asset: string\n network: string\n description?: string\n idempotencyKey?: string\n }\n\n try {\n const receipt = await this.resumeAuthorizedX402({\n paymentId: payment_id,\n paymentRequired: toolX402PaymentRequired({ url, payTo, amount, asset, network, description }),\n idempotencyKey,\n })\n return x402ToolReceipt(receipt)\n } catch (err) {\n return toolError(err)\n }\n }\n\n // #1328: the 'authorize_machine_payment' tool (mpp_demo only) is retired\n // along with the rest of the SDK's MPP-demo client surface — an unknown\n // toolName falls through to the Error below, same as any other retired name.\n\n if (toolName === 'get_payment_status') {\n const { payment_id } = input as { payment_id: string }\n const result = await this.getPaymentStatus(payment_id)\n return {\n payment_id: result.paymentId,\n kind: result.kind,\n rail: result.rail,\n status: result.status,\n phase: result.phase,\n next_action: result.nextAction,\n tx_hash: result.txHash,\n token: result.token,\n amount: result.amount,\n resource_url: result.resourceUrl,\n merchant_address: result.merchantAddress,\n amount_atomic: result.amountAtomic,\n asset: result.asset,\n network: result.network,\n description: result.description,\n idempotency_key: result.idempotencyKey,\n x402: result.x402,\n mpp: result.mpp,\n expires_at: result.expiresAt,\n chain_id: result.chainId,\n message: result.message,\n }\n }\n\n if (toolName === 'get_allowances') {\n return { ...await this.getAllowances() }\n }\n\n throw new Error(`Unknown tool: ${toolName}`)\n }\n\n // ── HTTP Helpers ─────────────────────────────────────────────────\n\n private async post<T>(path: string, body: Record<string, unknown>): Promise<T> {\n return this.havenApi.post<T>(path, body)\n }\n\n private async get<T>(path: string): Promise<T> {\n return this.havenApi.get<T>(path)\n }\n\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n","/**\n * Shared semantic descriptions for Haven agent payment tools.\n *\n * Two surfaces in this repo expose Haven as a tool: the Claude / OpenAI\n * function-calling tool definitions in `tools.ts` (used for direct SDK\n * integrations) and the MCP server in `packages/mcp` (used by any MCP-speaking\n * agent runtime). The two surfaces use different tool *names* — the SDK's\n * tools are tuned for tool-calling conventions (`make_payment`,\n * `authorize_x402_payment`); the MCP tools follow the MCP `haven_*` naming\n * (`haven_pay_x402_quote`).\n *\n * The underlying *operations* are the same, so the descriptive prose should\n * live in one place. Both surfaces import from this module and compose their\n * own tool descriptions from these semantic fragments. Drift is caught by\n * tests asserting each consumer's description string contains the shared\n * `summary` from this module.\n */\n\nexport interface ToolDescription {\n /** One-line summary of the operation. Used as the first sentence of every\n * downstream description and as a stable substring for drift tests. */\n summary: string\n /** Natural-language user intents that should make an agent prefer this\n * tool over adjacent tools. Empty or omitted when the summary is enough. */\n selectionGuidance?: string\n /** Concrete behaviour the tool performs end-to-end, including which\n * non-custodial guarantee applies. */\n behavior: string\n /** What the agent should do next on error / declined states.\n * Empty string if not applicable. */\n nextActionGuidance: string\n}\n\n/**\n * Build a single description string from the three fragments. Joined with\n * spaces so consumers can split on the summary substring if they need to.\n */\nexport function composeDescription(d: ToolDescription): string {\n return [d.summary, d.selectionGuidance, d.behavior, d.nextActionGuidance]\n .filter(Boolean)\n .join(' ')\n}\n\nexport const toolDescriptions = {\n quoteX402: {\n summary:\n 'Inspect an HTTP 402 x402 paid resource without creating a Haven payment, signature, approval, or on-chain transaction.',\n behavior:\n 'Probes the merchant directly and parses the 402 response. Pure read-only client behavior — Haven is not contacted.',\n nextActionGuidance:\n 'On success the returned quote is the input to haven_pay_x402_quote. Do not call the merchant again — Haven re-uses the captured request when paying.',\n },\n payX402: {\n summary:\n 'Pay an inspected x402 quote. The delegate key signs locally; Haven only validates and relays signed, on-chain-constrained payment transactions.',\n selectionGuidance:\n 'Do not use this for read-only allowance, budget, spend-limit, remaining-amount, reset-period, or what-can-I-spend questions; use the allowance lookup tool instead.',\n behavior:\n 'Signs the payment locally and returns the merchant response. Settlement is either direct account-to-merchant with no funding leg, or a bridge that first redeems the agent\\'s budget delegation to fund the delegate wallet for an EIP-3009 authorization. A payment outside the on-chain budget is declined before any money moves; nothing is queued for a human to approve later.',\n nextActionGuidance:\n 'Preserve the returned resume_state — it identifies this payment if you need to ask about it later. ' +\n 'This tool performs the merchant retry itself, so do not wait on a signal while the call is in flight. ' +\n 'If the process crashes after this call and a later haven_get_payment_status reports nextAction=retry_original_x402_request, Haven\\'s funding leg confirmed but no merchant response was ever recorded — call the resume tool with the preserved resume_state or payment_id instead of paying again. ' +\n 'If the response carries phase=insufficient_funds and nextAction=fund_account_or_raise_allowance, the payment cannot be retried until the account is funded or the agent budget raised — stop and tell the user the shortfall reported on the response.',\n },\n payX402OneShot: {\n summary:\n 'Fetch an x402 paid HTTP resource in a single call. Handles the full probe -> pay -> retry round trip and returns the merchant response.',\n selectionGuidance:\n 'Prefer this over the quote+pay split when the agent just wants the paid resource and does not need to inspect the price first. If you already have a quote from haven_quote_x402, use haven_pay_x402_quote instead. Do not use for read-only allowance, budget, spend-limit, remaining-amount, reset-period, or what-can-I-spend questions; use the allowance lookup tool instead.',\n behavior:\n 'Calls the URL, parses any HTTP 402 x402 challenge (or, since #3118, a native-MCP payment-required tool result under HTTP 200), signs the payment locally, then retries the original request with the signed payment header (sent under PAYMENT-SIGNATURE, plus the legacy X-PAYMENT on the EIP-3009 path only) and returns the merchant response. Settlement is either direct account-to-merchant with no funding leg, or a bridge that first redeems the agent\\'s budget delegation to fund the delegate wallet for an EIP-3009 authorization. A payment outside the on-chain budget is declined before any money moves; nothing is queued for a human to approve later. If the resource returns a non-402 status with no payment-required tool result, returns it unchanged without contacting Haven.',\n nextActionGuidance:\n 'Preserve the returned resume_state or paymentId — either identifies this payment if you need to ask about it later. ' +\n 'This tool performs the merchant retry itself, so do not wait on a signal while the call is in flight. ' +\n 'If the process crashes after this call and a later haven_get_payment_status reports nextAction=retry_original_x402_request, Haven\\'s funding leg confirmed but no merchant response was ever recorded — call the resume tool with the preserved resume_state or payment_id instead of paying again. ' +\n 'If the response carries phase=insufficient_funds and nextAction=fund_account_or_raise_allowance, the payment cannot be retried until the account is funded or the agent budget raised — stop and tell the user the shortfall reported on the response.',\n },\n resumeX402: {\n summary:\n 'Resume an x402 payment whose Haven-side authorization already succeeded but whose merchant retry did not complete.',\n behavior:\n 'Accepts either resume_state or payment_id, validates the x402 details against the authorized funding, and retries the merchant request with the signed payment header (PAYMENT-SIGNATURE, plus legacy X-PAYMENT on EIP-3009 only; also params._meta on an MCP tools/call body). No new Haven payment is created.',\n nextActionGuidance:\n 'Only call this after haven_get_payment_status reports nextAction=retry_original_x402_request — that means Haven\\'s funding leg confirmed but no merchant response was ever recorded, most often because the process crashed between funding and the merchant retry. ' +\n 'Any other nextAction reports a conflict instead of retrying, so do not call this speculatively. ' +\n 'Do not start a new merchant session and do not pay again — that would pay twice for one resource.',\n },\n // #1328: quoteMpp / payMpp / resumeMpp (the mpp_demo challenge/quote/resume\n // fragments) are retired along with the client surface they described —\n // MACHINE-PAYMENT-CHALLENGE was never produced by anything besides the now\n // deleted `/demo/mpp/*` route. Use the x402 fragments above instead.\n getPaymentStatus: {\n summary:\n 'Fetch structured Haven payment status for agent recovery.',\n behavior:\n 'State: phase, nextAction, rail, amount, merchant, resource, idempotency, message; parties: treasury/delegate/delegateAccount/merchant. awaiting_settlement_evidence: poll once, else unverified.',\n nextActionGuidance: '',\n },\n getResumeState: {\n summary:\n 'Rehydrate stored x402 resume_state by payment_id.',\n behavior:\n 'Returns the x402 context the agent originally received when the payment was authorized, reconstructed from Haven\\'s database. This is context only; signing still happens locally when a resume tool is called.',\n nextActionGuidance: '',\n },\n getAgent: {\n summary:\n 'Return the authenticated agent identity AND its live spend authority in one call: Haven wallet, delegate, chain, raw status, spend_authority_readiness, per-token remaining allowance (atomic + human-readable). The recommended first call in a new session.',\n selectionGuidance:\n 'Use this as the session bootstrap, or to confirm identity together with whether the agent can spend right now. For per-token detail (configured vs spent vs reset window) use haven_get_allowances.',\n behavior:\n 'Reads identity plus the live spend-authority snapshot — the active on-chain budget delegation. spend_authority_readiness (readiness is a deprecated alias, same value) is \"ready\" when at least one token has remaining spend authority, \"needs_approval\" when the agent is active but has none, and \"revoked\" when the credential is not active. It covers hosted identity + on-chain spend authority ONLY — the hosted server cannot see the LOCAL signer, so \"ready\" does not mean the signer can start; verify the signer with a signer tool call or connect --doctor. An over-budget payment is declined before any money moves; there is no approval queue — ask the owner to grant or raise the budget in Haven. allowances[] carries id, tokenAddress, remainingAtomic, remainingDisplay per token. Identity fields: id, name, status, accountAddress, delegateAddress, chainId.',\n nextActionGuidance: '',\n },\n getAllowances: {\n summary:\n 'Return configured and on-chain allowance state for the authenticated agent. On-chain allowance is the real spend gate.',\n selectionGuidance:\n 'Use this when the user asks about allowance, budget, spend limit, remaining amount, remaining allowance, remaining budget, daily limit, reset period, what can I spend, or what the agent can still spend. For whether the account actually HOLDS funds behind the budget use haven_check_funds.',\n behavior:\n 'Returns the per-token spend authority for the account: the active budget delegation (remaining = the period budget, which re-arms natively at the period boundary), each with id, onchain.remaining, remainingDisplay. An over-budget payment is declined before any money moves; nothing queues. Configured amounts from Haven are returned alongside.',\n nextActionGuidance: '',\n },\n // #3126 — the sufficiency signal, deliberately NOT a balance tool. The\n // constrained actor reads a boolean, never the treasury total.\n checkFunds: {\n summary:\n 'Check whether the agent\\'s account actually holds at least the given amount of a token — funds held, not spend permitted.',\n selectionGuidance:\n 'Use this before attempting a payment when it matters whether the money is really there: allowance answers say what you are PERMITTED to spend, never whether the account HOLDS it. For allowance, budget, spend-limit, remaining-budget, reset-period, or what-can-I-spend questions use the allowance lookup tool instead.',\n behavior:\n 'Returns covered: true (the account holds at least the checked amount), false (a live chain read reports less — the budget is backed by an empty account; stop and tell the user funds are missing), or null (the chain read failed — unverifiable, never treat it as absence; coverageError says why). The account balance itself is deliberately not returned: this is a sufficiency signal, not a balance read. budget_remaining_atomic is the permitted figure from the allowance lookup (the SDK spells it budgetRemainingAtomic), named so it can never be confused with holdings.',\n nextActionGuidance:\n 'On covered=false, do not attempt the payment — tell the user the account is short and let them fund it; on covered=null, retry the check shortly or proceed knowing the payment may fail on-chain.',\n },\n listReceipts: {\n summary:\n 'List machine-payment receipts, newest first, by page.',\n selectionGuidance:\n \"This agent's payment evidence, not the wallet's transaction history (sweeps, funding legs, other agents); use the allowance tool instead for remaining allowance or what-can-I-spend questions.\",\n behavior:\n \"Page { receipts, total, hasMore, nextCursor }; hasMore: pass nextCursor as cursor. parties.treasuryAccount is Haven's authoritative payer. protocolReceiptPayload is the merchant's PAYMENT-RESPONSE relayed verbatim: merchant-controlled, unverified, not Haven's record; payer may differ from payerAddress. Proof header values omitted.\",\n nextActionGuidance: '',\n },\n verifyReceipt: {\n summary:\n 'Verify a payment receipt offline — confirm the agent authorised the transfer.',\n selectionGuidance:\n 'Use this to check a receipt you already hold; it needs no network and does not trust Haven. Use the history tool to fetch receipts in the first place.',\n behavior:\n 'Recovers the signer from the receipt authorisation and confirms it matches the agent delegate. Returns verified true/false with the recovered signer or a reason. Pure and local — no backend call.',\n nextActionGuidance: '',\n },\n payMcpTool: {\n summary:\n 'Call a named tool on an MCP merchant that requires an x402 payment, handling the full initialize → pay → retry round trip in one call.',\n selectionGuidance:\n 'Use this when the agent wants to call a specific tool on an MCP merchant (e.g. Soundside, Coinbase Bazaar) and payment is required. ' +\n 'Prefer this over haven_pay_x402 when you know the merchant_url and tool_name — it builds the JSON-RPC envelope internally. ' +\n 'Use haven_pay_x402 for arbitrary HTTP resources. ' +\n 'Do NOT use for read-only allowance or budget questions — use haven_get_allowances.',\n behavior:\n 'Builds the JSON-RPC tools/call envelope, runs the MCP Streamable-HTTP initialize handshake automatically (if the endpoint is MCP-shaped), ' +\n 'pays any HTTP 402 x402 challenge against the agent\\'s on-chain budget delegation, and retries the request, returning the JSON-RPC result (the actual merchant output) on success. ' +\n 'Amounts within the remaining on-chain budget execute automatically; anything outside it is declined before any money moves — follow the response\\'s nextAction when present.',\n nextActionGuidance:\n 'On a decline, report the reason to the user and ask them to raise the budget in Haven — there is no approval queue to wait on. ' +\n 'This tool retries the merchant itself while it runs, so do not wait on a signal mid-call. ' +\n 'If the process crashes after payment, a later haven_get_payment_status call may report nextAction=retry_original_x402_request — resume via haven_resume_x402_payment instead of paying again.',\n },\n discoverTools: {\n summary:\n 'Step 1 of a purchase: discover payable services from Haven\\'s curated merchant catalog — names, prices, the next call.',\n selectionGuidance:\n 'Use this when the user asks what the agent can buy, pay for, or which paid services exist — or when you need a resource URL for a service the user described. ' +\n 'Use verified=verified for entries Haven watched pass a live quote probe (operator-curated or self-submitted) — domain_verified is the only ownership claim; never treat these badges as proof of merchant honesty, quality, or reliability. ' +\n 'Do NOT use for balance, budget, or spend-limit questions — use haven_get_allowances. ' +\n 'Do NOT use to pay — each returned entry names the next tool to call.',\n behavior:\n 'Use each entry\\'s suggested_tool + suggested_arguments first; an entry without them says why. ' +\n 'Read-only lookup against Haven\\'s curated catalog; entries are periodically re-verified against the live merchant and degraded entries are flagged. ' +\n 'Use category for a case-insensitive category filter (for example, VPN or vpn), or search for a product name, category, or description term. ' +\n 'Returns name, description, price, rail, resource URL, tool_name, tool_arguments, the hint, and the provenance badges source/domain_verified/verified_payable. ' +\n 'The catalog price (price_display/price_atomic, marked price_is_indicative) is a last-verified hint, NOT authoritative — the real price comes from the merchant\\'s live 402 at pay time. ' +\n 'Never creates a payment, signature, or approval.',\n nextActionGuidance:\n 'Call suggested_tool with suggested_arguments VERBATIM (no hint: read suggested_tool_omitted_reason). Confirm the price from the live quote or pay result, not the catalog; if the next tool takes a cap, pass the user\\'s cap as max_amount_human in whole tokens (\"no more than 1 USDC\" → max_amount_human: \"1\"), never atomic units by hand.',\n },\n submitCatalogEntry: {\n summary:\n 'Submit a merchant\\'s payable (x402/MCP) endpoint to Haven\\'s Verified Payable Directory for verification and listing.',\n selectionGuidance:\n 'Use this when a merchant or seller asks to be listed in the directory, or when you have discovered a payable endpoint and want it registered. ' +\n 'The submission is queue-only: it books a spot and returns a verify_token. The seller must then prove control of the domain (a well-known line or DNS TXT record); only after that plus a live quote probe does the entry become listed. ' +\n 'Do NOT use to pay — check the returned status with getCatalogSubmissionStatus instead.',\n behavior:\n 'Sends the https resource_url to Haven\\'s public submission endpoint. The request path makes no outbound request to the merchant. ' +\n 'Returns id + verify_token + status; the verify_token is shown exactly once. Ownership proof is always required later and cannot be skipped from the agent side. ' +\n 'The website field is a honeypot for bots — leave it unset.',\n nextActionGuidance:\n 'Give the verify_token and the well-known instructions (from getCatalogSubmissionStatus) to the merchant so they can publish the proof line, then poll the submission status until it reaches verified_payable or failed.',\n },\n sweep_delegate: {\n summary:\n 'Sweep stranded USDC and/or ETH from the delegate wallet back to the originating account.',\n selectionGuidance:\n 'Use this when the user instructs you to recover stranded funds on the delegate wallet, or when a payment status returns nextAction=sweep_stranded_funds. ' +\n 'Do NOT use for normal payments — use haven_pay_x402. ' +\n 'Do NOT use to read balances only — use haven_get_allowances, or haven_check_funds for whether the account holds funds.',\n behavior:\n 'Reads the delegate EOA\\'s on-chain USDC and ETH balances. For each non-zero balance, signs and submits a transfer from the delegate EOA to the originating account (hardcoded destination). ' +\n 'The delegate key signs locally — Haven never sees it and the backend never constructs signed transactions (CASP/MiCA Red Line #2). ' +\n 'Returns tx hashes and recovered amounts. Returns an empty transfers list when nothing is stranded. ' +\n 'Each transfer carries confirmation: \"confirmed\" (a receipt was seen — the funds are in the account) or \"unconfirmed\" ' +\n '(broadcast but not confirmed within 90 seconds — still in the mempool, may still land). The top-level unconfirmed flag is true when any transfer is unconfirmed.',\n nextActionGuidance:\n 'If transfers is non-empty, confirm the amounts with the user. ' +\n 'Report a transfer as recovered ONLY when its confirmation is \"confirmed\". ' +\n 'For an \"unconfirmed\" transfer, tell the user it was submitted but not yet confirmed, give them its txHash and explorerUrl to check, and do not re-run the sweep immediately — a re-run after it lands will simply find nothing stranded.',\n },\n send: {\n summary:\n 'Send ETH or USDC directly from the agent\\'s Haven wallet to a recipient address.',\n selectionGuidance:\n 'Use this for plain transfers — refunding a user, paying a freelancer, topping up a co-agent\\'s wallet, or moving funds between addresses. ' +\n 'Do NOT use for x402 paid endpoints — use haven_pay_x402 instead. ' +\n 'Do NOT use for read-only allowance, budget, or what-can-I-spend questions — use haven_get_allowances. ' +\n 'Do NOT use to check whether funds are held before sending — use haven_check_funds.',\n behavior:\n 'Sends the amount by redeeming the agent\\'s on-chain budget delegation, account to recipient with no funding leg. ' +\n 'Budget, recipient and expiry are enforced on-chain while the transfer is prepared, so a request outside them is declined before any money moves or any signing — never queued for a human to approve. ' +\n 'The agent\\'s signing key signs the account\\'s typed data; a current signer refuses any that does not match the payment\\'s hash (USEROP_BINDING_MISMATCH), an older signer signs it and the account rejects it on-chain. Haven never receives the key.',\n nextActionGuidance:\n 'On a decline, report the reason to the user and ask them to grant or raise the budget in Haven — there is nothing to poll and no approval will arrive. ' +\n 'After a successful send, poll haven_get_payment_status until nextAction=none.',\n },\n reportSettlementEvidence: {\n summary:\n 'Report an erc7710 payment\\'s real settlement transaction hash so Haven can verify it on-chain and confirm the payment.',\n behavior:\n 'Pass payment_id and settlement_tx_hash (0x + 64 hex chars) — from PAYMENT-RESPONSE or a prior settlement_tx_hash. Haven verifies on-chain before confirming; a zero, mismatched, or reverted hash is refused. Your own payments only.',\n nextActionGuidance:\n 'code DELIVERED_UNSETTLED: did not verify, do not retry — poll haven_get_payment_status. code SETTLEMENT_PENDING (retryable:true): not mined or RPC unreachable — report the same hash again shortly.',\n },\n} as const satisfies Record<string, ToolDescription>\n\nexport type SharedToolKey = keyof typeof toolDescriptions\n","/**\n * Pre-built tool definitions for AI agent frameworks.\n *\n * These definitions describe Haven's direct SDK tool-calling surface in the\n * formats expected by Claude (Anthropic) and OpenAI.\n *\n * The agent payment surface used by these tools is shared with the\n * `@haven_ai/mcp` server — both consume `toolDescriptions` from\n * `./tool-descriptions.ts`. Each consumer composes its own user-visible string\n * from the same semantic fragments, so guidance lands in both surfaces at\n * once and a downstream test asserts the shared summary appears in every\n * consumer description.\n *\n * Usage with Claude:\n * const response = await anthropic.messages.create({\n * tools: havenTools.claude(),\n * ...\n * })\n *\n * Usage with OpenAI:\n * const response = await openai.chat.completions.create({\n * tools: havenTools.openai(),\n * ...\n * })\n */\n\nimport { composeDescription, toolDescriptions as sharedDescriptions } from './tool-descriptions.js'\n\n// ── JSON Schema (shared across formats) ──────────────────────────\n\nconst makePaymentSchema = {\n type: 'object' as const,\n properties: {\n token: {\n type: 'string' as const,\n description: 'Token to send. Gnosis Chain: EURe, USDC.e, xDAI. Base: USDC, ETH.',\n },\n amount: {\n type: 'string' as const,\n description: 'Amount to send as a decimal string, e.g. \"5.00\"',\n },\n to: {\n type: 'string' as const,\n description: 'Recipient Ethereum address (0x...)',\n },\n reason: {\n type: 'string' as const,\n description: 'Brief reason for this payment (for audit trail)',\n },\n },\n required: ['token', 'amount', 'to', 'reason'] as const,\n}\n\nconst getPaymentStatusSchema = {\n type: 'object' as const,\n properties: {\n payment_id: {\n type: 'string' as const,\n description: 'The payment ID returned from make_payment',\n },\n },\n required: ['payment_id'] as const,\n}\n\nconst getAllowancesSchema = {\n type: 'object' as const,\n properties: {},\n required: [] as const,\n}\n\nconst authorizeX402Schema = {\n type: 'object' as const,\n properties: {\n url: {\n type: 'string' as const,\n description: 'The URL that returned HTTP 402',\n },\n payTo: {\n type: 'string' as const,\n description: 'Payment recipient address from the 402 response',\n },\n amount: {\n type: 'string' as const,\n description: 'Payment amount in atomic units (e.g. \"1000000\" for 1 USDC)',\n },\n asset: {\n type: 'string' as const,\n description: 'Token contract address from the 402 response',\n },\n network: {\n type: 'string' as const,\n description: 'CAIP-2 chain ID. \"eip155:100\" for Gnosis Chain, \"eip155:8453\" for Base.',\n },\n description: {\n type: 'string' as const,\n description: 'Description of the resource being paid for',\n },\n idempotencyKey: {\n type: 'string' as const,\n description: 'Stable caller-supplied key for this user intent. Reuse it when resuming the same payment.',\n },\n },\n required: ['url', 'payTo', 'amount', 'asset', 'network'] as const,\n}\n\nconst resumeX402Schema = {\n type: 'object' as const,\n properties: {\n payment_id: {\n type: 'string' as const,\n description: 'The payment ID returned by authorize_x402_payment.',\n },\n url: {\n type: 'string' as const,\n description: 'The original URL that returned HTTP 402.',\n },\n payTo: {\n type: 'string' as const,\n description: 'Payment recipient address from the original 402 response.',\n },\n amount: {\n type: 'string' as const,\n description: 'Payment amount in atomic units from the original 402 response.',\n },\n asset: {\n type: 'string' as const,\n description: 'Token contract address from the original 402 response.',\n },\n network: {\n type: 'string' as const,\n description: 'CAIP-2 chain ID or x402 network from the original 402 response.',\n },\n description: {\n type: 'string' as const,\n description: 'Description of the resource being paid for.',\n },\n idempotencyKey: {\n type: 'string' as const,\n description: 'Stable caller-supplied key used for the original authorization.',\n },\n },\n required: ['payment_id', 'url', 'payTo', 'amount', 'asset', 'network'] as const,\n}\n\nconst MAKE_PAYMENT_DESCRIPTION =\n 'Request and sign a payment from the user-controlled account within its on-chain budget. ' +\n 'For read-only allowance, budget, spend-limit, remaining-amount, or reset-period questions, use get_allowances instead of making a payment. ' +\n 'Haven authenticates the agent and relays the signed transaction that redeems the agent budget delegation; it does not hold keys or control funds. ' +\n 'Gnosis Chain tokens: EURe, USDC.e, xDAI. Base tokens: USDC, ETH.'\n\n// Descriptions are composed from the shared semantic source so the SDK and MCP\n// surfaces stay in lockstep. Each constant prepends the shared `summary` (the\n// stable substring tests assert on) and then appends the SDK-specific guidance\n// for tool-calling consumers.\n\nconst GET_STATUS_DESCRIPTION =\n sharedDescriptions.getPaymentStatus.summary + ' ' +\n 'Accepts payment intent IDs. Returns the current status, phase, next_action, transaction hash if available, and payment details.'\n\nconst GET_ALLOWANCES_DESCRIPTION = composeDescription(sharedDescriptions.getAllowances)\n\nconst AUTHORIZE_X402_DESCRIPTION =\n composeDescription(sharedDescriptions.payX402) + ' ' +\n 'In this SDK tool set, the allowance lookup tool is get_allowances. ' +\n 'When a paid API returns x402 payment requirements, use this tool to sign with the agent-owned delegate key; funding, when the scheme needs it, is redeemed from the agent budget delegation and is bounded by it. ' +\n 'Haven relays signed transactions only; the agent key authorizes payment and on-chain limits enforce spend. ' +\n 'A payment outside the on-chain budget is declined before any money moves — report the decline and ask the user to raise the budget in Haven; do not loop retries and do not wait for an approval, because none is queued. Preserve the original merchant/MCP session and x402 details. ' +\n 'On a manual HTTP retry always set PAYMENT-SIGNATURE (x402 v2) to the returned payment_header; a strict v2 merchant reads only that name. Also set X-PAYMENT (v1) on the EIP-3009 funding path for legacy merchants, but NEVER on erc7710 — that header carries a delegation chain and duplicating it is refused with HTTP 431.'\n\n// #2145: the backend now emits nextAction=retry_original_x402_request from\n// GET /payments/:id (agent-payment-status.ts) when the funding leg confirmed\n// but no merchant response was ever recorded — the crash-recovery case, after\n// a 15-minute grace window. This tool's gate requires that exact nextAction,\n// so it is reachable again on purpose; the description tells an agent to gate\n// on the structured field rather than call this speculatively.\nconst RESUME_X402_DESCRIPTION =\n sharedDescriptions.resumeX402.summary + ' ' +\n 'Only call this after get_payment_status reports nextAction=retry_original_x402_request — that means Haven\\'s funding leg confirmed but no merchant response was ever recorded (typically a crash between funding and the merchant retry). ' +\n 'Any other nextAction reports a conflict instead of retrying — do not call this speculatively, and do not pay again.'\n\nconst SWEEP_DELEGATE_DESCRIPTION = composeDescription(sharedDescriptions.sweep_delegate)\n\nconst sweepDelegateSchema = {\n type: 'object' as const,\n properties: {},\n required: [] as readonly string[],\n}\n\n// ── Claude (Anthropic) format ────────────────────────────────────\n\nexport interface ClaudeTool {\n name: string\n description: string\n input_schema: {\n type: 'object'\n properties: Record<string, unknown>\n required: readonly string[]\n }\n}\n\nfunction claudeTools(): ClaudeTool[] {\n return [\n {\n name: 'make_payment',\n description: MAKE_PAYMENT_DESCRIPTION,\n input_schema: makePaymentSchema,\n },\n {\n name: 'get_payment_status',\n description: GET_STATUS_DESCRIPTION,\n input_schema: getPaymentStatusSchema,\n },\n {\n name: 'get_allowances',\n description: GET_ALLOWANCES_DESCRIPTION,\n input_schema: getAllowancesSchema,\n },\n {\n name: 'authorize_x402_payment',\n description: AUTHORIZE_X402_DESCRIPTION,\n input_schema: authorizeX402Schema,\n },\n {\n name: 'resume_x402_payment',\n description: RESUME_X402_DESCRIPTION,\n input_schema: resumeX402Schema,\n },\n {\n name: 'haven_sweep_delegate',\n description: SWEEP_DELEGATE_DESCRIPTION,\n input_schema: sweepDelegateSchema,\n },\n ]\n}\n\n// ── OpenAI format ────────────────────────────────────────────────\n\nexport interface OpenAITool {\n type: 'function'\n function: {\n name: string\n description: string\n parameters: {\n type: 'object'\n properties: Record<string, unknown>\n required: readonly string[]\n }\n }\n}\n\nfunction openaiTools(): OpenAITool[] {\n return [\n {\n type: 'function',\n function: {\n name: 'make_payment',\n description: MAKE_PAYMENT_DESCRIPTION,\n parameters: makePaymentSchema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'get_payment_status',\n description: GET_STATUS_DESCRIPTION,\n parameters: getPaymentStatusSchema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'get_allowances',\n description: GET_ALLOWANCES_DESCRIPTION,\n parameters: getAllowancesSchema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'authorize_x402_payment',\n description: AUTHORIZE_X402_DESCRIPTION,\n parameters: authorizeX402Schema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'resume_x402_payment',\n description: RESUME_X402_DESCRIPTION,\n parameters: resumeX402Schema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'haven_sweep_delegate',\n description: SWEEP_DELEGATE_DESCRIPTION,\n parameters: sweepDelegateSchema,\n },\n },\n ]\n}\n\n// ── Public API ───────────────────────────────────────────────────\n\nexport const havenTools = {\n /** Tool definitions in Anthropic/Claude format */\n claude: claudeTools,\n\n /** Tool definitions in OpenAI function-calling format */\n openai: openaiTools,\n}\n","/**\n * Agent-facing onboarding guidance — canonical copy (#2523, epic #2519).\n *\n * Two exports, one source:\n *\n * 1. **The shared sentences** — the rules an agent must follow when it runs the\n * connector. They appear in the backend's `setup_prompt`\n * (`routes/agent-connection-setups.ts` `buildSetupPrompt`) AND in the runbook\n * below. Before this file they existed once, inline in the route; the runbook\n * would have been a second copy, and a second copy of a rule is how the two\n * drift into contradicting each other in front of an agent that has no way to\n * tell which is current.\n * 2. **`HAVEN_AGENT_RUNBOOK_MD`** — the runbook served as\n * `packages/frontend/public/for-agents.md`, written to the agent whose user\n * has no Haven account yet. `llms-full.txt`'s quickstart addresses the owner;\n * this addresses the agent, and its job is to say which steps are the human's\n * and exactly what to say at each hand-off.\n *\n * The frontend keeps the runbook as a static file rather than importing it:\n * `packages/frontend` has zero `@haven_ai/*` dependencies by design (standalone\n * Vercel deploys), and `public/` is served as-is. A byte-equality test\n * (`src/lib/__tests__/for-agents-runbook.test.ts`) pins the served file to this\n * string, exactly as `agent-skill-bundle.test.ts` pins the skill.\n *\n * Wording constraints, recorded because they are not stylistic (owner\n * constraints 2026-09-04, and `docs/regulatory/casp-risk-guardrails.md`\n * § Product Copy Rules): the human keeps every signature; there is no headless\n * account path; the runbook must never suggest the agent enters the user's\n * password; the owner-signed budget is what authorises a payment, and Haven\n * constructs and relays.\n */\n\n/** Secret hygiene — the one rule that survives every mode and every runtime. */\nexport const AGENT_SECRET_HYGIENE_SENTENCE =\n 'Do not print private keys, API keys, credential file contents, or config secrets in chat or logs.'\n\n/** Where the signing key is made, and what Haven receives instead of it. */\nexport const AGENT_LOCAL_KEY_SENTENCE =\n 'The Haven connector generates the signing key locally and sends Haven only the public signing address plus proof.'\n\n/** Sandboxed environments: the command does not change, the environment does. */\nexport const AGENT_NETWORK_ACCESS_SENTENCE =\n 'Network access is expected: this command downloads the npm package and contacts the Haven API, so if your environment is sandboxed, run it with network access enabled or request network access escalation; that changes the execution environment, not the command, and is not a third command modification.'\n\n/** #2483: `--json` is a SHOULD addressed to agents, not to a human pasting the command. */\nexport const AGENT_JSON_MODE_SENTENCE =\n 'If you are an AI agent running this command yourself rather than a human pasting it, you should append --json: the connector then emits one machine-readable, secret-free result object on stdout with progress on stderr, and returns promptly instead of blocking while it waits for the budget approval.'\n\n/** #2483: one gate at a time — the approval relay comes before anything else. */\nexport const AGENT_APPROVAL_RELAY_JSON_SENTENCE =\n \"When a --json outcome reports approval.required: true, your first action must be to relay the approval instruction to me in your own reply — if the outcome carries approval.url, give me that link; otherwise tell me to return to Haven and approve this agent's budget — before verifying the connection, restarting anything, or any other step. Never build that link yourself: relay the one the outcome gave you or none at all. Any restart the outcome asks for is a separate instruction to give me afterwards, once the approval is done.\"\n\n/** #2486: the prose-mode twin of the sentence above; each mode relays exactly once. */\nexport const AGENT_APPROVAL_RELAY_PROSE_SENTENCE =\n \"If you ran the command without --json, the connector waits for the approval itself and prints its next steps when it finishes: relay the budget-approval instruction to me — the approval link if those steps printed one, otherwise that you need to return to Haven and approve this agent's budget — only if those printed next steps still ask for it. If they report the budget as already approved, there is nothing for me to approve.\"\n\n/**\n * #2551, handed to #2528 by PR #2567 so a third writer would not land on the\n * money-path prompt file for one line.\n *\n * The connector's `wiring_collision` refusal is the THIRD case where the agent\n * owes its user a decision rather than an action of its own — beside\n * `approval.required` and the runtime-refusal retry. Named explicitly because\n * the other two are, and an unnamed relay case is one an agent resolves by\n * guessing: here it would guess `--replace` (silently displacing a working\n * agent) or `--name` (quietly wiring a second one). Both are the user's call.\n */\nexport const AGENT_WIRING_COLLISION_RELAY_SENTENCE =\n 'If the connector refuses with wiring_collision, this machine is already wired to a different agent: relay that refusal to me with the superseded_agent_ids and suggested_name it carries, and let me choose whether to replace the existing wiring or add this agent alongside it. Never pick for me by adding --replace or --name yourself.'\n\n/** #1719: exactly two permitted changes, and the second is bounded by the refusal's own list. */\nexport const AGENT_COMMAND_MODIFICATION_SENTENCE =\n 'Only two changes to the command above are permitted, and no others: appending --json, and — only if the connector refuses because it could not determine the agent runtime — re-running it once with --runtime <name> added, naming the harness you are running in, using one of the values that refusal lists. Never invent a runtime name and never change anything else.'\n\n/**\n * The agent-facing section every published README carries (#2533, A6).\n *\n * ONE string, six copies, one instrument. All five npm READMEs plus the repo\n * README open with dashboard-first instructions, which strand the reader this\n * epic exists for: an agent whose user has no account yet. This is the entry\n * that redirects them, and it is defined here rather than written six times\n * because six hand-maintained copies is exactly the drift #2310 was about —\n * `agent-guidance.test.ts` fails if any copy differs by a byte.\n *\n * TWO links, and the second is not redundant. The path is correct wherever\n * Haven is actually served and needs no host we do not own (#2520's rule); the\n * GitHub URL is the one that resolves for a reader on npmjs.com, who has no\n * origin to resolve a path against. A path alone would be unfollowable in the\n * place these READMEs are most often read; an absolute app host alone would be\n * a host nobody owns. Naming both is the honest answer, and the runbook itself\n * is committed at that path, so the fallback is a real file rather than a\n * promise.\n *\n * Interrogative, not declarative-with-a-question-mark. `llms.txt` states the\n * same idea declaratively because there it is a LINK TITLE in a list; an H2\n * whose job is to catch the right reader and let everyone else skip is a\n * question. The mismatched mood was a haven-design-reviewer finding, fixed\n * while it was cheap: the string is byte-pinned in six files, so the cost of\n * changing it only ever goes up.\n *\n * It says what the agent CANNOT do first. The account and the passkey are the\n * user's, always — stating that up front is what stops an agent trying, and it\n * is the epic invariant no slice may weaken.\n */\nexport const AGENT_README_SECTION_MD = `## Are you an AI agent whose user has no Haven account yet?\n\nRead **\\`/for-agents.md\\`** on the Haven host your user gave you — or\n[the copy in this repository](https://github.com/d-hinders/Haven-AI/blob/dev/packages/frontend/public/for-agents.md)\nif you do not have that host yet.\n\nYour user creates the account and the passkey: those are theirs, they need a\nhuman, and you should never ask for their password. You can do everything else\n— including running the connector command from the setup prompt they paste you,\nand managing the account from the shell with \\`@haven_ai/cli\\`.`\n\n/**\n * The runbook, served at `/for-agents.md`.\n *\n * Every link is a same-origin path (#2520): resolve it against the host the\n * file was fetched from. The npm dist-tags are the placeholder `<channel>`\n * rather than literals — the connector's command and, since #2617, the CLI's\n * login in step 1 — for two reasons that point the same way: a published\n * package must not hard-code one (#2423, guarded by\n * `scripts/release-bump.test.mjs`), and this string is committed as a static\n * file, so baking in a channel `release-bump.mjs` later rewrites would put the\n * served copy out of parity at exactly the moment nobody is reading it. The\n * page tells the agent to run the command its setup prompt hands it, where the\n * tag is real and deployment-correct, and to read the CLI's tag from\n * `/.well-known/haven.json` (`packages.cli.channel`).\n *\n * The budget-approval hand-off is now a LINK when the connector has one, and a\n * tab when it does not — #2528 landed the half of this that was missing.\n * `ConnectOutcome` (`packages/connect/src/runtime.ts`) carries\n * `approval: { required, expires_at, url? }`; `url` is the same-origin\n * `approval_url` the register response returns, so the agent relays a\n * destination instead of \"return to Haven\".\n *\n * The step-5 hand-off is TWO blockquotes, not one with the alternative in\n * brackets. It was the bracket form briefly, to save ~110 bytes against the\n * size ceiling, and haven-design-reviewer was right to push back: this\n * section's own header says \"Send these as your own message\", so every other\n * script in it is paste-ready. A bracketed either/or inside the quote makes\n * the agent perform text surgery on something presented as copyable — and a\n * naive relay ships the raw brackets to the human, which reads as broken\n * rather than as a choice. Two quotes cost bytes and buy back the property\n * the section is built on. Do not re-compress this to save them.\n *\n * `AGENT_WIRING_COLLISION_RELAY_SENTENCE` is deliberately NOT in this page's\n * rule list, though it IS in the setup prompt (#2551 via #2567). This page's\n * list is already a curated subset of the prompt's — it omits the network and\n * local-key sentences and adds the prose-relay one — and a collision can only\n * happen to an agent that is running the connector, which means it is holding\n * the prompt, where the sentence is. Repeating it here would cost every agent\n * that fetches this page bytes for a rule it will be handed at the moment it\n * applies.\n *\n * TWO limits, stated because the copy below depends on both. First, `url` is\n * OPTIONAL and its absence is normal: a backend older than #2528 sends none,\n * and `approval.required: false` carries none because there is nothing to\n * approve — so every sentence here has to work with and without it, which is\n * why they read \"if the outcome carries a link\". Second, the outcome still has\n * NO setup id: #2528 added the link only, and the connector's own status poll\n * (`GET /:setupId/connector-status`) still answers `{ status, approved_budget }`.\n * An agent must not construct an approval URL out of parts — it has the whole\n * one or it has none. `?next=` / `?via=agent` / `?setup=` are the hand-off\n * link shapes from #2522.\n */\nexport const HAVEN_AGENT_RUNBOOK_MD = `# Haven for agents — set your user up to let you pay\n\nYou are an AI agent whose user has no Haven account yet, or has one but has not connected you.\n\n> Links below are paths on this same host: resolve them against the URL you fetched this file from.\n\n## What Haven is, in three sentences\n\nYour user gives you a **budget on their own account** — not their wallet, and not a key to their funds. The budget is a delegation they sign, enforced on-chain: a payment over it, to the wrong recipient, or past its expiry is refused at execution time, not by a dashboard promise. Haven constructs and relays the payments; you get an agent credential and a signing key made on your machine, and your user can revoke the budget without you and without Haven.\n\n## The sequence\n\nFour of the six steps are your user's — each needs a human signature or a human decision. The rest is yours. If they already have a funded account, start at step 3.\n\n1. **HUMAN — create the account.** Name, email, password, then a passkey (Face ID / Touch ID) or a wallet. Never offer to enter any of it: you must not have their password, and the passkey is bound to their device. With a terminal, \\`npx @haven_ai/cli@<channel> login --api <api-url>\\` afterwards gets you a scoped session for steps 3-4 (that flag or \\`HAVEN_API_URL\\`, on the first command — the session then remembers the backend; **the CLI's built-in default is Haven's hosted production backend**, so on any other deployment an omitted flag connects you somewhere real and wrong rather than failing) — they approve a code in the browser, you never hold their password. The \\`<channel>\\` in that command is the tag your deployment names — read it from \\`/.well-known/haven.json\\` (\\`packages.cli.channel\\`), never a tag you pick. Do not hold the process open while you wait: under \\`--json\\`, pass \\`--no-wait\\` to get the link object back at once, then poll it with \\`haven login --poll <device_code>\\` — one round per invocation, exit 3 while it is still pending, 0 once approved. It can set up agents and read the account; it cannot sign, approve a budget, move funds, or rotate any agent's keys.\n2. **HUMAN — fund it.** USDC only, no ETH: Haven sponsors the gas. \\`/.well-known/haven.json\\` names \\`chains.default\\` as the deployment's expected chain, but after login \\`haven wallets funding\\` prints the address, the amount and which chain in one place; confirm that chain before you message your user. Without a CLI session, the dashboard's funding card shows the address and amount and its Receive-funds screen names the chain; never assume one: a testnet deployment and production both call themselves Haven. Before you write that message, read the manifest: \\`environment\\` says whether this deployment is \\`production\\`, and each \\`chains.supported\\` entry says whether that chain is a \\`testnet\\`. Real money is at stake only on a non-testnet chain of a \\`production\\` deployment — tell your user which case theirs is.\n3. **HUMAN — create the agent, set its budget**, and paste you the **setup prompt** it hands back. With a CLI session (step 1) you can do this step yourself: \\`haven agents connect --name <n> --budget <amount> --token USDC --period <minutes>\\` prints the same connector command and approval link; add \\`--run\\` to do step 4 too.\n4. **YOU — run the connector command** in that prompt (below). It makes your signing key locally, registering only the public address.\n5. **HUMAN — approve the budget** with their passkey, in the Haven tab they created the agent in: it advances to the approval step by itself once your run registers.\n6. **YOU — verify, then pay.**\n\n## Budget changes later (second token, raise, revoke)\n\nThe first budget rides the setup above. After the agent exists, a CLI session can construct the LATER changes — a second token, a bigger amount, a recipient pin, a stop — and hand your user a link; the human still signs, every time:\n\n\\`\\`\\`\nhaven budget grant <agentId> --amount <n> --token USDC --period <minutes> [--recipient <address>] [--wait]\nhaven budget revoke <agentId> <delegationHash> [--wait]\n\\`\\`\\`\n\nThe CLI never signs: it prints a dashboard link, your user opens it and signs with their passkey or wallet. \\`--wait\\` polls until the human's signature lands. The hash for \\`revoke\\` is in \\`haven agents show <agentId>\\`.\n\n## Hand-off scripts\n\nSend these as your own message, \\`<host>\\` replaced by the host you fetched this file from. Say what you cannot do, not only what they must.\n\n**Before signup** (step 1):\n\n> I can do everything except the parts that need your signature. Please open \\`<host>/signup?next=/agents&via=agent\\` — name, email, password, then a passkey (Face ID / Touch ID) or a wallet. That is your account's key: I should not have it, and I will never ask for your password. Already have one? \\`<host>/login?next=/agents\\`.\n\n**At the passkey step:**\n\n> The passkey must be made on your own device — it is what keeps the account yours, so nobody, Haven included, can move your funds without you. If this browser cannot, open \\`<host>/onboarding?next=/agents\\` on your phone and finish there.\n\n**At funding** (step 2):\n\n> Your Haven account needs USDC before I can pay for anything — USDC only, no ETH: Haven sponsors the gas. Before you send anything, let me get you the exact address **and network** — \\`haven wallets funding\\` prints both, and the funding card on \\`<host>/dashboard\\` shows the same. Please do not send to an address or a chain I have not confirmed with you; a small amount first is fine.\n\n**At the budget** (step 3):\n\n> On \\`<host>/agents\\`, create an agent for me and set a budget — say 25 USDC per day. That is the limit I cannot exceed. It hands back a setup prompt: paste it to me and I run it here.\n\n**At budget approval** (step 5) — the moment your run reports that approval is required, before anything else. Send the first if your run carried \\`approval.url\\`, the second if it did not.\n\n> Setup is done on my side. Approve the budget here: <approval.url>. Approve it with your passkey; nothing can be spent until you do.\n\n> Setup is done on my side. Go back to the Haven tab where you created the agent — it should now be asking you to approve the budget. Approve it with your passkey; nothing can be spent until you do.\n\n## What you run\n\nThe setup prompt carries a **connector command** shaped like this:\n\n\\`\\`\\`\nnpx -y @haven_ai/connect@<channel> --setup EXAMPLE-SETUP-TOKEN-NOT-REAL --api <api-url> --ack-local-tools\n\\`\\`\\`\n\nRun the prompt's version, not this one: the token is one-time, the API URL is the backend's own, and \\`<channel>\\` is the npm tag your prompt names — never a tag you pick. The rules below come from that prompt, so \"me\" in them is your user, not Haven.\n\n- ${AGENT_JSON_MODE_SENTENCE}\n- ${AGENT_APPROVAL_RELAY_JSON_SENTENCE}\n- ${AGENT_APPROVAL_RELAY_PROSE_SENTENCE}\n- ${AGENT_COMMAND_MODIFICATION_SENTENCE}\n- ${AGENT_SECRET_HYGIENE_SENTENCE}\n\nIf the approval wait times out, nothing is lost — your agent is registered and the budget is still waiting to be approved. Send your user the \\`approval.url\\` your run reported, or, if it carried none, ask them to finish it in that same Haven tab. The outcome carries no setup id, so never assemble an approval link out of parts — relay the whole one it gave you or none at all.\n\n## How to verify\n\nCall \\`haven_get_agent\\`, one of the Haven MCP tools the connector wires into your runtime in step 4. It returns identity plus \\`spend_authority_readiness\\`:\n\n- \\`ready\\` — a budget is live; you can pay.\n- \\`needs_approval\\` — the connector finished, nobody approved yet. Ask your user again, in their Haven tab; there is no queue to wait in.\n- \\`revoked\\` — the credential is not active; ask your user to create a new agent.\n\n\\`ready\\` covers hosted identity and the budget only, not your local signer. Check that with \\`npx -y @haven_ai/connect@<channel> --doctor\\`, the same tag your prompt named — a separate command, so the two-changes rule does not bind it.\n\n## If you cannot open a browser\n\nNothing here needs you to. Steps 1-3 are links: hand your user the full \\`<host>/…\\` URL and ask them to say when it is done. Step 5 is a link only when your run reported one in \\`approval.url\\` — otherwise it is the tab they already have open, as above. Then poll \\`haven_get_agent\\` until it reads \\`ready\\`. Do not route around the sign-in wall — it makes the account theirs, not yours.\n\n## If something breaks\n\nIf a Haven result carries \\`client_update\\`, that client is out of date: update it — \\`upgrade_command\\` names the package and channel — then retry. \\`required: true\\` means payments are refused until you do. What changed: [/releases](/releases).\n\n## Vocabulary\n\n| Term | What it is |\n|---|---|\n| **setup prompt** | The text the dashboard hands your user to paste to you. Carries the command and its rules. |\n| **connector command** | The \\`npx -y @haven_ai/connect@…\\` line you run. One-time token, one use. |\n| **agent credential** | Your API key (\\`sk_agent_…\\`), written to \\`~/.haven\\`. It identifies you; alone it cannot move money. |\n| **delegate key** | Your signing key, made on this machine and never sent anywhere. |\n| **budget** | The on-chain delegation your user signed. It authorises the payment; Haven constructs and relays it. |\n\nNext: [your agent hit a 402](/402.md) · [everything agent-readable](/llms.txt)\n`\n\n/**\n * The **onboarding prompt** — the whole-onboarding text the dashboard offers a\n * signed-in user to paste to their agent (#2535, epic #2519).\n *\n * ## It is NOT the \"setup prompt\", and the distinction is load-bearing\n *\n * `setup prompt` is one of the four canonical agent-facing terms\n * (`docs/product/copy-guidelines.md` § Agent-facing vocabulary, settled by\n * #2533 and swept by #2576): it names the text the CONNECT MODAL hands back,\n * which carries a one-time setup token and the connector command. This string\n * is a different object with a different lifetime — it exists before any setup\n * does, contains no token and no secret, and is therefore safe to render to a\n * signed-in user who has not created an agent yet. Calling both \"the setup\n * prompt\" would undo the disambiguation those two issues paid for, so this one\n * is the **onboarding prompt** wherever it is named.\n *\n * ## Why a shared export rather than a route\n *\n * The issue offered `GET /agent-connection-setups/agent-prompt` or a static\n * export. The export wins on cost and on the #2523 precedent: no new route, no\n * auth question, and no `owner_cli` allow-list entry — and the allow-list is\n * fail-closed by design, so every entry is a decision. The route would only\n * earn those three if the prompt had to vary per user, and it deliberately does\n * not: it names commands and links, never account state.\n *\n * ## What keeps it from drifting from the setup prompt\n *\n * The two are built from the SAME sentence constants above — this one reuses\n * the approval-relay and secret-hygiene rules verbatim rather than paraphrasing\n * them, which is the whole reason those constants exist. A test asserts that\n * containment, so a reworded copy here fails rather than quietly disagreeing\n * with what `buildSetupPrompt` tells the same agent minutes later.\n *\n * The frontend cannot import this: `packages/frontend` has zero `@haven_ai/*`\n * runtime dependencies by design (standalone Vercel deploys). It keeps a copy\n * in `src/lib/agent-onboarding-prompt.ts`, byte-pinned to this string by\n * `src/lib/__tests__/agent-onboarding-prompt.test.ts`, exactly as the runbook\n * and the skill are pinned.\n *\n * ## The origin placeholder\n *\n * `{{HAVEN_ORIGIN}}` is substituted by the renderer with the host the user is\n * actually signed in to, so dev, preview and production each produce a truthful\n * prompt from one string. It is a placeholder rather than a build-time constant\n * for the same reason `<channel>` is one in the runbook: this text is committed,\n * and a baked host is wrong everywhere except where it was baked.\n *\n * ## Wording constraints (same as the runbook's, and not stylistic)\n *\n * The human keeps every signature; there is no headless account path; it must\n * never suggest the agent enters the user's password; the owner-signed budget\n * is what authorises a payment, and Haven constructs and relays. Every command\n * it names exists at merge time — `haven login` (#2526) and\n * `haven agents connect` (#2527) both landed before this shipped, which is the\n * condition #2535 made blocking.\n */\nexport const AGENT_ONBOARDING_PROMPT = `I have a Haven account and I am signed in at {{HAVEN_ORIGIN}}. Please set up Haven so you can pay for things within a budget I approve.\n\nStart by reading {{HAVEN_ORIGIN}}/for-agents.md — it is written for you and explains which steps are mine.\n\nThen:\n\n1. Run \\`npx @haven_ai/cli@<channel> login\\`. The \\`<channel>\\` in that command is the tag your deployment names — read it from \\`/.well-known/haven.json\\` (\\`packages.cli.channel\\`), never a tag you pick. It prints a link and a code and does not need my password — it must never ask for it. Give me the link straight away and wait for me to approve it in my browser.\n2. Once I have approved, run \\`haven agents connect --name <a name you choose> --budget <amount> --token USDC --period <minutes>\\` with the budget I tell you. If I have not given you one, ask me before running it. Add \\`--run\\` to complete the connection in the same step.\n3. ${AGENT_APPROVAL_RELAY_JSON_SENTENCE}\n4. Once I have approved the budget, verify with the \\`haven_get_agent\\` tool: \\`ready\\` means you can pay, \\`needs_approval\\` means my approval has not landed yet.\n\nTwo things only I can do: approving that budget with my passkey, and funding the account with USDC on Base — no ETH, Haven sponsors the gas. Tell me if either is missing rather than working around it.\n\n${AGENT_SECRET_HYGIENE_SENTENCE}`\n","import {\n AGENT_APPROVAL_RELAY_JSON_SENTENCE,\n AGENT_COMMAND_MODIFICATION_SENTENCE,\n AGENT_SECRET_HYGIENE_SENTENCE,\n AGENT_WIRING_COLLISION_RELAY_SENTENCE,\n} from './agent-guidance.js'\n\n/**\n * The generic Haven payment skill — canonical copy.\n *\n * This SDK file is the single source of truth for the generic, secret-free\n * skill content: no wallet address, no budget numbers, no per-agent values.\n * The agent learns its live budget at runtime via the `haven_get_agent` /\n * `haven_get_allowances` MCP tools, and can read identity + configured budget\n * for fast first-turn orientation from the non-secret `agent.json` the\n * connector writes (see `packages/connect/src/storage.ts`), so the same file\n * works for every user. `packages/connect` imports this directly to\n * auto-install the skill into runtime skills folders.\n *\n * `packages/frontend/src/lib/agent-skill-bundle.ts` keeps a deliberately\n * decoupled inline copy (the download fallback): the frontend does not depend\n * on the SDK, so it can deploy standalone on Vercel without an unpublished\n * export. It is NOT `@haven_ai/*`-free — it takes `@haven_ai/core` with the\n * `\"*\"` workspace pin — and this comment said otherwise until #2537 checked\n * the manifest; the material point is the one that survives, and it is about\n * the SDK specifically. A parity test in that package's test suite imports\n * this canonical string and asserts byte-for-byte equality, so the two copies\n * cannot drift.\n *\n * **The onboarding section (#2537) is COMPOSED, not written here.** Its rule\n * sentences are interpolated from `agent-guidance.ts`, which is also where the\n * backend's setup prompt and the `/for-agents.md` runbook get them: a rule an\n * agent meets twice must be one text, or the two copies drift into\n * contradicting each other in front of a reader with no way to tell which is\n * current. The prose around them is skill-only and lives here.\n *\n * **Those three bullets are quoted in the setup prompt's own voice**, where\n * the USER is speaking: \"me\"/\"I\" are the user, and \"the command above\" is the\n * connector command printed directly above them there — neither of which\n * holds in this file, which addresses the agent throughout and prints no\n * command. Any future user-voice quote here needs the same two-referent\n * gloss, and it must sit BEFORE the quote rather than after: the first draft\n * put it after, and both the reviewer and the design reviewer independently\n * found that an agent reading top-to-bottom meets `relay ... to me` before\n * it learns whose \"me\" that is — on the one instruction the section itself\n * calls the highest-priority one. `AGENT_APPROVAL_RELAY_PROSE_SENTENCE` is a\n * live sibling constant not pulled in here; if it ever is, this applies to it\n * too (design review, #2537).\n */\n\nexport const HAVEN_SKILL_MD = `---\nname: haven-pay\ndescription: Pay for things from the user's Haven wallet within their agent rules, and set Haven up when it is not yet connected. Use when the user asks to send, pay, tip, or transfer crypto; when a request hits an HTTP 402 (x402) paywall; or when they ask to create a Haven account, create an agent, or connect one.\n---\n\n# Haven: pay from a Haven wallet\n\nThis skill lets the agent make payments from the user's Haven wallet through\nthe Haven MCP tools. Every payment is checked against the agent's on-chain\nbudget before money moves; a payment above the remaining budget is declined —\nnothing is paid past the rules the user set.\n\nHosted tools run in the \\`mcp__haven__\\` namespace. Local signing tools run in\nthe \\`mcp__haven-signer__\\` namespace and keep the delegate key on this machine.\nThat namespacing is Claude-family; other runtimes name the servers by their\nown config keys (Codex: \\`haven\\`, \\`haven_signer\\`). Tool results carry the\nexact next step (\\`next_action\\`, \\`next_tool\\`, \\`next_arguments\\`, plus the\nruntime-neutral \\`next_tool_server\\` + \\`next_tool_name\\` + \\`next_tool_server_role\\`\n— the bare tool name on that logical server, whatever your runtime calls it).\nWhen no tool follows, \\`next_tool\\` is absent and \\`next_tool_omitted_reason\\`\nsays why; that is a complete answer.\nFollow those fields first; the prose below is fallback and orientation, not\nthe source of truth.\n\n## When to use this skill\n\n- The user asks to send money, pay someone, tip, donate, or transfer tokens.\n- A request returns HTTP 402 (x402): use the Haven pay tools to settle it,\n then retry the original request.\n\n## Onboarding and setup\n\nYou are in this mode when there is no Haven agent credential on this machine,\nor when your user asks you to create a Haven account, create an agent, or\nconnect one — for themselves or for someone else.\n\n**None of the tools below creates authority.** They spend a budget a human\nalready signed. There is no tool here that opens an account, mints a\ncredential, or approves a budget, so reaching for one of them to \"set Haven\nup\" cannot work; the steps are the ones in this section instead.\n\nStart by reading \\`/for-agents.md\\` on the Haven host — the origin of the\n\\`api_url\\` in your \\`agent.json\\` if you have one, otherwise the host your user\nnames. It is the full runbook: six steps, which four are your user's, and what\nto say at each hand-off.\n\nTwo of those steps you can do yourself, from the shell with \\`@haven_ai/cli\\`\n(installs the \\`haven\\` command):\n\n- \\`haven login\\` — a device-code browser flow. It prints a code and a link\n for your user to approve, so you never see or ask for their password. What\n the session can reach is an allow-list, not your user's full authority: it\n creates and manages agents and reads the account, and it cannot approve a\n budget, rotate a key, change a signer or move money — those are your user's.\n- \\`haven agents connect\\` with \\`--name\\`, \\`--budget\\`, \\`--token\\` and\n \\`--period\\` — creates a connection setup and prints two things: the\n connector command the backend built, and the approval link to give your user.\n Add \\`--run\\` to execute that command here as a child process.\n- \\`haven wallets funding\\` — prints the paste-ready funding instruction: what\n to send, to which address, on which chain. Read the chain from there rather\n than assuming one. \\`--wait\\` polls until the account counts as funded.\n\n**Four steps are your user's, and each one needs a human:** create the account\nand its passkey, fund the wallet, approve every agent's budget, and rotate a\ncredential. You can compose the funding message for them with\n\\`haven wallets funding\\`, but you cannot send the money — that transfer is\ntheirs, from a wallet you have no access to.\n\nRunning the connector command is the step that wires this machine to the new\nagent — the command \\`haven agents connect\\` printed, or the one your user\npasted you from the dashboard. Three rules bind you while you do it, quoted\nunchanged from the setup prompt your user is also holding so the two copies\ncannot drift into contradicting each other. They are written in your user's\nvoice, so read them accordingly: \"me\" and \"I\" below are your user, never\nHaven, and \"the command above\" is that connector command, not anything printed\nin this file. The first rule outranks anything else you were about to do next:\n\n- ${AGENT_APPROVAL_RELAY_JSON_SENTENCE}\n- ${AGENT_COMMAND_MODIFICATION_SENTENCE}\n- ${AGENT_WIRING_COLLISION_RELAY_SENTENCE}\n\n${AGENT_SECRET_HYGIENE_SENTENCE}\n\n## Identity and budget\n\nDo not guess the wallet address, network, or budget.\n\nFor instant orientation at the start of a session, read the non-secret\n\\`agent.json\\` the connector wrote to your Haven credential directory (typically\n\\`~/.haven/agents/<agent-id>/agent.json\\` — if you don't know the agent id, list\n\\`~/.haven/agents/\\` to find the folder). It\nholds your agent id, Haven wallet address, network, and *configured* per-token\nbudget, and contains no keys — the fastest way to answer \"who am I and what may\nI spend\" with no round trip. If that file is absent (some setups don't write\nit), use the tools below instead.\n\nBefore any payment, confirm the *live remaining* budget with the tools —\n\\`agent.json\\` shows the configured budget, not what is left after recent\nspending:\n\n- \\`mcp__haven__haven_get_agent\\` — the recommended first call: identity\n (wallet, network) plus \\`spend_authority_readiness\\` (\\`ready\\` / \\`needs_approval\\` /\n \\`revoked\\`) and live remaining per-token allowance, in one shot. That signal\n covers hosted identity and on-chain spend authority only — it cannot see the\n local signer; the signer is verified by calling any signer tool.\n- \\`mcp__haven__haven_get_allowances\\` — detailed per-token breakdown\n (configured, spent, reset window) when you need more than the summary.\n- \\`mcp__haven__haven_check_funds\\` — whether the account actually HOLDS at\n least a given amount of a token. Allowance answers above say what you are\n permitted to spend; this one says whether the money is really there,\n answered as \\`covered\\` true/false/null — never as a balance. On\n \\`covered: false\\`, stop and tell the user the account is short; on\n \\`covered: null\\` (the chain read failed), treat it as unverifiable rather\n than as absence.\n\nBudgets reset on a period the user chose. If a payment exceeds the remaining\nbudget it is declined before any money moves — tell the user; they can raise\nthe budget in the Haven dashboard, or wait for the period reset.\n\n## Paying\n\n**Catalog purchases — the primary path for MCP merchants:**\n\n1. \\`mcp__haven__haven_discover_tools\\` to find a payable service and its\n \\`catalog_id\\`.\n2. If the user needs the live price before authorizing a cap, call\n \\`mcp__haven__haven_quote_catalog_purchase\\` with \\`catalog_id\\`. It is\n read-only and informational only: it never reserves a price or creates a\n payment. Tell the user its \\`amount\\` / \\`amount_atomic\\`, then choose a cap.\n3. \\`mcp__haven__haven_prepare_catalog_purchase\\` with \\`catalog_id\\` and a\n spending cap. A cap is REQUIRED on this tool and is best practice on every\n paid call below too — it caps what the LIVE merchant quote may charge,\n checked before any funding intent is created. Write it the way the user\n said it: \\`max_amount_human\\` is whole tokens, so \"no more than 1 USDC\" is\n \\`max_amount_human: \"1\"\\`. (\\`max_amount\\` is the atomic-unit form, where\n \"1\" means 0.000001 USDC — do not convert by hand, and never send both.)\n4. Then FOLLOW THE RESPONSE'S GUIDANCE FIELDS: \\`next_action\\`, \\`next_tool\\`,\n and \\`next_arguments\\` name the exact next call — act on those first; the\n prose in this section is fallback and debugging detail. If the catalog\n entry is missing or degraded, the response instead names\n \\`mcp__haven__haven_pay_mcp_tool\\` (merchant URL, tool name, arguments) as\n the manual fallback.\n\n**Signing:** \\`mcp__haven-signer__haven_sign_x402\\` with \\`payment_id\\` ONLY —\nthe local signer fetches the exact signing bytes AND \\`payment_required\\`\nitself, so never relay \\`typed_data\\` or the 402 blob yourself. If the signer\nreports its fetched context carried no \\`payment_required\\` (older backend),\nre-call with \\`payment_required\\` added verbatim. Fallback for an older signer\nor backend: re-run the quote/prepare tool with the SAME \\`idempotency_key\\`\nplus \\`include_signing_payload=true\\`, then pass \\`payload_hash\\`,\n\\`x402_expected\\` (the nested \\`x402.expected\\` object), and\n\\`typed_data\\`/\\`typed_data_b64\\` through unchanged.\n\n**Settle:** \\`mcp__haven__haven_settle_mcp_tool\\` with \\`payment_id\\`,\n\\`signature\\`, and \\`payment_header\\` ONLY — Haven rehydrates the merchant call\ncontext (\\`merchant_url\\`, \\`tool_name\\`, \\`arguments\\`, \\`mcp_transport\\`)\nserver-side from \\`payment_id\\`. Pass those four fields explicitly only as a\nversion-skew fallback when Haven has no stored context for the id — both or\nnone together, never just one. If the settle result carries \\`settled: false\\`,\nfunding has not confirmed — follow the result's guidance fields and check\nstatus later, do not re-pay.\n\nStep-by-step alternative (also key-safe; for an older signer or backend, or\nwhen you already have a merchant URL and tool name instead of a\n\\`catalog_id\\`): if the user needs the live price before choosing a cap, first\ncall \\`mcp__haven__haven_quote_mcp_tool\\` with that merchant URL, tool name,\nand arguments. It is informational only; then call\n\\`mcp__haven__haven_pay_mcp_tool\\` with the same inputs and the explicit cap.\nThe paid call always obtains a fresh quote before it creates any intent. Then\ncontinue \\`mcp__haven__haven_pay_mcp_tool\\` →\n\\`mcp__haven-signer__haven_sign\\` → \\`mcp__haven__haven_submit\\` →\n\\`mcp__haven-signer__haven_x402_sign_header\\` →\n\\`mcp__haven__haven_complete_mcp_tool\\`. Call that last step with\n\\`payment_id\\` and the signer's \\`payment_header\\` ONLY. It does not take\n\\`payment_required\\`: Haven rehydrates the merchant call context\n(\\`merchant_url\\`, \\`tool_name\\`, \\`arguments\\`, \\`mcp_transport\\`) and the\n402 server-side from \\`payment_id\\`, exactly as at settle. Pass that context\nexplicitly only as a version-skew fallback when Haven has no stored context\nfor the id — \\`merchant_url\\` and \\`tool_name\\` both or none together, never\njust one.\nThe returned \\`expires_at\\` is the signing window; if a tool returns\n\\`PAYMENT_WINDOW_EXPIRED\\`, re-run the same quote/prepare tool with the same\n\\`idempotency_key\\`. Do not call the merchant yourself — Haven completes the\nmerchant leg for you.\n\n**Direct transfer / non-MCP paywall:** \\`mcp__haven__haven_pay\\` with\n\\`to\\`, \\`amount\\`, and \\`token\\` for a plain transfer. For an arbitrary,\nnon-MCP x402 paywall: \\`mcp__haven__haven_quote_x402\\` to get a quote, then\n\\`mcp__haven__haven_pay_x402_quote\\` — follow the result's guidance fields\nfirst and sign in the local Haven signer. On THIS path Haven does not talk to\nthe merchant: \\`mcp__haven-signer__haven_sign_x402\\` returns both\n\\`signature\\` and \\`payment_header\\`; relay \\`signature\\` with\n\\`mcp__haven__haven_submit\\`, then retry the paywalled URL yourself with\n\\`payment_header\\`. Do not pass that call's \\`x402_binding\\` to\n\\`mcp__haven-signer__haven_x402_sign_header\\` — the one-shot already spent it\nbuilding the header, so the call can only refuse. Then tell Haven what the\nmerchant answered: \\`mcp__haven__haven_report_x402_outcome\\` with the\n\\`payment_id\\`, \\`outcome\\` (\\`\"accepted\"\\` for a 2xx, else \\`\"rejected\"\\`)\nand the \\`merchant_status\\` you got. Because Haven never contacted that\nmerchant, this is the only way it can learn the purchase failed — without it a\nfailed purchase reads as complete for fifteen minutes. (The SDK's own\n\\`haven_pay_x402\\` tool does perform the merchant retry itself; that tool is\nnot part of the hosted MCP surface.) If the process\ncrashes after payment, a later \\`mcp__haven__haven_get_payment_status\\` call\nmay report \\`nextAction: 'retry_original_x402_request'\\` — only then call\n\\`mcp__haven__haven_resume_x402_payment\\` with the preserved resume state or\npayment id, instead of paying again.\n\n**Catalog tool arguments:** when \\`haven_discover_tools\\` returns\n\\`tool_arguments\\`, pass that object unchanged as the pay tool's\n\\`arguments\\` field (for example\n\\`tool_arguments: { \"tier\": \"50gb\" }\\` -> \\`arguments: { \"tier\": \"50gb\" }\\`).\n\n**Prices:** show the user the live price from a read-only quote or the pay-tool\nresult, never a catalog price. \\`haven_discover_tools\\` prices are indicative\n(\\`price_is_indicative\\`) and can be stale. A read-only quote is informational\nonly and does not reserve a price; the later paid call re-quotes and enforces\nthe cap. The pay-tool result's \\`amount\\` / \\`amount_atomic\\` is the merchant's\nown quoted price for that call — a ceiling the merchant settles at or below —\nso present it as the most the user will pay. It is a price, not an approval:\nthe payment goes through only if it also fits the cap you set and the on-chain\nbudget the user signed, which is enforced on-chain rather than by Haven.\n\n**Status:** \\`mcp__haven__haven_get_payment_status\\` with a \\`payment_id\\` to\ncheck on in-flight payments. Do not poll in a tight loop.\n\n## Declines and stop signals\n\n- A payment outside the agent's rules — above the remaining budget, wrong\n recipient, or expired budget — is declined before any money moves. Nothing\n is queued; tell the user, who can raise the budget in Haven.\n- \\`safe_to_continue: false\\` on a guidance block is a stop signal in\n machine-readable form: stop and involve the user before calling anything\n else for this payment.\n- Never ask the user for private keys. Signing happens only in the local Haven\n signer; the hosted Haven tools never receive the signing key. If a tool\n reports a missing or invalid credential, tell the user to re-run the Haven\n connector command.\n\n## Failure handling\n\nHaven tool failures are shaped like \\`{ success: false, code, message, ... }\\`\nor older \\`{ error, status, details? }\\` responses. A failure carries the same\n\\`next_action\\` / \\`next_tool\\` / \\`next_arguments\\` / \\`next_tool_omitted_reason\\`\nfields a success does; follow them first, then branch on \\`code\\` and surface\n\\`message\\` or \\`error\\` verbatim. Common cases:\n\n- \\`insufficient_funds\\`: the Haven wallet doesn't hold enough of that token.\n Suggest the user add funds in the Haven dashboard.\n- \\`PRICE_EXCEEDS_MAX\\`: the live merchant price exceeded your cap. No funds\n moved; ask the user before retrying with a higher one.\n- \\`AMBIGUOUS_MAX_AMOUNT\\`: you sent both \\`max_amount\\` and\n \\`max_amount_human\\`. Nothing was contacted or spent — re-send with exactly\n one (\\`max_amount_human\\` for a cap the user stated in tokens).\n- \\`MAX_AMOUNT_UNCONVERTIBLE\\`: \\`max_amount_human\\` does not fit this quote's\n asset — unknown decimals, or more decimal places than the asset supports.\n Round the cap, or send an exact atomic \\`max_amount\\`.\n- \\`PAYMENT_WINDOW_EXPIRED\\`: re-run the quote/prepare tool with the same\n \\`idempotency_key\\`, then sign the fresh payload.\n- \\`MERCHANT_NOT_READY\\`: the merchant refused the quote with its own\n \"cannot settle right now\" signal (a 503 \\`merchant_not_ready\\` with a\n \\`reason_code\\`) instead of a 402. No payment was created. Tell the user;\n retry later (the message carries \\`retry_after_s\\` when the merchant gave\n one) — this is not a wrong or broken endpoint.\n- \\`MERCHANT_REJECTED_AFTER_FUNDING\\`: the merchant refused the paid retry.\n On eip3009 (\\`rail\\` not \\`erc7710\\`): Stop-and-sweep — stop retrying the\n merchant and use \\`mcp__haven__haven_sweep_delegate\\` to recover stranded\n delegate funds. On erc7710 there is no funding leg and nothing to sweep:\n follow the message — it says whether the merchant declined to settle\n (re-quote later) or whether to check \\`haven_get_payment_status\\` after\n the payment window first.\n- \\`MERCHANT_UNRESPONSIVE_AFTER_FUNDING\\`: the merchant never answered the paid\n retry. This is NOT proof of rejection — the merchant may still settle late.\n On eip3009 (\\`rail\\` not \\`erc7710\\`), funding confirmed on-chain: Verify-then-sweep,\n never a blind sweep — check \\`mcp__haven__haven_get_payment_status\\`, retry\n \\`mcp__haven__haven_complete_mcp_tool\\` ONCE, and only sweep with\n \\`mcp__haven__haven_sweep_delegate\\` if no settlement appears. On erc7710\n there is no funding leg and nothing to sweep, and\n \\`mcp__haven__haven_complete_mcp_tool\\` has no erc7710 branch (it refuses a\n submitted intent) — do not retry it: the merchant may still redeem the\n settlement authorization within the payment window, so check\n \\`mcp__haven__haven_get_payment_status\\` after that window and re-quote only\n if it shows no settlement.\n- Budget exceeded: tell the user how much remains (from\n \\`mcp__haven__haven_get_allowances\\`) and that they can raise the budget in\n Haven.\n\n## Reporting after a purchase\n\nA settled \\`mcp__haven__haven_settle_mcp_tool\\` response carries\n\\`agent_summary.purchase_summary\\` and the remaining post-purchase allowance\nin \\`allowance\\` — report the product, Haven-derived payment/transaction\nfields, and what is left from those fields directly. \\`result\\` is optional\nraw merchant evidence; never use it to decide whether the purchase was paid.\nDo not call \\`haven_get_agent\\` or \\`haven_get_allowances\\` again just to\nreport a purchase you already made.\n\n## Revoke\n\nIf this agent's credential may have leaked, tell the user to pause or revoke\nthe agent in the Haven dashboard under Agents. New requests stop immediately\nfor that credential.\n`\n\n/** Directory name for the installed skill folder. */\nexport const SKILL_FOLDER_NAME = 'haven-pay'\n\n/**\n * The skill BODY — HAVEN_SKILL_MD with the YAML front-matter stripped.\n *\n * For runtimes whose instruction mechanism is a plain guidance file rather\n * than a skills folder (Codex's global AGENTS.md, #1332), the front-matter is\n * skill-registry metadata with no meaning and would render as a stray table.\n * Derived mechanically from the canonical string above, never maintained by\n * hand — the substance cannot fork per runtime.\n */\nexport const HAVEN_SKILL_BODY_MD = HAVEN_SKILL_MD.replace(/^---\\n[\\s\\S]*?\\n---\\n+/, '')\n","/**\n * #1271 / #1301: bounded same-origin merchant MCP endpoint discovery.\n *\n * An agent handed a BASE merchant URL previously had to hand-probe /, /mcp,\n * /sse, … until something answered 402. The demo merchant (and the #1266\n * contract) serves a machine-readable discovery document at\n * `/.well-known/haven-demo-merchant` (also at `/`) naming `mcp_url`. This\n * helper fetches ONLY those two fixed same-origin paths — no redirects\n * (`redirect: 'error'`), a 5 s timeout, a 64 KB read cap — and accepts the\n * document's `mcp_url` ONLY when it stays on the same origin as the input.\n * Anything else returns null and the caller reports the original probe\n * failure. Discovery finds endpoints; it carries no payment authority and an\n * off-origin `mcp_url` is never even fetched — this must not grow into a\n * general network scanner (SSRF bound, per the issue).\n *\n * Originally hosted-only (mcp-server, #1271). Moved here in #1301 so the\n * local/self-signed MCP package (`@haven_ai/mcp`) can share the EXACT same\n * bounded implementation instead of re-deriving discovery semantics —\n * behavior is byte-identical to the pre-move mcp-server copy; the #1271\n * contract tests in packages/mcp-server/src/tools.test.ts pass unmodified\n * against this moved implementation.\n */\nexport const MERCHANT_DISCOVERY_PATHS = ['/.well-known/haven-demo-merchant', '/'] as const\nexport const DISCOVERY_MAX_BYTES = 64 * 1024\n\nexport async function discoverMerchantMcpUrl(inputUrl: string): Promise<string | null> {\n let input: URL\n try {\n input = new URL(inputUrl)\n } catch {\n return null\n }\n for (const path of MERCHANT_DISCOVERY_PATHS) {\n try {\n const res = await globalThis.fetch(`${input.origin}${path}`, {\n method: 'GET',\n headers: { accept: 'application/json' },\n redirect: 'error',\n signal: AbortSignal.timeout(5_000),\n })\n if (!res.ok) continue\n const contentLength = Number(res.headers.get('content-length') ?? 0)\n if (contentLength > DISCOVERY_MAX_BYTES) continue\n const text = await res.text()\n if (text.length > DISCOVERY_MAX_BYTES) continue\n const doc = JSON.parse(text) as { mcp_url?: unknown }\n if (typeof doc.mcp_url !== 'string') continue\n const resolved = new URL(doc.mcp_url)\n if (resolved.origin !== input.origin) continue\n return resolved.toString()\n } catch {\n continue\n }\n }\n return null\n}\n\n/** Trailing-slash/percent-case echoes compare equal; unparseable never does. */\nexport function sameUrl(a: string, b: string): boolean {\n try {\n const ua = new URL(a)\n const ub = new URL(b)\n return ua.origin === ub.origin && ua.pathname.replace(/\\/+$/, '') === ub.pathname.replace(/\\/+$/, '')\n } catch {\n return false\n }\n}\n"]}
|