@haven_ai/sdk 0.3.0-alpha.0 → 0.5.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2731 @@
1
+ import { PaymentRequirements } from 'x402/types';
2
+ import { Hex, Address } from 'viem';
3
+
4
+ interface HavenClientConfig {
5
+ /** Haven API key (sk_agent_xxx) */
6
+ apiKey: string;
7
+ /** Agent's delegate EOA private key. If provided, the SDK handles signing automatically. */
8
+ delegateKey?: string;
9
+ /** Haven API base URL (default: http://localhost:3001) */
10
+ baseUrl?: string;
11
+ /** Optional wallet identity to send as the x402-wallet header. */
12
+ x402Wallet?: string;
13
+ /** Timeout in ms for individual HTTP requests (default: 30000) */
14
+ requestTimeout?: number;
15
+ /** Timeout (ms) for MERCHANT-facing requests — x402/MPP probes, MCP
16
+ * handshakes, paid retries. Separate from requestTimeout (Haven API):
17
+ * merchants may settle on-chain synchronously, so the default is
18
+ * deliberately generous. #1300. */
19
+ merchantTimeout?: number;
20
+ /** Timeout in ms when polling for tx confirmation (default: 90000) */
21
+ confirmationTimeout?: number;
22
+ /** Polling interval in ms when waiting for confirmation (default: 3000) */
23
+ pollingInterval?: number;
24
+ /**
25
+ * Extra headers to attach to every request to the Haven API.
26
+ *
27
+ * Used by the MCP server to tag requests with `X-Haven-MCP-Tool: <name>`
28
+ * so the backend can record an audit-log entry per tool invocation. Has
29
+ * no effect on outbound merchant requests (x402 / MPP) — those are
30
+ * standard HTTP and never carry Haven-internal headers.
31
+ */
32
+ defaultHeaders?: Record<string, string>;
33
+ /**
34
+ * `<package>/<version>` naming the published package that embeds this
35
+ * client, sent on every Haven API request as `X-Haven-Client` (#3303) so the
36
+ * backend can tell an outdated client what to run. Defaults to
37
+ * `@haven_ai/sdk/<this SDK's version>`. It cannot be set through
38
+ * `defaultHeaders` — the transport writes it last.
39
+ */
40
+ clientIdentity?: string;
41
+ /**
42
+ * JSON-RPC RPC URLs keyed by EIP-155 chain ID.
43
+ *
44
+ * When provided for a chain, the SDK waits for ≥1 on-chain confirmation of
45
+ * the funding tx (account → delegate EOA) before retrying the merchant. This prevents
46
+ * the race where the merchant's `balanceOf(delegate)` call runs before the
47
+ * funding block has propagated to the merchant's RPC node.
48
+ *
49
+ * Without this option the SDK proceeds as soon as Haven's backend confirms
50
+ * submission (backward-compatible default). Set it to a reliable RPC
51
+ * endpoint (e.g. Alchemy / Infura) for production usage.
52
+ *
53
+ * @example { 8453: 'https://mainnet.base.org' }
54
+ */
55
+ chainRpcs?: Record<number, string>;
56
+ }
57
+ interface PaymentRequest {
58
+ /** Token symbol: "EURe", "USDC.e", or "xDAI" */
59
+ token: string;
60
+ /** Amount as a decimal string, e.g. "5.00" */
61
+ amount: string;
62
+ /** Recipient Ethereum address (0x...) */
63
+ to: string;
64
+ /**
65
+ * Optional dedupe key (#1207): a retried request with the same key returns
66
+ * the FIRST request's result instead of minting a second transfer or a
67
+ * second approval. Same contract as /machine-payments/send. Max 128 chars.
68
+ */
69
+ idempotencyKey?: string;
70
+ }
71
+ interface SignData {
72
+ /** The hash to sign (keccak256, 0x-prefixed) */
73
+ hash: string;
74
+ /**
75
+ * Delegation rail: 'eip712_userop' (funding redemption) or
76
+ * 'eip712_delegation' (erc7710 settlement child). The backend spec makes it
77
+ * required; the legacy AllowanceModule reading — absent = raw ECDSA over
78
+ * `hash` — is retired (#2850), and the SDK client refuses an absent scheme.
79
+ * The session rail's 'eip191_userop' is retired (#834).
80
+ *
81
+ * When present, `hash` is NOT what gets signed — `typed_data` is (#1138).
82
+ */
83
+ signature_scheme?: 'eip712_userop' | 'eip712_delegation';
84
+ /**
85
+ * EIP-712 payload the account validates, signed VERBATIM (#829). Present
86
+ * whenever `signature_scheme` is — never reconstruct it from `components`.
87
+ */
88
+ typed_data?: {
89
+ domain: Record<string, unknown>;
90
+ types: Record<string, unknown>;
91
+ primaryType: string;
92
+ message: Record<string, unknown>;
93
+ };
94
+ /** Breakdown of values that were hashed — useful for debugging */
95
+ components: {
96
+ /**
97
+ * The PAYER account (the user's smart account). Not to be confused with
98
+ * `account`, which on the funding shapes holds the DELEGATE account
99
+ * address.
100
+ */
101
+ payer_account?: string;
102
+ token: string;
103
+ to: string;
104
+ amount: string;
105
+ payment_token: string;
106
+ payment: string;
107
+ nonce: number;
108
+ };
109
+ /** Human-readable signing instructions */
110
+ instructions: string;
111
+ }
112
+ interface PaymentIntent {
113
+ /** Unique payment ID */
114
+ paymentId: string;
115
+ /** Current status */
116
+ status: 'pending_signature';
117
+ /** ISO 8601 expiry timestamp */
118
+ expiresAt: string;
119
+ /** Data needed to sign the payment */
120
+ signData: SignData;
121
+ }
122
+ type PaymentStatus = 'pending_signature' | 'submitted' | 'confirmed' | 'pending_approval' | 'approved' | 'proposed' | 'executed' | 'rejected' | 'expired' | 'failed';
123
+ interface PaymentResult {
124
+ /** Unique payment ID */
125
+ paymentId: string;
126
+ /** Final status */
127
+ status: PaymentStatus;
128
+ /** Token that was sent */
129
+ token: string;
130
+ /** Amount that was sent (human-readable) */
131
+ amount: string;
132
+ /** Recipient address */
133
+ to: string;
134
+ /** On-chain transaction hash (present when confirmed) */
135
+ txHash: string | null;
136
+ /** Error message (present when failed) */
137
+ errorMessage: string | null;
138
+ /** Block explorer URL for the transaction (chain-dependent) */
139
+ explorerUrl: string | null;
140
+ /** ISO 8601 timestamps */
141
+ createdAt: string;
142
+ signedAt: string | null;
143
+ submittedAt: string | null;
144
+ confirmedAt: string | null;
145
+ expiresAt: string;
146
+ /**
147
+ * Platform fee surfaced on the result so it's never silently collected. Dark
148
+ * today (`amount` "0", `applied` false); always present so it's visible the
149
+ * moment fees go live.
150
+ */
151
+ fee?: PaymentFee | null;
152
+ }
153
+ /** The Haven platform fee applied to a payment (#386). */
154
+ interface PaymentFee {
155
+ /** Human-readable fee amount ("0" while the fee module is dark). */
156
+ amount: string;
157
+ /** Token the fee is denominated in. */
158
+ token: string;
159
+ /** Fee as basis points of gross (0 while dark). */
160
+ basisPoints: number;
161
+ /** True when a non-zero fee was actually applied. */
162
+ applied: boolean;
163
+ }
164
+ /** Payment requirements from an HTTP 402 response (x402 protocol). */
165
+ interface X402PaymentRequired {
166
+ x402Version: number;
167
+ resource: {
168
+ url: string;
169
+ description?: string;
170
+ mimeType?: string;
171
+ [key: string]: unknown;
172
+ };
173
+ accepts: X402PaymentOption[];
174
+ error?: string;
175
+ extensions?: Record<string, unknown>;
176
+ }
177
+ /** A single payment option from x402 PaymentRequired. */
178
+ interface X402PaymentOption {
179
+ scheme: string;
180
+ network: string;
181
+ amount: string;
182
+ maxAmountRequired?: string;
183
+ resource?: string;
184
+ description?: string;
185
+ mimeType?: string;
186
+ asset: string;
187
+ payTo: string;
188
+ maxTimeoutSeconds: number;
189
+ /**
190
+ * Merchant-supplied scheme metadata. Two keys are load-bearing for Haven
191
+ * (#1453), both from MetaMask's erc7710 x402 shape:
192
+ *
193
+ * assetTransferMethod — 'erc7710' marks this entry as settleable by
194
+ * redeeming a delegation chain. Absent/other means
195
+ * the standard EIP-3009 authorization.
196
+ * facilitatorAddresses — who may redeem it, pinned into the settlement
197
+ * child's redeemer caveat (#1058).
198
+ *
199
+ * Left as an open record on purpose: the field is the merchant's, and
200
+ * narrowing it to Haven's two keys would silently drop everything else a
201
+ * merchant sends. Read it through `x402AssetTransferMethod` /
202
+ * `x402FacilitatorAddresses` rather than indexing it raw.
203
+ */
204
+ extra?: Record<string, unknown>;
205
+ }
206
+ /** Receipt returned after a successful x402 payment. */
207
+ interface X402Receipt {
208
+ success: boolean;
209
+ paymentId: string;
210
+ txHash: string;
211
+ token: string;
212
+ amount: string;
213
+ to: string;
214
+ resourceUrl: string;
215
+ explorerUrl: string;
216
+ accepted?: X402PaymentOption;
217
+ paymentHeader?: string;
218
+ merchantTo?: string | null;
219
+ payer?: string;
220
+ chainId?: number;
221
+ haven?: {
222
+ paymentId: string;
223
+ fundingTxHash: string;
224
+ fundingExplorerUrl: string;
225
+ };
226
+ merchant?: {
227
+ payTo: string | null;
228
+ settlementTxHash?: string | null;
229
+ settlementExplorerUrl?: string | null;
230
+ };
231
+ x402?: {
232
+ amount: string;
233
+ token: string;
234
+ network: string;
235
+ asset: string;
236
+ resource: string;
237
+ };
238
+ }
239
+ interface X402AuthorizationOptions {
240
+ /** Stable caller-supplied key for this user intent. Prevents duplicate approvals across fresh 402 quotes. */
241
+ idempotencyKey?: string;
242
+ /**
243
+ * #1307: the merchant MCP-tool call context this quote was made against
244
+ * (merchant_url, tool_name, arguments, mcp_transport). Persisted on the
245
+ * intent so `getX402MerchantCallContext` can rehydrate it by payment_id at
246
+ * settle/complete time instead of the caller re-threading it. Optional —
247
+ * omit for a non-MCP-tool x402 merchant (plain HTTP resource).
248
+ */
249
+ mcpCallContext?: X402McpCallContext;
250
+ /**
251
+ * #1348: the agent's delegate address, when the caller already resolved it
252
+ * from `getAgent()` in this same flow — skips `createX402Intent`'s internal
253
+ * agent fetch (one full round trip on every guided purchase). Staleness
254
+ * caveat (#1358 review): the backend derives the funding shape by comparing
255
+ * `payTo` to the CURRENT delegate address, so a value made stale by a
256
+ * delegate rotation mid-flow is not always a clean failure — a pinned-budget
257
+ * agent gets a 403, but an open-budget delegation agent would route to the
258
+ * settlement shape with the stale address. The window is one tool call
259
+ * (previously sub-millisecond, now the merchant-quote duration), never
260
+ * externally suppliable; server-truth hardening is tracked in #1360. Only
261
+ * pass an address fetched in THIS flow; omit to keep the self-contained
262
+ * fetch.
263
+ */
264
+ delegateAddress?: string;
265
+ }
266
+ /**
267
+ * Keyless x402 construct result.
268
+ *
269
+ * Returned by `createX402Intent` — the non-custodial half of an x402 payment.
270
+ * It carries the unsigned funding payload (`signData`, account → delegate EOA)
271
+ * plus everything the *edge* needs to build and sign the EIP-3009 merchant
272
+ * header itself. The construct path never signs; both delegate signatures
273
+ * (funding payload + merchant header) happen on the machine that holds the key.
274
+ */
275
+ interface X402Intent {
276
+ /** Haven payment id for the funding transfer. */
277
+ paymentId: string;
278
+ /** Stable key used to create or refresh this x402 funding intent. */
279
+ idempotencyKey: string;
280
+ status: 'pending_signature';
281
+ /** ISO 8601 expiry of the funding intent, if returned. */
282
+ expiresAt?: string;
283
+ /** The unsigned funding payload to sign with the delegate key (account → delegate EOA). */
284
+ signData: SignData;
285
+ /** The selected x402 option — the edge needs this to build the EIP-3009 header. */
286
+ accepted: X402PaymentOption;
287
+ /** Resource URL the 402 came from. */
288
+ resourceUrl: string;
289
+ /** Merchant payTo address (the final recipient of the EIP-3009 transfer). */
290
+ merchantTo: string;
291
+ /** Atomic amount the edge signer must authorize in the merchant header. */
292
+ amountAtomic: string;
293
+ /** Token contract the merchant header must pay. */
294
+ asset: string;
295
+ /** x402 network the merchant header must use. */
296
+ network: string;
297
+ /** Haven-authenticated binding over the x402 expected context. */
298
+ expectedAuth: X402ExpectedAuth;
299
+ /**
300
+ * #1690: the payer identity Haven bound into the expected context (v3),
301
+ * relayed VERBATIM to the signer's wire shape. Absent until the backend
302
+ * flips X402_EMIT_PAYER_CONTEXT.
303
+ */
304
+ payerDelegate?: string;
305
+ payerAgentId?: string;
306
+ /**
307
+ * EIP-712 digest of `signData.typed_data`, present on the delegation rail
308
+ * (#1138). The edge signer needs it to reconstruct the v2 expected-context
309
+ * message that Haven signed.
310
+ */
311
+ expectedTypedDataHash?: string;
312
+ /** Delegate EOA the funding transfer tops up (the x402 payer). */
313
+ fundingTo: string;
314
+ }
315
+ interface X402ExpectedContext {
316
+ paymentId: string;
317
+ payloadHash: string;
318
+ resourceUrl: string;
319
+ merchantTo: string;
320
+ amount: string;
321
+ asset: string;
322
+ network: string;
323
+ /** Optional ISO expiry for the funding/quote window. When present, it is bound into the Haven-authenticated context. */
324
+ expiresAt?: string;
325
+ /**
326
+ * EIP-712 digest of the typed data the account actually validates
327
+ * (delegation rail, #1138). Present ⇒ the context is **version 2** and the
328
+ * signer must sign that typed data, never `payloadHash`.
329
+ *
330
+ * On the delegation rail `payloadHash` is the bare ERC-4337 UserOp hash,
331
+ * which is NOT what the account validates — binding it alone would leave the
332
+ * edge signer unable to verify the payload it is being asked to sign. Binding
333
+ * this digest makes Haven's declaration cover the real payload.
334
+ *
335
+ * Absent ⇒ the retired version-1 bare-hash context. Since #3272 the backend
336
+ * never emits one (`signX402ExpectedContext` requires this field) and
337
+ * `@haven_ai/signer` refuses it with its version-mismatch refusal; the field
338
+ * stays optional here only because the type also describes older payloads.
339
+ */
340
+ typedDataHash?: string;
341
+ /**
342
+ * The DELEGATE ADDRESS this quote was created for (#1690). Present ⇒ the
343
+ * context is **version 3** and the signer refuses to sign when this is not
344
+ * its own delegate — the guard that turns "quote as agent A, sign as agent
345
+ * B" from an on-chain revert three layers later into a named refusal.
346
+ * Inside the Haven-signed message on purpose: outside it, it is forgeable.
347
+ */
348
+ payerDelegate?: string;
349
+ /** The paying agent's id, for the refusal message's diagnosis (#1690). */
350
+ payerAgentId?: string;
351
+ }
352
+ interface X402ExpectedAuth {
353
+ /**
354
+ * 2 = carries `typedDataHash` (delegation rail, #1138). 3 = additionally binds
355
+ * the payer identity (#1690). 1 (hash-only, retired Safe rail) is never
356
+ * emitted since #3272 and the signer refuses it.
357
+ *
358
+ * Deliberately `number`, not a literal union (#1143). This is an **inbound**
359
+ * value: a signer parses a context Haven produced, and a signer older than the
360
+ * backend will legitimately receive a version it does not know. A closed union
361
+ * makes that state unrepresentable, which pushed the rejection down to the
362
+ * schema boundary and produced a raw validation error naming neither the cause
363
+ * nor the fix. The supported set lives in the signer
364
+ * (`SUPPORTED_X402_EXPECTED_VERSIONS`), which fails closed on anything outside
365
+ * it with an actionable message.
366
+ */
367
+ version: number;
368
+ message: string;
369
+ signature: string;
370
+ signer: string;
371
+ }
372
+ /** Serializable HTTP request state for retrying the same x402 merchant request. */
373
+ interface X402RequestSnapshot {
374
+ url: string;
375
+ method: string;
376
+ headers: [string, string][];
377
+ body?: string;
378
+ }
379
+ interface X402McpTransport {
380
+ handshakeRequired: boolean;
381
+ source: 'path' | 'bazaar';
382
+ }
383
+ /**
384
+ * #1307: the merchant MCP-tool call an x402 quote was made against — carried
385
+ * through `createX402Intent`'s options so Haven can persist it for the
386
+ * settle-leg rehydration handoff (`getX402MerchantCallContext`). Convenience
387
+ * metadata for retrying the merchant's OWN JSON-RPC call, never payment
388
+ * authority.
389
+ */
390
+ interface X402McpCallContext {
391
+ merchantUrl: string;
392
+ toolName: string;
393
+ arguments?: Record<string, unknown>;
394
+ mcpTransport?: X402McpTransport;
395
+ }
396
+ /**
397
+ * Response shape of `getX402MerchantCallContext` — the stored merchant call
398
+ * context for a payment_id, rehydrated instead of re-threaded (#1307).
399
+ */
400
+ interface X402MerchantCallContext {
401
+ paymentId: string;
402
+ merchantUrl: string;
403
+ toolName: string;
404
+ arguments: Record<string, unknown>;
405
+ mcpTransport?: X402McpTransport;
406
+ }
407
+ /** Quote parsed from an HTTP 402 response without creating a Haven payment. */
408
+ interface X402Quote {
409
+ rail: 'x402';
410
+ idempotencyKey: string;
411
+ paymentRequired: X402PaymentRequired;
412
+ accepted: X402PaymentOption;
413
+ /**
414
+ * #2054: which selector produced `accepted`, and therefore which entry every
415
+ * amount on this quote describes. `'standard'` is the untagged,
416
+ * EIP-3009-settleable entry; `'erc7710'` means the merchant advertises NO
417
+ * standard entry, so the quote describes its erc7710 one — settleable only
418
+ * from a delegation-rail account, a fact the quote layer cannot see (the
419
+ * rail is a property of the ACCOUNT, not of the 402). This field is
420
+ * descriptive: the actual settlement scheme is still chosen later, with the
421
+ * rail in hand, by `selectX402SettlementScheme`.
422
+ */
423
+ acceptedScheme: 'standard' | 'erc7710';
424
+ request: X402RequestSnapshot;
425
+ mcpTransport?: X402McpTransport;
426
+ resourceUrl: string;
427
+ /** #3097: `resourceUrl` (the merchant's declaration) is not `request.url` (what was quoted). */
428
+ resourceUrlDiffersFromRequest: boolean;
429
+ description: string | null;
430
+ mimeType: string | null;
431
+ amountAtomic: string;
432
+ amount: string;
433
+ token: string;
434
+ /**
435
+ * #1351: decimals for `asset` on `network`, resolved from the SAME
436
+ * address→token binding that produced `token` — the quote's own authority on
437
+ * how many atomic units one human unit is. `null` when the merchant's asset
438
+ * is not a token Haven recognises on that network, in which case `token` is
439
+ * an unverified fallback label and NO human→atomic conversion is safe.
440
+ * Consumers converting a human-denominated figure (a user-intent spending
441
+ * cap) MUST fail closed on `null` rather than assume 6.
442
+ */
443
+ decimals: number | null;
444
+ asset: string;
445
+ network: string;
446
+ chainId: number | null;
447
+ merchantAddress: string;
448
+ maxTimeoutSeconds: number;
449
+ }
450
+ /** State bundle an agent can persist while waiting for manual x402 approval. */
451
+ interface X402ResumeState {
452
+ rail: 'x402';
453
+ paymentId: string;
454
+ idempotencyKey: string;
455
+ paymentRequired: X402PaymentRequired;
456
+ accepted: X402PaymentOption;
457
+ url: string;
458
+ request?: X402RequestSnapshot;
459
+ resourceUrl: string;
460
+ description: string | null;
461
+ amountAtomic: string;
462
+ amount: string;
463
+ token: string;
464
+ asset: string;
465
+ network: string;
466
+ chainId: number | null;
467
+ merchantAddress: string;
468
+ }
469
+ type PaymentResumeState = X402ResumeState;
470
+ interface ResumeAuthorizedX402Input extends X402AuthorizationOptions {
471
+ /** Payment or approval request ID returned by authorizeX402 / haven.fetch. */
472
+ paymentId: string;
473
+ /** Original or freshly parsed x402 requirements for the merchant retry. */
474
+ paymentRequired: X402PaymentRequired;
475
+ }
476
+ interface ResumeX402PaymentInput extends X402AuthorizationOptions {
477
+ /** Payment or approval request ID returned by authorizeX402 / haven.fetch. */
478
+ paymentId: string;
479
+ /** Original paid URL. If paymentRequired is omitted, Haven will call it once to re-read the 402 challenge. */
480
+ url: string;
481
+ /** Original fetch options. Reused for the 402 probe and final merchant retry. */
482
+ init?: RequestInit;
483
+ /** Serializable original request captured by quoteX402() / pending approval errors. */
484
+ request?: X402RequestSnapshot;
485
+ /** Original or freshly parsed x402 requirements. Supplying this avoids an extra merchant 402 probe. */
486
+ paymentRequired?: X402PaymentRequired;
487
+ }
488
+ type MachinePaymentRail = 'x402' | 'mpp_demo' | 'mpp_crypto' | 'stripe_deposit' | 'spt';
489
+ interface HavenAgent {
490
+ id: string;
491
+ name: string;
492
+ status: string;
493
+ /** The agent's Haven account (smart account) address. */
494
+ accountAddress: string;
495
+ delegateAddress: string;
496
+ chainId: number;
497
+ /**
498
+ * Which on-chain policy primitive gates this agent's spend (#1306): the
499
+ * legacy Safe AllowanceModule (retired — no account can enter it since
500
+ * #1984, and it cannot spend since #1986) or the delegation
501
+ * rail's active budget delegations (#1090). Read-only reporting — the
502
+ * on-chain state is the actual gate either way, this only says which
503
+ * mechanism a caller should read/derive from.
504
+ */
505
+ executionRail: 'legacy' | 'delegation';
506
+ }
507
+ interface HavenAllowance {
508
+ id: string;
509
+ tokenAddress: string;
510
+ tokenSymbol: string;
511
+ configuredAmount: string;
512
+ resetPeriodMin: number;
513
+ /**
514
+ * #3128: human-readable `onchain.remaining`, e.g. "4.96 USDC" — the SAME
515
+ * string {@link HavenAgentAllowanceSummary.remainingDisplay} carries for
516
+ * this allowance, computed by one function from `onchain.remaining` and
517
+ * the token's decimals, so the two reads cannot disagree. Additive; the
518
+ * wire carries no display form (it is derived client-side).
519
+ */
520
+ remainingDisplay: string;
521
+ onchain: {
522
+ amount: string;
523
+ spent: string;
524
+ remaining: string;
525
+ effectiveSpent: string;
526
+ resetTimeMin: number;
527
+ lastResetMin: number;
528
+ nonce: number;
529
+ isResetPending: boolean;
530
+ /**
531
+ * Delegation rail only (#1319, provenance for #1145's fallback): true
532
+ * when `remaining` came from a live on-chain enforcer read, false when
533
+ * the read failed and `remaining` is the fallback full configured
534
+ * budget. Undefined on the legacy AllowanceModule rail, which has no
535
+ * fallback concept. Reporting only — the on-chain policy remains the
536
+ * actual spend gate either way.
537
+ */
538
+ remainingIsFromChain?: boolean;
539
+ };
540
+ }
541
+ interface HavenAllowanceSummary {
542
+ agentId: string;
543
+ accountAddress: string;
544
+ delegateAddress: string;
545
+ chainId: number;
546
+ allowances: HavenAllowance[];
547
+ }
548
+ /**
549
+ * Post-purchase allowance/budget summary attached to a settled x402 payment
550
+ * (#1310). Read-only reporting — the on-chain policy remains the actual
551
+ * spend gate either way, this only says what is left after the purchase.
552
+ *
553
+ * Deliberately the SAME rail-labeled field spelling as #1306's
554
+ * catalog-purchase preflight `allowance` block (never a new spelling),
555
+ * minus the preflight-only `sufficient` field: post-purchase reporting
556
+ * answers "what is left", not "was this purchase covered". Read through the
557
+ * exact same source as {@link HavenAllowanceSummary} / `haven_get_allowances`
558
+ * (`GET /machine-payments/allowances`; delegation-rail values are the #1090
559
+ * `deriveDelegationBudgets`-backed enforcer read, never `agent_allowances`),
560
+ * so this can never disagree with `haven_get_allowances` for the same
561
+ * fixture.
562
+ */
563
+ interface PostPurchaseAllowanceSummary {
564
+ /** Which on-chain policy primitive gates this agent's spend (#1306 labeling). */
565
+ rail: 'legacy' | 'delegation';
566
+ /** Remaining atomic units, read through the same source as {@link HavenAllowance.onchain.remaining}. */
567
+ remaining_atomic: string;
568
+ /** Human-readable remaining, e.g. "4.96 USDC". Omitted when the token's decimals are unknown. */
569
+ remaining_display?: string;
570
+ token_symbol?: string;
571
+ token_address?: string;
572
+ /** Minutes — mirrors {@link HavenAllowance.resetPeriodMin} / the delegation's period. */
573
+ reset_period?: number;
574
+ source: 'allowance_module' | 'active_delegations';
575
+ }
576
+ /**
577
+ * #3126 — the answer to "is there money actually HELD behind my budget?",
578
+ * asked as a sufficiency signal rather than a balance.
579
+ *
580
+ * Every other agent-readable figure in this package describes SPEND
581
+ * AUTHORITY — what the agent is PERMITTED to move this period
582
+ * ({@link HavenAllowanceSummary}). This shape answers the different question
583
+ * of whether the account HOLDS funds behind that authority, and deliberately
584
+ * answers it as `covered: boolean | null`, never as a figure: a constrained
585
+ * actor has no business reading the treasury total, and the boolean answers
586
+ * the only decision an agent has (attempt the payment, or tell the user
587
+ * funds are missing).
588
+ *
589
+ * The naming keeps the two concepts apart (the #3126 binding constraint):
590
+ * `budgetRemainingAtomic` is AUTHORITY — the same value
591
+ * {@link HavenAllowanceSummary} reports per token as `onchain.remaining` —
592
+ * while `covered` speaks only of HELD funds. Nothing here is named like the
593
+ * authority fields (`remaining`, `available`); nothing here returns a
594
+ * balance.
595
+ *
596
+ * `covered: null` means the chain read FAILED — unverifiable, never a
597
+ * guess. The same honesty rule `x402-funding-leg.ts`'s `delegateCanFund`
598
+ * established (#1521): treat null as "we do not know", not as "funded" or
599
+ * as absence; `coverageError` carries why.
600
+ */
601
+ interface HavenBalanceCoverage {
602
+ /**
603
+ * true: the chain reports the agent's account holds at least
604
+ * `checkedAmountAtomic` of the token. false: the chain read succeeded and
605
+ * reports LESS — tell the user funds are missing rather than retrying.
606
+ * null: the chain read failed — unverifiable, never treated as absence.
607
+ */
608
+ covered: boolean | null;
609
+ /** Present only when `covered` is null: why the chain read could not answer. */
610
+ coverageError?: string;
611
+ chainId: number;
612
+ tokenAddress: string;
613
+ tokenSymbol: string;
614
+ /** The amount the coverage question was asked about, in atomic units. */
615
+ checkedAmountAtomic: string;
616
+ /**
617
+ * Context, AUTHORITY not holdings: the agent's remaining spend authority
618
+ * for the requested token, in atomic units — the same derivation
619
+ * {@link HavenAllowanceSummary} reports (`onchain.remaining`; the #1090
620
+ * derivation, the #1145 enforcer read). Zero when no active budget row
621
+ * names the token. Compare it with `covered`, never instead of it.
622
+ */
623
+ budgetRemainingAtomic: string;
624
+ /**
625
+ * Provenance of `budgetRemainingAtomic` (#1319, same semantics as
626
+ * {@link HavenAllowance.onchain.remainingIsFromChain}): true when the
627
+ * budget figure came from a live enforcer read, false when it fell back
628
+ * to the configured budget. Absent when no budget row existed for the
629
+ * token (nothing was read).
630
+ */
631
+ budgetRemainingIsFromChain?: boolean;
632
+ }
633
+ /**
634
+ * Affirmative spend-readiness for the authenticated agent, derived from the raw
635
+ * agent status plus the remaining spend authority the backend reports per rail
636
+ * (the active budget delegation on the delegation rail — #1135; the retired
637
+ * AllowanceModule rail used an on-chain allowance instead):
638
+ * - `ready` — active and at least one token has remaining spend authority.
639
+ * - `needs_approval`— active but no remaining spend authority to auto-spend.
640
+ * The over-budget outcome differs by rail: on the retired
641
+ * AllowanceModule rail the payment was queued for the wallet
642
+ * owner to approve in Haven; on the delegation rail there is
643
+ * NO approval queue — an over-budget redemption reverts
644
+ * on-chain, so the owner must grant or raise the budget in
645
+ * Haven before the agent can pay.
646
+ * - `revoked` — the agent's status is not `active`; nothing auto-executes.
647
+ *
648
+ * Note: a hard-paused/disabled credential is rejected by the API before this
649
+ * call returns, so it surfaces as an API error rather than `revoked`. `revoked`
650
+ * is reached when the request authenticates but the agent status is non-active.
651
+ *
652
+ * Wallet token balance is intentionally NOT folded in here: the on-chain
653
+ * remaining allowance is the gate Haven enforces, and insufficient wallet
654
+ * funding surfaces at pay time as INSUFFICIENT_FUNDS.
655
+ */
656
+ type HavenAgentReadiness = 'ready' | 'needs_approval' | 'revoked';
657
+ /**
658
+ * Compact, agent-facing per-token spend authority for the bootstrap summary.
659
+ *
660
+ * #3128: a deliberately DIFFERENT view of the same allowance as
661
+ * {@link HavenAllowance} — flat, no `onchain` block, no spent/nonce/reset-time
662
+ * detail — but never a disjoint one: every field here is present on or
663
+ * derived from the {@link HavenAllowance} with the same `id`, and
664
+ * `remainingAtomic` / `remainingDisplay` equal that allowance's
665
+ * `onchain.remaining` / `remainingDisplay` byte for byte (pinned by test). A
666
+ * client that wants the id AND a display amount can therefore use either
667
+ * read alone.
668
+ */
669
+ interface HavenAgentAllowanceSummary {
670
+ /** #3128: the {@link HavenAllowance.id} this row summarises. */
671
+ id: string;
672
+ tokenSymbol: string;
673
+ /** #3128: the {@link HavenAllowance.tokenAddress}. */
674
+ tokenAddress: string;
675
+ /** Live on-chain remaining allowance in atomic units. */
676
+ remainingAtomic: string;
677
+ /** Human-readable remaining, e.g. "4.96 USDC". */
678
+ remainingDisplay: string;
679
+ /** Configured allowance amount (atomic) the owner granted. */
680
+ configuredAmount: string;
681
+ resetPeriodMin: number;
682
+ isResetPending: boolean;
683
+ }
684
+ /**
685
+ * One-shot "am I ready?" bootstrap: identity + live spend authority + a
686
+ * readiness signal, so an agent can answer "who am I and can I pay right now"
687
+ * from a single call at session start. Superset of {@link HavenAgent}.
688
+ */
689
+ interface HavenAgentSummary extends HavenAgent {
690
+ /**
691
+ * @deprecated Use {@link HavenAgentSummary.spend_authority_readiness} —
692
+ * same value, honest name. This signal covers hosted identity + on-chain
693
+ * spend authority ONLY; it says nothing about the LOCAL signer, which the
694
+ * hosted side cannot see (verify via a signer tool or connect --doctor).
695
+ * Kept as an alias; removal earliest after the next release train (#1590).
696
+ */
697
+ readiness: HavenAgentReadiness;
698
+ /**
699
+ * Spend-authority readiness: hosted identity + on-chain remaining spend
700
+ * authority. Deliberately named for what it covers — the LOCAL signer's
701
+ * availability is NOT included and must be verified separately (a signer
702
+ * tool call, or the connector's `--doctor`, whose exact command this build
703
+ * renders from `HAVEN_CONNECTOR_CHANNEL` — see `connector-channel.ts`).
704
+ */
705
+ spend_authority_readiness: HavenAgentReadiness;
706
+ allowances: HavenAgentAllowanceSummary[];
707
+ }
708
+ /**
709
+ * #2960 — one party vocabulary for "who paid" a Haven payment, additive
710
+ * alongside every existing lone `payer*`/`*Address` field (same discipline
711
+ * as the #2907 `safe`/`account` dual-emit, except these four are DISTINCT
712
+ * addresses, not same-value twins of one old field).
713
+ */
714
+ interface PaymentParties {
715
+ treasuryAccount: string | null;
716
+ delegate: string | null;
717
+ delegateAccount: string | null;
718
+ merchant: string | null;
719
+ }
720
+ /** @internal wire shape of {@link PaymentParties}. */
721
+ interface RawPaymentParties {
722
+ treasury_account: string | null;
723
+ delegate: string | null;
724
+ delegate_account: string | null;
725
+ merchant: string | null;
726
+ }
727
+ /**
728
+ * #3132 (owner decision 3 on #3130): what population a list row came from and
729
+ * what narrowed it, as two values. Receipts are `{ source: 'agent', filter:
730
+ * null }` — this agent's evidence rows only, no query-time narrowing. The
731
+ * wallet feed (`GET /transactions`, the CLI's `activity list`) is
732
+ * `source: 'wallet'` with `filter: 'agent'` when `agentId` narrows it, and it
733
+ * is a DIFFERENT population (explorer window plus synthesized intents; sweeps
734
+ * and funding legs included), never this view. A receipt read is not a
735
+ * transaction-history read.
736
+ */
737
+ interface HavenListScope {
738
+ source: 'wallet' | 'agent';
739
+ filter: 'agent' | 'account' | 'account+agent' | null;
740
+ }
741
+ interface HavenPaymentReceipt {
742
+ id: string;
743
+ /** #3132: present when the backend states it (absent on an older backend). */
744
+ scope?: HavenListScope;
745
+ paymentId: string;
746
+ paymentIntentId?: string | null;
747
+ approvalRequestId?: string | null;
748
+ /**
749
+ * #3134: the payment protocol this receipt settled on — one of the
750
+ * evidence-eligible rails (`x402`, `mpp_demo`, `mpp_crypto`, `spt`) — under the
751
+ * name the transactions feed uses for the same concept. Distinct from
752
+ * `scope.source`, which names the LIST population (#3132) — the transaction
753
+ * row carries the same two. Same name, narrower domain: never `'direct'`
754
+ * here — the feed's SQL default for an intent that names no protocol has no
755
+ * receipt analogue, because no protocol means no evidence row.
756
+ */
757
+ source: string;
758
+ /** @deprecated (#3134) twin of {@link source}; removed once all three release clocks have moved — see `mapPaymentReceipt`. */
759
+ rail: string;
760
+ /**
761
+ * #3134: the evidence row's recorded proof status, under the transactions
762
+ * feed's name. Same name, different nullability: `string` here because a
763
+ * receipt IS the evidence row, `string | null` on the feed, where a row may
764
+ * LEFT JOIN to none (#3132) — do not share a non-null-asserting helper.
765
+ */
766
+ paymentProofStatus: string;
767
+ /** @deprecated (#3134) twin of {@link paymentProofStatus}; removed once all three release clocks have moved — see `mapPaymentReceipt`. */
768
+ proofStatus: string;
769
+ /**
770
+ * @deprecated (#2998) meaning depends on the settlement scheme — the
771
+ * account → delegate funding transaction on eip3009, the (only) settlement
772
+ * transaction on erc7710. Prefer {@link fundingTxHash} / {@link settlementTxHash}, which
773
+ * name which is which.
774
+ */
775
+ txHash: string;
776
+ /** The account → delegate funding transaction, relayed by Haven (#2998); null on erc7710 (no funding leg) and on retired mpp-rail rows. */
777
+ fundingTxHash: string | null;
778
+ /**
779
+ * The delegate → merchant settlement transaction (#2998). Trust level differs
780
+ * by scheme: on erc7710 it is `txHash` itself and Haven VERIFIED it on-chain
781
+ * before the receipt existed; on eip3009 it is the merchant's claim as relayed
782
+ * (PAYMENT-RESPONSE), NOT verified on-chain by Haven — cite it as such.
783
+ */
784
+ settlementTxHash: string | null;
785
+ chainId: number;
786
+ /** #3134: the paid resource, under the transactions feed's protocol-prefixed name (`string | null` there; a receipt always has one). */
787
+ x402ResourceUrl: string;
788
+ /** @deprecated (#3134) twin of {@link x402ResourceUrl}; removed once all three release clocks have moved — see `mapPaymentReceipt`. */
789
+ resourceUrl: string;
790
+ /** #3134: the merchant paid, under the transactions feed's protocol-prefixed name. */
791
+ x402MerchantAddress: string | null;
792
+ /** @deprecated (#3134) twin of {@link x402MerchantAddress}; removed once all three release clocks have moved — see `mapPaymentReceipt`. */
793
+ merchantAddress: string | null;
794
+ payerAddress: string;
795
+ /** #2960: additive alongside `payerAddress` above (`parties.treasury_account` only). */
796
+ parties?: PaymentParties;
797
+ settlementAddress: string;
798
+ tokenSymbol: string;
799
+ tokenAddress: string;
800
+ amountRaw: string;
801
+ amount: string;
802
+ challengeId: string | null;
803
+ idempotencyKey: string | null;
804
+ challengePayload?: Record<string, unknown> | null;
805
+ selectedPayment?: Record<string, unknown> | null;
806
+ paymentProofHeaderName: string | null;
807
+ protocolReceiptHeaderName: string | null;
808
+ /**
809
+ * #3125 — the merchant's `PAYMENT-RESPONSE` object relayed VERBATIM:
810
+ * opaque, unvalidated, unverified, MERCHANT-CONTROLLED third-party data.
811
+ * Haven neither authors nor verifies anything inside it, including
812
+ * `protocolReceiptPayload.payer` —
813
+ * that `payer` is the merchant's claim, NOT Haven's record, and is not
814
+ * {@link payerAddress} (Haven's own, authoritative; field observation
815
+ * 2026-09-18: the two held different addresses on every row read). For who
816
+ * paid, read `parties` ({@link PaymentParties}) — `treasuryAccount`,
817
+ * `delegate`, `delegateAccount`, `merchant` are Haven-derived and
818
+ * authoritative; anything inside this object is not.
819
+ *
820
+ * Deliberately NOT namespaced or key-prefixed on the wire (#3125): the
821
+ * relay must stay the merchant's object verbatim (its `transaction` key
822
+ * feeds `settlementTxHash`), and prefixing the envelope could not prefix
823
+ * the merchant-controlled keys inside it — the `payer` collision lives
824
+ * there, so provenance is made legible at the read surfaces instead (this
825
+ * comment and the tool descriptions).
826
+ */
827
+ protocolReceiptPayload?: Record<string, unknown> | null;
828
+ merchantStatus: number | null;
829
+ confirmedAt: string | null;
830
+ createdAt: string;
831
+ updatedAt: string;
832
+ }
833
+ /**
834
+ * How long this SDK waits for an on-chain confirmation before it stops
835
+ * waiting (#1756).
836
+ *
837
+ * Lives here rather than in `client.ts` so the payment-confirmation poller
838
+ * and the delegate sweep share ONE number instead of forking it. The SDK's
839
+ * other chain waits are already bounded (`waitForFundingTx` at 30 s), so a
840
+ * fourth independently chosen literal is exactly the drift this constant
841
+ * exists to prevent.
842
+ */
843
+ declare const DEFAULT_CONFIRMATION_TIMEOUT_MS = 90000;
844
+ /**
845
+ * Whether a sweep transfer was observed to confirm (#1756).
846
+ *
847
+ * The distinction is the point: `unconfirmed` means the transfer was
848
+ * BROADCAST and may still land, which is neither success nor failure. It must
849
+ * never be collapsed into either — reporting a still-pending transaction as
850
+ * done, or as failed, are the same defect in opposite directions.
851
+ */
852
+ type SweepConfirmation =
853
+ /** A receipt was observed. The funds are in the agent's Haven account. */
854
+ 'confirmed'
855
+ /**
856
+ * Broadcast, but no receipt within `DEFAULT_CONFIRMATION_TIMEOUT_MS` (or the
857
+ * node returned no receipt). The transaction is still in the mempool and may
858
+ * mine at any time. `txHash` is the broadcast hash — check it on the
859
+ * explorer before re-running the sweep, and expect a re-run to find nothing
860
+ * stranded if it has since landed.
861
+ */
862
+ | 'unconfirmed';
863
+ /** One transferred asset in a delegate sweep. */
864
+ interface SweepEntry {
865
+ /** 'USDC' or 'ETH' */
866
+ asset: string;
867
+ /** Human-readable amount swept (e.g. "0.12") */
868
+ amount: string;
869
+ /** Atomic amount swept */
870
+ amountAtomic: string;
871
+ /**
872
+ * Transaction hash of the sweep transfer.
873
+ *
874
+ * The RECEIPT hash when `confirmation` is `confirmed`; the BROADCAST hash
875
+ * when it is `unconfirmed` — which is the whole reason the sweep returns
876
+ * instead of throwing on a deadline, since this hash is the only thing that
877
+ * lets a user recover the transfer by hand (#1756).
878
+ */
879
+ txHash: string;
880
+ /** Block explorer URL for the tx */
881
+ explorerUrl: string;
882
+ /**
883
+ * Did this transfer confirm on-chain within the deadline? (#1756)
884
+ *
885
+ * `unconfirmed` entries have MOVED NOTHING YET and may still move. Do not
886
+ * report a sweep as complete without checking this on every entry.
887
+ */
888
+ confirmation: SweepConfirmation;
889
+ }
890
+ /** Result of a `sweepDelegate()` call. */
891
+ interface SweepResult {
892
+ /** Address funds were swept FROM */
893
+ fromAddress: string;
894
+ /** Address funds were swept TO (always the agent's Haven account) */
895
+ toAddress: string;
896
+ /** Chain the sweep occurred on */
897
+ chainId: number;
898
+ /** One entry per transferred asset. Empty when nothing was stranded. */
899
+ transfers: SweepEntry[];
900
+ /**
901
+ * True when ANY entry is `unconfirmed` — i.e. the sweep broadcast something
902
+ * it could not confirm within the deadline (#1756).
903
+ *
904
+ * Derived from `transfers`, and present anyway because the consumer most
905
+ * likely to misread this result is an LLM reading the JSON of the
906
+ * `haven_sweep_delegate` tool, which will otherwise see a populated
907
+ * `transfers` array and report the money as recovered.
908
+ */
909
+ unconfirmed: boolean;
910
+ }
911
+ type PaymentStateKind = 'payment_intent' | 'approval_request';
912
+ interface AgentPaymentEnumSchema {
913
+ type: 'string';
914
+ enum: readonly string[];
915
+ description: string;
916
+ 'x-enumDescriptions': Record<string, string>;
917
+ }
918
+ declare const AgentPaymentPhase: {
919
+ /** The agent must sign and submit the prepared payment before Haven can relay it. */
920
+ readonly AgentSignatureRequired: "agent_signature_required";
921
+ /** Haven has received the signed payment and the agent should poll for confirmation. */
922
+ readonly PaymentSubmitted: "payment_submitted";
923
+ /** The direct payment is confirmed; the agent does not need to do more for this payment id. */
924
+ readonly PaymentConfirmed: "payment_confirmed";
925
+ /**
926
+ * #2115: RETIRED wire value — no live rail produces it. It described the
927
+ * Safe rail's approval queue, which no longer exists. Kept so a stored value
928
+ * still typechecks; see `AgentPaymentPhaseDescriptions` below for the
929
+ * agent-visible wording, which this comment used to contradict.
930
+ */
931
+ readonly UserApprovalRequired: "user_approval_required";
932
+ /** #2115: RETIRED wire value — no live rail produces it. Stop and tell the user. */
933
+ readonly UserExecutionRequired: "user_execution_required";
934
+ /** #2115: RETIRED wire value — no live rail produces it. Stop and tell the user. */
935
+ readonly WaitingForAdditionalApprovals: "waiting_for_additional_approvals";
936
+ /** The Haven funding leg was sent; the agent can continue the merchant/protocol leg. */
937
+ readonly FundingSent: "funding_sent";
938
+ /** The payment was rejected and cannot proceed; the agent should stop and tell the user. */
939
+ readonly Rejected: "rejected";
940
+ /** The payment expired before completion. */
941
+ readonly Expired: "expired";
942
+ /** Haven could not complete the payment; the agent should stop and surface the failure. */
943
+ readonly Failed: "failed";
944
+ /**
945
+ * Pre-flight check determined the delegate's existing balance plus the
946
+ * remaining on-chain budget cannot cover the requested amount, so no
947
+ * payment intent was created. The account must be funded or the agent's
948
+ * budget raised before retrying — #2115: the old wording contrasted this
949
+ * with `UserApprovalRequired` as if that were a live alternative, and named
950
+ * the retired rail's Safe and per-token allowance as the fix.
951
+ */
952
+ readonly InsufficientFunds: "insufficient_funds";
953
+ /**
954
+ * Haven's funding leg (account → delegate, the #946 EIP-3009 bridge)
955
+ * confirmed on-chain, but the merchant rejected the x402 retry. The delegate
956
+ * wallet may hold stranded USDC that was never settled to the merchant. The
957
+ * agent should stop, tell the user, and wait for the sweep flow to reclaim
958
+ * the funds.
959
+ */
960
+ readonly FundedButUnsettled: "funded_but_unsettled";
961
+ };
962
+ type AgentPaymentPhase = (typeof AgentPaymentPhase)[keyof typeof AgentPaymentPhase];
963
+ declare const AgentPaymentNextAction: {
964
+ /** Sign with the delegate key and submit the payment to Haven. */
965
+ readonly SignAndSubmitPayment: "sign_and_submit_payment";
966
+ /** Poll getPaymentStatus later using this payment id. */
967
+ readonly CheckStatusLater: "check_status_later";
968
+ /** No further agent action is required for this payment id. */
969
+ readonly None: "none";
970
+ /**
971
+ * #2115: RETIRED wire value — no live rail produces it and nothing maps to
972
+ * it. Stop and tell the user rather than polling; no approval will arrive.
973
+ */
974
+ readonly WaitForUserApproval: "wait_for_user_approval";
975
+ /** #2115: RETIRED wire value — no live rail produces it. Stop and tell the user rather than polling. */
976
+ readonly WaitForUserToCompletePayment: "wait_for_user_to_complete_payment";
977
+ /** Resume this payment id and retry the original x402 request with the merchant payment header. */
978
+ readonly RetryOriginalX402Request: "retry_original_x402_request";
979
+ /** Stop retrying this payment and tell the user what happened. */
980
+ readonly StopAndTellUser: "stop_and_tell_user";
981
+ /** Ask again only if the user still wants the payment after expiry. */
982
+ readonly RequestAgainIfUserStillWantsIt: "request_again_if_user_still_wants_it";
983
+ /** #1307: retry the SAME tool call, supplying the explicit context fields the server could not rehydrate. */
984
+ readonly RetryWithExplicitContext: "retry_with_explicit_context";
985
+ /**
986
+ * The x402 funding/quote window expired. Re-quote the same logical merchant
987
+ * operation with the same idempotency key to stay double-charge-safe.
988
+ */
989
+ readonly PaymentWindowExpired: "payment_window_expired";
990
+ /**
991
+ * Stop and tell the user that the originating account needs to be funded or
992
+ * the agent's per-token allowance needs to be raised before the payment
993
+ * can succeed. A user approval will not fix this state on its own.
994
+ *
995
+ * #2914: the account-vocabulary spelling, and the only one — the
996
+ * pre-#2907 `fund_safe_or_raise_allowance` wire value (and the
997
+ * `AgentPaymentNextActionAccountAlias` seam #2908 added to bridge it) are
998
+ * retired along with the rest of the #2908 compatibility window.
999
+ */
1000
+ readonly FundAccountOrRaiseAllowance: "fund_account_or_raise_allowance";
1001
+ /**
1002
+ * The delegate wallet may hold funds that were sent from the agent's Haven
1003
+ * account but never settled to the merchant. The wallet owner should initiate
1004
+ * a sweep to return those funds to that account.
1005
+ */
1006
+ readonly SweepStrandedFunds: "sweep_stranded_funds";
1007
+ /**
1008
+ * #2970: a `submitted` erc7710 x402 intent whose settlement window has
1009
+ * passed with no on-chain settlement evidence Haven could verify. Distinct
1010
+ * from {@link CheckStatusLater}, which this REPLACES once the window is
1011
+ * past — but it is not futile: Haven's settlement sweep (120s tick) scans
1012
+ * each candidate over its own window plus a 120s clock-skew allowance, so
1013
+ * it can still attribute the settlement for a short while after this value
1014
+ * first appears. Poll {@link CheckStatusLater}'s tool
1015
+ * (`haven_get_payment_status`) once more, roughly two minutes later; if it
1016
+ * still shows no evidence, tell the user the goods were delivered but
1017
+ * Haven holds no verified settlement evidence for this payment. If the
1018
+ * agent holds the merchant's real settlement transaction hash (from
1019
+ * `PAYMENT-RESPONSE`'s `transaction` field, or a prior settle/complete
1020
+ * result's `settlement_tx_hash`), report it with the hosted
1021
+ * `haven_report_settlement_evidence` tool instead of waiting —
1022
+ * `haven_report_x402_outcome` takes no hash and refuses a non-`confirmed`
1023
+ * intent.
1024
+ */
1025
+ readonly AwaitingSettlementEvidence: "awaiting_settlement_evidence";
1026
+ };
1027
+ type AgentPaymentNextAction = (typeof AgentPaymentNextAction)[keyof typeof AgentPaymentNextAction];
1028
+ declare const AgentPaymentFailureCode: {
1029
+ /** A merchant-authoritative x402 price exceeds the caller's pre-funding max_amount cap. */
1030
+ readonly PriceExceedsMax: "PRICE_EXCEEDS_MAX";
1031
+ /** The x402 funding/quote window expired before the signer or hosted settle step could finish. */
1032
+ readonly PaymentWindowExpired: "PAYMENT_WINDOW_EXPIRED";
1033
+ /** The merchant rejected the paid retry. On eip3009 the funding leg had succeeded (sweep);
1034
+ * on erc7710 there is no funding leg — nothing to sweep, follow the message (#2983). */
1035
+ readonly MerchantRejectedAfterFunding: "MERCHANT_REJECTED_AFTER_FUNDING";
1036
+ /** #1300 review: funding is on-chain but the merchant never ANSWERED the
1037
+ * paid retry within the timeout. NOT proof of rejection — the merchant
1038
+ * may still settle late, so the guidance is verify-then-act. On eip3009
1039
+ * the funding leg had succeeded (verify-then-sweep); on erc7710 there is
1040
+ * no funding leg — nothing to sweep, follow the message (#3000). */
1041
+ readonly MerchantUnresponsiveAfterFunding: "MERCHANT_UNRESPONSIVE_AFTER_FUNDING";
1042
+ /**
1043
+ * #1307: the caller omitted merchant_url/tool_name (asking Haven to
1044
+ * rehydrate the stored MCP merchant-call context by payment_id), but no
1045
+ * usable context was stored for this intent — either it was never an
1046
+ * MCP-tool quote, or the stored context is incomplete. The fallback is
1047
+ * mechanical: re-send merchant_url, tool_name, arguments, and
1048
+ * mcp_transport explicitly (the version-skew path).
1049
+ */
1050
+ readonly MerchantCallContextUnavailable: "MERCHANT_CALL_CONTEXT_UNAVAILABLE";
1051
+ /**
1052
+ * #1351: the caller supplied BOTH the atomic `max_amount` and the
1053
+ * human-denominated `max_amount_human` cap for one purchase. Haven refuses
1054
+ * to guess which the user meant — the two differ by a factor of 10^decimals,
1055
+ * so picking wrong is exactly the silent-overspend this cap exists to
1056
+ * prevent. Rejected before any merchant probe, funding intent, or signature.
1057
+ */
1058
+ readonly AmbiguousMaxAmount: "AMBIGUOUS_MAX_AMOUNT";
1059
+ /**
1060
+ * #1351: a human-denominated cap was supplied, but it cannot be converted to
1061
+ * atomic units against THIS quote — either the quote's asset has no known
1062
+ * decimals on its network, or the cap carries more fraction digits than the
1063
+ * asset can represent (truncating it would silently change the user's cap).
1064
+ * The fallback is the exact atomic `max_amount`.
1065
+ */
1066
+ readonly MaxAmountUnconvertible: "MAX_AMOUNT_UNCONVERTIBLE";
1067
+ /**
1068
+ * #2979: the merchant answered a `tools/call` probe with its own
1069
+ * machine-readable "cannot settle right now" refusal (HTTP 503,
1070
+ * `{ error: 'merchant_not_ready', reason_code, ... }`) instead of a 402
1071
+ * challenge — e.g. its settlement wallet is out of gas. No 402 was ever
1072
+ * issued and no payment was created; this is honest and (per
1073
+ * `retry_after_s`, when present) usually transient, unlike a permanent
1074
+ * endpoint miss.
1075
+ */
1076
+ readonly MerchantNotReady: "MERCHANT_NOT_READY";
1077
+ };
1078
+ type AgentPaymentFailureCode = (typeof AgentPaymentFailureCode)[keyof typeof AgentPaymentFailureCode];
1079
+ /**
1080
+ * Stable rail identifier carried on Haven agent payment responses and resume
1081
+ * state.
1082
+ *
1083
+ * Two layers of vocabulary share this enum because both reach the wire:
1084
+ *
1085
+ * - **Categorical rails** identify the rail family and are used as the
1086
+ * `PaymentResumeState` discriminator: `direct`, `x402` (`mpp` remains a
1087
+ * valid categorical VALUE on historical status reads, but #1328 retired
1088
+ * the `MppResumeState` variant that used to carry it — the mpp_demo
1089
+ * client resume flow no longer exists).
1090
+ * - **Granular rails** identify the specific protocol the backend persists
1091
+ * and returns on response bodies: `mpp_demo`, `mpp_crypto`,
1092
+ * `stripe_deposit`, `spt`. `x402` doubles as both categorical and
1093
+ * granular.
1094
+ *
1095
+ * Consumers reading the top-level `rail` field on a payment status response
1096
+ * should treat any `mpp*` value as the MPP family — this still applies to
1097
+ * historical `mpp_demo` rows, which remain readable.
1098
+ */
1099
+ declare const AgentPaymentRail: {
1100
+ /** Standard Haven payment from the user's account, redeemed through the agent's budget delegation. */
1101
+ readonly Direct: "direct";
1102
+ /** x402 HTTP 402 payment flow with a Haven funding leg and merchant retry leg. */
1103
+ readonly X402: "x402";
1104
+ /** Machine Payment Protocol family — categorical value used as a resume-state discriminator. */
1105
+ readonly Mpp: "mpp";
1106
+ /** Haven internal MPP demo rail. Not for production traffic. */
1107
+ readonly MppDemo: "mpp_demo";
1108
+ /** Crypto-settled MPP rail. */
1109
+ readonly MppCrypto: "mpp_crypto";
1110
+ /** Stripe-deposit-backed MPP rail. */
1111
+ readonly StripeDeposit: "stripe_deposit";
1112
+ /** Stripe Payment Token MPP rail. */
1113
+ readonly Spt: "spt";
1114
+ };
1115
+ type AgentPaymentRail = (typeof AgentPaymentRail)[keyof typeof AgentPaymentRail];
1116
+ type PaymentPhase = AgentPaymentPhase;
1117
+ type PaymentNextAction = AgentPaymentNextAction;
1118
+ 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")[];
1119
+ 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")[];
1120
+ 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")[];
1121
+ declare const AGENT_PAYMENT_RAIL_VALUES: ("x402" | "mpp_demo" | "mpp_crypto" | "stripe_deposit" | "spt" | "direct" | "mpp")[];
1122
+ declare const AgentPaymentPhaseDescriptions: Record<AgentPaymentPhase, string>;
1123
+ declare const AgentPaymentNextActionDescriptions: Record<AgentPaymentNextAction, string>;
1124
+ declare const AgentPaymentFailureCodeDescriptions: Record<AgentPaymentFailureCode, string>;
1125
+ /**
1126
+ * #1308: machine-readable warning codes carried in the `warnings` array on
1127
+ * x402 MCP tool responses. Warnings are ADVISORY — they never replace a
1128
+ * refusal, and existing failure codes stay authoritative for errors. The
1129
+ * legacy `cap_warning` string field is kept for compatibility; the structured
1130
+ * entry carries the same message under MISSING_MAX_AMOUNT.
1131
+ */
1132
+ declare const AgentPaymentWarningCode: {
1133
+ /** No max_amount cap was supplied — the live quoted price was accepted as-is. */
1134
+ readonly MissingMaxAmount: "MISSING_MAX_AMOUNT";
1135
+ /** The signing window closes soon; sign promptly or re-quote with the same idempotency key. */
1136
+ readonly QuoteExpiresSoon: "QUOTE_EXPIRES_SOON";
1137
+ /** The merchant URL was resolved via discovery — pass the RESOLVED url forward. */
1138
+ readonly MerchantUrlDiscovered: "MERCHANT_URL_DISCOVERED";
1139
+ /**
1140
+ * #1306: the catalog's last-verified price_atomic differs from the LIVE
1141
+ * merchant quote for a guided catalog purchase. The catalog price is only
1142
+ * ever indicative; the live quote in the same response is authoritative.
1143
+ */
1144
+ readonly CatalogPriceDiffers: "CATALOG_PRICE_DIFFERS";
1145
+ /**
1146
+ * #1306: the rail-aware allowance/budget pre-check could not be read (RPC
1147
+ * failure, etc). `sufficient` is reported as null rather than a fabricated
1148
+ * true/false — the on-chain policy remains the actual gate either way.
1149
+ */
1150
+ readonly AllowanceCheckUnavailable: "ALLOWANCE_CHECK_UNAVAILABLE";
1151
+ /**
1152
+ * #1319: the delegation-rail read itself SUCCEEDED, but the remaining
1153
+ * figure it returned is the #1145 fallback (the full configured budget)
1154
+ * rather than a live ERC20PeriodTransferEnforcer read — `sufficient` is a
1155
+ * real true/false, just computed from an optimistic number. Distinct from
1156
+ * {@link AgentPaymentWarningCode.AllowanceCheckUnavailable}, which fires
1157
+ * when the read failed outright and `sufficient` degrades to null. The
1158
+ * on-chain policy re-checks at redemption either way; this only says the
1159
+ * guidance shown here may be optimistic.
1160
+ */
1161
+ readonly AllowanceReadOptimistic: "ALLOWANCE_READ_OPTIMISTIC";
1162
+ /**
1163
+ * #2991: the quote tools' `expected_settlement_scheme` prediction of what
1164
+ * `haven_prepare_catalog_purchase` / `haven_pay_mcp_tool` will actually
1165
+ * select could not be computed — the agent's execution rail could not be
1166
+ * read from Haven, so `expected_settlement_scheme` is `null` rather than a
1167
+ * guess. `accepted_scheme` (the merchant's offer) is unaffected.
1168
+ */
1169
+ readonly X402SchemeUnknown: "X402_SCHEME_UNKNOWN";
1170
+ /**
1171
+ * #2968: the merchant answered 200 and handed over goods, but Haven holds NO
1172
+ * on-chain evidence that the payment moved. `settled: false` beside this code
1173
+ * is not a failure — it is the absence of proof, and the two must travel
1174
+ * together so an agent can tell "the user has the goods" apart from "the
1175
+ * money moved". Carries the intent's `expires_at`: after that instant the
1176
+ * settlement can no longer land at all.
1177
+ */
1178
+ readonly SettlementUnconfirmed: "SETTLEMENT_UNCONFIRMED";
1179
+ };
1180
+ type AgentPaymentWarningCode = (typeof AgentPaymentWarningCode)[keyof typeof AgentPaymentWarningCode];
1181
+ interface AgentPaymentWarning {
1182
+ code: AgentPaymentWarningCode;
1183
+ message: string;
1184
+ }
1185
+ /**
1186
+ * #1308: the structured next-step contract on x402 MCP tool responses. It
1187
+ * EXTENDS the existing taxonomy — `next_action` values come from
1188
+ * AgentPaymentNextAction, never a parallel vocabulary. `next_arguments`
1189
+ * carries the small, literally-usable arguments; bulky pass-through fields
1190
+ * (payment_required) are named in `reason` and taken from the SAME response.
1191
+ */
1192
+ interface AgentNextStep {
1193
+ /** From `AgentPaymentNextAction`. */
1194
+ next_action: AgentPaymentNextAction;
1195
+ /**
1196
+ * Claude-family namespaced tool name for the next call
1197
+ * (`mcp__<server>__<tool>`), when one exists.
1198
+ *
1199
+ * **Namespaced with the DEFAULT server names**, which is the most the hosted
1200
+ * server can know: local server names are the client's own config and never
1201
+ * reach Haven. Two runtimes are already not the default — Codex names servers
1202
+ * by config key (`haven`, `haven_signer`), and a connector run with
1203
+ * `--name <slug>` wires `haven-<slug>` / `haven-signer-<slug>` (#1694). On
1204
+ * either, this field and `next_tool_server` name a server the client does not
1205
+ * have. Prefer {@link AgentNextStep.next_tool_server_role} plus
1206
+ * {@link AgentNextStep.next_tool_name} whenever your servers are not the
1207
+ * default pair; see #2550.
1208
+ */
1209
+ next_tool?: string;
1210
+ /**
1211
+ * The server half of `next_tool`, unprefixed — `haven` or `haven-signer`.
1212
+ * Carries the same default-name caveat as `next_tool` (#1588, #2550).
1213
+ */
1214
+ next_tool_server?: string;
1215
+ /** The bare tool name, callable on whichever server plays the role below. */
1216
+ next_tool_name?: string;
1217
+ /**
1218
+ * Which of the CLIENT'S OWN servers to call (#2550). Runtime-neutral, and
1219
+ * the field to resolve against when your server names are not the defaults —
1220
+ * it names a role rather than a name the hosted server had to guess.
1221
+ */
1222
+ next_tool_server_role?: 'hosted' | 'signer';
1223
+ /** Small literal arguments for next_tool. Bulky fields are referenced by reason. */
1224
+ next_arguments?: Record<string, unknown>;
1225
+ /**
1226
+ * #3101 (epic #3105, decision 3): present exactly when `next_tool` is
1227
+ * absent — why no tool is named (the payment id is unknown, nothing is left
1228
+ * to do, the arguments could not be built). `next_tool` is never null.
1229
+ */
1230
+ next_tool_omitted_reason?: string;
1231
+ /** False when the agent should stop and involve the user before continuing. */
1232
+ safe_to_continue: boolean;
1233
+ reason: string;
1234
+ }
1235
+ /**
1236
+ * #1349: compact, Haven-generated reporting evidence for a completed x402
1237
+ * merchant purchase. `status`, money fields, merchant endpoint/address, and
1238
+ * funding transaction come from Haven payment state; `product` and
1239
+ * `invoice_id` are optional merchant-supplied display metadata. The raw
1240
+ * merchant result remains separate evidence and MUST NOT be used to infer
1241
+ * settlement status.
1242
+ */
1243
+ interface AgentPurchaseSummary {
1244
+ /** Set only after Haven has completed the funding and merchant-settlement flow. */
1245
+ status: 'settled';
1246
+ product: string | null;
1247
+ amount: string | null;
1248
+ amount_atomic: string | null;
1249
+ asset: string | null;
1250
+ network: string | null;
1251
+ merchant: {
1252
+ address: string | null;
1253
+ resource_url: string | null;
1254
+ };
1255
+ /** Merchant-supplied identifier, or null when the merchant did not supply one. */
1256
+ invoice_id: string | null;
1257
+ funding_tx_hash: string | null;
1258
+ /** Optional merchant receipt reference parsed from PAYMENT-RESPONSE; not Haven settlement proof. */
1259
+ settlement_tx_hash: string | null;
1260
+ /** Same read-only allowance block returned at the top level, or null when unavailable. */
1261
+ allowance: PostPurchaseAllowanceSummary | null;
1262
+ }
1263
+ /** #1308: compact reporting summary — what the agent tells the user. */
1264
+ interface AgentPaymentSummary {
1265
+ payment_id: string;
1266
+ status: string;
1267
+ amount?: string;
1268
+ amount_atomic?: string;
1269
+ token?: string;
1270
+ network?: string;
1271
+ expires_at?: string;
1272
+ product?: string;
1273
+ /**
1274
+ * Default reporting contract for a successful `haven_settle_mcp_tool` call.
1275
+ * The merchant's raw `result` remains available separately as advanced
1276
+ * evidence; do not parse it to determine whether a payment settled.
1277
+ */
1278
+ purchase_summary?: AgentPurchaseSummary;
1279
+ }
1280
+ declare const AgentPaymentRailDescriptions: Record<AgentPaymentRail, string>;
1281
+ declare const AgentPaymentPhaseSchema: AgentPaymentEnumSchema;
1282
+ declare const AgentPaymentNextActionSchema: AgentPaymentEnumSchema;
1283
+ declare const AgentPaymentFailureCodeSchema: AgentPaymentEnumSchema;
1284
+ declare const AgentPaymentRailSchema: AgentPaymentEnumSchema;
1285
+ interface PaymentStatusResult {
1286
+ paymentId: string;
1287
+ kind: PaymentStateKind;
1288
+ rail: string;
1289
+ status: PaymentStatus | string;
1290
+ phase: PaymentPhase;
1291
+ nextAction: PaymentNextAction;
1292
+ amount: string;
1293
+ token: string;
1294
+ resourceUrl: string | null;
1295
+ merchantAddress: string | null;
1296
+ /** Delegate EOA captured on the payment intent when it was created. */
1297
+ payerAddress?: string | null;
1298
+ /** #2960: additive alongside `payerAddress` above (`parties.delegate` only). */
1299
+ parties?: PaymentParties;
1300
+ txHash: string | null;
1301
+ expiresAt: string;
1302
+ chainId: number;
1303
+ message: string;
1304
+ /** Platform fee surfaced so it's never silently collected (#386). */
1305
+ fee?: PaymentFee | null;
1306
+ amountAtomic?: string | null;
1307
+ asset?: string | null;
1308
+ network?: string | null;
1309
+ description?: string | null;
1310
+ idempotencyKey?: string | null;
1311
+ x402?: {
1312
+ amountAtomic: string | null;
1313
+ asset: string | null;
1314
+ network: string | null;
1315
+ resourceUrl: string | null;
1316
+ merchantAddress: string | null;
1317
+ description: string | null;
1318
+ idempotencyKey: string | null;
1319
+ };
1320
+ mpp?: {
1321
+ amountAtomic: string | null;
1322
+ asset: string | null;
1323
+ network: string | null;
1324
+ resourceUrl: string | null;
1325
+ merchantAddress: string | null;
1326
+ description: string | null;
1327
+ idempotencyKey: string | null;
1328
+ challengeId: string | null;
1329
+ };
1330
+ }
1331
+ /**
1332
+ * Result of an erc7710 direct settlement (#1454).
1333
+ *
1334
+ * Deliberately NOT an `X402Receipt`. A 3009 receipt describes a completed
1335
+ * two-leg payment — funding tx included — whereas here nothing has settled yet
1336
+ * when this returns: the merchant redeems the delegation chain when the caller
1337
+ * retries with the header. Reusing the receipt type would let a caller read
1338
+ * `txHash` as "paid" on a payment that has not moved a cent.
1339
+ */
1340
+ interface X402Erc7710Settlement {
1341
+ paymentId: string;
1342
+ /**
1343
+ * Pass verbatim as the `PAYMENT-SIGNATURE` header on the merchant retry —
1344
+ * that name ALONE. erc7710 is always x402 v2, and this header carries the
1345
+ * delegation chain, so also sending the legacy `X-PAYMENT` overflows the
1346
+ * merchant's header limit (HTTP 431, #2341).
1347
+ */
1348
+ paymentHeader: string;
1349
+ /** The merchant address the child delegation is pinned to. */
1350
+ merchantPayTo: string;
1351
+ amountAtomic: string;
1352
+ asset: string;
1353
+ network: string;
1354
+ /** Facilitators the child is redeemable by, when the merchant advertised any. */
1355
+ facilitatorAddresses: string[] | null;
1356
+ }
1357
+ /** @internal */
1358
+ /** One payable service in Haven's merchant catalog (epic #1717). */
1359
+ interface HavenCatalogEntry {
1360
+ id: string;
1361
+ name: string;
1362
+ description: string;
1363
+ category: string;
1364
+ resourceUrl: string;
1365
+ rail: 'x402' | 'mpp';
1366
+ protocol: 'http' | 'mcp';
1367
+ toolName: string | null;
1368
+ toolArguments: Record<string, unknown> | null;
1369
+ priceDisplay: string | null;
1370
+ priceAtomic: string | null;
1371
+ asset: string | null;
1372
+ network: string | null;
1373
+ status: 'active' | 'degraded' | 'delisted';
1374
+ verifiedAt: string | null;
1375
+ /**
1376
+ * Where the entry came from. `operator` = curated in migrations/scripts
1377
+ * (the operator vouches for the listing; the catalog refresh probe still
1378
+ * checks the endpoint, see `verifiedPayable`). `ingestion` = submitted
1379
+ * through the Verified Payable Directory and passed domain-ownership proof
1380
+ * plus the read-only quote probe.
1381
+ */
1382
+ source: 'operator' | 'ingestion';
1383
+ /** True only for `ingestion` entries — the one ownership claim. See the epic's trust claim (never merchant honesty or quality). */
1384
+ domainVerified: boolean;
1385
+ /**
1386
+ * True when Haven watched this endpoint answer a live quote (#2978): the
1387
+ * directory probe for `ingestion` rows, the periodic catalog refresh probe
1388
+ * for `operator` rows (`status === 'active'` with `verifiedAt` set). False
1389
+ * for a degraded row of either source. `discoverTools({ verified:
1390
+ * 'verified' })` filters on this field, not on `source`.
1391
+ */
1392
+ verifiedPayable: boolean;
1393
+ /**
1394
+ * The merchant this entry belongs to (#3078). OPTIONAL on purpose: an
1395
+ * installed SDK may face a backend that predates the merchant layer, and
1396
+ * `discoverTools` must keep working against it — the field is absent, not
1397
+ * null, in that case.
1398
+ */
1399
+ merchant?: HavenCatalogMerchant;
1400
+ }
1401
+ /** A catalog entry's merchant as the wire carries it (#3078). */
1402
+ interface HavenCatalogMerchant {
1403
+ id: string;
1404
+ slug: string;
1405
+ name: string;
1406
+ /** `coming_soon` never reaches an entry in practice (a prospect has no offers). */
1407
+ listingStatus: 'live' | 'coming_soon';
1408
+ /** Haven-run test content: the demo store and the stranded-funds fixture. */
1409
+ isTestMerchant: boolean;
1410
+ }
1411
+ /**
1412
+ * #3128: one page of receipts. `total` is the count Haven holds for the
1413
+ * agent (an empty page with `total: 0` means no receipt exists — there is no
1414
+ * indexing delay behind this list); `hasMore` says the page was cut at the
1415
+ * limit; `nextCursor` is fed back as `cursor` for the next page. Against a
1416
+ * backend older than #3128 the three are `null` — "unknown", never a
1417
+ * fabricated 0 / false.
1418
+ */
1419
+ interface HavenPaymentReceiptsPage {
1420
+ receipts: HavenPaymentReceipt[];
1421
+ total: number | null;
1422
+ hasMore: boolean | null;
1423
+ nextCursor: string | null;
1424
+ }
1425
+ /** @internal */
1426
+ /** Wire shape of POST /catalog/submit (#1717, #1716). */
1427
+ interface CatalogSubmissionAccepted {
1428
+ id: string;
1429
+ verify_token: string;
1430
+ status: 'submitted' | 'ownership_verified' | 'verified_payable';
1431
+ }
1432
+ /** @internal Client-facing submission handle. */
1433
+ interface HavenCatalogSubmission {
1434
+ id: string;
1435
+ verifyToken: string;
1436
+ status: 'submitted' | 'ownership_verified' | 'verified_payable';
1437
+ }
1438
+ declare class HavenError extends Error {
1439
+ readonly code: string;
1440
+ readonly statusCode?: number | undefined;
1441
+ readonly paymentId?: string | undefined;
1442
+ constructor(message: string, code: string, statusCode?: number | undefined, paymentId?: string | undefined);
1443
+ }
1444
+ declare class HavenApiError extends HavenError {
1445
+ readonly body?: unknown | undefined;
1446
+ constructor(message: string, statusCode: number, body?: unknown | undefined, paymentId?: string);
1447
+ }
1448
+ /**
1449
+ * #1300: quoteX402 hit a URL that answered something other than 402 — the
1450
+ * typed form of "this is not the x402 endpoint". Exists so consumers (the
1451
+ * hosted MCP's #1271 discovery trigger) can key on a class instead of
1452
+ * message text.
1453
+ */
1454
+ /**
1455
+ * #1300: a merchant-facing fetch hit the client-side merchantTimeout. Typed
1456
+ * so consumers can distinguish "merchant never answered" from a real HTTP
1457
+ * error response — the funded-retry path routes this to verify-then-sweep
1458
+ * guidance instead of a bare 504.
1459
+ */
1460
+ declare class MerchantTimeoutError extends HavenApiError {
1461
+ readonly merchantErrorCode: "merchant_timeout";
1462
+ constructor(message: string);
1463
+ }
1464
+ declare class X402UnexpectedStatusError extends HavenApiError {
1465
+ readonly x402ErrorCode: "unexpected_non_402_status";
1466
+ /**
1467
+ * #2979: `body` is the merchant's own JSON, when the non-402 response
1468
+ * carried one — e.g. the demo merchant's `/mcp` readiness gate answers
1469
+ * `503 { error: 'merchant_not_ready', reason_code, ... }`. Optional and
1470
+ * best-effort: a non-JSON or unreadable body leaves this `undefined`, same
1471
+ * as before this field existed. Consumers key on it (not on the message
1472
+ * string) to distinguish an honest, machine-readable merchant refusal from
1473
+ * a genuine "this is not the x402 endpoint" miss, which otherwise look
1474
+ * identical — both are just "some non-402 status".
1475
+ */
1476
+ constructor(message: string, statusCode: number, body?: unknown);
1477
+ }
1478
+ /**
1479
+ * #1521: the idempotency key resolved to a payment that has already settled,
1480
+ * and the delegate can no longer fund a fresh authorization for it.
1481
+ *
1482
+ * This is the typed form of "you already bought this". It exists because the
1483
+ * alternative was indefensible: the SDK used to mint a new EIP-3009
1484
+ * authorization against the spent delegate and hand it back paired with the
1485
+ * ORIGINAL payment's `txHash`, so the caller learned what had happened only
1486
+ * from a merchant-side balance error that reads identically to a broken
1487
+ * payment rail.
1488
+ *
1489
+ * `receipt` is the ORIGINAL payment — a real receipt for real settled funds,
1490
+ * deliberately carrying no `paymentHeader`, because any header minted here
1491
+ * would be exactly the unfundable artifact this error replaces.
1492
+ */
1493
+ declare class X402AlreadySettledError extends HavenApiError {
1494
+ readonly receipt: X402Receipt;
1495
+ /**
1496
+ * `settled` — the delegate was checked on-chain and cannot fund a fresh
1497
+ * authorization, so this payment demonstrably completed.
1498
+ * `unverifiable` — no `chainRpcs` entry for the chain, so fundability
1499
+ * could not be established either way. Same refusal, weaker claim; say
1500
+ * which, rather than assert what was not checked.
1501
+ */
1502
+ readonly basis: 'settled' | 'unverifiable';
1503
+ readonly x402ErrorCode: "already_settled";
1504
+ constructor(message: string, receipt: X402Receipt,
1505
+ /**
1506
+ * `settled` — the delegate was checked on-chain and cannot fund a fresh
1507
+ * authorization, so this payment demonstrably completed.
1508
+ * `unverifiable` — no `chainRpcs` entry for the chain, so fundability
1509
+ * could not be established either way. Same refusal, weaker claim; say
1510
+ * which, rather than assert what was not checked.
1511
+ */
1512
+ basis: 'settled' | 'unverifiable');
1513
+ }
1514
+ declare class HavenPaymentStateError extends HavenApiError {
1515
+ readonly state: PaymentStatusResult;
1516
+ resumeState?: X402ResumeState;
1517
+ constructor(message: string, statusCode: number, state: PaymentStatusResult, body?: unknown);
1518
+ get status(): string;
1519
+ get phase(): PaymentPhase;
1520
+ get nextAction(): PaymentNextAction;
1521
+ }
1522
+ declare class HavenSigningError extends HavenError {
1523
+ constructor(message: string);
1524
+ }
1525
+ /**
1526
+ * #2972: `MerchantCompletion.reportSettlementEvidence` /
1527
+ * `HavenClient.reportSettlementEvidence` refuse a `0x00…00` settlement hash
1528
+ * BEFORE any network call — see `isZeroSettlementTxHash`. That marker is
1529
+ * never a real transaction (the demo merchant's own "delivered, not settled"
1530
+ * value), so posting it to `POST /machine-payments/evidence` could only ever
1531
+ * come back refused, at the cost of a real round trip. A typed error rather
1532
+ * than a `HavenApiError`-shaped 400: no request was ever attempted, so there
1533
+ * is no HTTP status or response body to carry.
1534
+ */
1535
+ declare class HavenZeroSettlementHashError extends HavenError {
1536
+ constructor(paymentId: string);
1537
+ }
1538
+ /**
1539
+ * Refusal codes the local signer returns when it does not recognise the
1540
+ * VERSION of a Haven-signed binding it was asked to sign (#1309). Distinct
1541
+ * from `AgentPaymentFailureCode`: these describe a **signer capability**
1542
+ * problem (this install cannot evaluate what Haven sent), not a payment-domain
1543
+ * outcome, and they never reach the backend's REST/OpenAPI surface — only the
1544
+ * local signer's own MCP tool responses (`haven_sign` / `haven_sign_x402` /
1545
+ * `haven_sign_sweep_delegate`). That is also why this pair does not go through
1546
+ * the `AgentPaymentFailureCode` four-gate (sdk → backend mirror → spec →
1547
+ * api-types): there is no backend mirror to keep in sync with.
1548
+ */
1549
+ declare const SignerRefusalCode: {
1550
+ /** `SUPPORTED_X402_EXPECTED_VERSIONS` in `@haven_ai/signer` does not include the received version. */
1551
+ readonly UnsupportedExpectedContextVersion: "UNSUPPORTED_EXPECTED_CONTEXT_VERSION";
1552
+ /** `SUPPORTED_SWEEP_BINDING_VERSIONS` in `@haven_ai/signer` does not include the received version. */
1553
+ readonly UnsupportedSweepBindingVersion: "UNSUPPORTED_SWEEP_BINDING_VERSION";
1554
+ };
1555
+ type SignerRefusalCode = (typeof SignerRefusalCode)[keyof typeof SignerRefusalCode];
1556
+ /**
1557
+ * Canonical recovery guidance for a stale local signer (#1309) — the ONE
1558
+ * string both the signer's structured refusal (`fallback` field, carried by
1559
+ * `HavenUnsupportedSignerVersionError`) and the hosted quote's advisory
1560
+ * `signer_compatibility.fallback` (#1155) render, so an agent that meets
1561
+ * either surface is told the identical fix. A second hand-maintained copy of
1562
+ * this sentence is exactly how the two surfaces could start disagreeing about
1563
+ * what to do.
1564
+ */
1565
+ declare function signerUpdateFallback(channel?: string): string;
1566
+ /**
1567
+ * The same sentence rendered for THIS build's channel (#2423). Every existing
1568
+ * consumer keeps importing this constant and keeps getting a string; the only
1569
+ * thing that moved is that `alpha` is no longer typed into it.
1570
+ *
1571
+ * The hosted MCP server is the one caller that does NOT use this constant: it
1572
+ * is deployed rather than published, so it renders `signerUpdateFallback()`
1573
+ * with the channel its own environment names.
1574
+ */
1575
+ declare const SIGNER_UPDATE_FALLBACK: string;
1576
+ /**
1577
+ * Thrown by the local signer when a Haven-signed binding (x402 expected
1578
+ * context or sweep authorization) carries a version outside what this signer
1579
+ * install enforces (#1143, structured as #1309). Machine-readable: `code`,
1580
+ * `supportedVersions`, and `receivedVersion` are DERIVED from the signer's own
1581
+ * `SUPPORTED_X402_EXPECTED_VERSIONS` / `SUPPORTED_SWEEP_BINDING_VERSIONS`
1582
+ * constants at the throw site, never a second literal — see
1583
+ * `assertSupportedBindingVersion` in `@haven_ai/signer`.
1584
+ *
1585
+ * This narrows HOW the refusal is reported. It does not weaken it: nothing is
1586
+ * signed either way, and the version stays inside the Haven-signed binding
1587
+ * message (callers must not "fix" a mismatch by rewriting it).
1588
+ */
1589
+ declare class HavenUnsupportedSignerVersionError extends HavenError {
1590
+ readonly supportedVersions: readonly number[];
1591
+ readonly receivedVersion: number;
1592
+ readonly fallback: string;
1593
+ constructor(message: string, code: SignerRefusalCode, supportedVersions: readonly number[], receivedVersion: number, fallback: string);
1594
+ }
1595
+ declare class HavenTimeoutError extends HavenError {
1596
+ constructor(paymentId: string);
1597
+ }
1598
+
1599
+ /**
1600
+ * Gasless delegate-sweep primitives — the single source of truth shared by the
1601
+ * edge signer (which signs) and the Haven backend (which relays).
1602
+ *
1603
+ * A stranded delegate EOA holds USDC but no ETH, so a raw ERC-20 transfer can't
1604
+ * pay for its own gas. Instead the delegate signs an *off-chain* EIP-3009
1605
+ * `TransferWithAuthorization` and the Haven relayer submits it on-chain and pays
1606
+ * gas. The relayer is only a gas payer: it holds no allowance and is never a
1607
+ * spender, so a relayer compromise cannot move user funds.
1608
+ *
1609
+ * Framework-neutral on purpose: `buildSweepTypedData` returns a plain
1610
+ * `{ domain, types, primaryType, message }` that both viem
1611
+ * (`signTypedData`/`recoverTypedDataAddress`) and ethers v6
1612
+ * (`signTypedData`/`verifyTypedData`) accept, so the signer (viem) and backend
1613
+ * (ethers) stay in lockstep without sharing a crypto library.
1614
+ */
1615
+ /** Base mainnet. The only chain Haven sweeps today. */
1616
+ declare const SWEEP_BASE_CHAIN_ID = 8453;
1617
+ /** Base Sepolia testnet — used by the dev environment / QA harness. */
1618
+ declare const SWEEP_BASE_SEPOLIA_CHAIN_ID = 84532;
1619
+ /** Canonical Circle USDC on Base (FiatTokenV2_2). */
1620
+ declare const SWEEP_BASE_USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
1621
+ /** Circle's canonical Base Sepolia testnet USDC. */
1622
+ declare const SWEEP_BASE_SEPOLIA_USDC_ADDRESS = "0x036CbD53842c5426634e7929541eC2318f3dCF7e";
1623
+ /** True when the gasless sweep supports a chain (its USDC domain + address are known). */
1624
+ declare function isSweepableChain(chainId: number): boolean;
1625
+ /** EIP-712 `TransferWithAuthorization` struct, per EIP-3009. */
1626
+ declare const TRANSFER_WITH_AUTHORIZATION_TYPES: {
1627
+ readonly TransferWithAuthorization: readonly [{
1628
+ readonly name: "from";
1629
+ readonly type: "address";
1630
+ }, {
1631
+ readonly name: "to";
1632
+ readonly type: "address";
1633
+ }, {
1634
+ readonly name: "value";
1635
+ readonly type: "uint256";
1636
+ }, {
1637
+ readonly name: "validAfter";
1638
+ readonly type: "uint256";
1639
+ }, {
1640
+ readonly name: "validBefore";
1641
+ readonly type: "uint256";
1642
+ }, {
1643
+ readonly name: "nonce";
1644
+ readonly type: "bytes32";
1645
+ }];
1646
+ };
1647
+ interface SweepEip712Domain {
1648
+ name: string;
1649
+ version: string;
1650
+ chainId: number;
1651
+ verifyingContract: string;
1652
+ }
1653
+ /**
1654
+ * A fully-specified EIP-3009 authorization. All amounts/times are decimal
1655
+ * strings (JSON-safe) and `nonce` is a 0x-prefixed 32-byte hex value. `token`
1656
+ * and `chainId` are carried explicitly so the signer can assert they are
1657
+ * canonical before signing.
1658
+ */
1659
+ interface SweepAuthorization {
1660
+ /** Delegate EOA the funds are swept FROM. */
1661
+ from: string;
1662
+ /** The agent's Haven account the funds are swept TO. */
1663
+ to: string;
1664
+ /** Atomic USDC amount (decimal string). */
1665
+ value: string;
1666
+ /** Unix seconds the authorization becomes valid (decimal string, usually "0"). */
1667
+ validAfter: string;
1668
+ /** Unix seconds the authorization expires (decimal string). */
1669
+ validBefore: string;
1670
+ /** Random 0x-prefixed 32-byte hex nonce. */
1671
+ nonce: string;
1672
+ /** USDC contract address. */
1673
+ token: string;
1674
+ /** Chain id (8453 today). */
1675
+ chainId: number;
1676
+ }
1677
+ /**
1678
+ * Haven's signature over the sweep authorization context, signed with the same
1679
+ * binding key the x402 expected-context uses. Lets the edge signer verify the
1680
+ * authorization actually came from Haven (and wasn't crafted by a compromised
1681
+ * hosted server pointing `to` at an attacker) before it signs.
1682
+ */
1683
+ interface SweepExpectedAuth {
1684
+ /**
1685
+ * Currently always 1. Typed as `number` for the same reason as
1686
+ * `X402ExpectedAuth.version` (#1143): it is inbound, so a stale signer must be
1687
+ * able to *receive* an unknown version in order to report it. The signer's
1688
+ * `SUPPORTED_SWEEP_BINDING_VERSIONS` is the authority on what it will sign.
1689
+ */
1690
+ version: number;
1691
+ message: string;
1692
+ signature: string;
1693
+ signer: string;
1694
+ }
1695
+ /** What `POST /machine-payments/sweep/prepare` returns when funds are stranded. */
1696
+ interface SweepPreparation {
1697
+ authorization: SweepAuthorization;
1698
+ expectedAuth: SweepExpectedAuth;
1699
+ }
1700
+ /** Wire response from `POST /machine-payments/sweep/prepare` (snake_case). */
1701
+ interface SweepPrepareResponse {
1702
+ /** Present and true when the delegate holds nothing to recover. */
1703
+ nothing_stranded?: boolean;
1704
+ /**
1705
+ * Present and true when the stranded balance is below the sweep floor (#700):
1706
+ * it is left on the delegate as dust rather than recovered, because the gas to
1707
+ * sweep it would exceed its value. `min_usdc` carries the configured floor. No
1708
+ * `authorization` is built.
1709
+ */
1710
+ below_min?: boolean;
1711
+ min_usdc?: string;
1712
+ /** The authorization to sign — absent when nothing is stranded or below the floor. */
1713
+ authorization?: SweepAuthorization;
1714
+ /** Haven's binding over the authorization — absent when nothing is stranded. */
1715
+ expected_auth?: SweepExpectedAuth;
1716
+ asset?: string;
1717
+ amount?: string;
1718
+ amount_atomic?: string;
1719
+ chain_id: number;
1720
+ sign_instructions?: string;
1721
+ message?: string;
1722
+ }
1723
+ /** Wire response from `POST /machine-payments/sweep/submit` (snake_case). */
1724
+ interface SweepSubmitResponse {
1725
+ tx_hash: string;
1726
+ asset: string;
1727
+ amount: string;
1728
+ amount_atomic: string;
1729
+ from_address: string;
1730
+ to_address: string;
1731
+ chain_id: number;
1732
+ explorer_url: string;
1733
+ idempotent_replay?: boolean;
1734
+ }
1735
+ /** Result of a submitted gasless sweep. */
1736
+ interface SweepSubmitResult {
1737
+ txHash: string;
1738
+ amount: string;
1739
+ amountAtomic: string;
1740
+ asset: string;
1741
+ fromAddress: string;
1742
+ toAddress: string;
1743
+ chainId: number;
1744
+ explorerUrl: string;
1745
+ }
1746
+ interface SweepTypedData {
1747
+ domain: SweepEip712Domain;
1748
+ types: typeof TRANSFER_WITH_AUTHORIZATION_TYPES;
1749
+ primaryType: 'TransferWithAuthorization';
1750
+ message: {
1751
+ from: string;
1752
+ to: string;
1753
+ value: bigint;
1754
+ validAfter: bigint;
1755
+ validBefore: bigint;
1756
+ nonce: string;
1757
+ };
1758
+ }
1759
+ /** Resolve the canonical USDC contract for a sweepable chain, or throw. */
1760
+ declare function sweepUsdcAddress(chainId: number): string;
1761
+ /** Resolve the USDC EIP-712 domain for a sweepable chain, or throw. */
1762
+ declare function sweepUsdcDomain(chainId: number): SweepEip712Domain;
1763
+ /**
1764
+ * Build the EIP-712 typed data for an authorization, validating that the token
1765
+ * and chain are canonical (the domain's `verifyingContract` must match the
1766
+ * authorization's `token`). Returns bigint-valued fields so both viem and
1767
+ * ethers v6 sign/recover identically.
1768
+ */
1769
+ declare function buildSweepTypedData(auth: SweepAuthorization): SweepTypedData;
1770
+ /**
1771
+ * Canonical, deterministic string the backend signs and the signer re-derives
1772
+ * for the authorization binding. The `Haven sweep authorization v1` namespace
1773
+ * (and `kind`) is distinct from the x402 expected-context namespace so an x402
1774
+ * binding can never be replayed as a sweep authorization even though they share
1775
+ * a signing key.
1776
+ */
1777
+ declare function buildSweepAuthorizationMessage(auth: SweepAuthorization): string;
1778
+
1779
+ /**
1780
+ * Client identity on Haven API requests (#3303, epic #3302).
1781
+ *
1782
+ * Every published Haven client names itself with one header,
1783
+ * `X-Haven-Client: <package>/<version>`, so the backend can tell an outdated
1784
+ * client what to run — a `client_update` hint on its responses, or, only below
1785
+ * a minimum the deployment has explicitly set, a 426 `client_outdated` refusal
1786
+ * at the payment-initiating routes (the signer: at sign-context). The backend's
1787
+ * table and decision live in `@haven_ai/core`'s `client-compat.ts`; this module
1788
+ * is the client half and deliberately holds no thresholds.
1789
+ *
1790
+ * Deliberately free of any other SDK import so `@haven_ai/sdk/edge` (the
1791
+ * signer's ethers-free entry) can re-export it.
1792
+ */
1793
+ /**
1794
+ * This SDK's own version. Owned by `scripts/release-bump.mjs`, which rewrites
1795
+ * it with the package version on every release — never hand-edit it.
1796
+ */
1797
+ declare const SDK_VERSION = "0.5.0-alpha.1";
1798
+ /** The request header every published Haven client sends. */
1799
+ declare const HAVEN_CLIENT_HEADER = "X-Haven-Client";
1800
+ /** `<package>/<version>` — the value of {@link HAVEN_CLIENT_HEADER}. */
1801
+ declare function havenClientIdentity(pkg: string, version: string): string;
1802
+ /** What a bare SDK embedder sends when it names no package of its own. */
1803
+ declare const SDK_CLIENT_IDENTITY: string;
1804
+ /**
1805
+ * The `client_update` object the backend attaches to a response when this
1806
+ * client is behind (`required: false`) or below a set minimum
1807
+ * (`required: true`). Every field is the backend's; the SDK never computes one.
1808
+ */
1809
+ interface HavenClientUpdate {
1810
+ package: string;
1811
+ current: string;
1812
+ recommended: string | null;
1813
+ min_version: string | null;
1814
+ required: boolean;
1815
+ upgrade_command: string;
1816
+ notes_url: string | null;
1817
+ }
1818
+ /** Narrow an unknown response field to a {@link HavenClientUpdate}, or undefined. */
1819
+ declare function readClientUpdate(value: unknown): HavenClientUpdate | undefined;
1820
+
1821
+ /**
1822
+ * #3101 (epic #3105, slice 2/5): the typed next-step builder.
1823
+ *
1824
+ * Every hosted payment tool ends by naming the agent's next tool and its
1825
+ * arguments (#1308). Until this module, the tool was a free string and the
1826
+ * arguments a `Record<string, unknown>`, so nothing tied the keys to the tool
1827
+ * named beside them — three sites handed `{ payment_id: null }` to a tool
1828
+ * whose `payment_id` is a required string, and the compiler could not see it.
1829
+ *
1830
+ * The builder is generic over a TARGET MAP the caller supplies: bare tool
1831
+ * name → { role, validate }. It is deliberately schema-library-agnostic (the
1832
+ * SDK carries no zod): the hosted server derives each target's argument type
1833
+ * from its own zod shape and passes a `validate` closure; this module only
1834
+ * needs to know the role (to render `mcp__<server>__<tool>`) and how to say
1835
+ * whether arguments parse. Keyed on the bare name + role (decision 1) so the
1836
+ * namespaced string is rendered in exactly one place and the runtime-neutral
1837
+ * `next_tool_server` / `next_tool_name` / `next_tool_server_role` fields are
1838
+ * derived from the same input rather than parsed back out of a literal.
1839
+ *
1840
+ * Decisions 3 and 8: `nextTool` is REQUIRED on the input and may be `null` —
1841
+ * a site that forgets it is a compile error; a site with no next tool says
1842
+ * why, and the wire omits `next_tool` and carries `next_tool_omitted_reason`.
1843
+ * `next_tool` is never null on the wire.
1844
+ */
1845
+ type NextToolServerRole = 'hosted' | 'signer';
1846
+ /** The DEFAULT server name each role is wired under (#1588, #2550). */
1847
+ declare const NEXT_TOOL_SERVER_NAMES: Record<NextToolServerRole, string>;
1848
+ /** Default server name → role. An unknown server yields no role rather than a guess (#2550). */
1849
+ declare const NEXT_TOOL_SERVER_ROLES: Record<string, NextToolServerRole>;
1850
+ /** Renders the Claude-family namespaced tool name — the one string clients have followed since #1308. */
1851
+ declare function renderNextTool(role: NextToolServerRole, name: string): string;
1852
+ /** Parses a namespaced literal back into its parts; `role` is absent for an unknown server. */
1853
+ declare function parseNextTool(literal: string): {
1854
+ server: string;
1855
+ name: string;
1856
+ role?: NextToolServerRole;
1857
+ } | null;
1858
+ /**
1859
+ * One target the builder may hand off to. `TArgs` is the argument type the
1860
+ * caller derived from the tool's declared schema; `validate` is the runtime
1861
+ * twin of that type and returns `null` when the arguments parse, else why not.
1862
+ */
1863
+ interface NextStepTarget<TArgs> {
1864
+ role: NextToolServerRole;
1865
+ validate: (input: unknown) => string | null;
1866
+ /** Phantom carrier for the argument type; never read at runtime. */
1867
+ readonly _args?: TArgs;
1868
+ }
1869
+ type NextStepTargets = Record<string, NextStepTarget<unknown>>;
1870
+ /** The argument type a target carries. */
1871
+ type NextStepArguments<Targets extends NextStepTargets, T extends keyof Targets> = Targets[T] extends NextStepTarget<infer A> ? A : never;
1872
+ /**
1873
+ * The handoff half of a next step: a registered tool with arguments that
1874
+ * tool accepts, or no tool with the reason. A discriminated union over the
1875
+ * target map's keys, so a wrong key, a missing required key, an unregistered
1876
+ * tool name and an omitted `nextTool` are each a compile error at the site.
1877
+ */
1878
+ type NextStepHandoff<Targets extends NextStepTargets> = {
1879
+ [T in keyof Targets & string]: {
1880
+ nextTool: T;
1881
+ nextArguments: NextStepArguments<Targets, T>;
1882
+ };
1883
+ }[keyof Targets & string] | {
1884
+ nextTool: null;
1885
+ nextToolOmittedReason: string;
1886
+ };
1887
+ type NextStepInput<Targets extends NextStepTargets> = NextStepHandoff<Targets> & {
1888
+ nextAction: AgentPaymentNextAction;
1889
+ safeToContinue: boolean;
1890
+ reason: string;
1891
+ };
1892
+ /** The wire shape: `AgentNextStep` (its `next_tool` family) — never a null `next_tool`. */
1893
+ type NextStep = AgentNextStep;
1894
+ /**
1895
+ * Per-`next_action` default tool (decision 9): the tool a site names unless it
1896
+ * has a reason to override. Only actions with ONE sensible target are listed;
1897
+ * `retry_original_x402_request` is absent because its only live emitter names
1898
+ * no tool on purpose (the agent's own HTTP retry); `sign_and_submit_payment`
1899
+ * is absent because the signer tool
1900
+ * depends on the settlement scheme (`haven_sign` for erc7710 delegations,
1901
+ * `haven_sign_x402` for the EIP-3009 bridge) and a wrong default there would be
1902
+ * worse than none.
1903
+ */
1904
+ declare const DEFAULT_NEXT_TOOL_BY_ACTION: {
1905
+ readonly check_status_later: "haven_get_payment_status";
1906
+ readonly sweep_stranded_funds: "haven_sweep_delegate";
1907
+ };
1908
+ declare function defaultNextToolFor(action: AgentPaymentNextAction): string | undefined;
1909
+ /**
1910
+ * Builds a `nextStep` function bound to a target map. The returned function
1911
+ * renders the wire fields from the bare name + role, and re-validates the
1912
+ * arguments at runtime: on a mismatch it FAILS SAFE — omits the tool and says
1913
+ * why in `next_tool_omitted_reason` — rather than throwing out of a handler
1914
+ * that has already moved money. The compile-time twin makes that branch
1915
+ * unreachable from typed sites; it exists for callers that bypass the types.
1916
+ */
1917
+ declare function createNextStepBuilder<Targets extends NextStepTargets>(targets: Targets): (input: NextStepInput<Targets>) => NextStep;
1918
+
1919
+ /**
1920
+ * The npm dist-tag the published Haven packages tell a user to re-run (#2423,
1921
+ * slice 3 of epic #2420).
1922
+ *
1923
+ * ## Why a constant and not a literal
1924
+ *
1925
+ * Roughly a dozen user- and agent-facing strings across `@haven_ai/sdk`,
1926
+ * `@haven_ai/signer`, `@haven_ai/connect` and the hosted MCP server say some
1927
+ * form of "re-run `npx @haven_ai/connect@alpha`". Every one of them was a
1928
+ * hard-coded literal, which is correct only for a build published under the
1929
+ * `alpha` dist-tag. Once `dev`-branch snapshots publish under a `dev` tag
1930
+ * (#2421), a snapshot build telling its tester to re-run `@alpha` would hand
1931
+ * them the production connector — silently replacing the very build they are
1932
+ * testing. So the tag becomes one build-time constant and every hint derives
1933
+ * from it.
1934
+ *
1935
+ * ## Who writes it
1936
+ *
1937
+ * `scripts/release-bump.mjs` rewrites {@link HAVEN_CONNECTOR_CHANNEL} from the
1938
+ * version it is bumping to, using exactly the rule `.github/workflows/publish.yml`
1939
+ * uses to pick the `--tag` for that same version:
1940
+ *
1941
+ * | version | dist-tag / channel |
1942
+ * |---|---|
1943
+ * | `0.1.34-alpha.0` | `alpha` |
1944
+ * | `0.0.0-dev.202609021200.abc1234` | `dev` |
1945
+ * | `0.2.0` | `latest` |
1946
+ *
1947
+ * One rule, two consumers. `scripts/ci/connector-channel-agreement.test.mjs`
1948
+ * executes the workflow's own shell and the bump script's own function over the
1949
+ * same version table and fails if they ever disagree.
1950
+ *
1951
+ * ## Build-time here, run-time there
1952
+ *
1953
+ * A published tarball cannot read a deployment's environment, so for the
1954
+ * published packages the channel is baked in at release time. A surface that is
1955
+ * *deployed* rather than published has no release at which to bake anything in,
1956
+ * so it reads the `HAVEN_CONNECTOR_CHANNEL` environment variable and falls back
1957
+ * to this constant. Two surfaces do that: the hosted MCP server
1958
+ * (`packages/mcp-server/src/connector-channel.ts`) and, since slice 2 (#2422),
1959
+ * the backend's connector handout (`parseConnectorChannel` in
1960
+ * `packages/backend/src/config.ts`). All three readers share one variable name,
1961
+ * one default and one validation pattern, and that agreement is EXECUTED rather
1962
+ * than asserted: `packages/backend/src/__tests__/connector-channel.test.ts`
1963
+ * runs this module's `resolveConnectorChannel` and the backend's
1964
+ * `parseConnectorChannel` over the same input table and fails if they ever
1965
+ * diverge.
1966
+ *
1967
+ * **This says nothing about how any environment is configured.** Setting the
1968
+ * variable anywhere is an operator action (epic #2420, operator step 3); no
1969
+ * code here can observe it and none of this comment asserts it has happened.
1970
+ */
1971
+ /** The published connector package. Never varies; only its tag does. */
1972
+ declare const CONNECTOR_PACKAGE_NAME = "@haven_ai/connect";
1973
+ /**
1974
+ * The npm dist-tag this build's re-run hints name.
1975
+ *
1976
+ * **Do not hand-edit.** `scripts/release-bump.mjs` owns this literal the same
1977
+ * way it owns `CONNECTOR_VERSION` and its siblings, and
1978
+ * `scripts/release-bump.test.mjs` fails if the two drift.
1979
+ */
1980
+ declare const HAVEN_CONNECTOR_CHANNEL = "alpha";
1981
+ /** True when `value` is a well-formed dist-tag. */
1982
+ declare function isConnectorChannel(value: string): boolean;
1983
+ /**
1984
+ * Resolve a channel from a deployment's `HAVEN_CONNECTOR_CHANNEL`.
1985
+ *
1986
+ * - unset, empty or whitespace ⇒ `fallback` (dashboards store a cleared
1987
+ * variable as `""`, and that must land on the production-safe value);
1988
+ * - well-formed ⇒ itself;
1989
+ * - anything else ⇒ **throws**. It does not quietly fall back: a typo such as
1990
+ * `dve` would then land on the production channel, and the environment would
1991
+ * look fixed while reproducing the exact defect this slice removes.
1992
+ *
1993
+ * Well-formed-but-wrong (`dve` again) is *not* caught here and cannot be — it
1994
+ * fails later at `npx`, where the error names the package. Stated rather than
1995
+ * implied.
1996
+ */
1997
+ declare function resolveConnectorChannel(raw: string | undefined | null, fallback?: string): string;
1998
+ /** `@haven_ai/connect@<channel>` — the spec an `npx` invocation names. */
1999
+ declare function connectorSpec(channel?: string): string;
2000
+ /**
2001
+ * The re-run command every hint embeds.
2002
+ *
2003
+ * `connectorRerunCommand()` → `npx @haven_ai/connect@alpha`
2004
+ * `connectorRerunCommand('--doctor')` → `npx @haven_ai/connect@alpha --doctor`
2005
+ *
2006
+ * `args` is appended verbatim so each call site keeps its own flags and its own
2007
+ * surrounding sentence. The wording of those sentences is deliberately NOT
2008
+ * moved here: several are inside signer refusal messages that users and agents
2009
+ * pattern-match on, and this change is meant to move the channel token and
2010
+ * nothing else.
2011
+ */
2012
+ declare function connectorRerunCommand(args?: string, options?: {
2013
+ channel?: string;
2014
+ npxFlags?: string;
2015
+ }): string;
2016
+
2017
+ /**
2018
+ * The Node.js floor Haven's published packages support (#1161).
2019
+ *
2020
+ * ## Why this lives in the SDK
2021
+ *
2022
+ * Three packages need to enforce the same floor — `connect` (at setup),
2023
+ * `signer` and `mcp` (at startup) — and `@haven_ai/sdk` is the only dependency
2024
+ * all three already share. A copy per package is how the floor drifted in the
2025
+ * first place: `engines` said `>=24` everywhere while connect's runtime manifest
2026
+ * enforced `20.0.0`, so a connect run on Node v23 passed the guard, installed
2027
+ * the signer, and signed a real payment. Two numbers for one fact is one number
2028
+ * too many.
2029
+ *
2030
+ * Each consumer still owns its own refusal — the error type, the exit code, the
2031
+ * wording of "what to do next" — because a library must never terminate its
2032
+ * host process. This module only answers *is this version supported* and *what
2033
+ * should we tell the user*.
2034
+ *
2035
+ * ## Why a floor is enforced at all
2036
+ *
2037
+ * `engines` is advisory: npm emits `EBADENGINE` and installs anyway unless the
2038
+ * user happens to have `engine-strict` set. For a normal library that is a
2039
+ * reasonable default. For the **signer** it is not — it holds the delegate key
2040
+ * and produces every payment signature, so a subtle runtime incompatibility
2041
+ * shows up as a wrong or missing signature on a money path. "It seemed to work"
2042
+ * is precisely the evidence that cannot be relied on there.
2043
+ */
2044
+ /**
2045
+ * The minimum supported Node.js version, as `major.minor.patch`.
2046
+ *
2047
+ * MUST equal the `engines.node` floor declared by every published Haven
2048
+ * package. A guard test in each package asserts exactly that against its own
2049
+ * `package.json`, so the two cannot drift again silently.
2050
+ */
2051
+ declare const HAVEN_MINIMUM_NODE_VERSION = "22.0.0";
2052
+ /**
2053
+ * Compare two Node versions. Negative when `left` is older.
2054
+ *
2055
+ * An unparseable version parses to `0.0.0` and therefore compares as older than
2056
+ * any real floor — fail-closed. A version string Haven cannot read is not
2057
+ * evidence of a supported runtime, and treating it as one would reopen exactly
2058
+ * the hole this module closes.
2059
+ */
2060
+ declare function compareNodeVersions(left: string, right: string): number;
2061
+ declare function isSupportedNodeVersion(nodeVersion?: string, minimumNodeVersion?: string): boolean;
2062
+ interface UnsupportedNodeVersionMessageOptions {
2063
+ /**
2064
+ * What is being refused, in the user's terms — "Haven setup", "The Haven
2065
+ * signer". Leads the message so the reader knows what just stopped.
2066
+ */
2067
+ subject: string;
2068
+ nodeVersion?: string;
2069
+ minimumNodeVersion?: string;
2070
+ /** Appended verbatim as the closing line. Used for the re-run instruction. */
2071
+ retryHint?: string;
2072
+ }
2073
+ /**
2074
+ * The refusal text.
2075
+ *
2076
+ * Names the detected version, the required version, and **how to fix it** — the
2077
+ * previous message stopped after the two version numbers, which tells a user
2078
+ * they are stuck without telling them how to get unstuck. The version-manager
2079
+ * lines are the fix for nearly everyone; the closing caveat is there because the
2080
+ * runtime that *spawns* the signer is frequently not the shell that was
2081
+ * upgraded, and a desktop app can keep launching the old Node long after
2082
+ * `node -v` in a terminal says otherwise.
2083
+ */
2084
+ declare function unsupportedNodeVersionMessage(options: UnsupportedNodeVersionMessageOptions): string;
2085
+
2086
+ /**
2087
+ * x402 protocol support for the Haven SDK.
2088
+ *
2089
+ * Provides:
2090
+ * - parsePaymentRequired() — extract payment requirements from a 402 response
2091
+ * - parsePaymentRequiredResponse() — async parser with JSON body fallback
2092
+ * - encodePaymentProof() — encode a receipt as a PAYMENT-SIGNATURE header
2093
+ *
2094
+ * The main authorizeX402() and fetchWithPayment() are methods on HavenClient
2095
+ * (see client.ts) since they need API access and signing.
2096
+ */
2097
+
2098
+ /**
2099
+ * Persisted, agent-scoped facts used to preflight a signed standard x402
2100
+ * payment header. This is an integrity comparison only: it never rebuilds,
2101
+ * modifies, persists, or submits the supplied authorization.
2102
+ */
2103
+ interface X402PaymentHeaderContext {
2104
+ merchantTo: string;
2105
+ amountAtomic: string;
2106
+ asset: string;
2107
+ network: string;
2108
+ resourceUrl: string;
2109
+ payer: string;
2110
+ chainId: number;
2111
+ }
2112
+ /** A deliberately value-free refusal for untrusted payment-header input. */
2113
+ declare class X402PaymentHeaderValidationError extends Error {
2114
+ constructor();
2115
+ }
2116
+ /**
2117
+ * Upper bound on the MERCHANT-requested part of the EIP-3009 authorization
2118
+ * window (#715, epic #713). The x402 library sets
2119
+ * `validBefore = now + maxTimeoutSeconds` straight from the MERCHANT's 402
2120
+ * challenge — without a cap, a malicious or sloppy merchant can request a
2121
+ * year-long window and a leaked signed authorization stays spendable that
2122
+ * whole time. 600 s is generous for any facilitator settle (typical is
2123
+ * 30–60 s). This cap applies only to the signed authorization, never to the
2124
+ * advertised requirements echoed in `accepted`. A merchant requiring more
2125
+ * than the bounded lifetime can still reject at verification; preserving its
2126
+ * offer does not widen Haven's signing policy.
2127
+ */
2128
+ declare const X402_MAX_AUTHORIZATION_WINDOW_SECONDS = 600;
2129
+ /**
2130
+ * Forward margin ADDED on top of the (clamped) merchant timeout when the
2131
+ * authorization is actually signed (#1256). The x402 verify rule requires
2132
+ * `validBefore ≥ now + maxTimeoutSeconds` AT THE FACILITATOR — but the
2133
+ * upstream library computes `validBefore = now + maxTimeoutSeconds` at
2134
+ * SIGNING time, leaving zero forward margin. Haven's flow guarantees elapsed
2135
+ * time between the two (the funding UserOp confirms before the merchant
2136
+ * retry, ~1 min plus latency), so every purchase against a merchant whose
2137
+ * `maxTimeoutSeconds` exceeded that latency failed structurally — measured
2138
+ * live on Base mainnet: Anchor requires 300 s, and 226 s remained at verify.
2139
+ *
2140
+ * 300 s covers funding + retry latency with room to spare. The #715 exposure
2141
+ * ceiling becomes clamped-timeout + margin ≤ 900 s total forward — a
2142
+ * deliberate widening from 600 s, recorded on #1256: an authorization that
2143
+ * cannot pass verify protects no one, and 900 s is still bounded by the same
2144
+ * clamp discipline.
2145
+ */
2146
+ declare const X402_SETTLEMENT_FORWARD_MARGIN_SECONDS = 300;
2147
+ declare function normalizePaymentRequired(value: unknown): X402PaymentRequired | null;
2148
+ /**
2149
+ * The x402 wire header names, in one place (#2289).
2150
+ *
2151
+ * v2 renamed all three; v1's only name was `X-PAYMENT`, used in BOTH
2152
+ * directions. Haven had adopted the v2 names for everything it *reads* and
2153
+ * kept the v1 name for the one thing it *writes*, which is how a strict v2
2154
+ * merchant came to never see a payment header at all.
2155
+ *
2156
+ * The 2026-08-31 owner decision was to send both outbound names on every
2157
+ * retry rather than switch on `x402Version`: a v1 merchant ignores the name it
2158
+ * does not know, a v2 merchant ignores the legacy one, and no version
2159
+ * heuristic has to be right for a payment to land.
2160
+ *
2161
+ * **That is no longer unconditional (#2341).** It held while the cost of a
2162
+ * spare header was zero, and on the EIP-3009 bridge it still is. On erc7710 it
2163
+ * is not: that header carries a whole delegation chain, and duplicating it
2164
+ * overflowed the merchant's header limit — HTTP 431, every erc7710 settlement
2165
+ * refused. `x402PaymentHeaderNamesFor` below is the live rule; read it rather
2166
+ * than this paragraph, which records why the simpler rule was right first.
2167
+ */
2168
+ /** v2 client→server payment payload. The name a strict v2 merchant reads. */
2169
+ declare const X402_PAYMENT_HEADER_NAME = "PAYMENT-SIGNATURE";
2170
+ /** v1 client→server payment payload; still accepted by most v2 merchants. */
2171
+ declare const X402_LEGACY_PAYMENT_HEADER_NAME = "X-PAYMENT";
2172
+ /** v2 server→client payment requirements. */
2173
+ declare const X402_PAYMENT_REQUIRED_HEADER_NAME = "PAYMENT-REQUIRED";
2174
+ /** v2 server→client settlement receipt. */
2175
+ declare const X402_PAYMENT_RESPONSE_HEADER_NAME = "PAYMENT-RESPONSE";
2176
+ /**
2177
+ * Both wire names, v2 first — the value an EIP-3009 retry actually sends.
2178
+ *
2179
+ * **Not the general answer any more (#2341), and not what a recorder should
2180
+ * reach for.** This was the evidence record's `paymentProofHeaderName` while
2181
+ * both names always went on the wire; erc7710 now sends one, so a recorder
2182
+ * still reading this constant would log a legacy header that was never sent —
2183
+ * exactly the drift the previous wording promised it prevented. Use
2184
+ * `x402PaymentHeaderNamesSent(paymentHeader)`. Kept exported because it is a
2185
+ * published surface and removing it would break consumers.
2186
+ */
2187
+ declare const X402_PAYMENT_HEADER_NAMES_SENT = "PAYMENT-SIGNATURE, X-PAYMENT";
2188
+ /**
2189
+ * The x402 v2 payment envelope: `{x402Version, resource?, accepted, payload,
2190
+ * extensions?}` per the spec's PaymentPayload (§5.2.2).
2191
+ *
2192
+ * The `resource` and `extensions` echoes are the #2361 fix, and they are not
2193
+ * optional politeness: the spec makes the extensions echo a MUST ("the client
2194
+ * must include at least the info received"), and CoinGecko's facilitator was
2195
+ * live-bisected rejecting the echo-less envelope with a bare 400 while
2196
+ * accepting the identical signature and `accepted`/`payload` bytes with the
2197
+ * echoes added (#2360, Base mainnet, 2026-09-01). Both objects are echoed
2198
+ * VERBATIM from the merchant's 402 — never reconstructed — and omitted when
2199
+ * the challenge carries none, which keeps the envelope byte-identical to the
2200
+ * pre-#2361 shape for echo-less merchants (Ampersend and Soundside settled
2201
+ * that shape live, so omission is the proven-compatible default).
2202
+ *
2203
+ * The `accepted` wrap itself is #303's shape and predates this helper — see
2204
+ * the #300/#303 history before "fixing" it: scheme/network live INSIDE
2205
+ * `accepted` in v2, never at the top level.
2206
+ */
2207
+ declare function x402V2PaymentEnvelope(paymentRequired: Pick<X402PaymentRequired, 'x402Version' | 'resource' | 'extensions'>, accepted: X402PaymentOption, payload: unknown): Record<string, unknown>;
2208
+ /**
2209
+ * Parse an HTTP 402 response into x402 PaymentRequired data.
2210
+ *
2211
+ * Supports:
2212
+ * - v2: PAYMENT-REQUIRED header (base64 JSON)
2213
+ * - v1 fallback: X-PAYMENT header or response body
2214
+ */
2215
+ declare function parsePaymentRequired(response: Response): X402PaymentRequired;
2216
+ /**
2217
+ * Parse an HTTP 402 response into x402 PaymentRequired data.
2218
+ *
2219
+ * Soundside and other Bazaar-style MCP endpoints return the PaymentRequired
2220
+ * object in the JSON body, while older Haven demos and many x402 examples use
2221
+ * base64 headers. This keeps the synchronous header parser intact and adds the
2222
+ * body fallback needed for those endpoints.
2223
+ */
2224
+ declare function parsePaymentRequiredResponse(response: Response): Promise<X402PaymentRequired>;
2225
+ /**
2226
+ * Select the best payment option from the x402 accepts array.
2227
+ *
2228
+ * Preference order:
2229
+ * 1. Option on a Haven-supported network with a known token
2230
+ * 2. Any option on a Haven-supported network
2231
+ * 3. null — no compatible option
2232
+ */
2233
+ declare function selectPaymentOption(accepts: X402PaymentOption[]): X402PaymentOption | null;
2234
+ /** The `extra.assetTransferMethod` value that marks an erc7710-settleable entry. */
2235
+ declare const ERC7710_ASSET_TRANSFER_METHOD = "erc7710";
2236
+ /**
2237
+ * Read `extra.assetTransferMethod` defensively. `extra` is the merchant's own
2238
+ * object, so it is untrusted shape: anything that is not the exact string is
2239
+ * treated as "not erc7710" rather than coerced.
2240
+ */
2241
+ declare function x402AssetTransferMethod(option: X402PaymentOption): string | null;
2242
+ /** True when the merchant advertises this entry as erc7710-settleable. */
2243
+ declare function isErc7710Option(option: X402PaymentOption): boolean;
2244
+ /**
2245
+ * The facilitator addresses a merchant advertises for an erc7710 entry, for
2246
+ * the #1058 redeemer pin — or `null` when it pins nothing.
2247
+ *
2248
+ * **An EMPTY array is `null`, not `[]`.** The backend rejects an empty
2249
+ * `redeemers` list with a 400 (`routes/x402.ts`), and the QA scenario already
2250
+ * treats empty as absent. Returning `[]` here would hand callers a value that
2251
+ * means "pin to nobody" — which is not a narrower pin, it is an unbuildable
2252
+ * delegation.
2253
+ *
2254
+ * Malformed entries are DROPPED rather than failing the whole option, and that
2255
+ * asymmetry is deliberate. A pin narrowed by a merchant's typo means the
2256
+ * facilitator that actually tries to redeem is not on the list, so redemption
2257
+ * reverts — and erc7710 has no funding leg, so nothing moved and nothing is
2258
+ * stranded. Refusing the option outright would instead deny a payment the
2259
+ * remaining valid facilitators could have settled. Losing the payment is the
2260
+ * worse outcome, precisely because the failure this issue closes (#1453) is the
2261
+ * one where funds move BEFORE the rejection.
2262
+ */
2263
+ declare function x402FacilitatorAddresses(option: X402PaymentOption): string[] | null;
2264
+ /**
2265
+ * Select an option that can be paid with the official x402 EIP-3009 exact
2266
+ * scheme. Haven's older tx-hash proof path can describe more networks; the
2267
+ * merchant-verified path currently needs Base USDC.
2268
+ *
2269
+ * **Skips erc7710-tagged entries (#1453).** It used to return the first
2270
+ * positional match and never look at `extra.assetTransferMethod`, so a merchant
2271
+ * that listed its erc7710 entry first made a Haven client echo that option
2272
+ * while signing a standard EIP-3009 authorization. The merchant rejects the
2273
+ * mismatch cleanly — but on the two-leg bridge the account→delegate funding
2274
+ * transfer has already executed, so the visible result is a stranded delegate
2275
+ * balance for the sweep to reclaim. Only our own demo merchant's ordering was
2276
+ * holding that shut, and that pin binds our merchant, not the ones we do not
2277
+ * control.
2278
+ */
2279
+ declare function selectStandardPaymentOption(accepts: X402PaymentOption[]): X402PaymentOption | null;
2280
+ /**
2281
+ * Select the erc7710-settleable option, if the merchant advertises one.
2282
+ */
2283
+ declare function selectErc7710PaymentOption(accepts: X402PaymentOption[]): X402PaymentOption | null;
2284
+ /** What a settlement-scheme decision resolved to. */
2285
+ interface X402SchemeSelection {
2286
+ scheme: 'erc7710' | 'eip3009';
2287
+ option: X402PaymentOption;
2288
+ /** Redeemer pin for the settlement child; only ever set on erc7710. */
2289
+ facilitatorAddresses: string[] | null;
2290
+ }
2291
+ /**
2292
+ * THE preference rule, in one place (#1450 owner decision, #1453).
2293
+ *
2294
+ * Prefer erc7710 whenever the account is on the delegation rail and the
2295
+ * merchant advertises `extra.assetTransferMethod: "erc7710"`; fall back to
2296
+ * the EIP-3009 bridge otherwise.
2297
+ *
2298
+ * Both halves of that condition are required, and the rail half is the
2299
+ * caller's to supply — the SDK cannot see which rail an account is on from a
2300
+ * 402 response alone. A legacy AllowanceModule account passing
2301
+ * `delegationRail: true` would select a scheme its account cannot settle; the
2302
+ * backend refuses that at authorize with the #1986 retired-rail 410 (#2245 —
2303
+ * previously a scheme-specific 400 that wrongly implied the legacy rail could
2304
+ * still settle via EIP-3009), which is where a rail mismatch SHOULD fail,
2305
+ * on-chain-adjacent rather than in a client that could be lying to itself.
2306
+ *
2307
+ * Returns `null` when neither scheme has a payable entry — the caller decides
2308
+ * whether that is an error or a reason to look elsewhere.
2309
+ */
2310
+ declare function selectX402SettlementScheme(accepts: X402PaymentOption[], opts: {
2311
+ delegationRail: boolean;
2312
+ }): X402SchemeSelection | null;
2313
+ declare function x402AuthorizationAmount(option: X402PaymentOption): string;
2314
+ /**
2315
+ * Canonical Haven-authenticated x402 expected context, recomputed byte-for-byte
2316
+ * by the edge signer before it signs anything.
2317
+ *
2318
+ * **Two versions, and the version is derived — never passed in (#1138).**
2319
+ * `typedDataHash` present ⇒ v2, absent ⇒ v1. A v1 message is byte-identical to
2320
+ * what shipped before, so existing signers keep verifying legacy-rail bindings
2321
+ * unchanged.
2322
+ *
2323
+ * The version lives in both the header line and the payload so neither can be
2324
+ * reinterpreted as the other: a v2 context cannot be replayed as a v1 one that
2325
+ * drops the typed-data commitment, and a v1 context cannot be presented as v2.
2326
+ * That downgrade is exactly the attack the digest exists to stop — see
2327
+ * `assertExpectedBinding` in `@haven_ai/signer`, which refuses to raw-sign a
2328
+ * hash under a v2 binding and refuses to sign typed data without one.
2329
+ */
2330
+ declare function buildX402ExpectedMessage(context: X402ExpectedContext): string;
2331
+ declare function toStandardPaymentRequirements(paymentRequired: X402PaymentRequired, option: X402PaymentOption): PaymentRequirements;
2332
+ /**
2333
+ * Strictly validate an edge-signed EIP-3009 X-PAYMENT header against the
2334
+ * persisted x402 intent context before a hosted relay can submit funding.
2335
+ *
2336
+ * The merchant/facilitator remains the final protocol verifier. This closes a
2337
+ * separate hosted-relay integrity gap: malformed or context-mismatched input
2338
+ * must never cause Haven to relay the funding signature first.
2339
+ */
2340
+ declare function validateStandardX402PaymentHeader(paymentHeader: string, context: X402PaymentHeaderContext): Promise<void>;
2341
+ /**
2342
+ * Encode a payment receipt as a base64 PAYMENT-SIGNATURE header value.
2343
+ *
2344
+ * This follows the x402 v2 protocol — the server's facilitator will
2345
+ * verify the on-chain transaction referenced by tx_hash.
2346
+ */
2347
+ declare function encodePaymentProof(receipt: {
2348
+ txHash: string;
2349
+ paymentId: string;
2350
+ token: string;
2351
+ amount: string;
2352
+ to: string;
2353
+ resourceUrl?: string;
2354
+ accepted?: X402PaymentOption;
2355
+ payer?: string;
2356
+ chainId?: number;
2357
+ }): string;
2358
+ /**
2359
+ * Resolve a token symbol from a contract address.
2360
+ *
2361
+ * Checks all supported chains. For chain-specific resolution,
2362
+ * pass the optional `network` CAIP-2 string (e.g. "eip155:100").
2363
+ */
2364
+ declare function resolveTokenFromAddress(address: string, network?: string): {
2365
+ symbol: string;
2366
+ decimals: number;
2367
+ } | null;
2368
+
2369
+ /**
2370
+ * #3271: the integrity check every client runs before signing a direct
2371
+ * delegation-rail payment's typed data.
2372
+ *
2373
+ * A direct payment (`POST /payments`, surfaced as `haven_send` / `haven_pay`)
2374
+ * is signed as the HybridDeleGator's EIP-712 `PackedUserOperation`, and Haven
2375
+ * returns two things for it: that typed data, and `payload_hash` — the
2376
+ * ERC-4337 v0.7 UserOperation hash of the same operation. Nothing used to tie
2377
+ * the two together at signing time. The typed data is multi-KB and reaches the
2378
+ * signer through a language model when it is relayed by hand, so one corrupted
2379
+ * character produced a valid-looking signature over the wrong digest, and the
2380
+ * first sign of it was `AA24 signature error` from the bundler (#3271,
2381
+ * reproduced on dev 2026-09-24).
2382
+ *
2383
+ * This recomputes the v0.7 hash from the typed data's own message and domain
2384
+ * and refuses unless it equals `payload_hash`, and it pins the parts of the
2385
+ * typed data the hash does NOT cover (domain name/version/verifyingContract,
2386
+ * the field list, the EntryPoint). It is a CORRUPTION check: the caller supplies
2387
+ * both values, so it proves they describe the same operation, never that Haven
2388
+ * prepared it. Provenance is the byte-free sign context (`payment_id`); what a
2389
+ * delegate key will sign at all is `assertBoundDirectPaymentUserOp`
2390
+ * (`direct-payment-guard.ts`, #3272 / #3283), which every caller of this check
2391
+ * — `HavenClient.signForData` and the signer's `haven_sign` — runs next.
2392
+ *
2393
+ * Pure viem, no ethers: `@haven_ai/sdk/edge` re-exports it for the edge signer,
2394
+ * and `edge-imports.test.ts` pins that graph.
2395
+ */
2396
+ /** Version of the direct-payment sign context (`GET /payments/:id/sign-context`). */
2397
+ declare const DIRECT_SIGN_CONTEXT_VERSION = 1;
2398
+ /** The ERC-4337 v0.7 EntryPoint — the only one the delegation rail submits to. */
2399
+ declare const ENTRY_POINT_V07 = "0x0000000071727De22E5E9d8BAf0edAc6f37da032";
2400
+ /**
2401
+ * The HybridDeleGator EIP-712 domain constants and the `PackedUserOperation`
2402
+ * field list, vendored from `@metamask/smart-accounts-kit`
2403
+ * (`contracts.HybridDeleGator.constants`, `SIGNABLE_USER_OP_TYPED_DATA`) so the
2404
+ * published packages need no runtime dependency on the kit. Pinned equal to the
2405
+ * kit's values by `userop-binding.test.ts`.
2406
+ */
2407
+ declare const HYBRID_DELEGATOR_DOMAIN_NAME = "HybridDeleGator";
2408
+ declare const HYBRID_DELEGATOR_DOMAIN_VERSION = "1";
2409
+ declare const PACKED_USER_OPERATION_FIELDS: ReadonlyArray<{
2410
+ name: string;
2411
+ type: string;
2412
+ }>;
2413
+ /** Refusal raised when UserOperation typed data (a direct payment, or the SDK's x402 funding leg) does not match its `payload_hash`. */
2414
+ declare class HavenUserOpBindingError extends HavenError {
2415
+ constructor(message: string);
2416
+ }
2417
+ /** True when the typed data is a `PackedUserOperation` (the direct-payment shape). */
2418
+ declare function isPackedUserOperationTypedData(value: unknown): boolean;
2419
+ /**
2420
+ * Compute the ERC-4337 v0.7 UserOperation hash from a HybridDeleGator
2421
+ * `PackedUserOperation` typed-data object — the value Haven returns as
2422
+ * `payload_hash` for a direct payment (`getUserOperationHash`, entryPoint 0.7).
2423
+ */
2424
+ declare function packedUserOperationHash(typedData: unknown): Hex;
2425
+ /**
2426
+ * Refuse (throw `HavenUserOpBindingError`) unless this `PackedUserOperation`
2427
+ * typed data is the operation `payloadHash` names, in the HybridDeleGator
2428
+ * domain of its own sender, against the v0.7 EntryPoint. Returns the
2429
+ * recomputed hash.
2430
+ */
2431
+ declare function assertUserOpTypedDataBinding(typedData: unknown, payloadHash: string): Hex;
2432
+
2433
+ /**
2434
+ * The counterfactual HybridDeleGator account address for an owner EOA (#3272).
2435
+ *
2436
+ * `haven_sign`'s unbound branch (`@haven_ai/signer`'s `tools.ts`) and, since
2437
+ * #3283, `HavenClient.signForData` (`direct-payment-guard.ts`) sign a
2438
+ * `PackedUserOperation`
2439
+ * only when its `sender` (== `domain.verifyingContract`) is THIS SIGNER'S OWN
2440
+ * delegate account — never any other HybridDeleGator, and never a third
2441
+ * party's. Haven provisions that account counterfactually at signup (#970):
2442
+ * it may have zero on-chain transactions, so the signer must be able to
2443
+ * compute its address OFFLINE, from nothing but the delegate key's own
2444
+ * address.
2445
+ *
2446
+ * This is exactly what `@metamask/smart-accounts-kit`'s
2447
+ * `getCounterfactualAccountData` computes for
2448
+ * `implementation: 'Hybrid'`, `deployParams: [owner, [], [], []]` (no passkey
2449
+ * co-owners — the only shape Haven's signup flow provisions), `deploySalt:
2450
+ * '0x'`: CREATE2 of an `ERC1967Proxy(HybridDeleGatorImpl, initialize(owner,
2451
+ * [], [], []))` behind the `SimpleFactory`.
2452
+ *
2453
+ * VENDORED, NOT IMPORTED. `@metamask/smart-accounts-kit` is a devDependency
2454
+ * only (see `package.json`) — this package installs on users' machines and
2455
+ * must not carry it at runtime. The constants below (the factory and
2456
+ * implementation addresses, the `ERC1967Proxy` bytecode) are copied from the
2457
+ * kit's pinned environment / `@metamask/delegation-abis`' bytecode export,
2458
+ * exactly like `settlement-child.ts` vendors the DelegationManager and caveat
2459
+ * enforcer addresses for the same reason. Cross-checked against the kit by
2460
+ * `packages/signer/src/delegate-account.pins.test.ts`, including against the real, on-chain
2461
+ * `direct-payment-userop.json` fixture.
2462
+ */
2463
+
2464
+ /**
2465
+ * SimpleFactory — deterministically deployed, so Base and Base Sepolia share
2466
+ * the address (matches `packages/backend/src/rails/delegation-contracts.ts`'s
2467
+ * `simpleFactory` pin for both chains).
2468
+ */
2469
+ declare const SIMPLE_FACTORY_ADDRESS: Address;
2470
+ /**
2471
+ * HybridDeleGator implementation — matches `delegation-contracts.ts`'s
2472
+ * `hybridDeleGatorImpl` pin for both chains.
2473
+ */
2474
+ declare const HYBRID_DELEGATOR_IMPLEMENTATION: Address;
2475
+ /**
2476
+ * Derive the counterfactual HybridDeleGator account address for `owner`, with
2477
+ * no passkey co-owners — the only shape Haven's signup flow provisions
2478
+ * (#970). Pure and offline: no RPC call, no dependency on the account having
2479
+ * been deployed. Verified byte-for-byte against
2480
+ * `@metamask/smart-accounts-kit`'s `getCounterfactualAccountData` by
2481
+ * `packages/signer/src/delegate-account.pins.test.ts`, including against a real Base Sepolia payload served by the dev backend
2482
+ * (`direct-payment-userop.json`).
2483
+ */
2484
+ declare function deriveDelegateAccountAddress(owner: Address): Address;
2485
+
2486
+ /**
2487
+ * Independent verification of an erc7710 x402 settlement child (#1455).
2488
+ *
2489
+ * Moved from `@haven_ai/signer` into the SDK by #3283 (epic #3284) so the
2490
+ * signer and `HavenClient.signForData` run ONE verifier. The signer checks the
2491
+ * child against the Haven-signed expected context; the SDK checks it against
2492
+ * the merchant's own 402, which Haven does not produce.
2493
+ *
2494
+ * WHY THIS EXISTS. `assertExpectedBinding` proves Haven *declared* a payload:
2495
+ * the expected context is signed by `HAVEN_X402_BINDING_SIGNER` and commits to
2496
+ * the digest of the exact bytes being signed. That is a real property, and it
2497
+ * is not this one. It says nothing about what the payload MEANS.
2498
+ *
2499
+ * A backend that declared `merchantTo = the real merchant` while pinning a
2500
+ * different payee in the child's `AllowedCalldata` caveat would produce a
2501
+ * perfectly consistent pair: the declaration binds the digest, the digest is
2502
+ * the child's, and the child pays someone else. The signature is the authority
2503
+ * here — the merchant's facilitator redeems it and pulls from the treasury — so
2504
+ * the signer has to re-derive the meaning locally or it is a pass-through with
2505
+ * extra steps.
2506
+ *
2507
+ * ADDRESSES ARE PINNED HERE ON PURPOSE. Reading the enforcer map from Haven
2508
+ * would make the check circular: an attacker who can pick which contract counts
2509
+ * as "the payee enforcer" can satisfy any comparison. Taking
2510
+ * `@metamask/smart-accounts-kit` as a runtime dependency was the other option
2511
+ * and was rejected — this package installs on users' machines. The constants
2512
+ * below are snapshot-pinned and cross-checked against the kit by a test
2513
+ * (`packages/signer/src/settlement-child.pins.test.ts`), the same pattern
2514
+ * `packages/core/src/chains.ts` uses against its registry.
2515
+ *
2516
+ * EXTRA CAVEATS ARE ALLOWED, and that is deliberate — verified, not assumed
2517
+ * (#1455 review challenged it directly).
2518
+ *
2519
+ * `DelegationManager.redeemDelegations` loops every caveat of every delegation
2520
+ * and calls `beforeHook` on each, with no break and no try/catch: a single
2521
+ * revert aborts the whole redemption, and nothing lets one caveat cause another
2522
+ * to be skipped. Top-level caveats are therefore strictly AND-ed, so one this
2523
+ * file does not recognise can only add a constraint, never remove one.
2524
+ *
2525
+ * The specific challenge was `LogicalOrWrapperEnforcer`, whose terms encode
2526
+ * several caveat GROUPS and whose own security notice warns that "the redeemer
2527
+ * can select the least restrictive group, bypassing stricter requirements in
2528
+ * other groups". That warning is about groups INSIDE the wrapper — it binds
2529
+ * whoever authors wrapper terms. The wrapper is itself one caveat among the
2530
+ * delegation's, so it is AND-ed with the four required below and cannot unlock
2531
+ * them.
2532
+ *
2533
+ * The shape that WOULD be dangerous is the inverse: a required caveat hidden
2534
+ * inside a wrapper group instead of sitting at top level, where the redeemer
2535
+ * could select a group that omits it. This file scans top-level caveats and
2536
+ * refuses on absence, so that child is refused for lacking the caveat — which
2537
+ * is the correct outcome and is pinned by a test.
2538
+ */
2539
+ /** DelegationManager, the EIP-712 `verifyingContract` for a delegation. */
2540
+ declare const DELEGATION_MANAGER = "0xdb9B1e94B5b69Df7e401DDbedE43491141047dB3";
2541
+ /**
2542
+ * Caveat enforcers, by role. Deterministically deployed, so Base and Base
2543
+ * Sepolia share addresses — verified for both chains by the pin test.
2544
+ */
2545
+ declare const CAVEAT_ENFORCERS: {
2546
+ readonly erc20TransferAmount: "0xf100b0819427117EcF76Ed94B358B1A5b5C6D2Fc";
2547
+ readonly allowedCalldata: "0xc2b0d624c1c4319760C96503BA27C347F3260f55";
2548
+ readonly timestamp: "0x1046bb45C8d673d4ea75321280DB34899413c069";
2549
+ readonly redeemer: "0xE144b0b2618071B4E56f746313528a669c7E65c5";
2550
+ };
2551
+ /** The backend's own ceiling (`MAX_SETTLEMENT_WINDOW_SECONDS`), enforced again here. */
2552
+ declare const MAX_SETTLEMENT_WINDOW_SECONDS = 600;
2553
+ interface SettlementChildTypedData {
2554
+ domain: {
2555
+ name?: string;
2556
+ version?: string;
2557
+ chainId?: number | string;
2558
+ verifyingContract?: string;
2559
+ };
2560
+ types: Record<string, unknown>;
2561
+ primaryType: string;
2562
+ message: Record<string, unknown>;
2563
+ }
2564
+ /** True when this typed data is a delegation — the shape that must never be signed unbound. */
2565
+ declare function isSettlementChildTypedData(value: unknown): value is SettlementChildTypedData;
2566
+ /**
2567
+ * Map an x402 network string to a chain id. Local on purpose (#1455 review):
2568
+ * the chain must come from Haven's SIGNED `network` field, never from the
2569
+ * payload under verification — see `verifySettlementChild`.
2570
+ */
2571
+ declare function chainIdForNetwork(network: string | undefined): number | undefined;
2572
+ interface SettlementChildExpectation {
2573
+ merchantTo: string;
2574
+ amount: string;
2575
+ asset: string;
2576
+ /**
2577
+ * Derived from the expected context's SIGNED `network`, never from
2578
+ * `typedData.domain.chainId`. Comparing the payload's own claim against
2579
+ * itself is a check that cannot fail — which is exactly what shipped in the
2580
+ * first draft of this file's call site, and what the review caught.
2581
+ */
2582
+ chainId: number;
2583
+ /** ISO timestamp; the child must not outlive it. */
2584
+ expiresAt?: string;
2585
+ /**
2586
+ * #3283 / #3281 criterion 8: the signer's OWN derived delegate account.
2587
+ * When set, the child's `delegator` must be exactly this account — the
2588
+ * child is a re-delegation of this agent's budget, never a grant from some
2589
+ * other account the key happens to control.
2590
+ */
2591
+ delegatorAccount?: string;
2592
+ /**
2593
+ * #3283: the facilitator addresses the merchant's 402 advertised
2594
+ * (`extra.facilitatorAddresses`). When non-empty, the child must carry a
2595
+ * `RedeemerEnforcer` caveat pinning exactly this set — otherwise the child
2596
+ * is a bearer instrument any party could redeem within its bounds.
2597
+ */
2598
+ redeemers?: readonly string[];
2599
+ }
2600
+ /** `@metamask/delegation-core`'s `ROOT_AUTHORITY` — a delegation chained to nothing. */
2601
+ declare const ROOT_AUTHORITY: string;
2602
+ /**
2603
+ * Verify a settlement child implements what the expected context declares.
2604
+ * Throws `HavenSigningError` on any disagreement; returns nothing on success.
2605
+ *
2606
+ * `now` is injectable so the expiry checks are testable without faking clocks.
2607
+ */
2608
+ declare function verifySettlementChild(typedData: SettlementChildTypedData, expected: SettlementChildExpectation, now?: number): void;
2609
+
2610
+ /** Wire code for a typed-data payload outside the signable allowlist. */
2611
+ declare const TYPED_DATA_NOT_ALLOWED: "TYPED_DATA_NOT_ALLOWED";
2612
+ /**
2613
+ * A typed-data payload was refused before signing because it is not a shape
2614
+ * a delegate key may sign. Nothing was signed. `@haven_ai/signer` subclasses
2615
+ * this to attach its MCP next step; the `code` is the same on both.
2616
+ */
2617
+ declare class HavenTypedDataRefusedError extends HavenSigningError {
2618
+ readonly code: typeof TYPED_DATA_NOT_ALLOWED;
2619
+ constructor(message: string);
2620
+ }
2621
+ /**
2622
+ * Chains the delegation rail has PINNED delegation contracts for
2623
+ * (`packages/backend/src/rails/delegation-contracts.ts`) — the only chains a
2624
+ * direct-payment UserOp may be scoped to. Gnosis (100) has no pinned
2625
+ * DelegationManager/enforcer set, so it is deliberately excluded even though
2626
+ * the delegate account itself could exist there.
2627
+ */
2628
+ declare const DIRECT_PAYMENT_CHAIN_IDS: ReadonlySet<number>;
2629
+ /** The DeleGator's single-execution `execute((address,uint256,bytes))` — selector `0x5c1c6dcd`. */
2630
+ declare const EXECUTE_ABI: readonly [{
2631
+ readonly type: "function";
2632
+ readonly name: "execute";
2633
+ readonly inputs: readonly [{
2634
+ readonly name: "_execution";
2635
+ readonly type: "tuple";
2636
+ readonly components: readonly [{
2637
+ readonly name: "target";
2638
+ readonly type: "address";
2639
+ }, {
2640
+ readonly name: "value";
2641
+ readonly type: "uint256";
2642
+ }, {
2643
+ readonly name: "callData";
2644
+ readonly type: "bytes";
2645
+ }];
2646
+ }];
2647
+ readonly outputs: readonly [];
2648
+ readonly stateMutability: "payable";
2649
+ }];
2650
+ /**
2651
+ * The content + provenance allowlist (#3272 criteria 1–2). Call ONLY after
2652
+ * `assertUserOpTypedDataBinding` has already proven `typedData` is a
2653
+ * well-formed `PackedUserOperation` matching its own hash — this function
2654
+ * trusts `typedData.domain`/`message` are shaped correctly and checks only
2655
+ * what they SAY. Throws `HavenTypedDataRefusedError` (never returns) on any
2656
+ * disagreement.
2657
+ */
2658
+ declare function assertBoundDirectPaymentUserOp(typedData: Record<string, unknown>, delegateAddress: string): void;
2659
+
2660
+ /**
2661
+ * The settlement-child half of the same surface (#3283): verify an erc7710
2662
+ * child against `expectation` (from somewhere Haven did not write — the
2663
+ * merchant's 402 in the SDK, the Haven-signed expected context in the
2664
+ * signer), AND that it is re-delegated from this key's OWN account. Throws
2665
+ * `HavenTypedDataRefusedError` (code `TYPED_DATA_NOT_ALLOWED`) on any
2666
+ * disagreement.
2667
+ */
2668
+ declare function assertOwnSettlementChild(typedData: unknown, expectation: SettlementChildExpectation, delegateAddress: string): void;
2669
+ /**
2670
+ * #3281 (epic #3284, criterion 5): pin WHERE an x402 EIP-3009 funding leg's
2671
+ * redemption sends the money. The funding leg is always
2672
+ * `transfer(<delegate EOA>, <amount>)` of the quoted token
2673
+ * (`delegation-authorize.ts` → `prepareDelegationPayment(agent, token,
2674
+ * payTo = the delegate EOA, amountRaw)`), so the single execution must be
2675
+ * exactly `encodePacked(asset, 0, transfer(delegateAddress, amount))`.
2676
+ *
2677
+ * `delegateAddress` is the signer's OWN key address — local, not from Haven —
2678
+ * so even a compromised binding key can at most move budget into the agent's
2679
+ * own EOA (the hot-delegate residual the sweep returns), never to an attacker.
2680
+ * `asset` and `amount` come from the Haven-signed expected context and keep
2681
+ * the leg consistent with what Haven declared.
2682
+ *
2683
+ * Call ONLY after `assertBoundDirectPaymentUserOp` has passed on the same
2684
+ * typed data (it proves the `execute` → `redeemDelegations` shape this reads).
2685
+ * Throws `HavenTypedDataRefusedError` on any disagreement.
2686
+ */
2687
+ declare function assertFundingLegPaysDelegate(typedData: Record<string, unknown>, expected: {
2688
+ delegateAddress: string;
2689
+ asset: string;
2690
+ amount: string;
2691
+ }): void;
2692
+
2693
+ /**
2694
+ * Runtime-agnostic base64 helpers — the single source of truth for the wire
2695
+ * encoding shared by the SDK and the edge signer (#325).
2696
+ *
2697
+ * Why this module exists: the SDK used `atob`/`btoa` (Web globals) while the
2698
+ * signer used `Buffer` (Node-only). Both worked because both currently run in
2699
+ * Node ≥ 16, but the duplication was a latent wire-incompatibility — and the
2700
+ * signer is headed for non-Node runtimes (browsers, Cloudflare Workers) where
2701
+ * `Buffer` does not exist (#314).
2702
+ *
2703
+ * Encoding contract:
2704
+ * - Output is ALWAYS standard base64 (`+`, `/`, padded). The x402 protocol's
2705
+ * reference implementation validates headers against
2706
+ * `/^[A-Za-z0-9+/]*={0,2}$/` — URL-safe output would be rejected.
2707
+ * - Decoding is tolerant: URL-safe input (`-`, `_`, unpadded) is normalized
2708
+ * before decoding, since third-party merchants are not guaranteed to be as
2709
+ * strict as the reference implementation.
2710
+ * - UTF-8 throughout. Naive `btoa(JSON.stringify(...))` throws on any
2711
+ * non-Latin-1 character (e.g. a merchant description with an emoji or
2712
+ * non-ASCII name); these helpers route through TextEncoder/TextDecoder on
2713
+ * the Web path so multibyte characters round-trip identically on both
2714
+ * runtimes.
2715
+ */
2716
+ /** Encode a UTF-8 string as standard base64. */
2717
+ declare function encodeBase64Utf8(value: string): string;
2718
+ /** Decode standard or URL-safe base64 to a UTF-8 string. */
2719
+ declare function decodeBase64Utf8(value: string): string;
2720
+ /** Encode a JSON-serializable value as a standard-base64 string. */
2721
+ declare function encodeBase64Json(value: unknown): string;
2722
+ /**
2723
+ * Decode a base64 JSON payload.
2724
+ *
2725
+ * Pass a `label` to get a wrapped error message instead of the raw
2726
+ * JSON/base64 error — call sites parsing untrusted merchant headers use this
2727
+ * to produce actionable failures.
2728
+ */
2729
+ declare function decodeBase64Json<T>(value: string, label?: string): T;
2730
+
2731
+ export { AgentPaymentRailSchema as $, type AgentPaymentWarning as A, type X402ResumeState as B, type X402McpTransport as C, type X402MerchantCallContext as D, HavenError as E, AGENT_PAYMENT_FAILURE_CODE_VALUES as F, AGENT_PAYMENT_NEXT_ACTION_VALUES as G, type HavenClientConfig as H, AGENT_PAYMENT_PHASE_VALUES as I, AGENT_PAYMENT_RAIL_VALUES as J, type AgentNextStep as K, type AgentPaymentEnumSchema as L, AgentPaymentFailureCode as M, AgentPaymentFailureCodeDescriptions as N, AgentPaymentFailureCodeSchema as O, type PaymentRequest as P, AgentPaymentNextAction as Q, type RawPaymentParties as R, type SweepResult as S, AgentPaymentNextActionDescriptions as T, AgentPaymentNextActionSchema as U, AgentPaymentPhase as V, AgentPaymentPhaseDescriptions as W, type X402PaymentRequired as X, AgentPaymentPhaseSchema as Y, AgentPaymentRail as Z, AgentPaymentRailDescriptions as _, type HavenClientUpdate as a, type UnsupportedNodeVersionMessageOptions as a$, type AgentPaymentSummary as a0, AgentPaymentWarningCode as a1, type AgentPurchaseSummary as a2, CONNECTOR_PACKAGE_NAME as a3, type CatalogSubmissionAccepted as a4, DEFAULT_CONFIRMATION_TIMEOUT_MS as a5, DEFAULT_NEXT_TOOL_BY_ACTION as a6, DIRECT_SIGN_CONTEXT_VERSION as a7, ENTRY_POINT_V07 as a8, ERC7710_ASSET_TRANSFER_METHOD as a9, type NextStepTarget as aA, type NextStepTargets as aB, type NextToolServerRole as aC, PACKED_USER_OPERATION_FIELDS as aD, type PaymentFee as aE, type PaymentNextAction as aF, type PaymentPhase as aG, type PaymentStatus as aH, ROOT_AUTHORITY as aI, SDK_CLIENT_IDENTITY as aJ, SDK_VERSION as aK, SIGNER_UPDATE_FALLBACK as aL, SWEEP_BASE_CHAIN_ID as aM, SWEEP_BASE_SEPOLIA_CHAIN_ID as aN, SWEEP_BASE_SEPOLIA_USDC_ADDRESS as aO, SWEEP_BASE_USDC_ADDRESS as aP, type SettlementChildExpectation as aQ, SignerRefusalCode as aR, type SweepConfirmation as aS, type SweepEip712Domain as aT, type SweepEntry as aU, type SweepExpectedAuth as aV, type SweepPreparation as aW, type SweepSubmitResult as aX, type SweepTypedData as aY, TRANSFER_WITH_AUTHORIZATION_TYPES as aZ, TYPED_DATA_NOT_ALLOWED as a_, HAVEN_CLIENT_HEADER as aa, HAVEN_CONNECTOR_CHANNEL as ab, HAVEN_MINIMUM_NODE_VERSION as ac, HYBRID_DELEGATOR_DOMAIN_NAME as ad, HYBRID_DELEGATOR_DOMAIN_VERSION as ae, type HavenAgentAllowanceSummary as af, type HavenAgentReadiness as ag, type HavenAllowance as ah, HavenApiError as ai, type HavenCatalogMerchant as aj, type HavenListScope as ak, HavenPaymentStateError as al, HavenSigningError as am, HavenTimeoutError as an, HavenTypedDataRefusedError as ao, HavenUnsupportedSignerVersionError as ap, HavenUserOpBindingError as aq, HavenZeroSettlementHashError as ar, type MachinePaymentRail as as, MerchantTimeoutError as at, NEXT_TOOL_SERVER_NAMES as au, NEXT_TOOL_SERVER_ROLES as av, type NextStep as aw, type NextStepArguments as ax, type NextStepHandoff as ay, type NextStepInput as az, type PaymentResult as b, DELEGATION_MANAGER as b$, X402AlreadySettledError as b0, type X402ExpectedAuth as b1, type X402ExpectedContext as b2, type X402PaymentHeaderContext as b3, X402PaymentHeaderValidationError as b4, type X402PaymentOption as b5, type X402RequestSnapshot as b6, type X402SchemeSelection as b7, X402UnexpectedStatusError as b8, X402_LEGACY_PAYMENT_HEADER_NAME as b9, isSupportedNodeVersion as bA, isSweepableChain as bB, normalizePaymentRequired as bC, packedUserOperationHash as bD, parseNextTool as bE, parsePaymentRequired as bF, parsePaymentRequiredResponse as bG, readClientUpdate as bH, renderNextTool as bI, resolveConnectorChannel as bJ, resolveTokenFromAddress as bK, selectErc7710PaymentOption as bL, selectPaymentOption as bM, selectStandardPaymentOption as bN, selectX402SettlementScheme as bO, signerUpdateFallback as bP, sweepUsdcAddress as bQ, sweepUsdcDomain as bR, toStandardPaymentRequirements as bS, unsupportedNodeVersionMessage as bT, validateStandardX402PaymentHeader as bU, verifySettlementChild as bV, x402AssetTransferMethod as bW, x402AuthorizationAmount as bX, x402FacilitatorAddresses as bY, x402V2PaymentEnvelope as bZ, CAVEAT_ENFORCERS as b_, X402_MAX_AUTHORIZATION_WINDOW_SECONDS as ba, X402_PAYMENT_HEADER_NAME as bb, X402_PAYMENT_HEADER_NAMES_SENT as bc, X402_PAYMENT_REQUIRED_HEADER_NAME as bd, X402_PAYMENT_RESPONSE_HEADER_NAME as be, X402_SETTLEMENT_FORWARD_MARGIN_SECONDS as bf, assertBoundDirectPaymentUserOp as bg, assertUserOpTypedDataBinding as bh, buildSweepAuthorizationMessage as bi, buildSweepTypedData as bj, buildX402ExpectedMessage as bk, compareNodeVersions as bl, connectorRerunCommand as bm, connectorSpec as bn, createNextStepBuilder as bo, decodeBase64Json as bp, decodeBase64Utf8 as bq, defaultNextToolFor as br, deriveDelegateAccountAddress as bs, encodeBase64Json as bt, encodeBase64Utf8 as bu, encodePaymentProof as bv, havenClientIdentity as bw, isConnectorChannel as bx, isErc7710Option as by, isPackedUserOperationTypedData as bz, type PaymentIntent as c, DIRECT_PAYMENT_CHAIN_IDS as c0, EXECUTE_ABI as c1, HYBRID_DELEGATOR_IMPLEMENTATION as c2, MAX_SETTLEMENT_WINDOW_SECONDS as c3, SIMPLE_FACTORY_ADDRESS as c4, type SettlementChildTypedData as c5, assertFundingLegPaysDelegate as c6, assertOwnSettlementChild as c7, chainIdForNetwork as c8, isSettlementChildTypedData as c9, type X402AuthorizationOptions as d, type X402Intent as e, type PaymentStatusResult as f, type HavenAgent as g, type HavenAgentSummary as h, type SweepPrepareResponse as i, type SweepAuthorization as j, type SweepSubmitResponse as k, type HavenAllowanceSummary as l, type HavenBalanceCoverage as m, type PostPurchaseAllowanceSummary as n, type HavenCatalogEntry as o, type HavenCatalogSubmission as p, type HavenPaymentReceipt as q, type HavenPaymentReceiptsPage as r, type PaymentResumeState as s, type X402Receipt as t, type X402Quote as u, type X402Erc7710Settlement as v, type X402McpCallContext as w, type SignData as x, type ResumeAuthorizedX402Input as y, type ResumeX402PaymentInput as z };