import { PaymentRequirements } from 'x402/types'; interface HavenClientConfig { /** Haven API key (sk_agent_xxx) */ apiKey: string; /** Agent's delegate EOA private key. If provided, the SDK handles signing automatically. */ delegateKey?: string; /** Haven API base URL (default: http://localhost:3001) */ baseUrl?: string; /** Optional wallet identity to send as the x402-wallet header. */ x402Wallet?: string; /** Timeout in ms for individual HTTP requests (default: 30000) */ requestTimeout?: number; /** Timeout (ms) for MERCHANT-facing requests — x402/MPP probes, MCP * handshakes, paid retries. Separate from requestTimeout (Haven API): * merchants may settle on-chain synchronously, so the default is * deliberately generous. #1300. */ merchantTimeout?: number; /** Timeout in ms when polling for tx confirmation (default: 90000) */ confirmationTimeout?: number; /** Polling interval in ms when waiting for confirmation (default: 3000) */ pollingInterval?: number; /** * Extra headers to attach to every request to the Haven API. * * Used by the MCP server to tag requests with `X-Haven-MCP-Tool: ` * so the backend can record an audit-log entry per tool invocation. Has * no effect on outbound merchant requests (x402 / MPP) — those are * standard HTTP and never carry Haven-internal headers. */ defaultHeaders?: Record; /** * JSON-RPC RPC URLs keyed by EIP-155 chain ID. * * When provided for a chain, the SDK waits for ≥1 on-chain confirmation of * the AllowanceModule funding tx before retrying the merchant. This prevents * the race where the merchant's `balanceOf(delegate)` call runs before the * funding block has propagated to the merchant's RPC node. * * Without this option the SDK proceeds as soon as Haven's backend confirms * submission (backward-compatible default). Set it to a reliable RPC * endpoint (e.g. Alchemy / Infura) for production usage. * * @example { 8453: 'https://mainnet.base.org' } */ chainRpcs?: Record; } interface PaymentRequest { /** Token symbol: "EURe", "USDC.e", or "xDAI" */ token: string; /** Amount as a decimal string, e.g. "5.00" */ amount: string; /** Recipient Ethereum address (0x...) */ to: string; /** * Optional dedupe key (#1207): a retried request with the same key returns * the FIRST request's result instead of minting a second transfer or a * second approval. Same contract as /machine-payments/send. Max 128 chars. */ idempotencyKey?: string; } interface SignData { /** The hash to sign (keccak256, 0x-prefixed) */ hash: string; /** * Delegation rail: 'eip712_userop' (funding redemption) or * 'eip712_delegation' (erc7710 settlement child). The backend spec makes it * required; the legacy AllowanceModule reading — absent = raw ECDSA over * `hash` — is retired (#2850), and the SDK client refuses an absent scheme. * The session rail's 'eip191_userop' is retired (#834). * * When present, `hash` is NOT what gets signed — `typed_data` is (#1138). */ signature_scheme?: 'eip712_userop' | 'eip712_delegation'; /** * EIP-712 payload the account validates, signed VERBATIM (#829). Present * whenever `signature_scheme` is — never reconstruct it from `components`. */ typed_data?: { domain: Record; types: Record; primaryType: string; message: Record; }; /** Breakdown of values that were hashed — useful for debugging */ components: { /** * The PAYER account (the user's smart account). Not to be confused with * `account`, which on the funding shapes holds the DELEGATE account * address. */ payer_account?: string; token: string; to: string; amount: string; payment_token: string; payment: string; nonce: number; }; /** Human-readable signing instructions */ instructions: string; } interface PaymentIntent { /** Unique payment ID */ paymentId: string; /** Current status */ status: 'pending_signature'; /** ISO 8601 expiry timestamp */ expiresAt: string; /** Data needed to sign the payment */ signData: SignData; } type PaymentStatus = 'pending_signature' | 'submitted' | 'confirmed' | 'pending_approval' | 'approved' | 'proposed' | 'executed' | 'rejected' | 'expired' | 'failed'; interface PaymentResult { /** Unique payment ID */ paymentId: string; /** Final status */ status: PaymentStatus; /** Token that was sent */ token: string; /** Amount that was sent (human-readable) */ amount: string; /** Recipient address */ to: string; /** On-chain transaction hash (present when confirmed) */ txHash: string | null; /** Error message (present when failed) */ errorMessage: string | null; /** Block explorer URL for the transaction (chain-dependent) */ explorerUrl: string | null; /** ISO 8601 timestamps */ createdAt: string; signedAt: string | null; submittedAt: string | null; confirmedAt: string | null; expiresAt: string; /** * Platform fee surfaced on the result so it's never silently collected. Dark * today (`amount` "0", `applied` false); always present so it's visible the * moment fees go live. */ fee?: PaymentFee | null; } /** The Haven platform fee applied to a payment (#386). */ interface PaymentFee { /** Human-readable fee amount ("0" while the fee module is dark). */ amount: string; /** Token the fee is denominated in. */ token: string; /** Fee as basis points of gross (0 while dark). */ basisPoints: number; /** True when a non-zero fee was actually applied. */ applied: boolean; } /** Payment requirements from an HTTP 402 response (x402 protocol). */ interface X402PaymentRequired { x402Version: number; resource: { url: string; description?: string; mimeType?: string; [key: string]: unknown; }; accepts: X402PaymentOption[]; error?: string; extensions?: Record; } /** A single payment option from x402 PaymentRequired. */ interface X402PaymentOption { scheme: string; network: string; amount: string; maxAmountRequired?: string; resource?: string; description?: string; mimeType?: string; asset: string; payTo: string; maxTimeoutSeconds: number; /** * Merchant-supplied scheme metadata. Two keys are load-bearing for Haven * (#1453), both from MetaMask's erc7710 x402 shape: * * assetTransferMethod — 'erc7710' marks this entry as settleable by * redeeming a delegation chain. Absent/other means * the standard EIP-3009 authorization. * facilitatorAddresses — who may redeem it, pinned into the settlement * child's redeemer caveat (#1058). * * Left as an open record on purpose: the field is the merchant's, and * narrowing it to Haven's two keys would silently drop everything else a * merchant sends. Read it through `x402AssetTransferMethod` / * `x402FacilitatorAddresses` rather than indexing it raw. */ extra?: Record; } /** Receipt returned after a successful x402 payment. */ interface X402Receipt { success: boolean; paymentId: string; txHash: string; token: string; amount: string; to: string; resourceUrl: string; explorerUrl: string; accepted?: X402PaymentOption; paymentHeader?: string; merchantTo?: string | null; payer?: string; chainId?: number; haven?: { paymentId: string; fundingTxHash: string; fundingExplorerUrl: string; }; merchant?: { payTo: string | null; settlementTxHash?: string | null; settlementExplorerUrl?: string | null; }; x402?: { amount: string; token: string; network: string; asset: string; resource: string; }; } interface X402AuthorizationOptions { /** Stable caller-supplied key for this user intent. Prevents duplicate approvals across fresh 402 quotes. */ idempotencyKey?: string; /** * #1307: the merchant MCP-tool call context this quote was made against * (merchant_url, tool_name, arguments, mcp_transport). Persisted on the * intent so `getX402MerchantCallContext` can rehydrate it by payment_id at * settle/complete time instead of the caller re-threading it. Optional — * omit for a non-MCP-tool x402 merchant (plain HTTP resource). */ mcpCallContext?: X402McpCallContext; /** * #1348: the agent's delegate address, when the caller already resolved it * from `getAgent()` in this same flow — skips `createX402Intent`'s internal * agent fetch (one full round trip on every guided purchase). Staleness * caveat (#1358 review): the backend derives the funding shape by comparing * `payTo` to the CURRENT delegate address, so a value made stale by a * delegate rotation mid-flow is not always a clean failure — a pinned-budget * agent gets a 403, but an open-budget delegation agent would route to the * settlement shape with the stale address. The window is one tool call * (previously sub-millisecond, now the merchant-quote duration), never * externally suppliable; server-truth hardening is tracked in #1360. Only * pass an address fetched in THIS flow; omit to keep the self-contained * fetch. */ delegateAddress?: string; } /** * Keyless x402 construct result. * * Returned by `createX402Intent` — the non-custodial half of an x402 payment. * It carries the unsigned funding hash (`signData.hash`, Safe → delegate EOA) * plus everything the *edge* needs to build and sign the EIP-3009 merchant * header itself. The construct path never signs; both delegate signatures * (funding hash + merchant header) happen on the machine that holds the key. */ interface X402Intent { /** Haven payment id for the funding transfer. */ paymentId: string; /** Stable key used to create or refresh this x402 funding intent. */ idempotencyKey: string; status: 'pending_signature'; /** ISO 8601 expiry of the funding intent, if returned. */ expiresAt?: string; /** The unsigned funding hash to sign with the delegate key (Safe → delegate EOA). */ signData: SignData; /** The selected x402 option — the edge needs this to build the EIP-3009 header. */ accepted: X402PaymentOption; /** Resource URL the 402 came from. */ resourceUrl: string; /** Merchant payTo address (the final recipient of the EIP-3009 transfer). */ merchantTo: string; /** Atomic amount the edge signer must authorize in the merchant header. */ amountAtomic: string; /** Token contract the merchant header must pay. */ asset: string; /** x402 network the merchant header must use. */ network: string; /** Haven-authenticated binding over the x402 expected context. */ expectedAuth: X402ExpectedAuth; /** * #1690: the payer identity Haven bound into the expected context (v3), * relayed VERBATIM to the signer's wire shape. Absent until the backend * flips X402_EMIT_PAYER_CONTEXT. */ payerDelegate?: string; payerAgentId?: string; /** * EIP-712 digest of `signData.typed_data`, present on the delegation rail * (#1138). The edge signer needs it to reconstruct the v2 expected-context * message that Haven signed. */ expectedTypedDataHash?: string; /** Delegate EOA the funding transfer tops up (the x402 payer). */ fundingTo: string; } interface X402ExpectedContext { paymentId: string; payloadHash: string; resourceUrl: string; merchantTo: string; amount: string; asset: string; network: string; /** Optional ISO expiry for the funding/quote window. When present, it is bound into the Haven-authenticated context. */ expiresAt?: string; /** * EIP-712 digest of the typed data the account actually validates * (delegation rail, #1138). Present ⇒ the context is **version 2** and the * signer must sign that typed data, never `payloadHash`. * * On the delegation rail `payloadHash` is the bare ERC-4337 UserOp hash, * which is NOT what the account validates — binding it alone would leave the * edge signer unable to verify the payload it is being asked to sign. Binding * this digest makes Haven's declaration cover the real payload. */ typedDataHash?: string; /** * The DELEGATE ADDRESS this quote was created for (#1690). Present ⇒ the * context is **version 3** and the signer refuses to sign when this is not * its own delegate — the guard that turns "quote as agent A, sign as agent * B" from an on-chain revert three layers later into a named refusal. * Inside the Haven-signed message on purpose: outside it, it is forgeable. */ payerDelegate?: string; /** The paying agent's id, for the refusal message's diagnosis (#1690). */ payerAgentId?: string; } interface X402ExpectedAuth { /** * 1 = hash-only (legacy rail). 2 = carries `typedDataHash` (delegation rail, * #1138). * * Deliberately `number`, not a literal union (#1143). This is an **inbound** * value: a signer parses a context Haven produced, and a signer older than the * backend will legitimately receive a version it does not know. A closed union * makes that state unrepresentable, which pushed the rejection down to the * schema boundary and produced a raw validation error naming neither the cause * nor the fix. The supported set lives in the signer * (`SUPPORTED_X402_EXPECTED_VERSIONS`), which fails closed on anything outside * it with an actionable message. */ version: number; message: string; signature: string; signer: string; } /** Serializable HTTP request state for retrying the same x402 merchant request. */ interface X402RequestSnapshot { url: string; method: string; headers: [string, string][]; body?: string; } interface X402McpTransport { handshakeRequired: boolean; source: 'path' | 'bazaar'; } /** * #1307: the merchant MCP-tool call an x402 quote was made against — carried * through `createX402Intent`'s options so Haven can persist it for the * settle-leg rehydration handoff (`getX402MerchantCallContext`). Convenience * metadata for retrying the merchant's OWN JSON-RPC call, never payment * authority. */ interface X402McpCallContext { merchantUrl: string; toolName: string; arguments?: Record; mcpTransport?: X402McpTransport; } /** * Response shape of `getX402MerchantCallContext` — the stored merchant call * context for a payment_id, rehydrated instead of re-threaded (#1307). */ interface X402MerchantCallContext { paymentId: string; merchantUrl: string; toolName: string; arguments: Record; mcpTransport?: X402McpTransport; } /** Quote parsed from an HTTP 402 response without creating a Haven payment. */ interface X402Quote { rail: 'x402'; idempotencyKey: string; paymentRequired: X402PaymentRequired; accepted: X402PaymentOption; /** * #2054: which selector produced `accepted`, and therefore which entry every * amount on this quote describes. `'standard'` is the untagged, * EIP-3009-settleable entry; `'erc7710'` means the merchant advertises NO * standard entry, so the quote describes its erc7710 one — settleable only * from a delegation-rail account, a fact the quote layer cannot see (the * rail is a property of the ACCOUNT, not of the 402). This field is * descriptive: the actual settlement scheme is still chosen later, with the * rail in hand, by `selectX402SettlementScheme`. */ acceptedScheme: 'standard' | 'erc7710'; request: X402RequestSnapshot; mcpTransport?: X402McpTransport; resourceUrl: string; /** #3097: `resourceUrl` (the merchant's declaration) is not `request.url` (what was quoted). */ resourceUrlDiffersFromRequest: boolean; description: string | null; mimeType: string | null; amountAtomic: string; amount: string; token: string; /** * #1351: decimals for `asset` on `network`, resolved from the SAME * address→token binding that produced `token` — the quote's own authority on * how many atomic units one human unit is. `null` when the merchant's asset * is not a token Haven recognises on that network, in which case `token` is * an unverified fallback label and NO human→atomic conversion is safe. * Consumers converting a human-denominated figure (a user-intent spending * cap) MUST fail closed on `null` rather than assume 6. */ decimals: number | null; asset: string; network: string; chainId: number | null; merchantAddress: string; maxTimeoutSeconds: number; } /** State bundle an agent can persist while waiting for manual x402 approval. */ interface X402ResumeState { rail: 'x402'; paymentId: string; idempotencyKey: string; paymentRequired: X402PaymentRequired; accepted: X402PaymentOption; url: string; request?: X402RequestSnapshot; resourceUrl: string; description: string | null; amountAtomic: string; amount: string; token: string; asset: string; network: string; chainId: number | null; merchantAddress: string; } type PaymentResumeState = X402ResumeState; interface ResumeAuthorizedX402Input extends X402AuthorizationOptions { /** Payment or approval request ID returned by authorizeX402 / haven.fetch. */ paymentId: string; /** Original or freshly parsed x402 requirements for the merchant retry. */ paymentRequired: X402PaymentRequired; } interface ResumeX402PaymentInput extends X402AuthorizationOptions { /** Payment or approval request ID returned by authorizeX402 / haven.fetch. */ paymentId: string; /** Original paid URL. If paymentRequired is omitted, Haven will call it once to re-read the 402 challenge. */ url: string; /** Original fetch options. Reused for the 402 probe and final merchant retry. */ init?: RequestInit; /** Serializable original request captured by quoteX402() / pending approval errors. */ request?: X402RequestSnapshot; /** Original or freshly parsed x402 requirements. Supplying this avoids an extra merchant 402 probe. */ paymentRequired?: X402PaymentRequired; } type MachinePaymentRail = 'x402' | 'mpp_demo' | 'mpp_crypto' | 'stripe_deposit' | 'spt'; interface HavenAgent { id: string; name: string; status: string; /** The agent's Haven account (smart account) address. */ accountAddress: string; delegateAddress: string; chainId: number; /** * Which on-chain policy primitive gates this agent's spend (#1306): the * legacy Safe AllowanceModule (retired — no account can enter it since * #1984, and it cannot spend since #1986) or the delegation * rail's active budget delegations (#1090). Read-only reporting — the * on-chain state is the actual gate either way, this only says which * mechanism a caller should read/derive from. */ executionRail: 'legacy' | 'delegation'; } interface HavenAllowance { id: string; tokenAddress: string; tokenSymbol: string; configuredAmount: string; resetPeriodMin: number; /** * #3128: human-readable `onchain.remaining`, e.g. "4.96 USDC" — the SAME * string {@link HavenAgentAllowanceSummary.remainingDisplay} carries for * this allowance, computed by one function from `onchain.remaining` and * the token's decimals, so the two reads cannot disagree. Additive; the * wire carries no display form (it is derived client-side). */ remainingDisplay: string; onchain: { amount: string; spent: string; remaining: string; effectiveSpent: string; resetTimeMin: number; lastResetMin: number; nonce: number; isResetPending: boolean; /** * Delegation rail only (#1319, provenance for #1145's fallback): true * when `remaining` came from a live on-chain enforcer read, false when * the read failed and `remaining` is the fallback full configured * budget. Undefined on the legacy AllowanceModule rail, which has no * fallback concept. Reporting only — the on-chain policy remains the * actual spend gate either way. */ remainingIsFromChain?: boolean; }; } interface HavenAllowanceSummary { agentId: string; accountAddress: string; delegateAddress: string; chainId: number; allowances: HavenAllowance[]; } /** * Post-purchase allowance/budget summary attached to a settled x402 payment * (#1310). Read-only reporting — the on-chain policy remains the actual * spend gate either way, this only says what is left after the purchase. * * Deliberately the SAME rail-labeled field spelling as #1306's * catalog-purchase preflight `allowance` block (never a new spelling), * minus the preflight-only `sufficient` field: post-purchase reporting * answers "what is left", not "was this purchase covered". Read through the * exact same source as {@link HavenAllowanceSummary} / `haven_get_allowances` * (`GET /machine-payments/allowances`; delegation-rail values are the #1090 * `deriveDelegationBudgets`-backed enforcer read, never `agent_allowances`), * so this can never disagree with `haven_get_allowances` for the same * fixture. */ interface PostPurchaseAllowanceSummary { /** Which on-chain policy primitive gates this agent's spend (#1306 labeling). */ rail: 'legacy' | 'delegation'; /** Remaining atomic units, read through the same source as {@link HavenAllowance.onchain.remaining}. */ remaining_atomic: string; /** Human-readable remaining, e.g. "4.96 USDC". Omitted when the token's decimals are unknown. */ remaining_display?: string; token_symbol?: string; token_address?: string; /** Minutes — mirrors {@link HavenAllowance.resetPeriodMin} / the delegation's period. */ reset_period?: number; source: 'allowance_module' | 'active_delegations'; } /** * #3126 — the answer to "is there money actually HELD behind my budget?", * asked as a sufficiency signal rather than a balance. * * Every other agent-readable figure in this package describes SPEND * AUTHORITY — what the agent is PERMITTED to move this period * ({@link HavenAllowanceSummary}). This shape answers the different question * of whether the account HOLDS funds behind that authority, and deliberately * answers it as `covered: boolean | null`, never as a figure: a constrained * actor has no business reading the treasury total, and the boolean answers * the only decision an agent has (attempt the payment, or tell the user * funds are missing). * * The naming keeps the two concepts apart (the #3126 binding constraint): * `budgetRemainingAtomic` is AUTHORITY — the same value * {@link HavenAllowanceSummary} reports per token as `onchain.remaining` — * while `covered` speaks only of HELD funds. Nothing here is named like the * authority fields (`remaining`, `available`); nothing here returns a * balance. * * `covered: null` means the chain read FAILED — unverifiable, never a * guess. The same honesty rule `x402-funding-leg.ts`'s `delegateCanFund` * established (#1521): treat null as "we do not know", not as "funded" or * as absence; `coverageError` carries why. */ interface HavenBalanceCoverage { /** * true: the chain reports the agent's account holds at least * `checkedAmountAtomic` of the token. false: the chain read succeeded and * reports LESS — tell the user funds are missing rather than retrying. * null: the chain read failed — unverifiable, never treated as absence. */ covered: boolean | null; /** Present only when `covered` is null: why the chain read could not answer. */ coverageError?: string; chainId: number; tokenAddress: string; tokenSymbol: string; /** The amount the coverage question was asked about, in atomic units. */ checkedAmountAtomic: string; /** * Context, AUTHORITY not holdings: the agent's remaining spend authority * for the requested token, in atomic units — the same derivation * {@link HavenAllowanceSummary} reports (`onchain.remaining`; the #1090 * derivation, the #1145 enforcer read). Zero when no active budget row * names the token. Compare it with `covered`, never instead of it. */ budgetRemainingAtomic: string; /** * Provenance of `budgetRemainingAtomic` (#1319, same semantics as * {@link HavenAllowance.onchain.remainingIsFromChain}): true when the * budget figure came from a live enforcer read, false when it fell back * to the configured budget. Absent when no budget row existed for the * token (nothing was read). */ budgetRemainingIsFromChain?: boolean; } /** * Affirmative spend-readiness for the authenticated agent, derived from the raw * agent status plus the remaining spend authority the backend reports per rail * (the on-chain AllowanceModule on the legacy rail; the active budget * delegation on the delegation rail — #1135): * - `ready` — active and at least one token has remaining spend authority. * - `needs_approval`— active but no remaining spend authority to auto-spend. * The over-budget outcome differs by rail: on the legacy * AllowanceModule rail the payment is queued for the wallet * owner to approve in Haven; on the delegation rail there is * NO approval queue — an over-budget redemption reverts * on-chain, so the owner must grant or raise the budget in * Haven before the agent can pay. * - `revoked` — the agent's status is not `active`; nothing auto-executes. * * Note: a hard-paused/disabled credential is rejected by the API before this * call returns, so it surfaces as an API error rather than `revoked`. `revoked` * is reached when the request authenticates but the agent status is non-active. * * Wallet token balance is intentionally NOT folded in here: the on-chain * remaining allowance is the gate Haven enforces, and insufficient wallet * funding surfaces at pay time as INSUFFICIENT_FUNDS. */ type HavenAgentReadiness = 'ready' | 'needs_approval' | 'revoked'; /** * Compact, agent-facing per-token spend authority for the bootstrap summary. * * #3128: a deliberately DIFFERENT view of the same allowance as * {@link HavenAllowance} — flat, no `onchain` block, no spent/nonce/reset-time * detail — but never a disjoint one: every field here is present on or * derived from the {@link HavenAllowance} with the same `id`, and * `remainingAtomic` / `remainingDisplay` equal that allowance's * `onchain.remaining` / `remainingDisplay` byte for byte (pinned by test). A * client that wants the id AND a display amount can therefore use either * read alone. */ interface HavenAgentAllowanceSummary { /** #3128: the {@link HavenAllowance.id} this row summarises. */ id: string; tokenSymbol: string; /** #3128: the {@link HavenAllowance.tokenAddress}. */ tokenAddress: string; /** Live on-chain remaining allowance in atomic units. */ remainingAtomic: string; /** Human-readable remaining, e.g. "4.96 USDC". */ remainingDisplay: string; /** Configured allowance amount (atomic) the owner granted. */ configuredAmount: string; resetPeriodMin: number; isResetPending: boolean; } /** * One-shot "am I ready?" bootstrap: identity + live spend authority + a * readiness signal, so an agent can answer "who am I and can I pay right now" * from a single call at session start. Superset of {@link HavenAgent}. */ interface HavenAgentSummary extends HavenAgent { /** * @deprecated Use {@link HavenAgentSummary.spend_authority_readiness} — * same value, honest name. This signal covers hosted identity + on-chain * spend authority ONLY; it says nothing about the LOCAL signer, which the * hosted side cannot see (verify via a signer tool or connect --doctor). * Kept as an alias; removal earliest after the next release train (#1590). */ readiness: HavenAgentReadiness; /** * Spend-authority readiness: hosted identity + on-chain remaining spend * authority. Deliberately named for what it covers — the LOCAL signer's * availability is NOT included and must be verified separately (a signer * tool call, or the connector's `--doctor`, whose exact command this build * renders from `HAVEN_CONNECTOR_CHANNEL` — see `connector-channel.ts`). */ spend_authority_readiness: HavenAgentReadiness; allowances: HavenAgentAllowanceSummary[]; } /** * #2960 — one party vocabulary for "who paid" a Haven payment, additive * alongside every existing lone `payer*`/`*Address` field (same discipline * as the #2907 `safe`/`account` dual-emit, except these four are DISTINCT * addresses, not same-value twins of one old field). */ interface PaymentParties { treasuryAccount: string | null; delegate: string | null; delegateAccount: string | null; merchant: string | null; } /** @internal wire shape of {@link PaymentParties}. */ interface RawPaymentParties { treasury_account: string | null; delegate: string | null; delegate_account: string | null; merchant: string | null; } interface HavenPaymentReceipt { id: string; paymentId: string; paymentIntentId?: string | null; approvalRequestId?: string | null; rail: string; proofStatus: string; /** * @deprecated (#2998) meaning depends on the settlement scheme — the * account → delegate funding transaction on eip3009, the (only) settlement * transaction on erc7710. Prefer {@link fundingTxHash} / {@link settlementTxHash}, which * name which is which. */ txHash: string; /** The account → delegate funding transaction, relayed by Haven (#2998); null on erc7710 (no funding leg) and on retired mpp-rail rows. */ fundingTxHash: string | null; /** * The delegate → merchant settlement transaction (#2998). Trust level differs * by scheme: on erc7710 it is `txHash` itself and Haven VERIFIED it on-chain * before the receipt existed; on eip3009 it is the merchant's claim as relayed * (PAYMENT-RESPONSE), NOT verified on-chain by Haven — cite it as such. */ settlementTxHash: string | null; chainId: number; resourceUrl: string; merchantAddress: string | null; payerAddress: string; /** #2960: additive alongside `payerAddress` above (`parties.treasury_account` only). */ parties?: PaymentParties; settlementAddress: string; tokenSymbol: string; tokenAddress: string; amountRaw: string; amount: string; challengeId: string | null; idempotencyKey: string | null; challengePayload?: Record | null; selectedPayment?: Record | null; paymentProofHeaderName: string | null; protocolReceiptHeaderName: string | null; /** * #3125 — the merchant's `PAYMENT-RESPONSE` object relayed VERBATIM: * opaque, unvalidated, unverified, MERCHANT-CONTROLLED third-party data. * Haven neither authors nor verifies anything inside it, including * `protocolReceiptPayload.payer` — * that `payer` is the merchant's claim, NOT Haven's record, and is not * {@link payerAddress} (Haven's own, authoritative; field observation * 2026-09-18: the two held different addresses on every row read). For who * paid, read `parties` ({@link PaymentParties}) — `treasuryAccount`, * `delegate`, `delegateAccount`, `merchant` are Haven-derived and * authoritative; anything inside this object is not. * * Deliberately NOT namespaced or key-prefixed on the wire (#3125): the * relay must stay the merchant's object verbatim (its `transaction` key * feeds `settlementTxHash`), and prefixing the envelope could not prefix * the merchant-controlled keys inside it — the `payer` collision lives * there, so provenance is made legible at the read surfaces instead (this * comment and the tool descriptions). */ protocolReceiptPayload?: Record | null; merchantStatus: number | null; confirmedAt: string | null; createdAt: string; updatedAt: string; } /** * How long this SDK waits for an on-chain confirmation before it stops * waiting (#1756). * * Lives here rather than in `client.ts` so the payment-confirmation poller * and the delegate sweep share ONE number instead of forking it. The SDK's * other chain waits are already bounded (`waitForFundingTx` at 30 s), so a * fourth independently chosen literal is exactly the drift this constant * exists to prevent. */ declare const DEFAULT_CONFIRMATION_TIMEOUT_MS = 90000; /** * Whether a sweep transfer was observed to confirm (#1756). * * The distinction is the point: `unconfirmed` means the transfer was * BROADCAST and may still land, which is neither success nor failure. It must * never be collapsed into either — reporting a still-pending transaction as * done, or as failed, are the same defect in opposite directions. */ type SweepConfirmation = /** A receipt was observed. The funds are in the Safe. */ 'confirmed' /** * Broadcast, but no receipt within `DEFAULT_CONFIRMATION_TIMEOUT_MS` (or the * node returned no receipt). The transaction is still in the mempool and may * mine at any time. `txHash` is the broadcast hash — check it on the * explorer before re-running the sweep, and expect a re-run to find nothing * stranded if it has since landed. */ | 'unconfirmed'; /** One transferred asset in a delegate sweep. */ interface SweepEntry { /** 'USDC' or 'ETH' */ asset: string; /** Human-readable amount swept (e.g. "0.12") */ amount: string; /** Atomic amount swept */ amountAtomic: string; /** * Transaction hash of the sweep transfer. * * The RECEIPT hash when `confirmation` is `confirmed`; the BROADCAST hash * when it is `unconfirmed` — which is the whole reason the sweep returns * instead of throwing on a deadline, since this hash is the only thing that * lets a user recover the transfer by hand (#1756). */ txHash: string; /** Block explorer URL for the tx */ explorerUrl: string; /** * Did this transfer confirm on-chain within the deadline? (#1756) * * `unconfirmed` entries have MOVED NOTHING YET and may still move. Do not * report a sweep as complete without checking this on every entry. */ confirmation: SweepConfirmation; } /** Result of a `sweepDelegate()` call. */ interface SweepResult { /** Address funds were swept FROM */ fromAddress: string; /** Address funds were swept TO (always the originating Safe) */ toAddress: string; /** Chain the sweep occurred on */ chainId: number; /** One entry per transferred asset. Empty when nothing was stranded. */ transfers: SweepEntry[]; /** * True when ANY entry is `unconfirmed` — i.e. the sweep broadcast something * it could not confirm within the deadline (#1756). * * Derived from `transfers`, and present anyway because the consumer most * likely to misread this result is an LLM reading the JSON of the * `haven_sweep_delegate` tool, which will otherwise see a populated * `transfers` array and report the money as recovered. */ unconfirmed: boolean; } type PaymentStateKind = 'payment_intent' | 'approval_request'; interface AgentPaymentEnumSchema { type: 'string'; enum: readonly string[]; description: string; 'x-enumDescriptions': Record; } declare const AgentPaymentPhase: { /** The agent must sign and submit the prepared payment before Haven can relay it. */ readonly AgentSignatureRequired: "agent_signature_required"; /** Haven has received the signed payment and the agent should poll for confirmation. */ readonly PaymentSubmitted: "payment_submitted"; /** The direct payment is confirmed; the agent does not need to do more for this payment id. */ readonly PaymentConfirmed: "payment_confirmed"; /** * #2115: RETIRED wire value — no live rail produces it. It described the * Safe rail's approval queue, which no longer exists. Kept so a stored value * still typechecks; see `AgentPaymentPhaseDescriptions` below for the * agent-visible wording, which this comment used to contradict. */ readonly UserApprovalRequired: "user_approval_required"; /** #2115: RETIRED wire value — no live rail produces it. Stop and tell the user. */ readonly UserExecutionRequired: "user_execution_required"; /** #2115: RETIRED wire value — no live rail produces it. Stop and tell the user. */ readonly WaitingForAdditionalApprovals: "waiting_for_additional_approvals"; /** The Haven funding leg was sent; the agent can continue the merchant/protocol leg. */ readonly FundingSent: "funding_sent"; /** The payment was rejected and cannot proceed; the agent should stop and tell the user. */ readonly Rejected: "rejected"; /** The payment expired before completion. */ readonly Expired: "expired"; /** Haven could not complete the payment; the agent should stop and surface the failure. */ readonly Failed: "failed"; /** * Pre-flight check determined the delegate's existing balance plus the * remaining on-chain budget cannot cover the requested amount, so no * payment intent was created. The account must be funded or the agent's * budget raised before retrying — #2115: the old wording contrasted this * with `UserApprovalRequired` as if that were a live alternative, and named * the retired rail's Safe and per-token allowance as the fix. */ readonly InsufficientFunds: "insufficient_funds"; /** * Haven's funding leg (account → delegate, the #946 EIP-3009 bridge) * confirmed on-chain, but the merchant rejected the x402 retry. The delegate * wallet may hold stranded USDC that was never settled to the merchant. The * agent should stop, tell the user, and wait for the sweep flow to reclaim * the funds. */ readonly FundedButUnsettled: "funded_but_unsettled"; }; type AgentPaymentPhase = (typeof AgentPaymentPhase)[keyof typeof AgentPaymentPhase]; declare const AgentPaymentNextAction: { /** Sign with the delegate key and submit the payment to Haven. */ readonly SignAndSubmitPayment: "sign_and_submit_payment"; /** Poll getPaymentStatus later using this payment id. */ readonly CheckStatusLater: "check_status_later"; /** No further agent action is required for this payment id. */ readonly None: "none"; /** * #2115: RETIRED wire value — no live rail produces it and nothing maps to * it. Stop and tell the user rather than polling; no approval will arrive. */ readonly WaitForUserApproval: "wait_for_user_approval"; /** #2115: RETIRED wire value — no live rail produces it. Stop and tell the user rather than polling. */ readonly WaitForUserToCompletePayment: "wait_for_user_to_complete_payment"; /** Resume this payment id and retry the original x402 request with the merchant payment header. */ readonly RetryOriginalX402Request: "retry_original_x402_request"; /** Stop retrying this payment and tell the user what happened. */ readonly StopAndTellUser: "stop_and_tell_user"; /** Ask again only if the user still wants the payment after expiry. */ readonly RequestAgainIfUserStillWantsIt: "request_again_if_user_still_wants_it"; /** #1307: retry the SAME tool call, supplying the explicit context fields the server could not rehydrate. */ readonly RetryWithExplicitContext: "retry_with_explicit_context"; /** * The x402 funding/quote window expired. Re-quote the same logical merchant * operation with the same idempotency key to stay double-charge-safe. */ readonly PaymentWindowExpired: "payment_window_expired"; /** * Stop and tell the user that the originating account needs to be funded or * the agent's per-token allowance needs to be raised before the payment * can succeed. A user approval will not fix this state on its own. * * #2914: the account-vocabulary spelling, and the only one — the * pre-#2907 `fund_safe_or_raise_allowance` wire value (and the * `AgentPaymentNextActionAccountAlias` seam #2908 added to bridge it) are * retired along with the rest of the #2908 compatibility window. */ readonly FundAccountOrRaiseAllowance: "fund_account_or_raise_allowance"; /** * The delegate wallet may hold funds that were sent from the Safe but never * settled to the merchant. The wallet owner should initiate a sweep to * return those funds to the originating Safe. */ readonly SweepStrandedFunds: "sweep_stranded_funds"; /** * #2970: a `submitted` erc7710 x402 intent whose settlement window has * passed with no on-chain settlement evidence Haven could verify. Distinct * from {@link CheckStatusLater}, which this REPLACES once the window is * past — but it is not futile: Haven's settlement sweep (120s tick) scans * each candidate over its own window plus a 120s clock-skew allowance, so * it can still attribute the settlement for a short while after this value * first appears. Poll {@link CheckStatusLater}'s tool * (`haven_get_payment_status`) once more, roughly two minutes later; if it * still shows no evidence, tell the user the goods were delivered but * Haven holds no verified settlement evidence for this payment. If the * agent holds the merchant's real settlement transaction hash (from * `PAYMENT-RESPONSE`'s `transaction` field, or a prior settle/complete * result's `settlement_tx_hash`), report it with the hosted * `haven_report_settlement_evidence` tool instead of waiting — * `haven_report_x402_outcome` takes no hash and refuses a non-`confirmed` * intent. */ readonly AwaitingSettlementEvidence: "awaiting_settlement_evidence"; }; type AgentPaymentNextAction = (typeof AgentPaymentNextAction)[keyof typeof AgentPaymentNextAction]; declare const AgentPaymentFailureCode: { /** A merchant-authoritative x402 price exceeds the caller's pre-funding max_amount cap. */ readonly PriceExceedsMax: "PRICE_EXCEEDS_MAX"; /** The x402 funding/quote window expired before the signer or hosted settle step could finish. */ readonly PaymentWindowExpired: "PAYMENT_WINDOW_EXPIRED"; /** The merchant rejected the paid retry. On eip3009 the funding leg had succeeded (sweep); * on erc7710 there is no funding leg — nothing to sweep, follow the message (#2983). */ readonly MerchantRejectedAfterFunding: "MERCHANT_REJECTED_AFTER_FUNDING"; /** #1300 review: funding is on-chain but the merchant never ANSWERED the * paid retry within the timeout. NOT proof of rejection — the merchant * may still settle late, so the guidance is verify-then-act. On eip3009 * the funding leg had succeeded (verify-then-sweep); on erc7710 there is * no funding leg — nothing to sweep, follow the message (#3000). */ readonly MerchantUnresponsiveAfterFunding: "MERCHANT_UNRESPONSIVE_AFTER_FUNDING"; /** * #1307: the caller omitted merchant_url/tool_name (asking Haven to * rehydrate the stored MCP merchant-call context by payment_id), but no * usable context was stored for this intent — either it was never an * MCP-tool quote, or the stored context is incomplete. The fallback is * mechanical: re-send merchant_url, tool_name, arguments, and * mcp_transport explicitly (the version-skew path). */ readonly MerchantCallContextUnavailable: "MERCHANT_CALL_CONTEXT_UNAVAILABLE"; /** * #1351: the caller supplied BOTH the atomic `max_amount` and the * human-denominated `max_amount_human` cap for one purchase. Haven refuses * to guess which the user meant — the two differ by a factor of 10^decimals, * so picking wrong is exactly the silent-overspend this cap exists to * prevent. Rejected before any merchant probe, funding intent, or signature. */ readonly AmbiguousMaxAmount: "AMBIGUOUS_MAX_AMOUNT"; /** * #1351: a human-denominated cap was supplied, but it cannot be converted to * atomic units against THIS quote — either the quote's asset has no known * decimals on its network, or the cap carries more fraction digits than the * asset can represent (truncating it would silently change the user's cap). * The fallback is the exact atomic `max_amount`. */ readonly MaxAmountUnconvertible: "MAX_AMOUNT_UNCONVERTIBLE"; /** * #2979: the merchant answered a `tools/call` probe with its own * machine-readable "cannot settle right now" refusal (HTTP 503, * `{ error: 'merchant_not_ready', reason_code, ... }`) instead of a 402 * challenge — e.g. its settlement wallet is out of gas. No 402 was ever * issued and no payment was created; this is honest and (per * `retry_after_s`, when present) usually transient, unlike a permanent * endpoint miss. */ readonly MerchantNotReady: "MERCHANT_NOT_READY"; }; type AgentPaymentFailureCode = (typeof AgentPaymentFailureCode)[keyof typeof AgentPaymentFailureCode]; /** * Stable rail identifier carried on Haven agent payment responses and resume * state. * * Two layers of vocabulary share this enum because both reach the wire: * * - **Categorical rails** identify the rail family and are used as the * `PaymentResumeState` discriminator: `direct`, `x402` (`mpp` remains a * valid categorical VALUE on historical status reads, but #1328 retired * the `MppResumeState` variant that used to carry it — the mpp_demo * client resume flow no longer exists). * - **Granular rails** identify the specific protocol the backend persists * and returns on response bodies: `mpp_demo`, `mpp_crypto`, * `stripe_deposit`, `spt`. `x402` doubles as both categorical and * granular. * * Consumers reading the top-level `rail` field on a payment status response * should treat any `mpp*` value as the MPP family — this still applies to * historical `mpp_demo` rows, which remain readable. */ declare const AgentPaymentRail: { /** Standard Haven payment from the user's Safe through an approved delegate allowance. */ readonly Direct: "direct"; /** x402 HTTP 402 payment flow with a Haven funding leg and merchant retry leg. */ readonly X402: "x402"; /** Machine Payment Protocol family — categorical value used as a resume-state discriminator. */ readonly Mpp: "mpp"; /** Haven internal MPP demo rail. Not for production traffic. */ readonly MppDemo: "mpp_demo"; /** Crypto-settled MPP rail. */ readonly MppCrypto: "mpp_crypto"; /** Stripe-deposit-backed MPP rail. */ readonly StripeDeposit: "stripe_deposit"; /** Stripe Payment Token MPP rail. */ readonly Spt: "spt"; }; type AgentPaymentRail = (typeof AgentPaymentRail)[keyof typeof AgentPaymentRail]; type PaymentPhase = AgentPaymentPhase; type PaymentNextAction = AgentPaymentNextAction; declare const AGENT_PAYMENT_PHASE_VALUES: ("rejected" | "expired" | "failed" | "agent_signature_required" | "payment_submitted" | "payment_confirmed" | "user_approval_required" | "user_execution_required" | "waiting_for_additional_approvals" | "funding_sent" | "insufficient_funds" | "funded_but_unsettled")[]; declare const AGENT_PAYMENT_NEXT_ACTION_VALUES: ("sign_and_submit_payment" | "check_status_later" | "none" | "wait_for_user_approval" | "wait_for_user_to_complete_payment" | "retry_original_x402_request" | "stop_and_tell_user" | "request_again_if_user_still_wants_it" | "retry_with_explicit_context" | "payment_window_expired" | "fund_account_or_raise_allowance" | "sweep_stranded_funds" | "awaiting_settlement_evidence")[]; declare const AGENT_PAYMENT_FAILURE_CODE_VALUES: ("PRICE_EXCEEDS_MAX" | "PAYMENT_WINDOW_EXPIRED" | "MERCHANT_REJECTED_AFTER_FUNDING" | "MERCHANT_UNRESPONSIVE_AFTER_FUNDING" | "MERCHANT_CALL_CONTEXT_UNAVAILABLE" | "AMBIGUOUS_MAX_AMOUNT" | "MAX_AMOUNT_UNCONVERTIBLE" | "MERCHANT_NOT_READY")[]; declare const AGENT_PAYMENT_RAIL_VALUES: ("x402" | "mpp_demo" | "mpp_crypto" | "stripe_deposit" | "spt" | "direct" | "mpp")[]; declare const AgentPaymentPhaseDescriptions: Record; declare const AgentPaymentNextActionDescriptions: Record; declare const AgentPaymentFailureCodeDescriptions: Record; /** * #1308: machine-readable warning codes carried in the `warnings` array on * x402 MCP tool responses. Warnings are ADVISORY — they never replace a * refusal, and existing failure codes stay authoritative for errors. The * legacy `cap_warning` string field is kept for compatibility; the structured * entry carries the same message under MISSING_MAX_AMOUNT. */ declare const AgentPaymentWarningCode: { /** No max_amount cap was supplied — the live quoted price was accepted as-is. */ readonly MissingMaxAmount: "MISSING_MAX_AMOUNT"; /** The signing window closes soon; sign promptly or re-quote with the same idempotency key. */ readonly QuoteExpiresSoon: "QUOTE_EXPIRES_SOON"; /** The merchant URL was resolved via discovery — pass the RESOLVED url forward. */ readonly MerchantUrlDiscovered: "MERCHANT_URL_DISCOVERED"; /** * #1306: the catalog's last-verified price_atomic differs from the LIVE * merchant quote for a guided catalog purchase. The catalog price is only * ever indicative; the live quote in the same response is authoritative. */ readonly CatalogPriceDiffers: "CATALOG_PRICE_DIFFERS"; /** * #1306: the rail-aware allowance/budget pre-check could not be read (RPC * failure, etc). `sufficient` is reported as null rather than a fabricated * true/false — the on-chain policy remains the actual gate either way. */ readonly AllowanceCheckUnavailable: "ALLOWANCE_CHECK_UNAVAILABLE"; /** * #1319: the delegation-rail read itself SUCCEEDED, but the remaining * figure it returned is the #1145 fallback (the full configured budget) * rather than a live ERC20PeriodTransferEnforcer read — `sufficient` is a * real true/false, just computed from an optimistic number. Distinct from * {@link AgentPaymentWarningCode.AllowanceCheckUnavailable}, which fires * when the read failed outright and `sufficient` degrades to null. The * on-chain policy re-checks at redemption either way; this only says the * guidance shown here may be optimistic. */ readonly AllowanceReadOptimistic: "ALLOWANCE_READ_OPTIMISTIC"; /** * #2991: the quote tools' `expected_settlement_scheme` prediction of what * `haven_prepare_catalog_purchase` / `haven_pay_mcp_tool` will actually * select could not be computed — the agent's execution rail could not be * read from Haven, so `expected_settlement_scheme` is `null` rather than a * guess. `accepted_scheme` (the merchant's offer) is unaffected. */ readonly X402SchemeUnknown: "X402_SCHEME_UNKNOWN"; /** * #2968: the merchant answered 200 and handed over goods, but Haven holds NO * on-chain evidence that the payment moved. `settled: false` beside this code * is not a failure — it is the absence of proof, and the two must travel * together so an agent can tell "the user has the goods" apart from "the * money moved". Carries the intent's `expires_at`: after that instant the * settlement can no longer land at all. */ readonly SettlementUnconfirmed: "SETTLEMENT_UNCONFIRMED"; }; type AgentPaymentWarningCode = (typeof AgentPaymentWarningCode)[keyof typeof AgentPaymentWarningCode]; interface AgentPaymentWarning { code: AgentPaymentWarningCode; message: string; } /** * #1308: the structured next-step contract on x402 MCP tool responses. It * EXTENDS the existing taxonomy — `next_action` values come from * AgentPaymentNextAction, never a parallel vocabulary. `next_arguments` * carries the small, literally-usable arguments; bulky pass-through fields * (payment_required) are named in `reason` and taken from the SAME response. */ interface AgentNextStep { /** From `AgentPaymentNextAction`. */ next_action: AgentPaymentNextAction; /** * Claude-family namespaced tool name for the next call * (`mcp____`), when one exists. * * **Namespaced with the DEFAULT server names**, which is the most the hosted * server can know: local server names are the client's own config and never * reach Haven. Two runtimes are already not the default — Codex names servers * by config key (`haven`, `haven_signer`), and a connector run with * `--name ` wires `haven-` / `haven-signer-` (#1694). On * either, this field and `next_tool_server` name a server the client does not * have. Prefer {@link AgentNextStep.next_tool_server_role} plus * {@link AgentNextStep.next_tool_name} whenever your servers are not the * default pair; see #2550. */ next_tool?: string; /** * The server half of `next_tool`, unprefixed — `haven` or `haven-signer`. * Carries the same default-name caveat as `next_tool` (#1588, #2550). */ next_tool_server?: string; /** The bare tool name, callable on whichever server plays the role below. */ next_tool_name?: string; /** * Which of the CLIENT'S OWN servers to call (#2550). Runtime-neutral, and * the field to resolve against when your server names are not the defaults — * it names a role rather than a name the hosted server had to guess. */ next_tool_server_role?: 'hosted' | 'signer'; /** Small literal arguments for next_tool. Bulky fields are referenced by reason. */ next_arguments?: Record; /** * #3101 (epic #3105, decision 3): present exactly when `next_tool` is * absent — why no tool is named (the payment id is unknown, nothing is left * to do, the arguments could not be built). `next_tool` is never null. */ next_tool_omitted_reason?: string; /** False when the agent should stop and involve the user before continuing. */ safe_to_continue: boolean; reason: string; } /** * #1349: compact, Haven-generated reporting evidence for a completed x402 * merchant purchase. `status`, money fields, merchant endpoint/address, and * funding transaction come from Haven payment state; `product` and * `invoice_id` are optional merchant-supplied display metadata. The raw * merchant result remains separate evidence and MUST NOT be used to infer * settlement status. */ interface AgentPurchaseSummary { /** Set only after Haven has completed the funding and merchant-settlement flow. */ status: 'settled'; product: string | null; amount: string | null; amount_atomic: string | null; asset: string | null; network: string | null; merchant: { address: string | null; resource_url: string | null; }; /** Merchant-supplied identifier, or null when the merchant did not supply one. */ invoice_id: string | null; funding_tx_hash: string | null; /** Optional merchant receipt reference parsed from PAYMENT-RESPONSE; not Haven settlement proof. */ settlement_tx_hash: string | null; /** Same read-only allowance block returned at the top level, or null when unavailable. */ allowance: PostPurchaseAllowanceSummary | null; } /** #1308: compact reporting summary — what the agent tells the user. */ interface AgentPaymentSummary { payment_id: string; status: string; amount?: string; amount_atomic?: string; token?: string; network?: string; expires_at?: string; product?: string; /** * Default reporting contract for a successful `haven_settle_mcp_tool` call. * The merchant's raw `result` remains available separately as advanced * evidence; do not parse it to determine whether a payment settled. */ purchase_summary?: AgentPurchaseSummary; } declare const AgentPaymentRailDescriptions: Record; declare const AgentPaymentPhaseSchema: AgentPaymentEnumSchema; declare const AgentPaymentNextActionSchema: AgentPaymentEnumSchema; declare const AgentPaymentFailureCodeSchema: AgentPaymentEnumSchema; declare const AgentPaymentRailSchema: AgentPaymentEnumSchema; interface PaymentStatusResult { paymentId: string; kind: PaymentStateKind; rail: string; status: PaymentStatus | string; phase: PaymentPhase; nextAction: PaymentNextAction; amount: string; token: string; resourceUrl: string | null; merchantAddress: string | null; /** Delegate EOA captured on the payment intent when it was created. */ payerAddress?: string | null; /** #2960: additive alongside `payerAddress` above (`parties.delegate` only). */ parties?: PaymentParties; txHash: string | null; expiresAt: string; chainId: number; message: string; /** Platform fee surfaced so it's never silently collected (#386). */ fee?: PaymentFee | null; amountAtomic?: string | null; asset?: string | null; network?: string | null; description?: string | null; idempotencyKey?: string | null; x402?: { amountAtomic: string | null; asset: string | null; network: string | null; resourceUrl: string | null; merchantAddress: string | null; description: string | null; idempotencyKey: string | null; }; mpp?: { amountAtomic: string | null; asset: string | null; network: string | null; resourceUrl: string | null; merchantAddress: string | null; description: string | null; idempotencyKey: string | null; challengeId: string | null; }; } /** * Result of an erc7710 direct settlement (#1454). * * Deliberately NOT an `X402Receipt`. A 3009 receipt describes a completed * two-leg payment — funding tx included — whereas here nothing has settled yet * when this returns: the merchant redeems the delegation chain when the caller * retries with the header. Reusing the receipt type would let a caller read * `txHash` as "paid" on a payment that has not moved a cent. */ interface X402Erc7710Settlement { paymentId: string; /** * Pass verbatim as the `PAYMENT-SIGNATURE` header on the merchant retry — * that name ALONE. erc7710 is always x402 v2, and this header carries the * delegation chain, so also sending the legacy `X-PAYMENT` overflows the * merchant's header limit (HTTP 431, #2341). */ paymentHeader: string; /** The merchant address the child delegation is pinned to. */ merchantPayTo: string; amountAtomic: string; asset: string; network: string; /** Facilitators the child is redeemable by, when the merchant advertised any. */ facilitatorAddresses: string[] | null; } /** @internal */ /** One payable service in Haven's merchant catalog (epic #1717). */ interface HavenCatalogEntry { id: string; name: string; description: string; category: string; resourceUrl: string; rail: 'x402' | 'mpp'; protocol: 'http' | 'mcp'; toolName: string | null; toolArguments: Record | null; priceDisplay: string | null; priceAtomic: string | null; asset: string | null; network: string | null; status: 'active' | 'degraded' | 'delisted'; verifiedAt: string | null; /** * Where the entry came from. `operator` = curated in migrations/scripts * (the operator vouches for the listing; the catalog refresh probe still * checks the endpoint, see `verifiedPayable`). `ingestion` = submitted * through the Verified Payable Directory and passed domain-ownership proof * plus the read-only quote probe. */ source: 'operator' | 'ingestion'; /** True only for `ingestion` entries — the one ownership claim. See the epic's trust claim (never merchant honesty or quality). */ domainVerified: boolean; /** * True when Haven watched this endpoint answer a live quote (#2978): the * directory probe for `ingestion` rows, the periodic catalog refresh probe * for `operator` rows (`status === 'active'` with `verifiedAt` set). False * for a degraded row of either source. `discoverTools({ verified: * 'verified' })` filters on this field, not on `source`. */ verifiedPayable: boolean; /** * The merchant this entry belongs to (#3078). OPTIONAL on purpose: an * installed SDK may face a backend that predates the merchant layer, and * `discoverTools` must keep working against it — the field is absent, not * null, in that case. */ merchant?: HavenCatalogMerchant; } /** A catalog entry's merchant as the wire carries it (#3078). */ interface HavenCatalogMerchant { id: string; slug: string; name: string; /** `coming_soon` never reaches an entry in practice (a prospect has no offers). */ listingStatus: 'live' | 'coming_soon'; /** Haven-run test content: the demo store and the stranded-funds fixture. */ isTestMerchant: boolean; } /** * #3128: one page of receipts. `total` is the count Haven holds for the * agent (an empty page with `total: 0` means no receipt exists — there is no * indexing delay behind this list); `hasMore` says the page was cut at the * limit; `nextCursor` is fed back as `cursor` for the next page. Against a * backend older than #3128 the three are `null` — "unknown", never a * fabricated 0 / false. */ interface HavenPaymentReceiptsPage { receipts: HavenPaymentReceipt[]; total: number | null; hasMore: boolean | null; nextCursor: string | null; } /** @internal */ /** Wire shape of POST /catalog/submit (#1717, #1716). */ interface CatalogSubmissionAccepted { id: string; verify_token: string; status: 'submitted' | 'ownership_verified' | 'verified_payable'; } /** @internal Client-facing submission handle. */ interface HavenCatalogSubmission { id: string; verifyToken: string; status: 'submitted' | 'ownership_verified' | 'verified_payable'; } declare class HavenError extends Error { readonly code: string; readonly statusCode?: number | undefined; readonly paymentId?: string | undefined; constructor(message: string, code: string, statusCode?: number | undefined, paymentId?: string | undefined); } declare class HavenApiError extends HavenError { readonly body?: unknown | undefined; constructor(message: string, statusCode: number, body?: unknown | undefined, paymentId?: string); } /** * #1300: quoteX402 hit a URL that answered something other than 402 — the * typed form of "this is not the x402 endpoint". Exists so consumers (the * hosted MCP's #1271 discovery trigger) can key on a class instead of * message text. */ /** * #1300: a merchant-facing fetch hit the client-side merchantTimeout. Typed * so consumers can distinguish "merchant never answered" from a real HTTP * error response — the funded-retry path routes this to verify-then-sweep * guidance instead of a bare 504. */ declare class MerchantTimeoutError extends HavenApiError { readonly merchantErrorCode: "merchant_timeout"; constructor(message: string); } declare class X402UnexpectedStatusError extends HavenApiError { readonly x402ErrorCode: "unexpected_non_402_status"; /** * #2979: `body` is the merchant's own JSON, when the non-402 response * carried one — e.g. the demo merchant's `/mcp` readiness gate answers * `503 { error: 'merchant_not_ready', reason_code, ... }`. Optional and * best-effort: a non-JSON or unreadable body leaves this `undefined`, same * as before this field existed. Consumers key on it (not on the message * string) to distinguish an honest, machine-readable merchant refusal from * a genuine "this is not the x402 endpoint" miss, which otherwise look * identical — both are just "some non-402 status". */ constructor(message: string, statusCode: number, body?: unknown); } /** * #1521: the idempotency key resolved to a payment that has already settled, * and the delegate can no longer fund a fresh authorization for it. * * This is the typed form of "you already bought this". It exists because the * alternative was indefensible: the SDK used to mint a new EIP-3009 * authorization against the spent delegate and hand it back paired with the * ORIGINAL payment's `txHash`, so the caller learned what had happened only * from a merchant-side balance error that reads identically to a broken * payment rail. * * `receipt` is the ORIGINAL payment — a real receipt for real settled funds, * deliberately carrying no `paymentHeader`, because any header minted here * would be exactly the unfundable artifact this error replaces. */ declare class X402AlreadySettledError extends HavenApiError { readonly receipt: X402Receipt; /** * `settled` — the delegate was checked on-chain and cannot fund a fresh * authorization, so this payment demonstrably completed. * `unverifiable` — no `chainRpcs` entry for the chain, so fundability * could not be established either way. Same refusal, weaker claim; say * which, rather than assert what was not checked. */ readonly basis: 'settled' | 'unverifiable'; readonly x402ErrorCode: "already_settled"; constructor(message: string, receipt: X402Receipt, /** * `settled` — the delegate was checked on-chain and cannot fund a fresh * authorization, so this payment demonstrably completed. * `unverifiable` — no `chainRpcs` entry for the chain, so fundability * could not be established either way. Same refusal, weaker claim; say * which, rather than assert what was not checked. */ basis: 'settled' | 'unverifiable'); } declare class HavenPaymentStateError extends HavenApiError { readonly state: PaymentStatusResult; resumeState?: X402ResumeState; constructor(message: string, statusCode: number, state: PaymentStatusResult, body?: unknown); get status(): string; get phase(): PaymentPhase; get nextAction(): PaymentNextAction; } declare class HavenSigningError extends HavenError { constructor(message: string); } /** * #2972: `MerchantCompletion.reportSettlementEvidence` / * `HavenClient.reportSettlementEvidence` refuse a `0x00…00` settlement hash * BEFORE any network call — see `isZeroSettlementTxHash`. That marker is * never a real transaction (the demo merchant's own "delivered, not settled" * value), so posting it to `POST /machine-payments/evidence` could only ever * come back refused, at the cost of a real round trip. A typed error rather * than a `HavenApiError`-shaped 400: no request was ever attempted, so there * is no HTTP status or response body to carry. */ declare class HavenZeroSettlementHashError extends HavenError { constructor(paymentId: string); } /** * Refusal codes the local signer returns when it does not recognise the * VERSION of a Haven-signed binding it was asked to sign (#1309). Distinct * from `AgentPaymentFailureCode`: these describe a **signer capability** * problem (this install cannot evaluate what Haven sent), not a payment-domain * outcome, and they never reach the backend's REST/OpenAPI surface — only the * local signer's own MCP tool responses (`haven_sign` / `haven_sign_x402` / * `haven_sign_sweep_delegate`). That is also why this pair does not go through * the `AgentPaymentFailureCode` four-gate (sdk → backend mirror → spec → * api-types): there is no backend mirror to keep in sync with. */ declare const SignerRefusalCode: { /** `SUPPORTED_X402_EXPECTED_VERSIONS` in `@haven_ai/signer` does not include the received version. */ readonly UnsupportedExpectedContextVersion: "UNSUPPORTED_EXPECTED_CONTEXT_VERSION"; /** `SUPPORTED_SWEEP_BINDING_VERSIONS` in `@haven_ai/signer` does not include the received version. */ readonly UnsupportedSweepBindingVersion: "UNSUPPORTED_SWEEP_BINDING_VERSION"; }; type SignerRefusalCode = (typeof SignerRefusalCode)[keyof typeof SignerRefusalCode]; /** * Canonical recovery guidance for a stale local signer (#1309) — the ONE * string both the signer's structured refusal (`fallback` field, carried by * `HavenUnsupportedSignerVersionError`) and the hosted quote's advisory * `signer_compatibility.fallback` (#1155) render, so an agent that meets * either surface is told the identical fix. A second hand-maintained copy of * this sentence is exactly how the two surfaces could start disagreeing about * what to do. */ declare function signerUpdateFallback(channel?: string): string; /** * The same sentence rendered for THIS build's channel (#2423). Every existing * consumer keeps importing this constant and keeps getting a string; the only * thing that moved is that `alpha` is no longer typed into it. * * The hosted MCP server is the one caller that does NOT use this constant: it * is deployed rather than published, so it renders `signerUpdateFallback()` * with the channel its own environment names. */ declare const SIGNER_UPDATE_FALLBACK: string; /** * Thrown by the local signer when a Haven-signed binding (x402 expected * context or sweep authorization) carries a version outside what this signer * install enforces (#1143, structured as #1309). Machine-readable: `code`, * `supportedVersions`, and `receivedVersion` are DERIVED from the signer's own * `SUPPORTED_X402_EXPECTED_VERSIONS` / `SUPPORTED_SWEEP_BINDING_VERSIONS` * constants at the throw site, never a second literal — see * `assertSupportedBindingVersion` in `@haven_ai/signer`. * * This narrows HOW the refusal is reported. It does not weaken it: nothing is * signed either way, and the version stays inside the Haven-signed binding * message (callers must not "fix" a mismatch by rewriting it). */ declare class HavenUnsupportedSignerVersionError extends HavenError { readonly supportedVersions: readonly number[]; readonly receivedVersion: number; readonly fallback: string; constructor(message: string, code: SignerRefusalCode, supportedVersions: readonly number[], receivedVersion: number, fallback: string); } declare class HavenTimeoutError extends HavenError { constructor(paymentId: string); } /** * Verifiable payment receipts. * * A self-contained proof bundle for a settled Haven payment that anyone can * verify **independently of Haven**. The anchor is the agent delegate's * signature over the on-chain transfer hash: recover the signer and confirm it * is the agent's delegate, and you have cryptographic proof the agent authorised * exactly this transfer — no need to trust Haven's backend. The on-chain * `txHash` is the settlement source of truth (verify on any explorer). * * This lives in the SDK so agents and users can verify receipts client-side * with zero Haven trust. */ declare const RECEIPT_VERSION = "haven-receipt-1"; interface PaymentReceipt { version: typeof RECEIPT_VERSION; paymentId: string; payment: { token: string; tokenAddress: string; amount: string; amountSek: string | null; recipient: string; /** The payer's smart-account address. */ account: string; /** * #2960: one party vocabulary for "who paid", additive alongside `account` * above (which is `parties.treasury_account` only). Optional: a server * from before #2960 emits neither. Ignored by `verifyPaymentReceipt`, * which reads only `authorization`. */ parties?: RawPaymentParties; chainId: number; settledAt: string | null; resourceUrl: string | null; }; /** The agent's cryptographic authorisation — what makes the receipt verifiable. */ authorization: { delegate: string; signHash: string; signature: string | null; }; onChain: { txHash: string | null; chainId: number; }; } type ReceiptVerification = { verified: true; recoveredSigner: string; } | { verified: false; reason: 'missing_signature' | 'bad_signature' | 'signer_mismatch'; recoveredSigner?: string; }; /** * Verify a receipt independently: recover the signer from the authorisation and * confirm it is the agent's delegate. Pure — `recover` is injectable but * defaults to standard ECDSA recovery, so this runs anywhere (no Haven backend). */ declare function verifyPaymentReceipt(receipt: PaymentReceipt, recover?: (hash: string, signature: string) => string): ReceiptVerification; /** * Gasless delegate-sweep primitives — the single source of truth shared by the * edge signer (which signs) and the Haven backend (which relays). * * A stranded delegate EOA holds USDC but no ETH, so a raw ERC-20 transfer can't * pay for its own gas. Instead the delegate signs an *off-chain* EIP-3009 * `TransferWithAuthorization` and the Haven relayer submits it on-chain and pays * gas. The relayer is only a gas payer: it holds no allowance and is never a * spender, so a relayer compromise cannot move user funds. * * Framework-neutral on purpose: `buildSweepTypedData` returns a plain * `{ domain, types, primaryType, message }` that both viem * (`signTypedData`/`recoverTypedDataAddress`) and ethers v6 * (`signTypedData`/`verifyTypedData`) accept, so the signer (viem) and backend * (ethers) stay in lockstep without sharing a crypto library. */ /** Base mainnet. The only chain Haven sweeps today. */ declare const SWEEP_BASE_CHAIN_ID = 8453; /** Base Sepolia testnet — used by the dev environment / QA harness. */ declare const SWEEP_BASE_SEPOLIA_CHAIN_ID = 84532; /** Canonical Circle USDC on Base (FiatTokenV2_2). */ declare const SWEEP_BASE_USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; /** Circle's canonical Base Sepolia testnet USDC. */ declare const SWEEP_BASE_SEPOLIA_USDC_ADDRESS = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"; /** True when the gasless sweep supports a chain (its USDC domain + address are known). */ declare function isSweepableChain(chainId: number): boolean; /** EIP-712 `TransferWithAuthorization` struct, per EIP-3009. */ declare const TRANSFER_WITH_AUTHORIZATION_TYPES: { readonly TransferWithAuthorization: readonly [{ readonly name: "from"; readonly type: "address"; }, { readonly name: "to"; readonly type: "address"; }, { readonly name: "value"; readonly type: "uint256"; }, { readonly name: "validAfter"; readonly type: "uint256"; }, { readonly name: "validBefore"; readonly type: "uint256"; }, { readonly name: "nonce"; readonly type: "bytes32"; }]; }; interface SweepEip712Domain { name: string; version: string; chainId: number; verifyingContract: string; } /** * A fully-specified EIP-3009 authorization. All amounts/times are decimal * strings (JSON-safe) and `nonce` is a 0x-prefixed 32-byte hex value. `token` * and `chainId` are carried explicitly so the signer can assert they are * canonical before signing. */ interface SweepAuthorization { /** Delegate EOA the funds are swept FROM. */ from: string; /** Originating Safe the funds are swept TO. */ to: string; /** Atomic USDC amount (decimal string). */ value: string; /** Unix seconds the authorization becomes valid (decimal string, usually "0"). */ validAfter: string; /** Unix seconds the authorization expires (decimal string). */ validBefore: string; /** Random 0x-prefixed 32-byte hex nonce. */ nonce: string; /** USDC contract address. */ token: string; /** Chain id (8453 today). */ chainId: number; } /** * Haven's signature over the sweep authorization context, signed with the same * binding key the x402 expected-context uses. Lets the edge signer verify the * authorization actually came from Haven (and wasn't crafted by a compromised * hosted server pointing `to` at an attacker) before it signs. */ interface SweepExpectedAuth { /** * Currently always 1. Typed as `number` for the same reason as * `X402ExpectedAuth.version` (#1143): it is inbound, so a stale signer must be * able to *receive* an unknown version in order to report it. The signer's * `SUPPORTED_SWEEP_BINDING_VERSIONS` is the authority on what it will sign. */ version: number; message: string; signature: string; signer: string; } /** What `POST /machine-payments/sweep/prepare` returns when funds are stranded. */ interface SweepPreparation { authorization: SweepAuthorization; expectedAuth: SweepExpectedAuth; } /** Wire response from `POST /machine-payments/sweep/prepare` (snake_case). */ interface SweepPrepareResponse { /** Present and true when the delegate holds nothing to recover. */ nothing_stranded?: boolean; /** * Present and true when the stranded balance is below the sweep floor (#700): * it is left on the delegate as dust rather than recovered, because the gas to * sweep it would exceed its value. `min_usdc` carries the configured floor. No * `authorization` is built. */ below_min?: boolean; min_usdc?: string; /** The authorization to sign — absent when nothing is stranded or below the floor. */ authorization?: SweepAuthorization; /** Haven's binding over the authorization — absent when nothing is stranded. */ expected_auth?: SweepExpectedAuth; asset?: string; amount?: string; amount_atomic?: string; chain_id: number; sign_instructions?: string; message?: string; } /** Wire response from `POST /machine-payments/sweep/submit` (snake_case). */ interface SweepSubmitResponse { tx_hash: string; asset: string; amount: string; amount_atomic: string; from_address: string; to_address: string; chain_id: number; explorer_url: string; idempotent_replay?: boolean; } /** Result of a submitted gasless sweep. */ interface SweepSubmitResult { txHash: string; amount: string; amountAtomic: string; asset: string; fromAddress: string; toAddress: string; chainId: number; explorerUrl: string; } interface SweepTypedData { domain: SweepEip712Domain; types: typeof TRANSFER_WITH_AUTHORIZATION_TYPES; primaryType: 'TransferWithAuthorization'; message: { from: string; to: string; value: bigint; validAfter: bigint; validBefore: bigint; nonce: string; }; } /** Resolve the canonical USDC contract for a sweepable chain, or throw. */ declare function sweepUsdcAddress(chainId: number): string; /** Resolve the USDC EIP-712 domain for a sweepable chain, or throw. */ declare function sweepUsdcDomain(chainId: number): SweepEip712Domain; /** * Build the EIP-712 typed data for an authorization, validating that the token * and chain are canonical (the domain's `verifyingContract` must match the * authorization's `token`). Returns bigint-valued fields so both viem and * ethers v6 sign/recover identically. */ declare function buildSweepTypedData(auth: SweepAuthorization): SweepTypedData; /** * Canonical, deterministic string the backend signs and the signer re-derives * for the authorization binding. The `Haven sweep authorization v1` namespace * (and `kind`) is distinct from the x402 expected-context namespace so an x402 * binding can never be replayed as a sweep authorization even though they share * a signing key. */ declare function buildSweepAuthorizationMessage(auth: SweepAuthorization): string; /** * Merchant delivery and the evidence trail behind it (#1620, epic #1613). * * Where `mcp-merchant-transport.ts` (#1616) owns the wire — timeouts, * sessions, SSE framing — this module owns what has to be TRUE around a * merchant call once a payment exists: which wallet the merchant should see, * what the payment's live state permits, and what gets written down * afterwards. * * The reporting is deliberately best-effort and deliberately asymmetric. A * merchant that REJECTS a retry after Haven already moved money is a * reconciliation event and is recorded as one; a merchant that accepts is * evidence, plus its own receipt when it offers one. Neither write may ever * change the caller-visible outcome — the resource is already paid for, and * an exception thrown from bookkeeping would turn a completed payment into a * reported failure. That is why every one of these swallows. * * Scheme-neutral by construction: it is handed a receipt or a payment id and * never asks how the money moved, which is what lets the #1508 no-funding-leg * path through the same door as the 3009 path. * * Internal to `HavenClient`. Exported for direct tests and composition only. */ /** #2292: what an agent says a merchant answered to a retry Haven did not make. */ type X402MerchantOutcome = 'accepted' | 'rejected'; /** #2292: what Haven wrote down for such a report. */ interface X402MerchantOutcomeReport { paymentId: string; outcome: X402MerchantOutcome; /** Haven's own funding tx for this payment — the anchor, never caller-supplied. */ txHash: string; /** Haven's own recorded resource URL — likewise never caller-supplied. */ resourceUrl: string; recorded: 'reconciliation_event' | 'evidence'; } /** * #2970: what `reportEvidence` learned about the report it just made. * * `confirmed` mirrors the backend's 202 (`modules/mpp/evidence.ts`) — the * intent is now `confirmed` (or was already, on the funding-leg path) with * THIS hash recorded. `retryable` mirrors its 503 (`settlement_unobservable`, * exhausted the retry budget above): the chain could not be read, or the * transaction is not mined yet — ask again later. `refused` mirrors every * terminal refusal (409 `settlement_unverified`, a validation error, an * unknown payment id, or a transport failure with no HTTP status at all, * reported as `statusCode: 0`) — reporting the same hash again will not * change the answer. */ type EvidenceReportOutcome = { outcome: 'confirmed'; } | { outcome: 'retryable'; statusCode: number | undefined; } | { outcome: 'refused'; statusCode: number; }; /** * #2970: a hash of the form `0x00…00` is never a real transaction — it is the * demo merchant's own "delivered, not settled" marker (`ZERO_TX_HASH` in * `packages/demo-merchant-mcp/src/x402.ts`), reused rather than invented here * so the hosted gate and any other consumer recognise it the same way. Treated * as equivalent to "no hash was reported": there is nothing on-chain to verify, * so asking the backend to look is a wasted round trip that can only ever * resolve to a refusal. */ declare function isZeroSettlementTxHash(hash: string | null | undefined): boolean; declare class HavenClient { private readonly delegateKey; private readonly havenApi; private readonly accountReads; private readonly delegateSweep; private readonly x402Wallet; private readonly merchantTransport; private readonly confirmationTimeout; private readonly pollingInterval; private readonly chainRpcs; private readonly inFlightX402; /** * The EIP-3009 funding-leg lifecycle (#1618). The facade holds a reference * and delegates; it does not reimplement any of it. */ private readonly fundingLeg; /** * The erc7710 direct-settlement lifecycle (#1619). Separate from the funding * leg on purpose: this scheme has no funding leg to share. */ private readonly erc7710; /** * Merchant delivery and the evidence trail behind it (#1620). Scheme-neutral * on purpose — both settlement schemes finish through the same door. */ private readonly merchantCompletion; /** Delegate address derived from the private key (if provided) */ readonly delegateAddress: string | undefined; constructor(config: HavenClientConfig); /** * Run `fn` with extra Haven-API headers scoped to the async work it * performs. Used by the MCP server to tag every Haven API request that * a single tool dispatch makes with `X-Haven-MCP-Tool: ` so the * backend can write an audit-log row attributing the call. * * The headers are held in an `AsyncLocalStorage` so overlapping * dispatches do not leak headers into each other's requests. The store * inherits across `await` boundaries, so any Haven API call made while * `fn` is awaiting will pick up the right headers. * * Has no effect on outbound merchant requests (x402 / MPP) — those * never go through the internal `request` path that reads the * context. */ withRequestContext(headers: Record, fn: () => Promise): Promise; /** * Send a payment in one call. * * Creates the intent, signs the hash, submits the signature, * and polls until confirmed (or throws on failure/timeout). * * Requires `delegateKey` to be set in the client config. */ pay(request: PaymentRequest): Promise; /** * Step 1: Create a payment intent. * * Returns the intent with the hash to sign. */ createIntent(request: PaymentRequest): Promise; /** * Keyless x402 construct. * * The non-custodial half of an x402 payment: posts the funding request to * `/x402` and returns the unsigned funding hash plus the data the caller * needs to build and sign the EIP-3009 merchant header itself. Crucially it * does **not** sign — neither the funding hash nor the merchant header — so * it works without a `delegateKey`. Both delegate signatures happen on the * machine that holds the key (the edge); the hosted MCP server relays only. * * Use this from the hosted, keyless server. The all-in-one `authorizeX402` * remains for local clients that hold the key. * * Throws (via the shared payment-state path) when the amount exceeds the * on-chain allowance — there is nothing to sign until the user approves. */ createX402Intent(paymentRequired: X402PaymentRequired, options?: X402AuthorizationOptions): Promise; /** * Step 2: Sign a hash with the delegate key. * * Returns the 65-byte signature (0x-prefixed). * Requires `delegateKey` to be set in the client config. */ sign(hash: string): string; /** * Sign a payment's `sign_data` with the correct scheme for its rail. * * Dispatching on the server-provided scheme means a caller never has to * know which rail an account is on; an unknown scheme — or an absent one, * since the legacy AllowanceModule rail retired (#2850) — is a hard error, * never a guessed signature. The session rail's 'eip191_userop' is retired * (#834) — the backend refuses those intents with HTTP 410 before any * sign_data reaches a client, so encountering it here is a hard error too. */ private signForData; /** * Step 3: Submit a signature to execute the payment. * * The signature can come from `client.sign()` or from external signing. */ submitSignature(paymentId: string, signature: string): Promise<{ status: string; txHash?: string; }>; /** * Get the current status of a payment. */ getPayment(paymentId: string): Promise; /** * Get agent-actionable status for a payment intent or approval request. * * Use this for IDs returned by agent tools and machine-payment/x402 flows. * `getPayment()` remains available for payment-intent-only integrations. */ getPaymentStatus(paymentId: string): Promise; /** * Get the agent identity tied to this API key. */ getAgent(): Promise; /** * One-shot "am I ready?" bootstrap: identity + live spend authority + a * readiness signal, in a single call. Folds {@link getAgent} and * {@link getAllowances} together and derives a {@link HavenAgentReadiness} * so an agent can answer "who am I and can I pay right now" at session start * without two round trips and manual assembly. */ getAgentSummary(): Promise; /** * Sweep stranded USDC and ETH from the delegate EOA back to the originating Safe. * * The delegate key held by this client signs and submits the transfer transactions * directly — Haven's backend never handles the key or constructs signed txs * (CASP/MiCA Red Line #2). Funds always go to the Safe linked to this agent. * * Requires `chainRpcs` to be set for the agent's chain in `HavenClientConfig`. */ sweepDelegate(): Promise; /** * Hosted (keyless) split-signer sweep — step 1 of 2. * * Asks the backend to build a gasless EIP-3009 sweep authorization for the * delegate's stranded USDC. Returns `nothing_stranded` when the delegate is * empty, otherwise an `authorization` + Haven `expected_auth` to hand to the * edge signer's `haven_sign_sweep_delegate`. No key is required on this client. */ prepareSweep(): Promise; /** * Hosted (keyless) split-signer sweep — step 2 of 2. * * Relays the delegate-signed authorization. The Haven relayer submits the * on-chain `transferWithAuthorization` and pays gas; this client never holds * the key. */ submitSweep(authorization: SweepAuthorization, signature: string): Promise; /** * Get configured and on-chain allowances for the authenticated agent. */ getAllowances(): Promise; /** * #3126 — is the checked amount of the token actually HELD on the * agent's own account? * * This is the companion to {@link getAllowances}, not a variant of it: * allowances answer what the agent is PERMITTED to spend this period; * this answers whether the account HOLDS funds behind that permission, * as a sufficiency signal — `covered: true | false | null` — never as a * balance. `covered: null` means the chain read failed: treat it as * unverifiable, not as absence (`coverageError` says why). The account's * balance itself is deliberately not returned. */ checkFunds(input: { token: string; amountAtomic: string; }): Promise; /** * `POST /machine-payments/budget-precheck` (#3054): ask Haven to decide — * server-side — whether `amountAtomic` of `token` fits the agent's * remaining delegation budget, the same compare the guided prepare used to * run locally over its allowances read. * * On insufficiency Haven refuses (403, `delegation_budget_exceeded`) and * the refusal reaches the `payment_refusals` ledger with * `source: 'hosted_prepare'` — the point of the endpoint. This method * surfaces that decision as a thrown {@link HavenApiError}; it does NOT * swallow it, because swallowing would turn a decided refusal into the * degrade-to-warning path and the ledger row would still land while the * purchase proceeded. * * camelCase body like the route family; the response mirrors the wire * (`sufficient`, `remaining_atomic`). `resourceUrl` is the merchant * resource being bought — the ledger dedupe window's discriminating * column — never this request's own URL. */ precheckBudget(input: { chainId?: number; token: string; amountAtomic: string; merchantTo?: string; resourceUrl?: string; }): Promise<{ sufficient: boolean; remaining_atomic: string; remaining_is_from_chain?: boolean; }>; /** * Post-purchase allowance/budget summary for a settled payment (#1310). * * Reuses the EXACT rail-aware read path {@link getAllowances} / #1306's * catalog-purchase preflight `allowance` block use — `GET * /machine-payments/allowances`, with delegation-rail values coming from * the #1090 `deriveDelegationBudgets`-backed enforcer read, never * `agent_allowances` — so this can never disagree with * {@link getAllowances} for the same fixture. The settled token is * resolved from {@link getPaymentStatus} so callers pass only * `paymentId`, never a second haven_get_agent-style round trip. * * NEVER throws: any failed read (status lookup, agent lookup, or the * allowance/budget lookup itself) degrades to `{ allowance: null, * warnings: [ALLOWANCE_CHECK_UNAVAILABLE] }` rather than converting a * successful settlement into a failure — the on-chain policy remains the * actual spend gate regardless of whether this report can be produced. * * Freshness caveat (#1319): the delegation rail's on-chain enforcer read * can silently fall back to the optimistic full period budget without * throwing when the RPC read itself fails (#1145's fund-safe design, * unchanged here). {@link getAllowances}'s `onchain.remainingIsFromChain` * now carries that provenance on the wire, and the #1306 catalog-purchase * preflight (`haven_prepare_catalog_purchase`) surfaces it as a warning — * this summary does not (yet). `remaining_atomic` here reflects the last * successful chain read, not a guaranteed-live one, and callers should not * phrase it as guaranteed-fresh. */ getPostPurchaseAllowanceSummary(paymentId: string): Promise<{ allowance: PostPurchaseAllowanceSummary | null; warnings: AgentPaymentWarning[]; payment: PaymentStatusResult | null; }>; /** * `haven_get_payment_status` convenience: fetch status and, for a * genuinely SETTLED x402 payment, attach the same post-purchase * allowance/budget summary a settle response carries. * * #1310/#1311 parity: this is the ONE home for logic that was duplicated * verbatim in the hosted and local `haven_get_payment_status` handlers — * `packages/mcp-server/src/tools/state-direct-recovery.ts` since #2809 (it * was `packages/mcp-server/src/tools.ts` when this was written) and * `packages/mcp/src/tools.ts` — extracted * here because both packages already depend on `@haven_ai/sdk` and call * methods on a `HavenClient` instance, so this needed no new dependency * edge. `funded_but_unsettled` is deliberately excluded: that phase means * the merchant did NOT accept the retry. Every other phase/rail returns * the status untouched. */ getPaymentStatusWithPostPurchaseAllowance(paymentId: string): Promise; /** * Discover payable services from Haven's merchant catalog (epic #1717). * * Read-only: returns catalog entries (price, rail, protocol) so an agent * can choose a service and pay it with the regular payment tools in the * same session. Never creates payments or signatures. */ discoverTools(options?: { category?: string; search?: string; rail?: 'x402' | 'mpp'; /** * `'verified'` (epic #1717, #2978) returns entries whose endpoint Haven * watched answer a live quote — `verifiedPayable === true` — from * EITHER source: an operator-curated row that keeps passing its * periodic 402 probe, or a self-submitted row that also passed * domain-ownership proof. It is not a provenance filter; `'operator'` * still filters on provenance (`source === 'operator'`) regardless of * badge state, and `'any'` (the default) returns the merged listing. */ verified?: 'any' | 'verified' | 'operator'; }): Promise; /** * Submit a merchant's payable (x402/MCP) endpoint to the Verified Payable * Directory (epic #1717, #1716). Queue-only: writes a submission row and * returns the id + verify_token. The request path makes no outbound * request; domain-ownership proof and the read-only quote probe run later * on the leader-locked monitor. Ownership proof is ALWAYS required before * any listing — this method cannot skip it. `website` is a honeypot field * that bots fill; leave it unset. */ submitCatalogEntry(resourceUrl: string, options?: { website?: string; }): Promise; /** * Fetch one submission's coarse status by id (epic #1717, #1716). Public * and read-only. While the submission can still prove ownership the * response carries the exact well-known / DNS-TXT `instructions`; the * verify token is never returned here. */ getCatalogSubmissionStatus(id: string): Promise<{ id: string; status: 'submitted' | 'ownership_verified' | 'verified_payable' | 'failed' | 'delisted'; instructions?: { expires_at: string; well_known: { url: string; content: string; instruction: string; }; dns_txt: { name: string; value: string; instruction: string; }; } | null; }>; /** * Fetch one curated catalog entry by id (#1306). * * Chain-scoped for free by the backend's SQL when the client is * agent-authenticated (#1299): an unknown id and an id curated for a * DIFFERENT chain than this agent's both 404 identically — this method does * not (and must not) re-filter by chain in JS. Read-only, like * {@link discoverTools}. */ getCatalogEntry(id: string): Promise; /** * List recent machine-payment receipts/evidence for bookkeeping. */ listReceipts(options?: { limit?: number; }): Promise; /** #3128: one page of receipts with `total`, `hasMore` and `nextCursor`. */ listReceiptsPage(options?: { limit?: number; cursor?: string; }): Promise; /** * Fetch the verifiable receipt bundle for a settled payment and verify it * locally. The server's own verification is ignored — the receipt is verified * here (independently of Haven) by recovering the signer from the * authorisation, so the result is trustworthy even if the backend lied. */ getReceipt(paymentId: string): Promise<{ receipt: PaymentReceipt; verification: ReceiptVerification; }>; /** * Rehydrate the x402 resume-state bundle for a payment id (#1328: the MPP * resume-state variant retired along with the rest of the mpp_demo surface). * * The server returns stored protocol context only. The client still signs the * merchant proof locally when resumeX402Payment() runs. */ getResumeState(paymentId: string): Promise; /** * Poll until a payment reaches a terminal status (confirmed, failed, expired). */ waitForConfirmation(paymentId: string): Promise; /** * Authorize an x402 payment. * * Takes the parsed PaymentRequired from a 402 response, selects a compatible * option, funds the delegate wallet through Haven, and returns the standard * x402 header that the merchant can verify and settle. * * Requires `delegateKey` to be set in the client config. */ authorizeX402(paymentRequired: X402PaymentRequired, options?: X402AuthorizationOptions): Promise; /** * Probe a paid endpoint and return its x402 quote without creating a Haven * payment or approval request. */ quoteX402(url: string, init?: RequestInit, options?: X402AuthorizationOptions): Promise; /** * Probe an MCP tool for its x402 quote without creating a payment. * * Unlike the generic {@link quoteX402} helper, this completes the * Streamable-HTTP MCP lifecycle before sending the unpaid `tools/call`. * Hosted MCP uses this path while remaining keyless: it resolves only the * agent's public delegate address for `x402-wallet`; signing remains local. * It refuses before the quote when the merchant does not establish a session; * callers that need a plain x402 endpoint must use {@link quoteX402}. */ quoteMcpX402(url: string, init?: RequestInit, options?: X402AuthorizationOptions): Promise; /** * Pay a previously inspected x402 quote and retry the exact captured request. */ payX402Quote(quote: X402Quote, options?: X402AuthorizationOptions): Promise; /** * Pay a merchant through **erc7710 direct settlement** (#1454, epic #1450). * * **Nothing has settled when this returns** — that is why it does not return * an `X402Receipt`; the caller still has to retry the merchant with the * header. **MCP callers must pass `options.resourceUrl`**, because an in-band * MCP 402 challenge frequently carries no `resource` object at all. * * Both caveats, and why this scheme has no funding leg, are explained where * the lifecycle lives: `x402-erc7710.ts` (#1619). */ settleX402Erc7710(paymentRequired: X402PaymentRequired, options?: { resourceUrl?: string; }): Promise; /** * The AUTHORIZE half of erc7710 settlement (#1456): select the scheme, build * the request, and return the child to be signed — without signing it. * * Split out because the hosted topology cannot use `settleX402Erc7710()`: * that method signs in-process with `delegateKey`, and hosted Haven does not * have one and must not. */ prepareX402Erc7710(paymentRequired: X402PaymentRequired, options?: { resourceUrl?: string; /** * The account's rail, when the caller has ALREADY read it — passing it * skips a duplicate fetch (#1456). An optimisation, not a trust * boundary: the backend independently refuses a non-delegation account * at the rail seam (the #1986 retired-rail 410, #2245). */ delegationRail?: boolean; /** * #1547: the merchant MCP-tool call this authorization was quoted * against, persisted so the settle leg can rehydrate it by payment_id * (#1307). */ mcpCallContext?: X402McpCallContext; /** * #2041: replay key, as `createX402Intent` already takes one. Without it * a retried authorize mints a second signable settlement child instead * of replaying the first. */ idempotencyKey?: string; }): Promise<{ paymentId: string; signData: SignData; settlement: Omit; }>; /** * The SETTLE half (#1456): exchange the signed child for the merchant header. * * The SDK builds no header on this path — the backend assembles the MetaMask * erc7710 payload. Whoever produced the signature (an in-process delegate * key, or the local edge signer over the hosted boundary) is irrelevant. */ submitX402Erc7710(paymentId: string, signature: string): Promise; resumeAuthorizedX402(input: ResumeAuthorizedX402Input): Promise; resumeX402Payment(input: ResumeX402PaymentInput | X402ResumeState): Promise; /** * Fetch wrapper that automatically handles HTTP 402 responses. * * Works like the standard `fetch()` but intercepts 402 responses, * pays via x402 through Haven, and retries the request. * * ```ts * const response = await haven.fetch('https://paid-api.com/data') * const data = await response.json() * ``` * * **MCP-over-x402 auto-handshake (issue #315):** when the endpoint is * MCP-shaped — the URL path ends in `/mcp`, or the 402 body carries a * Coinbase Bazaar `extensions.bazaar` block — the SDK runs the MCP * `initialize` handshake, threads the resulting `mcp-session-id`, * `Accept: application/json, text/event-stream`, and `x402-wallet` headers * through every request, and collapses SSE responses to the JSON-RPC * `result`. The caller just passes `(url, { body })` and never sees the * protocol plumbing. A non-MCP server (handshake error / no session id) * falls back to standard x402 behaviour. * * Requires `delegateKey` to be set in the client config. */ fetch(url: string, init?: RequestInit, options?: X402AuthorizationOptions): Promise; /** * Deliver an already-signed x402 payment header to the merchant and return * the merchant's response. Used by the hosted MCP server to complete the * merchant leg of an MCP tool payment after the edge signer has built the * merchant payment header. * * Custody note: this never needs the delegate key. It relays a signed, * amount/merchant/nonce-bound EIP-3009 authorization the edge signer already * produced — the hosted server cannot mint or reuse signing authority. * * When the URL is MCP-shaped (`/mcp` path) or the quote-time transport context * says the merchant was Bazaar-discoverable, runs a fresh `initialize` * handshake (the quote-time session is gone once funding confirms; the x402 * challenge is stateless w.r.t. the MCP session, so a fresh session is * accepted), threads the session + wallet headers, sets the x402 payment * header under the names that scheme requires (#2341), and * collapses an SSE JSON-RPC response to its `result`. */ /** * Wait for a payment's Safe→delegate funding tx to reach ≥1 on-chain * confirmation. The hosted x402 completion path MUST call this after funding * and before delivering the merchant payment header, so the merchant's * balanceOf(delegate) / transferWithAuthorization verification sees the funded * balance — otherwise it rejects with "Payment verification failed". The * SDK's local path already does this (see `X402FundingLeg.authorize`); the hosted * split flow regressed when the 5→3 collapse removed the incidental * inter-call latency that used to mask it. * * **NOT a no-op when the funding tx hash is absent** (#1508). The WAIT is * skipped without a hash or a chain RPC, but the `GET /payments/:id` read * below runs UNCONDITIONALLY — it is how the fallback hash and the chainId * are obtained. That distinction is load-bearing: this method must never be * called on a scheme with no funding leg, because the read itself fails once * the intent reaches a status the backend maps to a non-2xx (`submitted` is a * 409), turning a settled payment into a reported error. The previous wording * here said "No-op when the funding tx hash ... is unavailable", and the * hosted erc7710 path was written against that promise — see * `deliverMerchantPayment`'s `noFundingLeg` option. */ ensureFundingConfirmed(paymentId: string, fundingTxHash?: string): Promise; completeX402MerchantCall(input: { url: string; init?: RequestInit; paymentId: string; paymentHeader: string; mcpTransport?: X402McpTransport; /** * #1508: the payment settles with NO funding leg (erc7710). This method was * written for EIP-3009 and encodes that lifecycle in two places — the * readiness gate wants `confirmed`, and a Haven funding tx hash is * mandatory. Neither is reachable on a scheme where the MERCHANT redeems * the delegation chain: the intent sits at `submitted` by design, and there * is no Haven-submitted transaction at all. Set this to take the * no-funding-leg path through both. */ noFundingLeg?: boolean; }): Promise<{ status: number; ok: boolean; body: unknown; settlementTxHash?: string; /** * #2970: what the evidence report (below) learned, when one was made. * `undefined` when there was no hash to report at all — no funding tx on * the erc7710 branch and no (or a zero) merchant-reported settlement hash. * The hosted erc7710 settle/complete gate reads this to decide whether * `settled: true` is honest; the 3009 branch's `settled: true` does not * need it — see `paid-mcp-completion.ts` for why. */ evidenceOutcome?: EvidenceReportOutcome; }>; /** * #2292: report the outcome of a merchant retry the AGENT performed. * * The hosted `haven_complete_mcp_tool` / `completeX402MerchantCall` path is * for merchants Haven calls itself. On the plain-HTTP x402 path Haven never * talks to the merchant, so the outcome of that retry had no way back — * see `MerchantCompletion.reportMerchantOutcome` for what is verified about * a caller-asserted report and what deliberately is not. */ reportX402MerchantOutcome(input: { paymentId: string; outcome: X402MerchantOutcome; merchantStatus: number; merchantBody?: string; }): Promise; /** * #2972: report the merchant's real settlement transaction hash for an * erc7710 x402 payment — the remedy for `DELIVERED_UNSETTLED` / * `SETTLEMENT_PENDING` / `awaiting_settlement_evidence` when the agent * holds the hash (`PAYMENT-RESPONSE.transaction`, or a prior settle/ * complete result's `settlement_tx_hash`) and Haven does not. See * `MerchantCompletion.reportSettlementEvidence` for the fail-closed * verification this posts into (`observeErc7710Settlement`) and the * client-side zero-hash refusal. */ reportSettlementEvidence(paymentId: string, settlementTxHash: string): Promise; /** * GET /x402/:id/merchant-call-context — the settle-leg twin of #1263's * sign-context fetch (#1307). Re-serves the stored merchant MCP-tool call * context (merchant_url, tool_name, arguments, mcp_transport) recorded at * quote time, so `haven_settle_mcp_tool` / `haven_complete_mcp_tool` can * omit those fields and let Haven rehydrate them by payment_id instead of * the caller re-threading them. Throws `HavenApiError` (404 unknown/foreign * payment_id, 409 no stored context, 410 expired) — the caller decides the * fallback (re-send the full context explicitly). */ getX402MerchantCallContext(paymentId: string): Promise; /** * Wait for a funding tx to be mined with ≥1 confirmation before the * merchant retry, eliminating the race where the merchant's * `balanceOf(delegate)` runs before the funding block propagates. * * Skipped when `chainRpcs` does not include the chain; in that case Haven's * backend has already confirmed on-chain submission and callers accept the * small propagation window as a trade-off for not configuring an RPC URL. */ private throwIfNonSignableAuthorizationState; /** * Execute a tool call by name and input. * * Designed to plug directly into agent tool-call handlers: * * ```ts * if (block.type === 'tool_use') { * const result = await haven.executeTool(block.name, block.input) * // send result back to the model * } * ``` */ executeTool(toolName: string, input: Record): Promise>; private post; private get; } /** * Pre-built tool definitions for AI agent frameworks. * * These definitions describe Haven's direct SDK tool-calling surface in the * formats expected by Claude (Anthropic) and OpenAI. * * The agent payment surface used by these tools is shared with the * `@haven_ai/mcp` server — both consume `toolDescriptions` from * `./tool-descriptions.ts`. Each consumer composes its own user-visible string * from the same semantic fragments, so guidance lands in both surfaces at * once and a downstream test asserts the shared summary appears in every * consumer description. * * Usage with Claude: * const response = await anthropic.messages.create({ * tools: havenTools.claude(), * ... * }) * * Usage with OpenAI: * const response = await openai.chat.completions.create({ * tools: havenTools.openai(), * ... * }) */ interface ClaudeTool { name: string; description: string; input_schema: { type: 'object'; properties: Record; required: readonly string[]; }; } declare function claudeTools(): ClaudeTool[]; interface OpenAITool { type: 'function'; function: { name: string; description: string; parameters: { type: 'object'; properties: Record; required: readonly string[]; }; }; } declare function openaiTools(): OpenAITool[]; declare const havenTools: { /** Tool definitions in Anthropic/Claude format */ claude: typeof claudeTools; /** Tool definitions in OpenAI function-calling format */ openai: typeof openaiTools; }; /** * Sign a hash using raw ECDSA (no Ethereum message prefix). * * This matches what Safe's AllowanceModule `checkSignature` expects — * a direct ecrecover over the hash, NOT the "\x19Ethereum Signed Message" variant. * * Uses ethers.SigningKey.sign() instead of wallet.signMessage() to avoid the prefix. */ declare function signHash(privateKey: string, hash: string): string; /** * Sign a delegation-rail payment (#829). * * The delegate SMART ACCOUNT validates an EIP-712 signature over the packed * UserOperation — signing the bare 4337 hash would be rejected on-chain. The * backend sends the exact typed data in `sign_data.typed_data`; we sign it * verbatim and never reconstruct it (a second source of truth could drift * from the account's own rules). */ interface Eip712TypedData { domain: Record; types: Record; primaryType: string; message: Record; } declare function signUserOpTypedDataForDelegation(privateKey: string, typedData: Eip712TypedData): Promise; /** * Derive the Ethereum address from a private key. */ declare function addressFromKey(privateKey: string): string; /** * Verify that a signature over a hash recovers to the expected address. */ declare function verifySignature(hash: string, signature: string, expectedAddress: string): boolean; /** * Shared semantic descriptions for Haven agent payment tools. * * Two surfaces in this repo expose Haven as a tool: the Claude / OpenAI * function-calling tool definitions in `tools.ts` (used for direct SDK * integrations) and the MCP server in `packages/mcp` (used by any MCP-speaking * agent runtime). The two surfaces use different tool *names* — the SDK's * tools are tuned for tool-calling conventions (`make_payment`, * `authorize_x402_payment`); the MCP tools follow the MCP `haven_*` naming * (`haven_pay_x402_quote`). * * The underlying *operations* are the same, so the descriptive prose should * live in one place. Both surfaces import from this module and compose their * own tool descriptions from these semantic fragments. Drift is caught by * tests asserting each consumer's description string contains the shared * `summary` from this module. */ interface ToolDescription { /** One-line summary of the operation. Used as the first sentence of every * downstream description and as a stable substring for drift tests. */ summary: string; /** Natural-language user intents that should make an agent prefer this * tool over adjacent tools. Empty or omitted when the summary is enough. */ selectionGuidance?: string; /** Concrete behaviour the tool performs end-to-end, including which * non-custodial guarantee applies. */ behavior: string; /** What the agent should do next on error / declined states. * Empty string if not applicable. */ nextActionGuidance: string; } /** * Build a single description string from the three fragments. Joined with * spaces so consumers can split on the summary substring if they need to. */ declare function composeDescription(d: ToolDescription): string; declare const toolDescriptions: { readonly quoteX402: { readonly summary: "Inspect an HTTP 402 x402 paid resource without creating a Haven payment, signature, approval, or on-chain transaction."; readonly behavior: "Probes the merchant directly and parses the 402 response. Pure read-only client behavior — Haven is not contacted."; readonly nextActionGuidance: "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."; }; readonly payX402: { readonly summary: "Pay an inspected x402 quote. The delegate key signs locally; Haven only validates and relays signed, on-chain-constrained payment transactions."; readonly selectionGuidance: "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."; readonly behavior: "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."; readonly nextActionGuidance: string; }; readonly payX402OneShot: { readonly summary: "Fetch an x402 paid HTTP resource in a single call. Handles the full probe -> pay -> retry round trip and returns the merchant response."; readonly selectionGuidance: "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."; readonly behavior: "Calls the URL, parses any HTTP 402 x402 challenge, signs the payment locally, then retries the original request with the signed payment header (sent under PAYMENT-SIGNATURE, plus the legacy X-PAYMENT on the EIP-3009 path only) and returns the merchant response. Settlement is either direct account-to-merchant with no funding leg, or a bridge that first redeems the agent's budget delegation to fund the delegate wallet for an EIP-3009 authorization. A payment outside the on-chain budget is declined before any money moves; nothing is queued for a human to approve later. If the resource returns a non-402 status, returns it unchanged without contacting Haven."; readonly nextActionGuidance: string; }; readonly resumeX402: { readonly summary: "Resume an x402 payment whose Haven-side authorization already succeeded but whose merchant retry did not complete."; readonly behavior: "Accepts either resume_state or payment_id, validates the original x402 details against the authorized Haven funding, and retries the merchant request with the signed payment header (sent under PAYMENT-SIGNATURE, plus the legacy X-PAYMENT on the EIP-3009 path only). No new Haven payment is created."; readonly nextActionGuidance: string; }; readonly getPaymentStatus: { readonly summary: "Fetch structured Haven payment status for agent recovery."; readonly behavior: "State: phase, nextAction, rail, amount, merchant, resource, idempotency, message; parties: treasury/delegate/delegateAccount/merchant. awaiting_settlement_evidence: poll once, else unverified."; readonly nextActionGuidance: ""; }; readonly getResumeState: { readonly summary: "Rehydrate stored x402 resume_state by payment_id."; readonly behavior: "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."; readonly nextActionGuidance: ""; }; readonly getAgent: { readonly summary: "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."; readonly selectionGuidance: "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."; readonly behavior: "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."; readonly nextActionGuidance: ""; }; readonly getAllowances: { readonly summary: "Return configured and on-chain allowance state for the authenticated agent. On-chain allowance is the real spend gate."; readonly selectionGuidance: "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."; readonly behavior: "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."; readonly nextActionGuidance: ""; }; readonly checkFunds: { readonly summary: "Check whether the agent's account actually holds at least the given amount of a token — funds held, not spend permitted."; readonly selectionGuidance: "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."; readonly behavior: "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."; readonly nextActionGuidance: "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."; }; readonly listReceipts: { readonly summary: "List machine-payment receipts, newest first, by page."; readonly selectionGuidance: "For transaction history or payment evidence; use the allowance tool instead for remaining allowance or what-can-I-spend questions."; readonly behavior: "Page: { receipts, total, hasMore, nextCursor }; total 0 = none exist (no indexing delay); hasMore = cut at limit, send 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 are omitted."; readonly nextActionGuidance: ""; }; readonly verifyReceipt: { readonly summary: "Verify a payment receipt offline — confirm the agent authorised the transfer."; readonly selectionGuidance: "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."; readonly behavior: "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."; readonly nextActionGuidance: ""; }; readonly payMcpTool: { readonly summary: "Call a named tool on an MCP merchant that requires an x402 payment, handling the full initialize → pay → retry round trip in one call."; readonly selectionGuidance: string; readonly behavior: string; readonly nextActionGuidance: string; }; readonly discoverTools: { readonly summary: "Step 1 of a purchase: discover payable services from Haven's curated merchant catalog — names, prices, the next call."; readonly selectionGuidance: string; readonly behavior: string; readonly nextActionGuidance: "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."; }; readonly submitCatalogEntry: { readonly summary: "Submit a merchant's payable (x402/MCP) endpoint to Haven's Verified Payable Directory for verification and listing."; readonly selectionGuidance: string; readonly behavior: string; readonly nextActionGuidance: "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."; }; readonly sweep_delegate: { readonly summary: "Sweep stranded USDC and/or ETH from the delegate wallet back to the originating account."; readonly selectionGuidance: string; readonly behavior: string; readonly nextActionGuidance: string; }; readonly send: { readonly summary: "Send ETH or USDC directly from the agent's Haven wallet to a recipient address."; readonly selectionGuidance: string; readonly behavior: string; readonly nextActionGuidance: string; }; readonly reportSettlementEvidence: { readonly summary: "Report an erc7710 payment's real settlement transaction hash so Haven can verify it on-chain and confirm the payment."; readonly behavior: "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."; readonly nextActionGuidance: "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."; }; }; type SharedToolKey = keyof typeof toolDescriptions; /** * The generic Haven payment skill — canonical copy. * * This SDK file is the single source of truth for the generic, secret-free * skill content: no wallet address, no budget numbers, no per-agent values. * The agent learns its live budget at runtime via the `haven_get_agent` / * `haven_get_allowances` MCP tools, and can read identity + configured budget * for fast first-turn orientation from the non-secret `agent.json` the * connector writes (see `packages/connect/src/storage.ts`), so the same file * works for every user. `packages/connect` imports this directly to * auto-install the skill into runtime skills folders. * * `packages/frontend/src/lib/agent-skill-bundle.ts` keeps a deliberately * decoupled inline copy (the download fallback): the frontend does not depend * on the SDK, so it can deploy standalone on Vercel without an unpublished * export. It is NOT `@haven_ai/*`-free — it takes `@haven_ai/core` with the * `"*"` workspace pin — and this comment said otherwise until #2537 checked * the manifest; the material point is the one that survives, and it is about * the SDK specifically. A parity test in that package's test suite imports * this canonical string and asserts byte-for-byte equality, so the two copies * cannot drift. * * **The onboarding section (#2537) is COMPOSED, not written here.** Its rule * sentences are interpolated from `agent-guidance.ts`, which is also where the * backend's setup prompt and the `/for-agents.md` runbook get them: a rule an * agent meets twice must be one text, or the two copies drift into * contradicting each other in front of a reader with no way to tell which is * current. The prose around them is skill-only and lives here. * * **Those three bullets are quoted in the setup prompt's own voice**, where * the USER is speaking: "me"/"I" are the user, and "the command above" is the * connector command printed directly above them there — neither of which * holds in this file, which addresses the agent throughout and prints no * command. Any future user-voice quote here needs the same two-referent * gloss, and it must sit BEFORE the quote rather than after: the first draft * put it after, and both the reviewer and the design reviewer independently * found that an agent reading top-to-bottom meets `relay ... to me` before * it learns whose "me" that is — on the one instruction the section itself * calls the highest-priority one. `AGENT_APPROVAL_RELAY_PROSE_SENTENCE` is a * live sibling constant not pulled in here; if it ever is, this applies to it * too (design review, #2537). */ declare 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 \u2014\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\u2014 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 \u2014 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 \u2014 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` \u2014 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 \u2014 those are your user's.\n- `haven agents connect` with `--name`, `--budget`, `--token` and\n `--period` \u2014 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` \u2014 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 \u2014 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 \u2014 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- When a --json outcome reports approval.required: true, your first action must be to relay the approval instruction to me in your own reply \u2014 if the outcome carries approval.url, give me that link; otherwise tell me to return to Haven and approve this agent's budget \u2014 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- Only two changes to the command above are permitted, and no others: appending --json, and \u2014 only if the connector refuses because it could not determine the agent runtime \u2014 re-running it once with --runtime 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- 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\nDo not print private keys, API keys, credential file contents, or config secrets in chat or logs.\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.json` \u2014 if you don't know the agent id, list\n`~/.haven/agents/` to find the folder). It\nholds your agent id, Haven wallet address, network, and *configured* per-token\nbudget, and contains no keys \u2014 the fastest way to answer \"who am I and what may\nI spend\" with no round trip. If that file is absent (some setups don't write\nit), use the tools below instead.\n\nBefore any payment, confirm the *live remaining* budget with the tools \u2014\n`agent.json` shows the configured budget, not what is left after recent\nspending:\n\n- `mcp__haven__haven_get_agent` \u2014 the recommended first call: identity\n (wallet, network) plus `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 \u2014 it cannot see the\n local signer; the signer is verified by calling any signer tool.\n- `mcp__haven__haven_get_allowances` \u2014 detailed per-token breakdown\n (configured, spent, reset window) when you need more than the summary.\n- `mcp__haven__haven_check_funds` \u2014 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 \u2014 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 \u2014 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 \u2014 the primary path for MCP merchants:**\n\n1. `mcp__haven__haven_discover_tools` to find a payable service and its\n `catalog_id`.\n2. If the user needs the live price before authorizing a cap, call\n `mcp__haven__haven_quote_catalog_purchase` with `catalog_id`. It is\n read-only and informational only: it never reserves a price or creates a\n payment. Tell the user its `amount` / `amount_atomic`, then choose a cap.\n3. `mcp__haven__haven_prepare_catalog_purchase` with `catalog_id` and a\n spending cap. A cap is REQUIRED on this tool and is best practice on every\n paid call below too \u2014 it caps what the LIVE merchant quote may charge,\n checked before any funding intent is created. Write it the way the user\n said it: `max_amount_human` is whole tokens, so \"no more than 1 USDC\" is\n `max_amount_human: \"1\"`. (`max_amount` is the atomic-unit form, where\n \"1\" means 0.000001 USDC \u2014 do not convert by hand, and never send both.)\n4. Then FOLLOW THE RESPONSE'S GUIDANCE FIELDS: `next_action`, `next_tool`,\n and `next_arguments` name the exact next call \u2014 act on those first; the\n prose in this section is fallback and debugging detail. If the catalog\n entry is missing or degraded, the response instead names\n `mcp__haven__haven_pay_mcp_tool` (merchant URL, tool name, arguments) as\n the manual fallback.\n\n**Signing:** `mcp__haven-signer__haven_sign_x402` with `payment_id` ONLY \u2014\nthe local signer fetches the exact signing bytes AND `payment_required`\nitself, so never relay `typed_data` or the 402 blob yourself. If the signer\nreports its fetched context carried no `payment_required` (older backend),\nre-call with `payment_required` added verbatim. Fallback for an older signer\nor backend: re-run the quote/prepare tool with the SAME `idempotency_key`\nplus `include_signing_payload=true`, then pass `payload_hash`,\n`x402_expected` (the nested `x402.expected` object), and\n`typed_data`/`typed_data_b64` through unchanged.\n\n**Settle:** `mcp__haven__haven_settle_mcp_tool` with `payment_id`,\n`signature`, and `payment_header` ONLY \u2014 Haven rehydrates the merchant call\ncontext (`merchant_url`, `tool_name`, `arguments`, `mcp_transport`)\nserver-side from `payment_id`. Pass those four fields explicitly only as a\nversion-skew fallback when Haven has no stored context for the id \u2014 both or\nnone together, never just one. If the settle result carries `settled: false`,\nfunding has not confirmed \u2014 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` \u2192\n`mcp__haven-signer__haven_sign` \u2192 `mcp__haven__haven_submit` \u2192\n`mcp__haven-signer__haven_x402_sign_header` \u2192\n`mcp__haven__haven_complete_mcp_tool`. 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 \u2014 `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 \u2014 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` \u2014 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` \u2014 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 \u2014 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'` \u2014 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 \u2014 a ceiling the merchant settles at or below \u2014\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 \u2014 above the remaining budget, wrong\n recipient, or expired budget \u2014 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 \u2014 re-send with exactly\n one (`max_amount_human` for a cap the user stated in tokens).\n- `MAX_AMOUNT_UNCONVERTIBLE`: `max_amount_human` does not fit this quote's\n asset \u2014 unknown decimals, or more decimal places than the asset supports.\n Round the cap, or send an exact atomic `max_amount`.\n- `PAYMENT_WINDOW_EXPIRED`: re-run the quote/prepare tool with the same\n `idempotency_key`, then sign the fresh payload.\n- `MERCHANT_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) \u2014 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 \u2014 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 \u2014 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 \u2014 the merchant may still settle late.\n On eip3009 (`rail` not `erc7710`), funding confirmed on-chain: Verify-then-sweep,\n never a blind sweep \u2014 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) \u2014 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` \u2014 report the product, Haven-derived payment/transaction\nfields, and what is left from those fields directly. `result` is optional\nraw merchant evidence; never use it to decide whether the purchase was paid.\nDo not call `haven_get_agent` or `haven_get_allowances` again just to\nreport a purchase you already made.\n\n## Revoke\n\nIf this agent's credential may have leaked, tell the user to pause or revoke\nthe agent in the Haven dashboard under Agents. New requests stop immediately\nfor that credential.\n"; /** Directory name for the installed skill folder. */ declare const SKILL_FOLDER_NAME = "haven-pay"; /** * The skill BODY — HAVEN_SKILL_MD with the YAML front-matter stripped. * * For runtimes whose instruction mechanism is a plain guidance file rather * than a skills folder (Codex's global AGENTS.md, #1332), the front-matter is * skill-registry metadata with no meaning and would render as a stray table. * Derived mechanically from the canonical string above, never maintained by * hand — the substance cannot fork per runtime. */ declare const HAVEN_SKILL_BODY_MD: string; /** * Agent-facing onboarding guidance — canonical copy (#2523, epic #2519). * * Two exports, one source: * * 1. **The shared sentences** — the rules an agent must follow when it runs the * connector. They appear in the backend's `setup_prompt` * (`routes/agent-connection-setups.ts` `buildSetupPrompt`) AND in the runbook * below. Before this file they existed once, inline in the route; the runbook * would have been a second copy, and a second copy of a rule is how the two * drift into contradicting each other in front of an agent that has no way to * tell which is current. * 2. **`HAVEN_AGENT_RUNBOOK_MD`** — the runbook served as * `packages/frontend/public/for-agents.md`, written to the agent whose user * has no Haven account yet. `llms-full.txt`'s quickstart addresses the owner; * this addresses the agent, and its job is to say which steps are the human's * and exactly what to say at each hand-off. * * The frontend keeps the runbook as a static file rather than importing it: * `packages/frontend` has zero `@haven_ai/*` dependencies by design (standalone * Vercel deploys), and `public/` is served as-is. A byte-equality test * (`src/lib/__tests__/for-agents-runbook.test.ts`) pins the served file to this * string, exactly as `agent-skill-bundle.test.ts` pins the skill. * * Wording constraints, recorded because they are not stylistic (owner * constraints 2026-09-04, and `docs/regulatory/casp-risk-guardrails.md` * § Product Copy Rules): the human keeps every signature; there is no headless * account path; the runbook must never suggest the agent enters the user's * password; the owner-signed budget is what authorises a payment, and Haven * constructs and relays. */ /** Secret hygiene — the one rule that survives every mode and every runtime. */ declare const AGENT_SECRET_HYGIENE_SENTENCE = "Do not print private keys, API keys, credential file contents, or config secrets in chat or logs."; /** Where the signing key is made, and what Haven receives instead of it. */ declare const AGENT_LOCAL_KEY_SENTENCE = "The Haven connector generates the signing key locally and sends Haven only the public signing address plus proof."; /** Sandboxed environments: the command does not change, the environment does. */ declare const AGENT_NETWORK_ACCESS_SENTENCE = "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."; /** #2483: `--json` is a SHOULD addressed to agents, not to a human pasting the command. */ declare const AGENT_JSON_MODE_SENTENCE = "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."; /** #2483: one gate at a time — the approval relay comes before anything else. */ declare const AGENT_APPROVAL_RELAY_JSON_SENTENCE = "When a --json outcome reports approval.required: true, your first action must be to relay the approval instruction to me in your own reply \u2014 if the outcome carries approval.url, give me that link; otherwise tell me to return to Haven and approve this agent's budget \u2014 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."; /** #2486: the prose-mode twin of the sentence above; each mode relays exactly once. */ declare const AGENT_APPROVAL_RELAY_PROSE_SENTENCE = "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 \u2014 the approval link if those steps printed one, otherwise that you need to return to Haven and approve this agent's budget \u2014 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."; /** * #2551, handed to #2528 by PR #2567 so a third writer would not land on the * money-path prompt file for one line. * * The connector's `wiring_collision` refusal is the THIRD case where the agent * owes its user a decision rather than an action of its own — beside * `approval.required` and the runtime-refusal retry. Named explicitly because * the other two are, and an unnamed relay case is one an agent resolves by * guessing: here it would guess `--replace` (silently displacing a working * agent) or `--name` (quietly wiring a second one). Both are the user's call. */ declare const AGENT_WIRING_COLLISION_RELAY_SENTENCE = "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."; /** #1719: exactly two permitted changes, and the second is bounded by the refusal's own list. */ declare const AGENT_COMMAND_MODIFICATION_SENTENCE = "Only two changes to the command above are permitted, and no others: appending --json, and \u2014 only if the connector refuses because it could not determine the agent runtime \u2014 re-running it once with --runtime 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."; /** * The agent-facing section every published README carries (#2533, A6). * * ONE string, six copies, one instrument. All five npm READMEs plus the repo * README open with dashboard-first instructions, which strand the reader this * epic exists for: an agent whose user has no account yet. This is the entry * that redirects them, and it is defined here rather than written six times * because six hand-maintained copies is exactly the drift #2310 was about — * `agent-guidance.test.ts` fails if any copy differs by a byte. * * TWO links, and the second is not redundant. The path is correct wherever * Haven is actually served and needs no host we do not own (#2520's rule); the * GitHub URL is the one that resolves for a reader on npmjs.com, who has no * origin to resolve a path against. A path alone would be unfollowable in the * place these READMEs are most often read; an absolute app host alone would be * a host nobody owns. Naming both is the honest answer, and the runbook itself * is committed at that path, so the fallback is a real file rather than a * promise. * * Interrogative, not declarative-with-a-question-mark. `llms.txt` states the * same idea declaratively because there it is a LINK TITLE in a list; an H2 * whose job is to catch the right reader and let everyone else skip is a * question. The mismatched mood was a haven-design-reviewer finding, fixed * while it was cheap: the string is byte-pinned in six files, so the cost of * changing it only ever goes up. * * It says what the agent CANNOT do first. The account and the passkey are the * user's, always — stating that up front is what stops an agent trying, and it * is the epic invariant no slice may weaken. */ declare 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 \u2014 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\u2014 including running the connector command from the setup prompt they paste you,\nand managing the account from the shell with `@haven_ai/cli`."; /** * The runbook, served at `/for-agents.md`. * * Every link is a same-origin path (#2520): resolve it against the host the * file was fetched from. The npm dist-tags are the placeholder `` * rather than literals — the connector's command and, since #2617, the CLI's * login in step 1 — for two reasons that point the same way: a published * package must not hard-code one (#2423, guarded by * `scripts/release-bump.test.mjs`), and this string is committed as a static * file, so baking in a channel `release-bump.mjs` later rewrites would put the * served copy out of parity at exactly the moment nobody is reading it. The * page tells the agent to run the command its setup prompt hands it, where the * tag is real and deployment-correct, and to read the CLI's tag from * `/.well-known/haven.json` (`packages.cli.channel`). * * The budget-approval hand-off is now a LINK when the connector has one, and a * tab when it does not — #2528 landed the half of this that was missing. * `ConnectOutcome` (`packages/connect/src/runtime.ts`) carries * `approval: { required, expires_at, url? }`; `url` is the same-origin * `approval_url` the register response returns, so the agent relays a * destination instead of "return to Haven". * * The step-5 hand-off is TWO blockquotes, not one with the alternative in * brackets. It was the bracket form briefly, to save ~110 bytes against the * size ceiling, and haven-design-reviewer was right to push back: this * section's own header says "Send these as your own message", so every other * script in it is paste-ready. A bracketed either/or inside the quote makes * the agent perform text surgery on something presented as copyable — and a * naive relay ships the raw brackets to the human, which reads as broken * rather than as a choice. Two quotes cost bytes and buy back the property * the section is built on. Do not re-compress this to save them. * * `AGENT_WIRING_COLLISION_RELAY_SENTENCE` is deliberately NOT in this page's * rule list, though it IS in the setup prompt (#2551 via #2567). This page's * list is already a curated subset of the prompt's — it omits the network and * local-key sentences and adds the prose-relay one — and a collision can only * happen to an agent that is running the connector, which means it is holding * the prompt, where the sentence is. Repeating it here would cost every agent * that fetches this page bytes for a rule it will be handed at the moment it * applies. * * TWO limits, stated because the copy below depends on both. First, `url` is * OPTIONAL and its absence is normal: a backend older than #2528 sends none, * and `approval.required: false` carries none because there is nothing to * approve — so every sentence here has to work with and without it, which is * why they read "if the outcome carries a link". Second, the outcome still has * NO setup id: #2528 added the link only, and the connector's own status poll * (`GET /:setupId/connector-status`) still answers `{ status, approved_budget }`. * An agent must not construct an approval URL out of parts — it has the whole * one or it has none. `?next=` / `?via=agent` / `?setup=` are the hand-off * link shapes from #2522. */ declare const HAVEN_AGENT_RUNBOOK_MD = "# Haven for agents \u2014 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** \u2014 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 \u2014 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 \u2014 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@ login --api ` afterwards gets you a scoped session for steps 3-4 (that flag or `HAVEN_API_URL`, on the first command \u2014 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) \u2014 they approve a code in the browser, you never hold their password. The `` in that command is the tag your deployment names \u2014 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 ` \u2014 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 \u2014 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 \u2014 tell your user which case theirs is.\n3. **HUMAN \u2014 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 --budget --token USDC --period ` prints the same connector command and approval link; add `--run` to do step 4 too.\n4. **YOU \u2014 run the connector command** in that prompt (below). It makes your signing key locally, registering only the public address.\n5. **HUMAN \u2014 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 \u2014 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 \u2014 a second token, a bigger amount, a recipient pin, a stop \u2014 and hand your user a link; the human still signs, every time:\n\n```\nhaven budget grant --amount --token USDC --period [--recipient
] [--wait]\nhaven budget revoke [--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 `.\n\n## Hand-off scripts\n\nSend these as your own message, `` 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 `/signup?next=/agents&via=agent` \u2014 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? `/login?next=/agents`.\n\n**At the passkey step:**\n\n> The passkey must be made on your own device \u2014 it is what keeps the account yours, so nobody, Haven included, can move your funds without you. If this browser cannot, open `/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 \u2014 USDC only, no ETH: Haven sponsors the gas. Before you send anything, let me get you the exact address **and network** \u2014 `haven wallets funding` prints both, and the funding card on `/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 `/agents`, create an agent for me and set a budget \u2014 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) \u2014 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: . 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 \u2014 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@ --setup EXAMPLE-SETUP-TOKEN-NOT-REAL --api --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 `` is the npm tag your prompt names \u2014 never a tag you pick. The rules below come from that prompt, so \"me\" in them is your user, not Haven.\n\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- When a --json outcome reports approval.required: true, your first action must be to relay the approval instruction to me in your own reply \u2014 if the outcome carries approval.url, give me that link; otherwise tell me to return to Haven and approve this agent's budget \u2014 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- 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 \u2014 the approval link if those steps printed one, otherwise that you need to return to Haven and approve this agent's budget \u2014 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- Only two changes to the command above are permitted, and no others: appending --json, and \u2014 only if the connector refuses because it could not determine the agent runtime \u2014 re-running it once with --runtime 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- Do not print private keys, API keys, credential file contents, or config secrets in chat or logs.\n\nIf the approval wait times out, nothing is lost \u2014 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 \u2014 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` \u2014 a budget is live; you can pay.\n- `needs_approval` \u2014 the connector finished, nobody approved yet. Ask your user again, in their Haven tab; there is no queue to wait in.\n- `revoked` \u2014 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@ --doctor`, the same tag your prompt named \u2014 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 `/\u2026` URL and ask them to say when it is done. Step 5 is a link only when your run reported one in `approval.url` \u2014 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 \u2014 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@\u2026` line you run. One-time token, one use. |\n| **agent credential** | Your API key (`sk_agent_\u2026`), 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) \u00B7 [everything agent-readable](/llms.txt)\n"; /** * The **onboarding prompt** — the whole-onboarding text the dashboard offers a * signed-in user to paste to their agent (#2535, epic #2519). * * ## It is NOT the "setup prompt", and the distinction is load-bearing * * `setup prompt` is one of the four canonical agent-facing terms * (`docs/product/copy-guidelines.md` § Agent-facing vocabulary, settled by * #2533 and swept by #2576): it names the text the CONNECT MODAL hands back, * which carries a one-time setup token and the connector command. This string * is a different object with a different lifetime — it exists before any setup * does, contains no token and no secret, and is therefore safe to render to a * signed-in user who has not created an agent yet. Calling both "the setup * prompt" would undo the disambiguation those two issues paid for, so this one * is the **onboarding prompt** wherever it is named. * * ## Why a shared export rather than a route * * The issue offered `GET /agent-connection-setups/agent-prompt` or a static * export. The export wins on cost and on the #2523 precedent: no new route, no * auth question, and no `owner_cli` allow-list entry — and the allow-list is * fail-closed by design, so every entry is a decision. The route would only * earn those three if the prompt had to vary per user, and it deliberately does * not: it names commands and links, never account state. * * ## What keeps it from drifting from the setup prompt * * The two are built from the SAME sentence constants above — this one reuses * the approval-relay and secret-hygiene rules verbatim rather than paraphrasing * them, which is the whole reason those constants exist. A test asserts that * containment, so a reworded copy here fails rather than quietly disagreeing * with what `buildSetupPrompt` tells the same agent minutes later. * * The frontend cannot import this: `packages/frontend` has zero `@haven_ai/*` * runtime dependencies by design (standalone Vercel deploys). It keeps a copy * in `src/lib/agent-onboarding-prompt.ts`, byte-pinned to this string by * `src/lib/__tests__/agent-onboarding-prompt.test.ts`, exactly as the runbook * and the skill are pinned. * * ## The origin placeholder * * `{{HAVEN_ORIGIN}}` is substituted by the renderer with the host the user is * actually signed in to, so dev, preview and production each produce a truthful * prompt from one string. It is a placeholder rather than a build-time constant * for the same reason `` is one in the runbook: this text is committed, * and a baked host is wrong everywhere except where it was baked. * * ## Wording constraints (same as the runbook's, and not stylistic) * * The human keeps every signature; there is no headless account path; it must * never suggest the agent enters the user's password; the owner-signed budget * is what authorises a payment, and Haven constructs and relays. Every command * it names exists at merge time — `haven login` (#2526) and * `haven agents connect` (#2527) both landed before this shipped, which is the * condition #2535 made blocking. */ declare 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 \u2014 it is written for you and explains which steps are mine.\n\nThen:\n\n1. Run `npx @haven_ai/cli@ login`. The `` in that command is the tag your deployment names \u2014 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 \u2014 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 --budget --token USDC --period ` 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. When a --json outcome reports approval.required: true, your first action must be to relay the approval instruction to me in your own reply \u2014 if the outcome carries approval.url, give me that link; otherwise tell me to return to Haven and approve this agent's budget \u2014 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.\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 \u2014 no ETH, Haven sponsors the gas. Tell me if either is missing rather than working around it.\n\nDo not print private keys, API keys, credential file contents, or config secrets in chat or logs."; /** * #3101 (epic #3105, slice 2/5): the typed next-step builder. * * Every hosted payment tool ends by naming the agent's next tool and its * arguments (#1308). Until this module, the tool was a free string and the * arguments a `Record`, so nothing tied the keys to the tool * named beside them — three sites handed `{ payment_id: null }` to a tool * whose `payment_id` is a required string, and the compiler could not see it. * * The builder is generic over a TARGET MAP the caller supplies: bare tool * name → { role, validate }. It is deliberately schema-library-agnostic (the * SDK carries no zod): the hosted server derives each target's argument type * from its own zod shape and passes a `validate` closure; this module only * needs to know the role (to render `mcp____`) and how to say * whether arguments parse. Keyed on the bare name + role (decision 1) so the * namespaced string is rendered in exactly one place and the runtime-neutral * `next_tool_server` / `next_tool_name` / `next_tool_server_role` fields are * derived from the same input rather than parsed back out of a literal. * * Decisions 3 and 8: `nextTool` is REQUIRED on the input and may be `null` — * a site that forgets it is a compile error; a site with no next tool says * why, and the wire omits `next_tool` and carries `next_tool_omitted_reason`. * `next_tool` is never null on the wire. */ type NextToolServerRole = 'hosted' | 'signer'; /** The DEFAULT server name each role is wired under (#1588, #2550). */ declare const NEXT_TOOL_SERVER_NAMES: Record; /** Default server name → role. An unknown server yields no role rather than a guess (#2550). */ declare const NEXT_TOOL_SERVER_ROLES: Record; /** Renders the Claude-family namespaced tool name — the one string clients have followed since #1308. */ declare function renderNextTool(role: NextToolServerRole, name: string): string; /** Parses a namespaced literal back into its parts; `role` is absent for an unknown server. */ declare function parseNextTool(literal: string): { server: string; name: string; role?: NextToolServerRole; } | null; /** * One target the builder may hand off to. `TArgs` is the argument type the * caller derived from the tool's declared schema; `validate` is the runtime * twin of that type and returns `null` when the arguments parse, else why not. */ interface NextStepTarget { role: NextToolServerRole; validate: (input: unknown) => string | null; /** Phantom carrier for the argument type; never read at runtime. */ readonly _args?: TArgs; } type NextStepTargets = Record>; /** The argument type a target carries. */ type NextStepArguments = Targets[T] extends NextStepTarget ? A : never; /** * The handoff half of a next step: a registered tool with arguments that * tool accepts, or no tool with the reason. A discriminated union over the * target map's keys, so a wrong key, a missing required key, an unregistered * tool name and an omitted `nextTool` are each a compile error at the site. */ type NextStepHandoff = { [T in keyof Targets & string]: { nextTool: T; nextArguments: NextStepArguments; }; }[keyof Targets & string] | { nextTool: null; nextToolOmittedReason: string; }; type NextStepInput = NextStepHandoff & { nextAction: AgentPaymentNextAction; safeToContinue: boolean; reason: string; }; /** The wire shape: `AgentNextStep` (its `next_tool` family) — never a null `next_tool`. */ type NextStep = AgentNextStep; /** * Per-`next_action` default tool (decision 9): the tool a site names unless it * has a reason to override. Only actions with ONE sensible target are listed; * `retry_original_x402_request` is absent because its only live emitter names * no tool on purpose (the agent's own HTTP retry); `sign_and_submit_payment` * is absent because the signer tool * depends on the settlement scheme (`haven_sign` for erc7710 delegations, * `haven_sign_x402` for the EIP-3009 bridge) and a wrong default there would be * worse than none. */ declare const DEFAULT_NEXT_TOOL_BY_ACTION: { readonly check_status_later: "haven_get_payment_status"; readonly sweep_stranded_funds: "haven_sweep_delegate"; }; declare function defaultNextToolFor(action: AgentPaymentNextAction): string | undefined; /** * Builds a `nextStep` function bound to a target map. The returned function * renders the wire fields from the bare name + role, and re-validates the * arguments at runtime: on a mismatch it FAILS SAFE — omits the tool and says * why in `next_tool_omitted_reason` — rather than throwing out of a handler * that has already moved money. The compile-time twin makes that branch * unreachable from typed sites; it exists for callers that bypass the types. */ declare function createNextStepBuilder(targets: Targets): (input: NextStepInput) => NextStep; /** * The npm dist-tag the published Haven packages tell a user to re-run (#2423, * slice 3 of epic #2420). * * ## Why a constant and not a literal * * Roughly a dozen user- and agent-facing strings across `@haven_ai/sdk`, * `@haven_ai/signer`, `@haven_ai/connect` and the hosted MCP server say some * form of "re-run `npx @haven_ai/connect@alpha`". Every one of them was a * hard-coded literal, which is correct only for a build published under the * `alpha` dist-tag. Once `dev`-branch snapshots publish under a `dev` tag * (#2421), a snapshot build telling its tester to re-run `@alpha` would hand * them the production connector — silently replacing the very build they are * testing. So the tag becomes one build-time constant and every hint derives * from it. * * ## Who writes it * * `scripts/release-bump.mjs` rewrites {@link HAVEN_CONNECTOR_CHANNEL} from the * version it is bumping to, using exactly the rule `.github/workflows/publish.yml` * uses to pick the `--tag` for that same version: * * | version | dist-tag / channel | * |---|---| * | `0.1.34-alpha.0` | `alpha` | * | `0.0.0-dev.202609021200.abc1234` | `dev` | * | `0.2.0` | `latest` | * * One rule, two consumers. `scripts/ci/connector-channel-agreement.test.mjs` * executes the workflow's own shell and the bump script's own function over the * same version table and fails if they ever disagree. * * ## Build-time here, run-time there * * A published tarball cannot read a deployment's environment, so for the * published packages the channel is baked in at release time. A surface that is * *deployed* rather than published has no release at which to bake anything in, * so it reads the `HAVEN_CONNECTOR_CHANNEL` environment variable and falls back * to this constant. Two surfaces do that: the hosted MCP server * (`packages/mcp-server/src/connector-channel.ts`) and, since slice 2 (#2422), * the backend's connector handout (`parseConnectorChannel` in * `packages/backend/src/config.ts`). All three readers share one variable name, * one default and one validation pattern, and that agreement is EXECUTED rather * than asserted: `packages/backend/src/__tests__/connector-channel.test.ts` * runs this module's `resolveConnectorChannel` and the backend's * `parseConnectorChannel` over the same input table and fails if they ever * diverge. * * **This says nothing about how any environment is configured.** Setting the * variable anywhere is an operator action (epic #2420, operator step 3); no * code here can observe it and none of this comment asserts it has happened. */ /** The published connector package. Never varies; only its tag does. */ declare const CONNECTOR_PACKAGE_NAME = "@haven_ai/connect"; /** * The npm dist-tag this build's re-run hints name. * * **Do not hand-edit.** `scripts/release-bump.mjs` owns this literal the same * way it owns `CONNECTOR_VERSION` and its siblings, and * `scripts/release-bump.test.mjs` fails if the two drift. */ declare const HAVEN_CONNECTOR_CHANNEL = "alpha"; /** True when `value` is a well-formed dist-tag. */ declare function isConnectorChannel(value: string): boolean; /** * Resolve a channel from a deployment's `HAVEN_CONNECTOR_CHANNEL`. * * - unset, empty or whitespace ⇒ `fallback` (dashboards store a cleared * variable as `""`, and that must land on the production-safe value); * - well-formed ⇒ itself; * - anything else ⇒ **throws**. It does not quietly fall back: a typo such as * `dve` would then land on the production channel, and the environment would * look fixed while reproducing the exact defect this slice removes. * * Well-formed-but-wrong (`dve` again) is *not* caught here and cannot be — it * fails later at `npx`, where the error names the package. Stated rather than * implied. */ declare function resolveConnectorChannel(raw: string | undefined | null, fallback?: string): string; /** `@haven_ai/connect@` — the spec an `npx` invocation names. */ declare function connectorSpec(channel?: string): string; /** * The re-run command every hint embeds. * * `connectorRerunCommand()` → `npx @haven_ai/connect@alpha` * `connectorRerunCommand('--doctor')` → `npx @haven_ai/connect@alpha --doctor` * * `args` is appended verbatim so each call site keeps its own flags and its own * surrounding sentence. The wording of those sentences is deliberately NOT * moved here: several are inside signer refusal messages that users and agents * pattern-match on, and this change is meant to move the channel token and * nothing else. */ declare function connectorRerunCommand(args?: string, options?: { channel?: string; npxFlags?: string; }): string; /** * The Node.js floor Haven's published packages support (#1161). * * ## Why this lives in the SDK * * Three packages need to enforce the same floor — `connect` (at setup), * `signer` and `mcp` (at startup) — and `@haven_ai/sdk` is the only dependency * all three already share. A copy per package is how the floor drifted in the * first place: `engines` said `>=24` everywhere while connect's runtime manifest * enforced `20.0.0`, so a connect run on Node v23 passed the guard, installed * the signer, and signed a real payment. Two numbers for one fact is one number * too many. * * Each consumer still owns its own refusal — the error type, the exit code, the * wording of "what to do next" — because a library must never terminate its * host process. This module only answers *is this version supported* and *what * should we tell the user*. * * ## Why a floor is enforced at all * * `engines` is advisory: npm emits `EBADENGINE` and installs anyway unless the * user happens to have `engine-strict` set. For a normal library that is a * reasonable default. For the **signer** it is not — it holds the delegate key * and produces every payment signature, so a subtle runtime incompatibility * shows up as a wrong or missing signature on a money path. "It seemed to work" * is precisely the evidence that cannot be relied on there. */ /** * The minimum supported Node.js version, as `major.minor.patch`. * * MUST equal the `engines.node` floor declared by every published Haven * package. A guard test in each package asserts exactly that against its own * `package.json`, so the two cannot drift again silently. */ declare const HAVEN_MINIMUM_NODE_VERSION = "22.0.0"; /** * Compare two Node versions. Negative when `left` is older. * * An unparseable version parses to `0.0.0` and therefore compares as older than * any real floor — fail-closed. A version string Haven cannot read is not * evidence of a supported runtime, and treating it as one would reopen exactly * the hole this module closes. */ declare function compareNodeVersions(left: string, right: string): number; declare function isSupportedNodeVersion(nodeVersion?: string, minimumNodeVersion?: string): boolean; interface UnsupportedNodeVersionMessageOptions { /** * What is being refused, in the user's terms — "Haven setup", "The Haven * signer". Leads the message so the reader knows what just stopped. */ subject: string; nodeVersion?: string; minimumNodeVersion?: string; /** Appended verbatim as the closing line. Used for the re-run instruction. */ retryHint?: string; } /** * The refusal text. * * Names the detected version, the required version, and **how to fix it** — the * previous message stopped after the two version numbers, which tells a user * they are stuck without telling them how to get unstuck. The version-manager * lines are the fix for nearly everyone; the closing caveat is there because the * runtime that *spawns* the signer is frequently not the shell that was * upgraded, and a desktop app can keep launching the old Node long after * `node -v` in a terminal says otherwise. */ declare function unsupportedNodeVersionMessage(options: UnsupportedNodeVersionMessageOptions): string; /** * #2914 (naming epic #2906, phase 5 — the CONTRACTION): the compatibility * window #2908 opened (read both server-response names, prefer the new; * emit both camelCase names; write only the new) closed with the * `0.2.0-alpha.0` release reaching `main` on 2026-09-14 and a further * promotion on 2026-09-16. The account-vocabulary name is now the ONLY name * on every wire shape this module touches; `safe_address` / `safe_id` / * `sign_data.components.safe` are no longer read from a server response. * * `readAccountAddress` and `readAccountId` collapsed to a single field read * once the fallback was removed, so they are gone — read `raw.account_address` * / `raw.account_id` directly. `accountAddressTwins` is gone too: the SDK's * public shapes carry `accountAddress` only, never a `safeAddress` twin. * * `readX402ReceiptPayer` survives because it still has a real multi-step * chain (`payer`, then the top-level account address, then the nested * `sign_data.components` twin) once the old names are dropped from it. */ /** * The x402 receipt's `payer` off a funding-authorization response: the * explicit `payer`, then the top-level `account_address`, then * `sign_data.components.payer_account`. * * `components.account` is deliberately NOT in this chain: on the funding * shapes it holds the DELEGATE account address, a different address, and * reading it here would silently corrupt the receipt's payer. */ declare function readX402ReceiptPayer(raw: { payer?: string; account_address?: string; sign_data?: { components?: { payer_account?: string; account?: string; }; }; }): string | undefined; /** * x402 protocol support for the Haven SDK. * * Provides: * - parsePaymentRequired() — extract payment requirements from a 402 response * - parsePaymentRequiredResponse() — async parser with JSON body fallback * - encodePaymentProof() — encode a receipt as a PAYMENT-SIGNATURE header * * The main authorizeX402() and fetchWithPayment() are methods on HavenClient * (see client.ts) since they need API access and signing. */ /** * Persisted, agent-scoped facts used to preflight a signed standard x402 * payment header. This is an integrity comparison only: it never rebuilds, * modifies, persists, or submits the supplied authorization. */ interface X402PaymentHeaderContext { merchantTo: string; amountAtomic: string; asset: string; network: string; resourceUrl: string; payer: string; chainId: number; } /** A deliberately value-free refusal for untrusted payment-header input. */ declare class X402PaymentHeaderValidationError extends Error { constructor(); } /** * Upper bound on the MERCHANT-requested part of the EIP-3009 authorization * window (#715, epic #713). The x402 library sets * `validBefore = now + maxTimeoutSeconds` straight from the MERCHANT's 402 * challenge — without a cap, a malicious or sloppy merchant can request a * year-long window and a leaked signed authorization stays spendable that * whole time. 600 s is generous for any facilitator settle (typical is * 30–60 s). This cap applies only to the signed authorization, never to the * advertised requirements echoed in `accepted`. A merchant requiring more * than the bounded lifetime can still reject at verification; preserving its * offer does not widen Haven's signing policy. */ declare const X402_MAX_AUTHORIZATION_WINDOW_SECONDS = 600; /** * Forward margin ADDED on top of the (clamped) merchant timeout when the * authorization is actually signed (#1256). The x402 verify rule requires * `validBefore ≥ now + maxTimeoutSeconds` AT THE FACILITATOR — but the * upstream library computes `validBefore = now + maxTimeoutSeconds` at * SIGNING time, leaving zero forward margin. Haven's flow guarantees elapsed * time between the two (the funding UserOp confirms before the merchant * retry, ~1 min plus latency), so every purchase against a merchant whose * `maxTimeoutSeconds` exceeded that latency failed structurally — measured * live on Base mainnet: Anchor requires 300 s, and 226 s remained at verify. * * 300 s covers funding + retry latency with room to spare. The #715 exposure * ceiling becomes clamped-timeout + margin ≤ 900 s total forward — a * deliberate widening from 600 s, recorded on #1256: an authorization that * cannot pass verify protects no one, and 900 s is still bounded by the same * clamp discipline. */ declare const X402_SETTLEMENT_FORWARD_MARGIN_SECONDS = 300; declare function normalizePaymentRequired(value: unknown): X402PaymentRequired | null; /** * The x402 wire header names, in one place (#2289). * * v2 renamed all three; v1's only name was `X-PAYMENT`, used in BOTH * directions. Haven had adopted the v2 names for everything it *reads* and * kept the v1 name for the one thing it *writes*, which is how a strict v2 * merchant came to never see a payment header at all. * * The 2026-08-31 owner decision was to send both outbound names on every * retry rather than switch on `x402Version`: a v1 merchant ignores the name it * does not know, a v2 merchant ignores the legacy one, and no version * heuristic has to be right for a payment to land. * * **That is no longer unconditional (#2341).** It held while the cost of a * spare header was zero, and on the EIP-3009 bridge it still is. On erc7710 it * is not: that header carries a whole delegation chain, and duplicating it * overflowed the merchant's header limit — HTTP 431, every erc7710 settlement * refused. `x402PaymentHeaderNamesFor` below is the live rule; read it rather * than this paragraph, which records why the simpler rule was right first. */ /** v2 client→server payment payload. The name a strict v2 merchant reads. */ declare const X402_PAYMENT_HEADER_NAME = "PAYMENT-SIGNATURE"; /** v1 client→server payment payload; still accepted by most v2 merchants. */ declare const X402_LEGACY_PAYMENT_HEADER_NAME = "X-PAYMENT"; /** v2 server→client payment requirements. */ declare const X402_PAYMENT_REQUIRED_HEADER_NAME = "PAYMENT-REQUIRED"; /** v2 server→client settlement receipt. */ declare const X402_PAYMENT_RESPONSE_HEADER_NAME = "PAYMENT-RESPONSE"; /** * Both wire names, v2 first — the value an EIP-3009 retry actually sends. * * **Not the general answer any more (#2341), and not what a recorder should * reach for.** This was the evidence record's `paymentProofHeaderName` while * both names always went on the wire; erc7710 now sends one, so a recorder * still reading this constant would log a legacy header that was never sent — * exactly the drift the previous wording promised it prevented. Use * `x402PaymentHeaderNamesSent(paymentHeader)`. Kept exported because it is a * published surface and removing it would break consumers. */ declare const X402_PAYMENT_HEADER_NAMES_SENT = "PAYMENT-SIGNATURE, X-PAYMENT"; /** * The x402 v2 payment envelope: `{x402Version, resource?, accepted, payload, * extensions?}` per the spec's PaymentPayload (§5.2.2). * * The `resource` and `extensions` echoes are the #2361 fix, and they are not * optional politeness: the spec makes the extensions echo a MUST ("the client * must include at least the info received"), and CoinGecko's facilitator was * live-bisected rejecting the echo-less envelope with a bare 400 while * accepting the identical signature and `accepted`/`payload` bytes with the * echoes added (#2360, Base mainnet, 2026-09-01). Both objects are echoed * VERBATIM from the merchant's 402 — never reconstructed — and omitted when * the challenge carries none, which keeps the envelope byte-identical to the * pre-#2361 shape for echo-less merchants (Ampersend and Soundside settled * that shape live, so omission is the proven-compatible default). * * The `accepted` wrap itself is #303's shape and predates this helper — see * the #300/#303 history before "fixing" it: scheme/network live INSIDE * `accepted` in v2, never at the top level. */ declare function x402V2PaymentEnvelope(paymentRequired: Pick, accepted: X402PaymentOption, payload: unknown): Record; /** * Parse an HTTP 402 response into x402 PaymentRequired data. * * Supports: * - v2: PAYMENT-REQUIRED header (base64 JSON) * - v1 fallback: X-PAYMENT header or response body */ declare function parsePaymentRequired(response: Response): X402PaymentRequired; /** * Parse an HTTP 402 response into x402 PaymentRequired data. * * Soundside and other Bazaar-style MCP endpoints return the PaymentRequired * object in the JSON body, while older Haven demos and many x402 examples use * base64 headers. This keeps the synchronous header parser intact and adds the * body fallback needed for those endpoints. */ declare function parsePaymentRequiredResponse(response: Response): Promise; /** * Select the best payment option from the x402 accepts array. * * Preference order: * 1. Option on a Haven-supported network with a known token * 2. Any option on a Haven-supported network * 3. null — no compatible option */ declare function selectPaymentOption(accepts: X402PaymentOption[]): X402PaymentOption | null; /** The `extra.assetTransferMethod` value that marks an erc7710-settleable entry. */ declare const ERC7710_ASSET_TRANSFER_METHOD = "erc7710"; /** * Read `extra.assetTransferMethod` defensively. `extra` is the merchant's own * object, so it is untrusted shape: anything that is not the exact string is * treated as "not erc7710" rather than coerced. */ declare function x402AssetTransferMethod(option: X402PaymentOption): string | null; /** True when the merchant advertises this entry as erc7710-settleable. */ declare function isErc7710Option(option: X402PaymentOption): boolean; /** * The facilitator addresses a merchant advertises for an erc7710 entry, for * the #1058 redeemer pin — or `null` when it pins nothing. * * **An EMPTY array is `null`, not `[]`.** The backend rejects an empty * `redeemers` list with a 400 (`routes/x402.ts`), and the QA scenario already * treats empty as absent. Returning `[]` here would hand callers a value that * means "pin to nobody" — which is not a narrower pin, it is an unbuildable * delegation. * * Malformed entries are DROPPED rather than failing the whole option, and that * asymmetry is deliberate. A pin narrowed by a merchant's typo means the * facilitator that actually tries to redeem is not on the list, so redemption * reverts — and erc7710 has no funding leg, so nothing moved and nothing is * stranded. Refusing the option outright would instead deny a payment the * remaining valid facilitators could have settled. Losing the payment is the * worse outcome, precisely because the failure this issue closes (#1453) is the * one where funds move BEFORE the rejection. */ declare function x402FacilitatorAddresses(option: X402PaymentOption): string[] | null; /** * Select an option that can be paid with the official x402 EIP-3009 exact * scheme. Haven's older tx-hash proof path can describe more networks; the * merchant-verified path currently needs Base USDC. * * **Skips erc7710-tagged entries (#1453).** It used to return the first * positional match and never look at `extra.assetTransferMethod`, so a merchant * that listed its erc7710 entry first made a Haven client echo that option * while signing a standard EIP-3009 authorization. The merchant rejects the * mismatch cleanly — but on the legacy two-leg the Safe→delegate funding * transfer has already executed, so the visible result is a stranded delegate * balance for the sweep to reclaim. Only our own demo merchant's ordering was * holding that shut, and that pin binds our merchant, not the ones we do not * control. */ declare function selectStandardPaymentOption(accepts: X402PaymentOption[]): X402PaymentOption | null; /** * Select the erc7710-settleable option, if the merchant advertises one. */ declare function selectErc7710PaymentOption(accepts: X402PaymentOption[]): X402PaymentOption | null; /** What a settlement-scheme decision resolved to. */ interface X402SchemeSelection { scheme: 'erc7710' | 'eip3009'; option: X402PaymentOption; /** Redeemer pin for the settlement child; only ever set on erc7710. */ facilitatorAddresses: string[] | null; } /** * THE preference rule, in one place (#1450 owner decision, #1453). * * Prefer erc7710 whenever the account is on the delegation rail and the * merchant advertises `extra.assetTransferMethod: "erc7710"`; fall back to * the EIP-3009 bridge otherwise. * * Both halves of that condition are required, and the rail half is the * caller's to supply — the SDK cannot see which rail an account is on from a * 402 response alone. A legacy AllowanceModule account passing * `delegationRail: true` would select a scheme its account cannot settle; the * backend refuses that at authorize with the #1986 retired-rail 410 (#2245 — * previously a scheme-specific 400 that wrongly implied the legacy rail could * still settle via EIP-3009), which is where a rail mismatch SHOULD fail, * on-chain-adjacent rather than in a client that could be lying to itself. * * Returns `null` when neither scheme has a payable entry — the caller decides * whether that is an error or a reason to look elsewhere. */ declare function selectX402SettlementScheme(accepts: X402PaymentOption[], opts: { delegationRail: boolean; }): X402SchemeSelection | null; declare function x402AuthorizationAmount(option: X402PaymentOption): string; /** * Canonical Haven-authenticated x402 expected context, recomputed byte-for-byte * by the edge signer before it signs anything. * * **Two versions, and the version is derived — never passed in (#1138).** * `typedDataHash` present ⇒ v2, absent ⇒ v1. A v1 message is byte-identical to * what shipped before, so existing signers keep verifying legacy-rail bindings * unchanged. * * The version lives in both the header line and the payload so neither can be * reinterpreted as the other: a v2 context cannot be replayed as a v1 one that * drops the typed-data commitment, and a v1 context cannot be presented as v2. * That downgrade is exactly the attack the digest exists to stop — see * `assertExpectedBinding` in `@haven_ai/signer`, which refuses to raw-sign a * hash under a v2 binding and refuses to sign typed data without one. */ declare function buildX402ExpectedMessage(context: X402ExpectedContext): string; declare function toStandardPaymentRequirements(paymentRequired: X402PaymentRequired, option: X402PaymentOption): PaymentRequirements; /** * Strictly validate an edge-signed EIP-3009 X-PAYMENT header against the * persisted x402 intent context before a hosted relay can submit funding. * * The merchant/facilitator remains the final protocol verifier. This closes a * separate hosted-relay integrity gap: malformed or context-mismatched input * must never cause Haven to relay the funding signature first. */ declare function validateStandardX402PaymentHeader(paymentHeader: string, context: X402PaymentHeaderContext): Promise; /** * Encode a payment receipt as a base64 PAYMENT-SIGNATURE header value. * * This follows the x402 v2 protocol — the server's facilitator will * verify the on-chain transaction referenced by tx_hash. */ declare function encodePaymentProof(receipt: { txHash: string; paymentId: string; token: string; amount: string; to: string; resourceUrl?: string; accepted?: X402PaymentOption; payer?: string; chainId?: number; }): string; /** * Resolve a token symbol from a contract address. * * Checks all supported chains. For chain-specific resolution, * pass the optional `network` CAIP-2 string (e.g. "eip155:100"). */ declare function resolveTokenFromAddress(address: string, network?: string): { symbol: string; decimals: number; } | null; /** * Where the PAID retry goes — and whether it may go there at all (#3097). * * A merchant's 402 challenge declares `resource.url`. Haven records that * declaration as the resource's identity (the binding message, the intent * row, the resume checks all compare against it), but the paid request — * the one carrying `PAYMENT-SIGNATURE` — must go to the URL the CALLER * actually asked for whenever one exists. The declaration is the merchant's * word about itself, not an instruction to the client: the Ampersend * sandbox declares `http://` for a resource it serves over `https` (live, * 2026-09-17; its `http://` answers 308 → https), and a client that adopted * it sent the signed header in clear on the first hop. * * Two rules, both pure, both pinned by tests: * * - `resolveX402RetryTarget`: the caller's request URL wins; the merchant's * `resource.url` is the fallback for callers that only hold the challenge * (the hosted pay-from-quote path). The result says which one it chose and * whether the two disagree, so a quote can surface the disagreement. * - `isSecureX402RetryTarget`: `https` always; `http` only to a target that * cannot leave the machine or the test bench — loopback addresses and the * RFC 2606/6761 reserved names (`.test`, `.localhost`, `.invalid`, * `.example`), which every fixture in this repo uses. A public `http://` * target is refused BEFORE a signed header is handed to a transport. */ interface X402RetryTarget { /** The URL the paid request goes to. */ url: string; /** Which input produced it. */ source: 'request' | 'resource'; /** * True when the merchant's declared `resource.url` is not the caller's URL. * Absent (undefined) when nothing was compared — the caller named no URL * and the declaration was adopted as-is — so a consumer never reads * "false" as "the merchant agrees with what you quoted". */ resourceUrlDiffersFromRequest?: boolean; } declare function resolveX402RetryTarget(input: { requestUrl?: string | null; resourceUrl: string; }): X402RetryTarget; /** True when a retry carrying a payment header may be sent to `url`. */ declare function isSecureX402RetryTarget(url: string): boolean; declare const INSECURE_RETRY_TARGET_CODE = "INSECURE_RETRY_TARGET"; /** Refused before any signed header leaves: the paid retry would travel in clear. */ declare class HavenInsecureRetryTargetError extends HavenError { readonly url: string; constructor(url: string); } declare function assertSecureX402RetryTarget(url: string): void; /** * Runtime-agnostic base64 helpers — the single source of truth for the wire * encoding shared by the SDK and the edge signer (#325). * * Why this module exists: the SDK used `atob`/`btoa` (Web globals) while the * signer used `Buffer` (Node-only). Both worked because both currently run in * Node ≥ 16, but the duplication was a latent wire-incompatibility — and the * signer is headed for non-Node runtimes (browsers, Cloudflare Workers) where * `Buffer` does not exist (#314). * * Encoding contract: * - Output is ALWAYS standard base64 (`+`, `/`, padded). The x402 protocol's * reference implementation validates headers against * `/^[A-Za-z0-9+/]*={0,2}$/` — URL-safe output would be rejected. * - Decoding is tolerant: URL-safe input (`-`, `_`, unpadded) is normalized * before decoding, since third-party merchants are not guaranteed to be as * strict as the reference implementation. * - UTF-8 throughout. Naive `btoa(JSON.stringify(...))` throws on any * non-Latin-1 character (e.g. a merchant description with an emoji or * non-ASCII name); these helpers route through TextEncoder/TextDecoder on * the Web path so multibyte characters round-trip identically on both * runtimes. */ /** Encode a UTF-8 string as standard base64. */ declare function encodeBase64Utf8(value: string): string; /** Decode standard or URL-safe base64 to a UTF-8 string. */ declare function decodeBase64Utf8(value: string): string; /** Encode a JSON-serializable value as a standard-base64 string. */ declare function encodeBase64Json(value: unknown): string; /** * Decode a base64 JSON payload. * * Pass a `label` to get a wrapped error message instead of the raw * JSON/base64 error — call sites parsing untrusted merchant headers use this * to produce actionable failures. */ declare function decodeBase64Json(value: string, label?: string): T; /** * #1271 / #1301: bounded same-origin merchant MCP endpoint discovery. * * An agent handed a BASE merchant URL previously had to hand-probe /, /mcp, * /sse, … until something answered 402. The demo merchant (and the #1266 * contract) serves a machine-readable discovery document at * `/.well-known/haven-demo-merchant` (also at `/`) naming `mcp_url`. This * helper fetches ONLY those two fixed same-origin paths — no redirects * (`redirect: 'error'`), a 5 s timeout, a 64 KB read cap — and accepts the * document's `mcp_url` ONLY when it stays on the same origin as the input. * Anything else returns null and the caller reports the original probe * failure. Discovery finds endpoints; it carries no payment authority and an * off-origin `mcp_url` is never even fetched — this must not grow into a * general network scanner (SSRF bound, per the issue). * * Originally hosted-only (mcp-server, #1271). Moved here in #1301 so the * local/self-signed MCP package (`@haven_ai/mcp`) can share the EXACT same * bounded implementation instead of re-deriving discovery semantics — * behavior is byte-identical to the pre-move mcp-server copy; the #1271 * contract tests in packages/mcp-server/src/tools.test.ts pass unmodified * against this moved implementation. */ declare const MERCHANT_DISCOVERY_PATHS: readonly ["/.well-known/haven-demo-merchant", "/"]; declare const DISCOVERY_MAX_BYTES: number; declare function discoverMerchantMcpUrl(inputUrl: string): Promise; /** Trailing-slash/percent-case echoes compare equal; unparseable never does. */ declare function sameUrl(a: string, b: string): boolean; export { AGENT_APPROVAL_RELAY_JSON_SENTENCE, AGENT_APPROVAL_RELAY_PROSE_SENTENCE, AGENT_COMMAND_MODIFICATION_SENTENCE, AGENT_JSON_MODE_SENTENCE, AGENT_LOCAL_KEY_SENTENCE, AGENT_NETWORK_ACCESS_SENTENCE, AGENT_ONBOARDING_PROMPT, AGENT_PAYMENT_FAILURE_CODE_VALUES, AGENT_PAYMENT_NEXT_ACTION_VALUES, AGENT_PAYMENT_PHASE_VALUES, AGENT_PAYMENT_RAIL_VALUES, AGENT_README_SECTION_MD, AGENT_SECRET_HYGIENE_SENTENCE, AGENT_WIRING_COLLISION_RELAY_SENTENCE, type AgentNextStep, type AgentPaymentEnumSchema, AgentPaymentFailureCode, AgentPaymentFailureCodeDescriptions, AgentPaymentFailureCodeSchema, AgentPaymentNextAction, AgentPaymentNextActionDescriptions, AgentPaymentNextActionSchema, AgentPaymentPhase, AgentPaymentPhaseDescriptions, AgentPaymentPhaseSchema, AgentPaymentRail, AgentPaymentRailDescriptions, AgentPaymentRailSchema, type AgentPaymentSummary, type AgentPaymentWarning, AgentPaymentWarningCode, type AgentPurchaseSummary, CONNECTOR_PACKAGE_NAME, type CatalogSubmissionAccepted, type ClaudeTool, DEFAULT_CONFIRMATION_TIMEOUT_MS, DEFAULT_NEXT_TOOL_BY_ACTION, DISCOVERY_MAX_BYTES, ERC7710_ASSET_TRANSFER_METHOD, type EvidenceReportOutcome, HAVEN_AGENT_RUNBOOK_MD, HAVEN_CONNECTOR_CHANNEL, HAVEN_MINIMUM_NODE_VERSION, HAVEN_SKILL_BODY_MD, HAVEN_SKILL_MD, type HavenAgent, type HavenAgentAllowanceSummary, type HavenAgentReadiness, type HavenAgentSummary, type HavenAllowance, type HavenAllowanceSummary, HavenApiError, type HavenBalanceCoverage, type HavenCatalogEntry, type HavenCatalogMerchant, type HavenCatalogSubmission, HavenClient, type HavenClientConfig, HavenError, HavenInsecureRetryTargetError, type HavenPaymentReceipt, type HavenPaymentReceiptsPage, HavenPaymentStateError, HavenSigningError, HavenTimeoutError, HavenUnsupportedSignerVersionError, HavenZeroSettlementHashError, INSECURE_RETRY_TARGET_CODE, MERCHANT_DISCOVERY_PATHS, type MachinePaymentRail, MerchantTimeoutError, NEXT_TOOL_SERVER_NAMES, NEXT_TOOL_SERVER_ROLES, type NextStep, type NextStepArguments, type NextStepHandoff, type NextStepInput, type NextStepTarget, type NextStepTargets, type NextToolServerRole, type OpenAITool, type PaymentFee, type PaymentIntent, type PaymentNextAction, type PaymentPhase, type PaymentReceipt, type PaymentRequest, type PaymentResult, type PaymentResumeState, type PaymentStatus, type PaymentStatusResult, type PostPurchaseAllowanceSummary, RECEIPT_VERSION, type ReceiptVerification, type ResumeAuthorizedX402Input, type ResumeX402PaymentInput, SIGNER_UPDATE_FALLBACK, SKILL_FOLDER_NAME, SWEEP_BASE_CHAIN_ID, SWEEP_BASE_SEPOLIA_CHAIN_ID, SWEEP_BASE_SEPOLIA_USDC_ADDRESS, SWEEP_BASE_USDC_ADDRESS, type SharedToolKey, type SignData, SignerRefusalCode, type SweepAuthorization, type SweepConfirmation, type SweepEip712Domain, type SweepEntry, type SweepExpectedAuth, type SweepPreparation, type SweepPrepareResponse, type SweepResult, type SweepSubmitResponse, type SweepSubmitResult, type SweepTypedData, TRANSFER_WITH_AUTHORIZATION_TYPES, type ToolDescription, type UnsupportedNodeVersionMessageOptions, X402AlreadySettledError, type X402AuthorizationOptions, type X402Erc7710Settlement, type X402ExpectedAuth, type X402ExpectedContext, type X402Intent, type X402McpCallContext, type X402McpTransport, type X402MerchantCallContext, type X402MerchantOutcome, type X402MerchantOutcomeReport, type X402PaymentHeaderContext, X402PaymentHeaderValidationError, type X402PaymentOption, type X402PaymentRequired, type X402Quote, type X402Receipt, type X402RequestSnapshot, type X402ResumeState, type X402RetryTarget, type X402SchemeSelection, X402UnexpectedStatusError, X402_LEGACY_PAYMENT_HEADER_NAME, X402_MAX_AUTHORIZATION_WINDOW_SECONDS, X402_PAYMENT_HEADER_NAME, X402_PAYMENT_HEADER_NAMES_SENT, X402_PAYMENT_REQUIRED_HEADER_NAME, X402_PAYMENT_RESPONSE_HEADER_NAME, X402_SETTLEMENT_FORWARD_MARGIN_SECONDS, addressFromKey, assertSecureX402RetryTarget, buildSweepAuthorizationMessage, buildSweepTypedData, buildX402ExpectedMessage, compareNodeVersions, composeDescription, connectorRerunCommand, connectorSpec, createNextStepBuilder, decodeBase64Json, decodeBase64Utf8, defaultNextToolFor, discoverMerchantMcpUrl, encodeBase64Json, encodeBase64Utf8, encodePaymentProof, havenTools, isConnectorChannel, isErc7710Option, isSecureX402RetryTarget, isSupportedNodeVersion, isSweepableChain, isZeroSettlementTxHash, normalizePaymentRequired, parseNextTool, parsePaymentRequired, parsePaymentRequiredResponse, readX402ReceiptPayer, renderNextTool, resolveConnectorChannel, resolveTokenFromAddress, resolveX402RetryTarget, sameUrl, selectErc7710PaymentOption, selectPaymentOption, selectStandardPaymentOption, selectX402SettlementScheme, signHash, signUserOpTypedDataForDelegation, signerUpdateFallback, sweepUsdcAddress, sweepUsdcDomain, toStandardPaymentRequirements, toolDescriptions, unsupportedNodeVersionMessage, validateStandardX402PaymentHeader, verifyPaymentReceipt, verifySignature, x402AssetTransferMethod, x402AuthorizationAmount, x402FacilitatorAddresses, x402V2PaymentEnvelope };