@haven_ai/sdk 0.4.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.
package/dist/index.d.cts CHANGED
@@ -1,1544 +1,7 @@
1
- import { PaymentRequirements } from 'x402/types';
2
-
3
- interface HavenClientConfig {
4
- /** Haven API key (sk_agent_xxx) */
5
- apiKey: string;
6
- /** Agent's delegate EOA private key. If provided, the SDK handles signing automatically. */
7
- delegateKey?: string;
8
- /** Haven API base URL (default: http://localhost:3001) */
9
- baseUrl?: string;
10
- /** Optional wallet identity to send as the x402-wallet header. */
11
- x402Wallet?: string;
12
- /** Timeout in ms for individual HTTP requests (default: 30000) */
13
- requestTimeout?: number;
14
- /** Timeout (ms) for MERCHANT-facing requests — x402/MPP probes, MCP
15
- * handshakes, paid retries. Separate from requestTimeout (Haven API):
16
- * merchants may settle on-chain synchronously, so the default is
17
- * deliberately generous. #1300. */
18
- merchantTimeout?: number;
19
- /** Timeout in ms when polling for tx confirmation (default: 90000) */
20
- confirmationTimeout?: number;
21
- /** Polling interval in ms when waiting for confirmation (default: 3000) */
22
- pollingInterval?: number;
23
- /**
24
- * Extra headers to attach to every request to the Haven API.
25
- *
26
- * Used by the MCP server to tag requests with `X-Haven-MCP-Tool: <name>`
27
- * so the backend can record an audit-log entry per tool invocation. Has
28
- * no effect on outbound merchant requests (x402 / MPP) — those are
29
- * standard HTTP and never carry Haven-internal headers.
30
- */
31
- defaultHeaders?: Record<string, string>;
32
- /**
33
- * JSON-RPC RPC URLs keyed by EIP-155 chain ID.
34
- *
35
- * When provided for a chain, the SDK waits for ≥1 on-chain confirmation of
36
- * the AllowanceModule funding tx before retrying the merchant. This prevents
37
- * the race where the merchant's `balanceOf(delegate)` call runs before the
38
- * funding block has propagated to the merchant's RPC node.
39
- *
40
- * Without this option the SDK proceeds as soon as Haven's backend confirms
41
- * submission (backward-compatible default). Set it to a reliable RPC
42
- * endpoint (e.g. Alchemy / Infura) for production usage.
43
- *
44
- * @example { 8453: 'https://mainnet.base.org' }
45
- */
46
- chainRpcs?: Record<number, string>;
47
- }
48
- interface PaymentRequest {
49
- /** Token symbol: "EURe", "USDC.e", or "xDAI" */
50
- token: string;
51
- /** Amount as a decimal string, e.g. "5.00" */
52
- amount: string;
53
- /** Recipient Ethereum address (0x...) */
54
- to: string;
55
- /**
56
- * Optional dedupe key (#1207): a retried request with the same key returns
57
- * the FIRST request's result instead of minting a second transfer or a
58
- * second approval. Same contract as /machine-payments/send. Max 128 chars.
59
- */
60
- idempotencyKey?: string;
61
- }
62
- interface SignData {
63
- /** The hash to sign (keccak256, 0x-prefixed) */
64
- hash: string;
65
- /**
66
- * Delegation rail: 'eip712_userop' (funding redemption) or
67
- * 'eip712_delegation' (erc7710 settlement child). The backend spec makes it
68
- * required; the legacy AllowanceModule reading — absent = raw ECDSA over
69
- * `hash` — is retired (#2850), and the SDK client refuses an absent scheme.
70
- * The session rail's 'eip191_userop' is retired (#834).
71
- *
72
- * When present, `hash` is NOT what gets signed — `typed_data` is (#1138).
73
- */
74
- signature_scheme?: 'eip712_userop' | 'eip712_delegation';
75
- /**
76
- * EIP-712 payload the account validates, signed VERBATIM (#829). Present
77
- * whenever `signature_scheme` is — never reconstruct it from `components`.
78
- */
79
- typed_data?: {
80
- domain: Record<string, unknown>;
81
- types: Record<string, unknown>;
82
- primaryType: string;
83
- message: Record<string, unknown>;
84
- };
85
- /** Breakdown of values that were hashed — useful for debugging */
86
- components: {
87
- /**
88
- * The PAYER account (the user's smart account). Not to be confused with
89
- * `account`, which on the funding shapes holds the DELEGATE account
90
- * address.
91
- */
92
- payer_account?: string;
93
- token: string;
94
- to: string;
95
- amount: string;
96
- payment_token: string;
97
- payment: string;
98
- nonce: number;
99
- };
100
- /** Human-readable signing instructions */
101
- instructions: string;
102
- }
103
- interface PaymentIntent {
104
- /** Unique payment ID */
105
- paymentId: string;
106
- /** Current status */
107
- status: 'pending_signature';
108
- /** ISO 8601 expiry timestamp */
109
- expiresAt: string;
110
- /** Data needed to sign the payment */
111
- signData: SignData;
112
- }
113
- type PaymentStatus = 'pending_signature' | 'submitted' | 'confirmed' | 'pending_approval' | 'approved' | 'proposed' | 'executed' | 'rejected' | 'expired' | 'failed';
114
- interface PaymentResult {
115
- /** Unique payment ID */
116
- paymentId: string;
117
- /** Final status */
118
- status: PaymentStatus;
119
- /** Token that was sent */
120
- token: string;
121
- /** Amount that was sent (human-readable) */
122
- amount: string;
123
- /** Recipient address */
124
- to: string;
125
- /** On-chain transaction hash (present when confirmed) */
126
- txHash: string | null;
127
- /** Error message (present when failed) */
128
- errorMessage: string | null;
129
- /** Block explorer URL for the transaction (chain-dependent) */
130
- explorerUrl: string | null;
131
- /** ISO 8601 timestamps */
132
- createdAt: string;
133
- signedAt: string | null;
134
- submittedAt: string | null;
135
- confirmedAt: string | null;
136
- expiresAt: string;
137
- /**
138
- * Platform fee surfaced on the result so it's never silently collected. Dark
139
- * today (`amount` "0", `applied` false); always present so it's visible the
140
- * moment fees go live.
141
- */
142
- fee?: PaymentFee | null;
143
- }
144
- /** The Haven platform fee applied to a payment (#386). */
145
- interface PaymentFee {
146
- /** Human-readable fee amount ("0" while the fee module is dark). */
147
- amount: string;
148
- /** Token the fee is denominated in. */
149
- token: string;
150
- /** Fee as basis points of gross (0 while dark). */
151
- basisPoints: number;
152
- /** True when a non-zero fee was actually applied. */
153
- applied: boolean;
154
- }
155
- /** Payment requirements from an HTTP 402 response (x402 protocol). */
156
- interface X402PaymentRequired {
157
- x402Version: number;
158
- resource: {
159
- url: string;
160
- description?: string;
161
- mimeType?: string;
162
- [key: string]: unknown;
163
- };
164
- accepts: X402PaymentOption[];
165
- error?: string;
166
- extensions?: Record<string, unknown>;
167
- }
168
- /** A single payment option from x402 PaymentRequired. */
169
- interface X402PaymentOption {
170
- scheme: string;
171
- network: string;
172
- amount: string;
173
- maxAmountRequired?: string;
174
- resource?: string;
175
- description?: string;
176
- mimeType?: string;
177
- asset: string;
178
- payTo: string;
179
- maxTimeoutSeconds: number;
180
- /**
181
- * Merchant-supplied scheme metadata. Two keys are load-bearing for Haven
182
- * (#1453), both from MetaMask's erc7710 x402 shape:
183
- *
184
- * assetTransferMethod — 'erc7710' marks this entry as settleable by
185
- * redeeming a delegation chain. Absent/other means
186
- * the standard EIP-3009 authorization.
187
- * facilitatorAddresses — who may redeem it, pinned into the settlement
188
- * child's redeemer caveat (#1058).
189
- *
190
- * Left as an open record on purpose: the field is the merchant's, and
191
- * narrowing it to Haven's two keys would silently drop everything else a
192
- * merchant sends. Read it through `x402AssetTransferMethod` /
193
- * `x402FacilitatorAddresses` rather than indexing it raw.
194
- */
195
- extra?: Record<string, unknown>;
196
- }
197
- /** Receipt returned after a successful x402 payment. */
198
- interface X402Receipt {
199
- success: boolean;
200
- paymentId: string;
201
- txHash: string;
202
- token: string;
203
- amount: string;
204
- to: string;
205
- resourceUrl: string;
206
- explorerUrl: string;
207
- accepted?: X402PaymentOption;
208
- paymentHeader?: string;
209
- merchantTo?: string | null;
210
- payer?: string;
211
- chainId?: number;
212
- haven?: {
213
- paymentId: string;
214
- fundingTxHash: string;
215
- fundingExplorerUrl: string;
216
- };
217
- merchant?: {
218
- payTo: string | null;
219
- settlementTxHash?: string | null;
220
- settlementExplorerUrl?: string | null;
221
- };
222
- x402?: {
223
- amount: string;
224
- token: string;
225
- network: string;
226
- asset: string;
227
- resource: string;
228
- };
229
- }
230
- interface X402AuthorizationOptions {
231
- /** Stable caller-supplied key for this user intent. Prevents duplicate approvals across fresh 402 quotes. */
232
- idempotencyKey?: string;
233
- /**
234
- * #1307: the merchant MCP-tool call context this quote was made against
235
- * (merchant_url, tool_name, arguments, mcp_transport). Persisted on the
236
- * intent so `getX402MerchantCallContext` can rehydrate it by payment_id at
237
- * settle/complete time instead of the caller re-threading it. Optional —
238
- * omit for a non-MCP-tool x402 merchant (plain HTTP resource).
239
- */
240
- mcpCallContext?: X402McpCallContext;
241
- /**
242
- * #1348: the agent's delegate address, when the caller already resolved it
243
- * from `getAgent()` in this same flow — skips `createX402Intent`'s internal
244
- * agent fetch (one full round trip on every guided purchase). Staleness
245
- * caveat (#1358 review): the backend derives the funding shape by comparing
246
- * `payTo` to the CURRENT delegate address, so a value made stale by a
247
- * delegate rotation mid-flow is not always a clean failure — a pinned-budget
248
- * agent gets a 403, but an open-budget delegation agent would route to the
249
- * settlement shape with the stale address. The window is one tool call
250
- * (previously sub-millisecond, now the merchant-quote duration), never
251
- * externally suppliable; server-truth hardening is tracked in #1360. Only
252
- * pass an address fetched in THIS flow; omit to keep the self-contained
253
- * fetch.
254
- */
255
- delegateAddress?: string;
256
- }
257
- /**
258
- * Keyless x402 construct result.
259
- *
260
- * Returned by `createX402Intent` — the non-custodial half of an x402 payment.
261
- * It carries the unsigned funding hash (`signData.hash`, Safe → delegate EOA)
262
- * plus everything the *edge* needs to build and sign the EIP-3009 merchant
263
- * header itself. The construct path never signs; both delegate signatures
264
- * (funding hash + merchant header) happen on the machine that holds the key.
265
- */
266
- interface X402Intent {
267
- /** Haven payment id for the funding transfer. */
268
- paymentId: string;
269
- /** Stable key used to create or refresh this x402 funding intent. */
270
- idempotencyKey: string;
271
- status: 'pending_signature';
272
- /** ISO 8601 expiry of the funding intent, if returned. */
273
- expiresAt?: string;
274
- /** The unsigned funding hash to sign with the delegate key (Safe → delegate EOA). */
275
- signData: SignData;
276
- /** The selected x402 option — the edge needs this to build the EIP-3009 header. */
277
- accepted: X402PaymentOption;
278
- /** Resource URL the 402 came from. */
279
- resourceUrl: string;
280
- /** Merchant payTo address (the final recipient of the EIP-3009 transfer). */
281
- merchantTo: string;
282
- /** Atomic amount the edge signer must authorize in the merchant header. */
283
- amountAtomic: string;
284
- /** Token contract the merchant header must pay. */
285
- asset: string;
286
- /** x402 network the merchant header must use. */
287
- network: string;
288
- /** Haven-authenticated binding over the x402 expected context. */
289
- expectedAuth: X402ExpectedAuth;
290
- /**
291
- * #1690: the payer identity Haven bound into the expected context (v3),
292
- * relayed VERBATIM to the signer's wire shape. Absent until the backend
293
- * flips X402_EMIT_PAYER_CONTEXT.
294
- */
295
- payerDelegate?: string;
296
- payerAgentId?: string;
297
- /**
298
- * EIP-712 digest of `signData.typed_data`, present on the delegation rail
299
- * (#1138). The edge signer needs it to reconstruct the v2 expected-context
300
- * message that Haven signed.
301
- */
302
- expectedTypedDataHash?: string;
303
- /** Delegate EOA the funding transfer tops up (the x402 payer). */
304
- fundingTo: string;
305
- }
306
- interface X402ExpectedContext {
307
- paymentId: string;
308
- payloadHash: string;
309
- resourceUrl: string;
310
- merchantTo: string;
311
- amount: string;
312
- asset: string;
313
- network: string;
314
- /** Optional ISO expiry for the funding/quote window. When present, it is bound into the Haven-authenticated context. */
315
- expiresAt?: string;
316
- /**
317
- * EIP-712 digest of the typed data the account actually validates
318
- * (delegation rail, #1138). Present ⇒ the context is **version 2** and the
319
- * signer must sign that typed data, never `payloadHash`.
320
- *
321
- * On the delegation rail `payloadHash` is the bare ERC-4337 UserOp hash,
322
- * which is NOT what the account validates — binding it alone would leave the
323
- * edge signer unable to verify the payload it is being asked to sign. Binding
324
- * this digest makes Haven's declaration cover the real payload.
325
- */
326
- typedDataHash?: string;
327
- /**
328
- * The DELEGATE ADDRESS this quote was created for (#1690). Present ⇒ the
329
- * context is **version 3** and the signer refuses to sign when this is not
330
- * its own delegate — the guard that turns "quote as agent A, sign as agent
331
- * B" from an on-chain revert three layers later into a named refusal.
332
- * Inside the Haven-signed message on purpose: outside it, it is forgeable.
333
- */
334
- payerDelegate?: string;
335
- /** The paying agent's id, for the refusal message's diagnosis (#1690). */
336
- payerAgentId?: string;
337
- }
338
- interface X402ExpectedAuth {
339
- /**
340
- * 1 = hash-only (legacy rail). 2 = carries `typedDataHash` (delegation rail,
341
- * #1138).
342
- *
343
- * Deliberately `number`, not a literal union (#1143). This is an **inbound**
344
- * value: a signer parses a context Haven produced, and a signer older than the
345
- * backend will legitimately receive a version it does not know. A closed union
346
- * makes that state unrepresentable, which pushed the rejection down to the
347
- * schema boundary and produced a raw validation error naming neither the cause
348
- * nor the fix. The supported set lives in the signer
349
- * (`SUPPORTED_X402_EXPECTED_VERSIONS`), which fails closed on anything outside
350
- * it with an actionable message.
351
- */
352
- version: number;
353
- message: string;
354
- signature: string;
355
- signer: string;
356
- }
357
- /** Serializable HTTP request state for retrying the same x402 merchant request. */
358
- interface X402RequestSnapshot {
359
- url: string;
360
- method: string;
361
- headers: [string, string][];
362
- body?: string;
363
- }
364
- interface X402McpTransport {
365
- handshakeRequired: boolean;
366
- source: 'path' | 'bazaar';
367
- }
368
- /**
369
- * #1307: the merchant MCP-tool call an x402 quote was made against — carried
370
- * through `createX402Intent`'s options so Haven can persist it for the
371
- * settle-leg rehydration handoff (`getX402MerchantCallContext`). Convenience
372
- * metadata for retrying the merchant's OWN JSON-RPC call, never payment
373
- * authority.
374
- */
375
- interface X402McpCallContext {
376
- merchantUrl: string;
377
- toolName: string;
378
- arguments?: Record<string, unknown>;
379
- mcpTransport?: X402McpTransport;
380
- }
381
- /**
382
- * Response shape of `getX402MerchantCallContext` — the stored merchant call
383
- * context for a payment_id, rehydrated instead of re-threaded (#1307).
384
- */
385
- interface X402MerchantCallContext {
386
- paymentId: string;
387
- merchantUrl: string;
388
- toolName: string;
389
- arguments: Record<string, unknown>;
390
- mcpTransport?: X402McpTransport;
391
- }
392
- /** Quote parsed from an HTTP 402 response without creating a Haven payment. */
393
- interface X402Quote {
394
- rail: 'x402';
395
- idempotencyKey: string;
396
- paymentRequired: X402PaymentRequired;
397
- accepted: X402PaymentOption;
398
- /**
399
- * #2054: which selector produced `accepted`, and therefore which entry every
400
- * amount on this quote describes. `'standard'` is the untagged,
401
- * EIP-3009-settleable entry; `'erc7710'` means the merchant advertises NO
402
- * standard entry, so the quote describes its erc7710 one — settleable only
403
- * from a delegation-rail account, a fact the quote layer cannot see (the
404
- * rail is a property of the ACCOUNT, not of the 402). This field is
405
- * descriptive: the actual settlement scheme is still chosen later, with the
406
- * rail in hand, by `selectX402SettlementScheme`.
407
- */
408
- acceptedScheme: 'standard' | 'erc7710';
409
- request: X402RequestSnapshot;
410
- mcpTransport?: X402McpTransport;
411
- resourceUrl: string;
412
- /** #3097: `resourceUrl` (the merchant's declaration) is not `request.url` (what was quoted). */
413
- resourceUrlDiffersFromRequest: boolean;
414
- description: string | null;
415
- mimeType: string | null;
416
- amountAtomic: string;
417
- amount: string;
418
- token: string;
419
- /**
420
- * #1351: decimals for `asset` on `network`, resolved from the SAME
421
- * address→token binding that produced `token` — the quote's own authority on
422
- * how many atomic units one human unit is. `null` when the merchant's asset
423
- * is not a token Haven recognises on that network, in which case `token` is
424
- * an unverified fallback label and NO human→atomic conversion is safe.
425
- * Consumers converting a human-denominated figure (a user-intent spending
426
- * cap) MUST fail closed on `null` rather than assume 6.
427
- */
428
- decimals: number | null;
429
- asset: string;
430
- network: string;
431
- chainId: number | null;
432
- merchantAddress: string;
433
- maxTimeoutSeconds: number;
434
- }
435
- /** State bundle an agent can persist while waiting for manual x402 approval. */
436
- interface X402ResumeState {
437
- rail: 'x402';
438
- paymentId: string;
439
- idempotencyKey: string;
440
- paymentRequired: X402PaymentRequired;
441
- accepted: X402PaymentOption;
442
- url: string;
443
- request?: X402RequestSnapshot;
444
- resourceUrl: string;
445
- description: string | null;
446
- amountAtomic: string;
447
- amount: string;
448
- token: string;
449
- asset: string;
450
- network: string;
451
- chainId: number | null;
452
- merchantAddress: string;
453
- }
454
- type PaymentResumeState = X402ResumeState;
455
- interface ResumeAuthorizedX402Input extends X402AuthorizationOptions {
456
- /** Payment or approval request ID returned by authorizeX402 / haven.fetch. */
457
- paymentId: string;
458
- /** Original or freshly parsed x402 requirements for the merchant retry. */
459
- paymentRequired: X402PaymentRequired;
460
- }
461
- interface ResumeX402PaymentInput extends X402AuthorizationOptions {
462
- /** Payment or approval request ID returned by authorizeX402 / haven.fetch. */
463
- paymentId: string;
464
- /** Original paid URL. If paymentRequired is omitted, Haven will call it once to re-read the 402 challenge. */
465
- url: string;
466
- /** Original fetch options. Reused for the 402 probe and final merchant retry. */
467
- init?: RequestInit;
468
- /** Serializable original request captured by quoteX402() / pending approval errors. */
469
- request?: X402RequestSnapshot;
470
- /** Original or freshly parsed x402 requirements. Supplying this avoids an extra merchant 402 probe. */
471
- paymentRequired?: X402PaymentRequired;
472
- }
473
- type MachinePaymentRail = 'x402' | 'mpp_demo' | 'mpp_crypto' | 'stripe_deposit' | 'spt';
474
- interface HavenAgent {
475
- id: string;
476
- name: string;
477
- status: string;
478
- /** The agent's Haven account (smart account) address. */
479
- accountAddress: string;
480
- delegateAddress: string;
481
- chainId: number;
482
- /**
483
- * Which on-chain policy primitive gates this agent's spend (#1306): the
484
- * legacy Safe AllowanceModule (retired — no account can enter it since
485
- * #1984, and it cannot spend since #1986) or the delegation
486
- * rail's active budget delegations (#1090). Read-only reporting — the
487
- * on-chain state is the actual gate either way, this only says which
488
- * mechanism a caller should read/derive from.
489
- */
490
- executionRail: 'legacy' | 'delegation';
491
- }
492
- interface HavenAllowance {
493
- id: string;
494
- tokenAddress: string;
495
- tokenSymbol: string;
496
- configuredAmount: string;
497
- resetPeriodMin: number;
498
- /**
499
- * #3128: human-readable `onchain.remaining`, e.g. "4.96 USDC" — the SAME
500
- * string {@link HavenAgentAllowanceSummary.remainingDisplay} carries for
501
- * this allowance, computed by one function from `onchain.remaining` and
502
- * the token's decimals, so the two reads cannot disagree. Additive; the
503
- * wire carries no display form (it is derived client-side).
504
- */
505
- remainingDisplay: string;
506
- onchain: {
507
- amount: string;
508
- spent: string;
509
- remaining: string;
510
- effectiveSpent: string;
511
- resetTimeMin: number;
512
- lastResetMin: number;
513
- nonce: number;
514
- isResetPending: boolean;
515
- /**
516
- * Delegation rail only (#1319, provenance for #1145's fallback): true
517
- * when `remaining` came from a live on-chain enforcer read, false when
518
- * the read failed and `remaining` is the fallback full configured
519
- * budget. Undefined on the legacy AllowanceModule rail, which has no
520
- * fallback concept. Reporting only — the on-chain policy remains the
521
- * actual spend gate either way.
522
- */
523
- remainingIsFromChain?: boolean;
524
- };
525
- }
526
- interface HavenAllowanceSummary {
527
- agentId: string;
528
- accountAddress: string;
529
- delegateAddress: string;
530
- chainId: number;
531
- allowances: HavenAllowance[];
532
- }
533
- /**
534
- * Post-purchase allowance/budget summary attached to a settled x402 payment
535
- * (#1310). Read-only reporting — the on-chain policy remains the actual
536
- * spend gate either way, this only says what is left after the purchase.
537
- *
538
- * Deliberately the SAME rail-labeled field spelling as #1306's
539
- * catalog-purchase preflight `allowance` block (never a new spelling),
540
- * minus the preflight-only `sufficient` field: post-purchase reporting
541
- * answers "what is left", not "was this purchase covered". Read through the
542
- * exact same source as {@link HavenAllowanceSummary} / `haven_get_allowances`
543
- * (`GET /machine-payments/allowances`; delegation-rail values are the #1090
544
- * `deriveDelegationBudgets`-backed enforcer read, never `agent_allowances`),
545
- * so this can never disagree with `haven_get_allowances` for the same
546
- * fixture.
547
- */
548
- interface PostPurchaseAllowanceSummary {
549
- /** Which on-chain policy primitive gates this agent's spend (#1306 labeling). */
550
- rail: 'legacy' | 'delegation';
551
- /** Remaining atomic units, read through the same source as {@link HavenAllowance.onchain.remaining}. */
552
- remaining_atomic: string;
553
- /** Human-readable remaining, e.g. "4.96 USDC". Omitted when the token's decimals are unknown. */
554
- remaining_display?: string;
555
- token_symbol?: string;
556
- token_address?: string;
557
- /** Minutes — mirrors {@link HavenAllowance.resetPeriodMin} / the delegation's period. */
558
- reset_period?: number;
559
- source: 'allowance_module' | 'active_delegations';
560
- }
561
- /**
562
- * #3126 — the answer to "is there money actually HELD behind my budget?",
563
- * asked as a sufficiency signal rather than a balance.
564
- *
565
- * Every other agent-readable figure in this package describes SPEND
566
- * AUTHORITY — what the agent is PERMITTED to move this period
567
- * ({@link HavenAllowanceSummary}). This shape answers the different question
568
- * of whether the account HOLDS funds behind that authority, and deliberately
569
- * answers it as `covered: boolean | null`, never as a figure: a constrained
570
- * actor has no business reading the treasury total, and the boolean answers
571
- * the only decision an agent has (attempt the payment, or tell the user
572
- * funds are missing).
573
- *
574
- * The naming keeps the two concepts apart (the #3126 binding constraint):
575
- * `budgetRemainingAtomic` is AUTHORITY — the same value
576
- * {@link HavenAllowanceSummary} reports per token as `onchain.remaining` —
577
- * while `covered` speaks only of HELD funds. Nothing here is named like the
578
- * authority fields (`remaining`, `available`); nothing here returns a
579
- * balance.
580
- *
581
- * `covered: null` means the chain read FAILED — unverifiable, never a
582
- * guess. The same honesty rule `x402-funding-leg.ts`'s `delegateCanFund`
583
- * established (#1521): treat null as "we do not know", not as "funded" or
584
- * as absence; `coverageError` carries why.
585
- */
586
- interface HavenBalanceCoverage {
587
- /**
588
- * true: the chain reports the agent's account holds at least
589
- * `checkedAmountAtomic` of the token. false: the chain read succeeded and
590
- * reports LESS — tell the user funds are missing rather than retrying.
591
- * null: the chain read failed — unverifiable, never treated as absence.
592
- */
593
- covered: boolean | null;
594
- /** Present only when `covered` is null: why the chain read could not answer. */
595
- coverageError?: string;
596
- chainId: number;
597
- tokenAddress: string;
598
- tokenSymbol: string;
599
- /** The amount the coverage question was asked about, in atomic units. */
600
- checkedAmountAtomic: string;
601
- /**
602
- * Context, AUTHORITY not holdings: the agent's remaining spend authority
603
- * for the requested token, in atomic units — the same derivation
604
- * {@link HavenAllowanceSummary} reports (`onchain.remaining`; the #1090
605
- * derivation, the #1145 enforcer read). Zero when no active budget row
606
- * names the token. Compare it with `covered`, never instead of it.
607
- */
608
- budgetRemainingAtomic: string;
609
- /**
610
- * Provenance of `budgetRemainingAtomic` (#1319, same semantics as
611
- * {@link HavenAllowance.onchain.remainingIsFromChain}): true when the
612
- * budget figure came from a live enforcer read, false when it fell back
613
- * to the configured budget. Absent when no budget row existed for the
614
- * token (nothing was read).
615
- */
616
- budgetRemainingIsFromChain?: boolean;
617
- }
618
- /**
619
- * Affirmative spend-readiness for the authenticated agent, derived from the raw
620
- * agent status plus the remaining spend authority the backend reports per rail
621
- * (the on-chain AllowanceModule on the legacy rail; the active budget
622
- * delegation on the delegation rail — #1135):
623
- * - `ready` — active and at least one token has remaining spend authority.
624
- * - `needs_approval`— active but no remaining spend authority to auto-spend.
625
- * The over-budget outcome differs by rail: on the legacy
626
- * AllowanceModule rail the payment is queued for the wallet
627
- * owner to approve in Haven; on the delegation rail there is
628
- * NO approval queue — an over-budget redemption reverts
629
- * on-chain, so the owner must grant or raise the budget in
630
- * Haven before the agent can pay.
631
- * - `revoked` — the agent's status is not `active`; nothing auto-executes.
632
- *
633
- * Note: a hard-paused/disabled credential is rejected by the API before this
634
- * call returns, so it surfaces as an API error rather than `revoked`. `revoked`
635
- * is reached when the request authenticates but the agent status is non-active.
636
- *
637
- * Wallet token balance is intentionally NOT folded in here: the on-chain
638
- * remaining allowance is the gate Haven enforces, and insufficient wallet
639
- * funding surfaces at pay time as INSUFFICIENT_FUNDS.
640
- */
641
- type HavenAgentReadiness = 'ready' | 'needs_approval' | 'revoked';
642
- /**
643
- * Compact, agent-facing per-token spend authority for the bootstrap summary.
644
- *
645
- * #3128: a deliberately DIFFERENT view of the same allowance as
646
- * {@link HavenAllowance} — flat, no `onchain` block, no spent/nonce/reset-time
647
- * detail — but never a disjoint one: every field here is present on or
648
- * derived from the {@link HavenAllowance} with the same `id`, and
649
- * `remainingAtomic` / `remainingDisplay` equal that allowance's
650
- * `onchain.remaining` / `remainingDisplay` byte for byte (pinned by test). A
651
- * client that wants the id AND a display amount can therefore use either
652
- * read alone.
653
- */
654
- interface HavenAgentAllowanceSummary {
655
- /** #3128: the {@link HavenAllowance.id} this row summarises. */
656
- id: string;
657
- tokenSymbol: string;
658
- /** #3128: the {@link HavenAllowance.tokenAddress}. */
659
- tokenAddress: string;
660
- /** Live on-chain remaining allowance in atomic units. */
661
- remainingAtomic: string;
662
- /** Human-readable remaining, e.g. "4.96 USDC". */
663
- remainingDisplay: string;
664
- /** Configured allowance amount (atomic) the owner granted. */
665
- configuredAmount: string;
666
- resetPeriodMin: number;
667
- isResetPending: boolean;
668
- }
669
- /**
670
- * One-shot "am I ready?" bootstrap: identity + live spend authority + a
671
- * readiness signal, so an agent can answer "who am I and can I pay right now"
672
- * from a single call at session start. Superset of {@link HavenAgent}.
673
- */
674
- interface HavenAgentSummary extends HavenAgent {
675
- /**
676
- * @deprecated Use {@link HavenAgentSummary.spend_authority_readiness} —
677
- * same value, honest name. This signal covers hosted identity + on-chain
678
- * spend authority ONLY; it says nothing about the LOCAL signer, which the
679
- * hosted side cannot see (verify via a signer tool or connect --doctor).
680
- * Kept as an alias; removal earliest after the next release train (#1590).
681
- */
682
- readiness: HavenAgentReadiness;
683
- /**
684
- * Spend-authority readiness: hosted identity + on-chain remaining spend
685
- * authority. Deliberately named for what it covers — the LOCAL signer's
686
- * availability is NOT included and must be verified separately (a signer
687
- * tool call, or the connector's `--doctor`, whose exact command this build
688
- * renders from `HAVEN_CONNECTOR_CHANNEL` — see `connector-channel.ts`).
689
- */
690
- spend_authority_readiness: HavenAgentReadiness;
691
- allowances: HavenAgentAllowanceSummary[];
692
- }
693
- /**
694
- * #2960 — one party vocabulary for "who paid" a Haven payment, additive
695
- * alongside every existing lone `payer*`/`*Address` field (same discipline
696
- * as the #2907 `safe`/`account` dual-emit, except these four are DISTINCT
697
- * addresses, not same-value twins of one old field).
698
- */
699
- interface PaymentParties {
700
- treasuryAccount: string | null;
701
- delegate: string | null;
702
- delegateAccount: string | null;
703
- merchant: string | null;
704
- }
705
- /** @internal wire shape of {@link PaymentParties}. */
706
- interface RawPaymentParties {
707
- treasury_account: string | null;
708
- delegate: string | null;
709
- delegate_account: string | null;
710
- merchant: string | null;
711
- }
712
- interface HavenPaymentReceipt {
713
- id: string;
714
- paymentId: string;
715
- paymentIntentId?: string | null;
716
- approvalRequestId?: string | null;
717
- rail: string;
718
- proofStatus: string;
719
- /**
720
- * @deprecated (#2998) meaning depends on the settlement scheme — the
721
- * account → delegate funding transaction on eip3009, the (only) settlement
722
- * transaction on erc7710. Prefer {@link fundingTxHash} / {@link settlementTxHash}, which
723
- * name which is which.
724
- */
725
- txHash: string;
726
- /** The account → delegate funding transaction, relayed by Haven (#2998); null on erc7710 (no funding leg) and on retired mpp-rail rows. */
727
- fundingTxHash: string | null;
728
- /**
729
- * The delegate → merchant settlement transaction (#2998). Trust level differs
730
- * by scheme: on erc7710 it is `txHash` itself and Haven VERIFIED it on-chain
731
- * before the receipt existed; on eip3009 it is the merchant's claim as relayed
732
- * (PAYMENT-RESPONSE), NOT verified on-chain by Haven — cite it as such.
733
- */
734
- settlementTxHash: string | null;
735
- chainId: number;
736
- resourceUrl: string;
737
- merchantAddress: string | null;
738
- payerAddress: string;
739
- /** #2960: additive alongside `payerAddress` above (`parties.treasury_account` only). */
740
- parties?: PaymentParties;
741
- settlementAddress: string;
742
- tokenSymbol: string;
743
- tokenAddress: string;
744
- amountRaw: string;
745
- amount: string;
746
- challengeId: string | null;
747
- idempotencyKey: string | null;
748
- challengePayload?: Record<string, unknown> | null;
749
- selectedPayment?: Record<string, unknown> | null;
750
- paymentProofHeaderName: string | null;
751
- protocolReceiptHeaderName: string | null;
752
- /**
753
- * #3125 — the merchant's `PAYMENT-RESPONSE` object relayed VERBATIM:
754
- * opaque, unvalidated, unverified, MERCHANT-CONTROLLED third-party data.
755
- * Haven neither authors nor verifies anything inside it, including
756
- * `protocolReceiptPayload.payer` —
757
- * that `payer` is the merchant's claim, NOT Haven's record, and is not
758
- * {@link payerAddress} (Haven's own, authoritative; field observation
759
- * 2026-09-18: the two held different addresses on every row read). For who
760
- * paid, read `parties` ({@link PaymentParties}) — `treasuryAccount`,
761
- * `delegate`, `delegateAccount`, `merchant` are Haven-derived and
762
- * authoritative; anything inside this object is not.
763
- *
764
- * Deliberately NOT namespaced or key-prefixed on the wire (#3125): the
765
- * relay must stay the merchant's object verbatim (its `transaction` key
766
- * feeds `settlementTxHash`), and prefixing the envelope could not prefix
767
- * the merchant-controlled keys inside it — the `payer` collision lives
768
- * there, so provenance is made legible at the read surfaces instead (this
769
- * comment and the tool descriptions).
770
- */
771
- protocolReceiptPayload?: Record<string, unknown> | null;
772
- merchantStatus: number | null;
773
- confirmedAt: string | null;
774
- createdAt: string;
775
- updatedAt: string;
776
- }
777
- /**
778
- * How long this SDK waits for an on-chain confirmation before it stops
779
- * waiting (#1756).
780
- *
781
- * Lives here rather than in `client.ts` so the payment-confirmation poller
782
- * and the delegate sweep share ONE number instead of forking it. The SDK's
783
- * other chain waits are already bounded (`waitForFundingTx` at 30 s), so a
784
- * fourth independently chosen literal is exactly the drift this constant
785
- * exists to prevent.
786
- */
787
- declare const DEFAULT_CONFIRMATION_TIMEOUT_MS = 90000;
788
- /**
789
- * Whether a sweep transfer was observed to confirm (#1756).
790
- *
791
- * The distinction is the point: `unconfirmed` means the transfer was
792
- * BROADCAST and may still land, which is neither success nor failure. It must
793
- * never be collapsed into either — reporting a still-pending transaction as
794
- * done, or as failed, are the same defect in opposite directions.
795
- */
796
- type SweepConfirmation =
797
- /** A receipt was observed. The funds are in the Safe. */
798
- 'confirmed'
799
- /**
800
- * Broadcast, but no receipt within `DEFAULT_CONFIRMATION_TIMEOUT_MS` (or the
801
- * node returned no receipt). The transaction is still in the mempool and may
802
- * mine at any time. `txHash` is the broadcast hash — check it on the
803
- * explorer before re-running the sweep, and expect a re-run to find nothing
804
- * stranded if it has since landed.
805
- */
806
- | 'unconfirmed';
807
- /** One transferred asset in a delegate sweep. */
808
- interface SweepEntry {
809
- /** 'USDC' or 'ETH' */
810
- asset: string;
811
- /** Human-readable amount swept (e.g. "0.12") */
812
- amount: string;
813
- /** Atomic amount swept */
814
- amountAtomic: string;
815
- /**
816
- * Transaction hash of the sweep transfer.
817
- *
818
- * The RECEIPT hash when `confirmation` is `confirmed`; the BROADCAST hash
819
- * when it is `unconfirmed` — which is the whole reason the sweep returns
820
- * instead of throwing on a deadline, since this hash is the only thing that
821
- * lets a user recover the transfer by hand (#1756).
822
- */
823
- txHash: string;
824
- /** Block explorer URL for the tx */
825
- explorerUrl: string;
826
- /**
827
- * Did this transfer confirm on-chain within the deadline? (#1756)
828
- *
829
- * `unconfirmed` entries have MOVED NOTHING YET and may still move. Do not
830
- * report a sweep as complete without checking this on every entry.
831
- */
832
- confirmation: SweepConfirmation;
833
- }
834
- /** Result of a `sweepDelegate()` call. */
835
- interface SweepResult {
836
- /** Address funds were swept FROM */
837
- fromAddress: string;
838
- /** Address funds were swept TO (always the originating Safe) */
839
- toAddress: string;
840
- /** Chain the sweep occurred on */
841
- chainId: number;
842
- /** One entry per transferred asset. Empty when nothing was stranded. */
843
- transfers: SweepEntry[];
844
- /**
845
- * True when ANY entry is `unconfirmed` — i.e. the sweep broadcast something
846
- * it could not confirm within the deadline (#1756).
847
- *
848
- * Derived from `transfers`, and present anyway because the consumer most
849
- * likely to misread this result is an LLM reading the JSON of the
850
- * `haven_sweep_delegate` tool, which will otherwise see a populated
851
- * `transfers` array and report the money as recovered.
852
- */
853
- unconfirmed: boolean;
854
- }
855
- type PaymentStateKind = 'payment_intent' | 'approval_request';
856
- interface AgentPaymentEnumSchema {
857
- type: 'string';
858
- enum: readonly string[];
859
- description: string;
860
- 'x-enumDescriptions': Record<string, string>;
861
- }
862
- declare const AgentPaymentPhase: {
863
- /** The agent must sign and submit the prepared payment before Haven can relay it. */
864
- readonly AgentSignatureRequired: "agent_signature_required";
865
- /** Haven has received the signed payment and the agent should poll for confirmation. */
866
- readonly PaymentSubmitted: "payment_submitted";
867
- /** The direct payment is confirmed; the agent does not need to do more for this payment id. */
868
- readonly PaymentConfirmed: "payment_confirmed";
869
- /**
870
- * #2115: RETIRED wire value — no live rail produces it. It described the
871
- * Safe rail's approval queue, which no longer exists. Kept so a stored value
872
- * still typechecks; see `AgentPaymentPhaseDescriptions` below for the
873
- * agent-visible wording, which this comment used to contradict.
874
- */
875
- readonly UserApprovalRequired: "user_approval_required";
876
- /** #2115: RETIRED wire value — no live rail produces it. Stop and tell the user. */
877
- readonly UserExecutionRequired: "user_execution_required";
878
- /** #2115: RETIRED wire value — no live rail produces it. Stop and tell the user. */
879
- readonly WaitingForAdditionalApprovals: "waiting_for_additional_approvals";
880
- /** The Haven funding leg was sent; the agent can continue the merchant/protocol leg. */
881
- readonly FundingSent: "funding_sent";
882
- /** The payment was rejected and cannot proceed; the agent should stop and tell the user. */
883
- readonly Rejected: "rejected";
884
- /** The payment expired before completion. */
885
- readonly Expired: "expired";
886
- /** Haven could not complete the payment; the agent should stop and surface the failure. */
887
- readonly Failed: "failed";
888
- /**
889
- * Pre-flight check determined the delegate's existing balance plus the
890
- * remaining on-chain budget cannot cover the requested amount, so no
891
- * payment intent was created. The account must be funded or the agent's
892
- * budget raised before retrying — #2115: the old wording contrasted this
893
- * with `UserApprovalRequired` as if that were a live alternative, and named
894
- * the retired rail's Safe and per-token allowance as the fix.
895
- */
896
- readonly InsufficientFunds: "insufficient_funds";
897
- /**
898
- * Haven's funding leg (account → delegate, the #946 EIP-3009 bridge)
899
- * confirmed on-chain, but the merchant rejected the x402 retry. The delegate
900
- * wallet may hold stranded USDC that was never settled to the merchant. The
901
- * agent should stop, tell the user, and wait for the sweep flow to reclaim
902
- * the funds.
903
- */
904
- readonly FundedButUnsettled: "funded_but_unsettled";
905
- };
906
- type AgentPaymentPhase = (typeof AgentPaymentPhase)[keyof typeof AgentPaymentPhase];
907
- declare const AgentPaymentNextAction: {
908
- /** Sign with the delegate key and submit the payment to Haven. */
909
- readonly SignAndSubmitPayment: "sign_and_submit_payment";
910
- /** Poll getPaymentStatus later using this payment id. */
911
- readonly CheckStatusLater: "check_status_later";
912
- /** No further agent action is required for this payment id. */
913
- readonly None: "none";
914
- /**
915
- * #2115: RETIRED wire value — no live rail produces it and nothing maps to
916
- * it. Stop and tell the user rather than polling; no approval will arrive.
917
- */
918
- readonly WaitForUserApproval: "wait_for_user_approval";
919
- /** #2115: RETIRED wire value — no live rail produces it. Stop and tell the user rather than polling. */
920
- readonly WaitForUserToCompletePayment: "wait_for_user_to_complete_payment";
921
- /** Resume this payment id and retry the original x402 request with the merchant payment header. */
922
- readonly RetryOriginalX402Request: "retry_original_x402_request";
923
- /** Stop retrying this payment and tell the user what happened. */
924
- readonly StopAndTellUser: "stop_and_tell_user";
925
- /** Ask again only if the user still wants the payment after expiry. */
926
- readonly RequestAgainIfUserStillWantsIt: "request_again_if_user_still_wants_it";
927
- /** #1307: retry the SAME tool call, supplying the explicit context fields the server could not rehydrate. */
928
- readonly RetryWithExplicitContext: "retry_with_explicit_context";
929
- /**
930
- * The x402 funding/quote window expired. Re-quote the same logical merchant
931
- * operation with the same idempotency key to stay double-charge-safe.
932
- */
933
- readonly PaymentWindowExpired: "payment_window_expired";
934
- /**
935
- * Stop and tell the user that the originating account needs to be funded or
936
- * the agent's per-token allowance needs to be raised before the payment
937
- * can succeed. A user approval will not fix this state on its own.
938
- *
939
- * #2914: the account-vocabulary spelling, and the only one — the
940
- * pre-#2907 `fund_safe_or_raise_allowance` wire value (and the
941
- * `AgentPaymentNextActionAccountAlias` seam #2908 added to bridge it) are
942
- * retired along with the rest of the #2908 compatibility window.
943
- */
944
- readonly FundAccountOrRaiseAllowance: "fund_account_or_raise_allowance";
945
- /**
946
- * The delegate wallet may hold funds that were sent from the Safe but never
947
- * settled to the merchant. The wallet owner should initiate a sweep to
948
- * return those funds to the originating Safe.
949
- */
950
- readonly SweepStrandedFunds: "sweep_stranded_funds";
951
- /**
952
- * #2970: a `submitted` erc7710 x402 intent whose settlement window has
953
- * passed with no on-chain settlement evidence Haven could verify. Distinct
954
- * from {@link CheckStatusLater}, which this REPLACES once the window is
955
- * past — but it is not futile: Haven's settlement sweep (120s tick) scans
956
- * each candidate over its own window plus a 120s clock-skew allowance, so
957
- * it can still attribute the settlement for a short while after this value
958
- * first appears. Poll {@link CheckStatusLater}'s tool
959
- * (`haven_get_payment_status`) once more, roughly two minutes later; if it
960
- * still shows no evidence, tell the user the goods were delivered but
961
- * Haven holds no verified settlement evidence for this payment. If the
962
- * agent holds the merchant's real settlement transaction hash (from
963
- * `PAYMENT-RESPONSE`'s `transaction` field, or a prior settle/complete
964
- * result's `settlement_tx_hash`), report it with the hosted
965
- * `haven_report_settlement_evidence` tool instead of waiting —
966
- * `haven_report_x402_outcome` takes no hash and refuses a non-`confirmed`
967
- * intent.
968
- */
969
- readonly AwaitingSettlementEvidence: "awaiting_settlement_evidence";
970
- };
971
- type AgentPaymentNextAction = (typeof AgentPaymentNextAction)[keyof typeof AgentPaymentNextAction];
972
- declare const AgentPaymentFailureCode: {
973
- /** A merchant-authoritative x402 price exceeds the caller's pre-funding max_amount cap. */
974
- readonly PriceExceedsMax: "PRICE_EXCEEDS_MAX";
975
- /** The x402 funding/quote window expired before the signer or hosted settle step could finish. */
976
- readonly PaymentWindowExpired: "PAYMENT_WINDOW_EXPIRED";
977
- /** The merchant rejected the paid retry. On eip3009 the funding leg had succeeded (sweep);
978
- * on erc7710 there is no funding leg — nothing to sweep, follow the message (#2983). */
979
- readonly MerchantRejectedAfterFunding: "MERCHANT_REJECTED_AFTER_FUNDING";
980
- /** #1300 review: funding is on-chain but the merchant never ANSWERED the
981
- * paid retry within the timeout. NOT proof of rejection — the merchant
982
- * may still settle late, so the guidance is verify-then-act. On eip3009
983
- * the funding leg had succeeded (verify-then-sweep); on erc7710 there is
984
- * no funding leg — nothing to sweep, follow the message (#3000). */
985
- readonly MerchantUnresponsiveAfterFunding: "MERCHANT_UNRESPONSIVE_AFTER_FUNDING";
986
- /**
987
- * #1307: the caller omitted merchant_url/tool_name (asking Haven to
988
- * rehydrate the stored MCP merchant-call context by payment_id), but no
989
- * usable context was stored for this intent — either it was never an
990
- * MCP-tool quote, or the stored context is incomplete. The fallback is
991
- * mechanical: re-send merchant_url, tool_name, arguments, and
992
- * mcp_transport explicitly (the version-skew path).
993
- */
994
- readonly MerchantCallContextUnavailable: "MERCHANT_CALL_CONTEXT_UNAVAILABLE";
995
- /**
996
- * #1351: the caller supplied BOTH the atomic `max_amount` and the
997
- * human-denominated `max_amount_human` cap for one purchase. Haven refuses
998
- * to guess which the user meant — the two differ by a factor of 10^decimals,
999
- * so picking wrong is exactly the silent-overspend this cap exists to
1000
- * prevent. Rejected before any merchant probe, funding intent, or signature.
1001
- */
1002
- readonly AmbiguousMaxAmount: "AMBIGUOUS_MAX_AMOUNT";
1003
- /**
1004
- * #1351: a human-denominated cap was supplied, but it cannot be converted to
1005
- * atomic units against THIS quote — either the quote's asset has no known
1006
- * decimals on its network, or the cap carries more fraction digits than the
1007
- * asset can represent (truncating it would silently change the user's cap).
1008
- * The fallback is the exact atomic `max_amount`.
1009
- */
1010
- readonly MaxAmountUnconvertible: "MAX_AMOUNT_UNCONVERTIBLE";
1011
- /**
1012
- * #2979: the merchant answered a `tools/call` probe with its own
1013
- * machine-readable "cannot settle right now" refusal (HTTP 503,
1014
- * `{ error: 'merchant_not_ready', reason_code, ... }`) instead of a 402
1015
- * challenge — e.g. its settlement wallet is out of gas. No 402 was ever
1016
- * issued and no payment was created; this is honest and (per
1017
- * `retry_after_s`, when present) usually transient, unlike a permanent
1018
- * endpoint miss.
1019
- */
1020
- readonly MerchantNotReady: "MERCHANT_NOT_READY";
1021
- };
1022
- type AgentPaymentFailureCode = (typeof AgentPaymentFailureCode)[keyof typeof AgentPaymentFailureCode];
1023
- /**
1024
- * Stable rail identifier carried on Haven agent payment responses and resume
1025
- * state.
1026
- *
1027
- * Two layers of vocabulary share this enum because both reach the wire:
1028
- *
1029
- * - **Categorical rails** identify the rail family and are used as the
1030
- * `PaymentResumeState` discriminator: `direct`, `x402` (`mpp` remains a
1031
- * valid categorical VALUE on historical status reads, but #1328 retired
1032
- * the `MppResumeState` variant that used to carry it — the mpp_demo
1033
- * client resume flow no longer exists).
1034
- * - **Granular rails** identify the specific protocol the backend persists
1035
- * and returns on response bodies: `mpp_demo`, `mpp_crypto`,
1036
- * `stripe_deposit`, `spt`. `x402` doubles as both categorical and
1037
- * granular.
1038
- *
1039
- * Consumers reading the top-level `rail` field on a payment status response
1040
- * should treat any `mpp*` value as the MPP family — this still applies to
1041
- * historical `mpp_demo` rows, which remain readable.
1042
- */
1043
- declare const AgentPaymentRail: {
1044
- /** Standard Haven payment from the user's Safe through an approved delegate allowance. */
1045
- readonly Direct: "direct";
1046
- /** x402 HTTP 402 payment flow with a Haven funding leg and merchant retry leg. */
1047
- readonly X402: "x402";
1048
- /** Machine Payment Protocol family — categorical value used as a resume-state discriminator. */
1049
- readonly Mpp: "mpp";
1050
- /** Haven internal MPP demo rail. Not for production traffic. */
1051
- readonly MppDemo: "mpp_demo";
1052
- /** Crypto-settled MPP rail. */
1053
- readonly MppCrypto: "mpp_crypto";
1054
- /** Stripe-deposit-backed MPP rail. */
1055
- readonly StripeDeposit: "stripe_deposit";
1056
- /** Stripe Payment Token MPP rail. */
1057
- readonly Spt: "spt";
1058
- };
1059
- type AgentPaymentRail = (typeof AgentPaymentRail)[keyof typeof AgentPaymentRail];
1060
- type PaymentPhase = AgentPaymentPhase;
1061
- type PaymentNextAction = AgentPaymentNextAction;
1062
- 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")[];
1063
- 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")[];
1064
- 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")[];
1065
- declare const AGENT_PAYMENT_RAIL_VALUES: ("x402" | "mpp_demo" | "mpp_crypto" | "stripe_deposit" | "spt" | "direct" | "mpp")[];
1066
- declare const AgentPaymentPhaseDescriptions: Record<AgentPaymentPhase, string>;
1067
- declare const AgentPaymentNextActionDescriptions: Record<AgentPaymentNextAction, string>;
1068
- declare const AgentPaymentFailureCodeDescriptions: Record<AgentPaymentFailureCode, string>;
1069
- /**
1070
- * #1308: machine-readable warning codes carried in the `warnings` array on
1071
- * x402 MCP tool responses. Warnings are ADVISORY — they never replace a
1072
- * refusal, and existing failure codes stay authoritative for errors. The
1073
- * legacy `cap_warning` string field is kept for compatibility; the structured
1074
- * entry carries the same message under MISSING_MAX_AMOUNT.
1075
- */
1076
- declare const AgentPaymentWarningCode: {
1077
- /** No max_amount cap was supplied — the live quoted price was accepted as-is. */
1078
- readonly MissingMaxAmount: "MISSING_MAX_AMOUNT";
1079
- /** The signing window closes soon; sign promptly or re-quote with the same idempotency key. */
1080
- readonly QuoteExpiresSoon: "QUOTE_EXPIRES_SOON";
1081
- /** The merchant URL was resolved via discovery — pass the RESOLVED url forward. */
1082
- readonly MerchantUrlDiscovered: "MERCHANT_URL_DISCOVERED";
1083
- /**
1084
- * #1306: the catalog's last-verified price_atomic differs from the LIVE
1085
- * merchant quote for a guided catalog purchase. The catalog price is only
1086
- * ever indicative; the live quote in the same response is authoritative.
1087
- */
1088
- readonly CatalogPriceDiffers: "CATALOG_PRICE_DIFFERS";
1089
- /**
1090
- * #1306: the rail-aware allowance/budget pre-check could not be read (RPC
1091
- * failure, etc). `sufficient` is reported as null rather than a fabricated
1092
- * true/false — the on-chain policy remains the actual gate either way.
1093
- */
1094
- readonly AllowanceCheckUnavailable: "ALLOWANCE_CHECK_UNAVAILABLE";
1095
- /**
1096
- * #1319: the delegation-rail read itself SUCCEEDED, but the remaining
1097
- * figure it returned is the #1145 fallback (the full configured budget)
1098
- * rather than a live ERC20PeriodTransferEnforcer read — `sufficient` is a
1099
- * real true/false, just computed from an optimistic number. Distinct from
1100
- * {@link AgentPaymentWarningCode.AllowanceCheckUnavailable}, which fires
1101
- * when the read failed outright and `sufficient` degrades to null. The
1102
- * on-chain policy re-checks at redemption either way; this only says the
1103
- * guidance shown here may be optimistic.
1104
- */
1105
- readonly AllowanceReadOptimistic: "ALLOWANCE_READ_OPTIMISTIC";
1106
- /**
1107
- * #2991: the quote tools' `expected_settlement_scheme` prediction of what
1108
- * `haven_prepare_catalog_purchase` / `haven_pay_mcp_tool` will actually
1109
- * select could not be computed — the agent's execution rail could not be
1110
- * read from Haven, so `expected_settlement_scheme` is `null` rather than a
1111
- * guess. `accepted_scheme` (the merchant's offer) is unaffected.
1112
- */
1113
- readonly X402SchemeUnknown: "X402_SCHEME_UNKNOWN";
1114
- /**
1115
- * #2968: the merchant answered 200 and handed over goods, but Haven holds NO
1116
- * on-chain evidence that the payment moved. `settled: false` beside this code
1117
- * is not a failure — it is the absence of proof, and the two must travel
1118
- * together so an agent can tell "the user has the goods" apart from "the
1119
- * money moved". Carries the intent's `expires_at`: after that instant the
1120
- * settlement can no longer land at all.
1121
- */
1122
- readonly SettlementUnconfirmed: "SETTLEMENT_UNCONFIRMED";
1123
- };
1124
- type AgentPaymentWarningCode = (typeof AgentPaymentWarningCode)[keyof typeof AgentPaymentWarningCode];
1125
- interface AgentPaymentWarning {
1126
- code: AgentPaymentWarningCode;
1127
- message: string;
1128
- }
1129
- /**
1130
- * #1308: the structured next-step contract on x402 MCP tool responses. It
1131
- * EXTENDS the existing taxonomy — `next_action` values come from
1132
- * AgentPaymentNextAction, never a parallel vocabulary. `next_arguments`
1133
- * carries the small, literally-usable arguments; bulky pass-through fields
1134
- * (payment_required) are named in `reason` and taken from the SAME response.
1135
- */
1136
- interface AgentNextStep {
1137
- /** From `AgentPaymentNextAction`. */
1138
- next_action: AgentPaymentNextAction;
1139
- /**
1140
- * Claude-family namespaced tool name for the next call
1141
- * (`mcp__<server>__<tool>`), when one exists.
1142
- *
1143
- * **Namespaced with the DEFAULT server names**, which is the most the hosted
1144
- * server can know: local server names are the client's own config and never
1145
- * reach Haven. Two runtimes are already not the default — Codex names servers
1146
- * by config key (`haven`, `haven_signer`), and a connector run with
1147
- * `--name <slug>` wires `haven-<slug>` / `haven-signer-<slug>` (#1694). On
1148
- * either, this field and `next_tool_server` name a server the client does not
1149
- * have. Prefer {@link AgentNextStep.next_tool_server_role} plus
1150
- * {@link AgentNextStep.next_tool_name} whenever your servers are not the
1151
- * default pair; see #2550.
1152
- */
1153
- next_tool?: string;
1154
- /**
1155
- * The server half of `next_tool`, unprefixed — `haven` or `haven-signer`.
1156
- * Carries the same default-name caveat as `next_tool` (#1588, #2550).
1157
- */
1158
- next_tool_server?: string;
1159
- /** The bare tool name, callable on whichever server plays the role below. */
1160
- next_tool_name?: string;
1161
- /**
1162
- * Which of the CLIENT'S OWN servers to call (#2550). Runtime-neutral, and
1163
- * the field to resolve against when your server names are not the defaults —
1164
- * it names a role rather than a name the hosted server had to guess.
1165
- */
1166
- next_tool_server_role?: 'hosted' | 'signer';
1167
- /** Small literal arguments for next_tool. Bulky fields are referenced by reason. */
1168
- next_arguments?: Record<string, unknown>;
1169
- /**
1170
- * #3101 (epic #3105, decision 3): present exactly when `next_tool` is
1171
- * absent — why no tool is named (the payment id is unknown, nothing is left
1172
- * to do, the arguments could not be built). `next_tool` is never null.
1173
- */
1174
- next_tool_omitted_reason?: string;
1175
- /** False when the agent should stop and involve the user before continuing. */
1176
- safe_to_continue: boolean;
1177
- reason: string;
1178
- }
1179
- /**
1180
- * #1349: compact, Haven-generated reporting evidence for a completed x402
1181
- * merchant purchase. `status`, money fields, merchant endpoint/address, and
1182
- * funding transaction come from Haven payment state; `product` and
1183
- * `invoice_id` are optional merchant-supplied display metadata. The raw
1184
- * merchant result remains separate evidence and MUST NOT be used to infer
1185
- * settlement status.
1186
- */
1187
- interface AgentPurchaseSummary {
1188
- /** Set only after Haven has completed the funding and merchant-settlement flow. */
1189
- status: 'settled';
1190
- product: string | null;
1191
- amount: string | null;
1192
- amount_atomic: string | null;
1193
- asset: string | null;
1194
- network: string | null;
1195
- merchant: {
1196
- address: string | null;
1197
- resource_url: string | null;
1198
- };
1199
- /** Merchant-supplied identifier, or null when the merchant did not supply one. */
1200
- invoice_id: string | null;
1201
- funding_tx_hash: string | null;
1202
- /** Optional merchant receipt reference parsed from PAYMENT-RESPONSE; not Haven settlement proof. */
1203
- settlement_tx_hash: string | null;
1204
- /** Same read-only allowance block returned at the top level, or null when unavailable. */
1205
- allowance: PostPurchaseAllowanceSummary | null;
1206
- }
1207
- /** #1308: compact reporting summary — what the agent tells the user. */
1208
- interface AgentPaymentSummary {
1209
- payment_id: string;
1210
- status: string;
1211
- amount?: string;
1212
- amount_atomic?: string;
1213
- token?: string;
1214
- network?: string;
1215
- expires_at?: string;
1216
- product?: string;
1217
- /**
1218
- * Default reporting contract for a successful `haven_settle_mcp_tool` call.
1219
- * The merchant's raw `result` remains available separately as advanced
1220
- * evidence; do not parse it to determine whether a payment settled.
1221
- */
1222
- purchase_summary?: AgentPurchaseSummary;
1223
- }
1224
- declare const AgentPaymentRailDescriptions: Record<AgentPaymentRail, string>;
1225
- declare const AgentPaymentPhaseSchema: AgentPaymentEnumSchema;
1226
- declare const AgentPaymentNextActionSchema: AgentPaymentEnumSchema;
1227
- declare const AgentPaymentFailureCodeSchema: AgentPaymentEnumSchema;
1228
- declare const AgentPaymentRailSchema: AgentPaymentEnumSchema;
1229
- interface PaymentStatusResult {
1230
- paymentId: string;
1231
- kind: PaymentStateKind;
1232
- rail: string;
1233
- status: PaymentStatus | string;
1234
- phase: PaymentPhase;
1235
- nextAction: PaymentNextAction;
1236
- amount: string;
1237
- token: string;
1238
- resourceUrl: string | null;
1239
- merchantAddress: string | null;
1240
- /** Delegate EOA captured on the payment intent when it was created. */
1241
- payerAddress?: string | null;
1242
- /** #2960: additive alongside `payerAddress` above (`parties.delegate` only). */
1243
- parties?: PaymentParties;
1244
- txHash: string | null;
1245
- expiresAt: string;
1246
- chainId: number;
1247
- message: string;
1248
- /** Platform fee surfaced so it's never silently collected (#386). */
1249
- fee?: PaymentFee | null;
1250
- amountAtomic?: string | null;
1251
- asset?: string | null;
1252
- network?: string | null;
1253
- description?: string | null;
1254
- idempotencyKey?: string | null;
1255
- x402?: {
1256
- amountAtomic: string | null;
1257
- asset: string | null;
1258
- network: string | null;
1259
- resourceUrl: string | null;
1260
- merchantAddress: string | null;
1261
- description: string | null;
1262
- idempotencyKey: string | null;
1263
- };
1264
- mpp?: {
1265
- amountAtomic: string | null;
1266
- asset: string | null;
1267
- network: string | null;
1268
- resourceUrl: string | null;
1269
- merchantAddress: string | null;
1270
- description: string | null;
1271
- idempotencyKey: string | null;
1272
- challengeId: string | null;
1273
- };
1274
- }
1275
- /**
1276
- * Result of an erc7710 direct settlement (#1454).
1277
- *
1278
- * Deliberately NOT an `X402Receipt`. A 3009 receipt describes a completed
1279
- * two-leg payment — funding tx included — whereas here nothing has settled yet
1280
- * when this returns: the merchant redeems the delegation chain when the caller
1281
- * retries with the header. Reusing the receipt type would let a caller read
1282
- * `txHash` as "paid" on a payment that has not moved a cent.
1283
- */
1284
- interface X402Erc7710Settlement {
1285
- paymentId: string;
1286
- /**
1287
- * Pass verbatim as the `PAYMENT-SIGNATURE` header on the merchant retry —
1288
- * that name ALONE. erc7710 is always x402 v2, and this header carries the
1289
- * delegation chain, so also sending the legacy `X-PAYMENT` overflows the
1290
- * merchant's header limit (HTTP 431, #2341).
1291
- */
1292
- paymentHeader: string;
1293
- /** The merchant address the child delegation is pinned to. */
1294
- merchantPayTo: string;
1295
- amountAtomic: string;
1296
- asset: string;
1297
- network: string;
1298
- /** Facilitators the child is redeemable by, when the merchant advertised any. */
1299
- facilitatorAddresses: string[] | null;
1300
- }
1301
- /** @internal */
1302
- /** One payable service in Haven's merchant catalog (epic #1717). */
1303
- interface HavenCatalogEntry {
1304
- id: string;
1305
- name: string;
1306
- description: string;
1307
- category: string;
1308
- resourceUrl: string;
1309
- rail: 'x402' | 'mpp';
1310
- protocol: 'http' | 'mcp';
1311
- toolName: string | null;
1312
- toolArguments: Record<string, unknown> | null;
1313
- priceDisplay: string | null;
1314
- priceAtomic: string | null;
1315
- asset: string | null;
1316
- network: string | null;
1317
- status: 'active' | 'degraded' | 'delisted';
1318
- verifiedAt: string | null;
1319
- /**
1320
- * Where the entry came from. `operator` = curated in migrations/scripts
1321
- * (the operator vouches for the listing; the catalog refresh probe still
1322
- * checks the endpoint, see `verifiedPayable`). `ingestion` = submitted
1323
- * through the Verified Payable Directory and passed domain-ownership proof
1324
- * plus the read-only quote probe.
1325
- */
1326
- source: 'operator' | 'ingestion';
1327
- /** True only for `ingestion` entries — the one ownership claim. See the epic's trust claim (never merchant honesty or quality). */
1328
- domainVerified: boolean;
1329
- /**
1330
- * True when Haven watched this endpoint answer a live quote (#2978): the
1331
- * directory probe for `ingestion` rows, the periodic catalog refresh probe
1332
- * for `operator` rows (`status === 'active'` with `verifiedAt` set). False
1333
- * for a degraded row of either source. `discoverTools({ verified:
1334
- * 'verified' })` filters on this field, not on `source`.
1335
- */
1336
- verifiedPayable: boolean;
1337
- /**
1338
- * The merchant this entry belongs to (#3078). OPTIONAL on purpose: an
1339
- * installed SDK may face a backend that predates the merchant layer, and
1340
- * `discoverTools` must keep working against it — the field is absent, not
1341
- * null, in that case.
1342
- */
1343
- merchant?: HavenCatalogMerchant;
1344
- }
1345
- /** A catalog entry's merchant as the wire carries it (#3078). */
1346
- interface HavenCatalogMerchant {
1347
- id: string;
1348
- slug: string;
1349
- name: string;
1350
- /** `coming_soon` never reaches an entry in practice (a prospect has no offers). */
1351
- listingStatus: 'live' | 'coming_soon';
1352
- /** Haven-run test content: the demo store and the stranded-funds fixture. */
1353
- isTestMerchant: boolean;
1354
- }
1355
- /**
1356
- * #3128: one page of receipts. `total` is the count Haven holds for the
1357
- * agent (an empty page with `total: 0` means no receipt exists — there is no
1358
- * indexing delay behind this list); `hasMore` says the page was cut at the
1359
- * limit; `nextCursor` is fed back as `cursor` for the next page. Against a
1360
- * backend older than #3128 the three are `null` — "unknown", never a
1361
- * fabricated 0 / false.
1362
- */
1363
- interface HavenPaymentReceiptsPage {
1364
- receipts: HavenPaymentReceipt[];
1365
- total: number | null;
1366
- hasMore: boolean | null;
1367
- nextCursor: string | null;
1368
- }
1369
- /** @internal */
1370
- /** Wire shape of POST /catalog/submit (#1717, #1716). */
1371
- interface CatalogSubmissionAccepted {
1372
- id: string;
1373
- verify_token: string;
1374
- status: 'submitted' | 'ownership_verified' | 'verified_payable';
1375
- }
1376
- /** @internal Client-facing submission handle. */
1377
- interface HavenCatalogSubmission {
1378
- id: string;
1379
- verifyToken: string;
1380
- status: 'submitted' | 'ownership_verified' | 'verified_payable';
1381
- }
1382
- declare class HavenError extends Error {
1383
- readonly code: string;
1384
- readonly statusCode?: number | undefined;
1385
- readonly paymentId?: string | undefined;
1386
- constructor(message: string, code: string, statusCode?: number | undefined, paymentId?: string | undefined);
1387
- }
1388
- declare class HavenApiError extends HavenError {
1389
- readonly body?: unknown | undefined;
1390
- constructor(message: string, statusCode: number, body?: unknown | undefined, paymentId?: string);
1391
- }
1392
- /**
1393
- * #1300: quoteX402 hit a URL that answered something other than 402 — the
1394
- * typed form of "this is not the x402 endpoint". Exists so consumers (the
1395
- * hosted MCP's #1271 discovery trigger) can key on a class instead of
1396
- * message text.
1397
- */
1398
- /**
1399
- * #1300: a merchant-facing fetch hit the client-side merchantTimeout. Typed
1400
- * so consumers can distinguish "merchant never answered" from a real HTTP
1401
- * error response — the funded-retry path routes this to verify-then-sweep
1402
- * guidance instead of a bare 504.
1403
- */
1404
- declare class MerchantTimeoutError extends HavenApiError {
1405
- readonly merchantErrorCode: "merchant_timeout";
1406
- constructor(message: string);
1407
- }
1408
- declare class X402UnexpectedStatusError extends HavenApiError {
1409
- readonly x402ErrorCode: "unexpected_non_402_status";
1410
- /**
1411
- * #2979: `body` is the merchant's own JSON, when the non-402 response
1412
- * carried one — e.g. the demo merchant's `/mcp` readiness gate answers
1413
- * `503 { error: 'merchant_not_ready', reason_code, ... }`. Optional and
1414
- * best-effort: a non-JSON or unreadable body leaves this `undefined`, same
1415
- * as before this field existed. Consumers key on it (not on the message
1416
- * string) to distinguish an honest, machine-readable merchant refusal from
1417
- * a genuine "this is not the x402 endpoint" miss, which otherwise look
1418
- * identical — both are just "some non-402 status".
1419
- */
1420
- constructor(message: string, statusCode: number, body?: unknown);
1421
- }
1422
- /**
1423
- * #1521: the idempotency key resolved to a payment that has already settled,
1424
- * and the delegate can no longer fund a fresh authorization for it.
1425
- *
1426
- * This is the typed form of "you already bought this". It exists because the
1427
- * alternative was indefensible: the SDK used to mint a new EIP-3009
1428
- * authorization against the spent delegate and hand it back paired with the
1429
- * ORIGINAL payment's `txHash`, so the caller learned what had happened only
1430
- * from a merchant-side balance error that reads identically to a broken
1431
- * payment rail.
1432
- *
1433
- * `receipt` is the ORIGINAL payment — a real receipt for real settled funds,
1434
- * deliberately carrying no `paymentHeader`, because any header minted here
1435
- * would be exactly the unfundable artifact this error replaces.
1436
- */
1437
- declare class X402AlreadySettledError extends HavenApiError {
1438
- readonly receipt: X402Receipt;
1439
- /**
1440
- * `settled` — the delegate was checked on-chain and cannot fund a fresh
1441
- * authorization, so this payment demonstrably completed.
1442
- * `unverifiable` — no `chainRpcs` entry for the chain, so fundability
1443
- * could not be established either way. Same refusal, weaker claim; say
1444
- * which, rather than assert what was not checked.
1445
- */
1446
- readonly basis: 'settled' | 'unverifiable';
1447
- readonly x402ErrorCode: "already_settled";
1448
- constructor(message: string, receipt: X402Receipt,
1449
- /**
1450
- * `settled` — the delegate was checked on-chain and cannot fund a fresh
1451
- * authorization, so this payment demonstrably completed.
1452
- * `unverifiable` — no `chainRpcs` entry for the chain, so fundability
1453
- * could not be established either way. Same refusal, weaker claim; say
1454
- * which, rather than assert what was not checked.
1455
- */
1456
- basis: 'settled' | 'unverifiable');
1457
- }
1458
- declare class HavenPaymentStateError extends HavenApiError {
1459
- readonly state: PaymentStatusResult;
1460
- resumeState?: X402ResumeState;
1461
- constructor(message: string, statusCode: number, state: PaymentStatusResult, body?: unknown);
1462
- get status(): string;
1463
- get phase(): PaymentPhase;
1464
- get nextAction(): PaymentNextAction;
1465
- }
1466
- declare class HavenSigningError extends HavenError {
1467
- constructor(message: string);
1468
- }
1469
- /**
1470
- * #2972: `MerchantCompletion.reportSettlementEvidence` /
1471
- * `HavenClient.reportSettlementEvidence` refuse a `0x00…00` settlement hash
1472
- * BEFORE any network call — see `isZeroSettlementTxHash`. That marker is
1473
- * never a real transaction (the demo merchant's own "delivered, not settled"
1474
- * value), so posting it to `POST /machine-payments/evidence` could only ever
1475
- * come back refused, at the cost of a real round trip. A typed error rather
1476
- * than a `HavenApiError`-shaped 400: no request was ever attempted, so there
1477
- * is no HTTP status or response body to carry.
1478
- */
1479
- declare class HavenZeroSettlementHashError extends HavenError {
1480
- constructor(paymentId: string);
1481
- }
1482
- /**
1483
- * Refusal codes the local signer returns when it does not recognise the
1484
- * VERSION of a Haven-signed binding it was asked to sign (#1309). Distinct
1485
- * from `AgentPaymentFailureCode`: these describe a **signer capability**
1486
- * problem (this install cannot evaluate what Haven sent), not a payment-domain
1487
- * outcome, and they never reach the backend's REST/OpenAPI surface — only the
1488
- * local signer's own MCP tool responses (`haven_sign` / `haven_sign_x402` /
1489
- * `haven_sign_sweep_delegate`). That is also why this pair does not go through
1490
- * the `AgentPaymentFailureCode` four-gate (sdk → backend mirror → spec →
1491
- * api-types): there is no backend mirror to keep in sync with.
1492
- */
1493
- declare const SignerRefusalCode: {
1494
- /** `SUPPORTED_X402_EXPECTED_VERSIONS` in `@haven_ai/signer` does not include the received version. */
1495
- readonly UnsupportedExpectedContextVersion: "UNSUPPORTED_EXPECTED_CONTEXT_VERSION";
1496
- /** `SUPPORTED_SWEEP_BINDING_VERSIONS` in `@haven_ai/signer` does not include the received version. */
1497
- readonly UnsupportedSweepBindingVersion: "UNSUPPORTED_SWEEP_BINDING_VERSION";
1498
- };
1499
- type SignerRefusalCode = (typeof SignerRefusalCode)[keyof typeof SignerRefusalCode];
1500
- /**
1501
- * Canonical recovery guidance for a stale local signer (#1309) — the ONE
1502
- * string both the signer's structured refusal (`fallback` field, carried by
1503
- * `HavenUnsupportedSignerVersionError`) and the hosted quote's advisory
1504
- * `signer_compatibility.fallback` (#1155) render, so an agent that meets
1505
- * either surface is told the identical fix. A second hand-maintained copy of
1506
- * this sentence is exactly how the two surfaces could start disagreeing about
1507
- * what to do.
1508
- */
1509
- declare function signerUpdateFallback(channel?: string): string;
1510
- /**
1511
- * The same sentence rendered for THIS build's channel (#2423). Every existing
1512
- * consumer keeps importing this constant and keeps getting a string; the only
1513
- * thing that moved is that `alpha` is no longer typed into it.
1514
- *
1515
- * The hosted MCP server is the one caller that does NOT use this constant: it
1516
- * is deployed rather than published, so it renders `signerUpdateFallback()`
1517
- * with the channel its own environment names.
1518
- */
1519
- declare const SIGNER_UPDATE_FALLBACK: string;
1520
- /**
1521
- * Thrown by the local signer when a Haven-signed binding (x402 expected
1522
- * context or sweep authorization) carries a version outside what this signer
1523
- * install enforces (#1143, structured as #1309). Machine-readable: `code`,
1524
- * `supportedVersions`, and `receivedVersion` are DERIVED from the signer's own
1525
- * `SUPPORTED_X402_EXPECTED_VERSIONS` / `SUPPORTED_SWEEP_BINDING_VERSIONS`
1526
- * constants at the throw site, never a second literal — see
1527
- * `assertSupportedBindingVersion` in `@haven_ai/signer`.
1528
- *
1529
- * This narrows HOW the refusal is reported. It does not weaken it: nothing is
1530
- * signed either way, and the version stays inside the Haven-signed binding
1531
- * message (callers must not "fix" a mismatch by rewriting it).
1532
- */
1533
- declare class HavenUnsupportedSignerVersionError extends HavenError {
1534
- readonly supportedVersions: readonly number[];
1535
- readonly receivedVersion: number;
1536
- readonly fallback: string;
1537
- constructor(message: string, code: SignerRefusalCode, supportedVersions: readonly number[], receivedVersion: number, fallback: string);
1538
- }
1539
- declare class HavenTimeoutError extends HavenError {
1540
- constructor(paymentId: string);
1541
- }
1
+ import { R as RawPaymentParties, H as HavenClientConfig, a as HavenClientUpdate, P as PaymentRequest, b as PaymentResult, c as PaymentIntent, X as X402PaymentRequired, d as X402AuthorizationOptions, e as X402Intent, f as PaymentStatusResult, g as HavenAgent, h as HavenAgentSummary, S as SweepResult, i as SweepPrepareResponse, j as SweepAuthorization, k as SweepSubmitResponse, l as HavenAllowanceSummary, m as HavenBalanceCoverage, n as PostPurchaseAllowanceSummary, A as AgentPaymentWarning, o as HavenCatalogEntry, p as HavenCatalogSubmission, q as HavenPaymentReceipt, r as HavenPaymentReceiptsPage, s as PaymentResumeState, t as X402Receipt, u as X402Quote, v as X402Erc7710Settlement, w as X402McpCallContext, x as SignData, y as ResumeAuthorizedX402Input, z as ResumeX402PaymentInput, B as X402ResumeState, C as X402McpTransport, D as X402MerchantCallContext, E as HavenError } from './base64-BUMXmruY.cjs';
2
+ export { F as AGENT_PAYMENT_FAILURE_CODE_VALUES, G as AGENT_PAYMENT_NEXT_ACTION_VALUES, I as AGENT_PAYMENT_PHASE_VALUES, J as AGENT_PAYMENT_RAIL_VALUES, K as AgentNextStep, L as AgentPaymentEnumSchema, M as AgentPaymentFailureCode, N as AgentPaymentFailureCodeDescriptions, O as AgentPaymentFailureCodeSchema, Q as AgentPaymentNextAction, T as AgentPaymentNextActionDescriptions, U as AgentPaymentNextActionSchema, V as AgentPaymentPhase, W as AgentPaymentPhaseDescriptions, Y as AgentPaymentPhaseSchema, Z as AgentPaymentRail, _ as AgentPaymentRailDescriptions, $ as AgentPaymentRailSchema, a0 as AgentPaymentSummary, a1 as AgentPaymentWarningCode, a2 as AgentPurchaseSummary, a3 as CONNECTOR_PACKAGE_NAME, a4 as CatalogSubmissionAccepted, a5 as DEFAULT_CONFIRMATION_TIMEOUT_MS, a6 as DEFAULT_NEXT_TOOL_BY_ACTION, a7 as DIRECT_SIGN_CONTEXT_VERSION, a8 as ENTRY_POINT_V07, a9 as ERC7710_ASSET_TRANSFER_METHOD, aa as HAVEN_CLIENT_HEADER, ab as HAVEN_CONNECTOR_CHANNEL, ac as HAVEN_MINIMUM_NODE_VERSION, ad as HYBRID_DELEGATOR_DOMAIN_NAME, ae as HYBRID_DELEGATOR_DOMAIN_VERSION, af as HavenAgentAllowanceSummary, ag as HavenAgentReadiness, ah as HavenAllowance, ai as HavenApiError, aj as HavenCatalogMerchant, ak as HavenListScope, al as HavenPaymentStateError, am as HavenSigningError, an as HavenTimeoutError, ao as HavenTypedDataRefusedError, ap as HavenUnsupportedSignerVersionError, aq as HavenUserOpBindingError, ar as HavenZeroSettlementHashError, as as MachinePaymentRail, at as MerchantTimeoutError, au as NEXT_TOOL_SERVER_NAMES, av as NEXT_TOOL_SERVER_ROLES, aw as NextStep, ax as NextStepArguments, ay as NextStepHandoff, az as NextStepInput, aA as NextStepTarget, aB as NextStepTargets, aC as NextToolServerRole, aD as PACKED_USER_OPERATION_FIELDS, aE as PaymentFee, aF as PaymentNextAction, aG as PaymentPhase, aH as PaymentStatus, aI as ROOT_AUTHORITY, aJ as SDK_CLIENT_IDENTITY, aK as SDK_VERSION, aL as SIGNER_UPDATE_FALLBACK, aM as SWEEP_BASE_CHAIN_ID, aN as SWEEP_BASE_SEPOLIA_CHAIN_ID, aO as SWEEP_BASE_SEPOLIA_USDC_ADDRESS, aP as SWEEP_BASE_USDC_ADDRESS, aQ as SettlementChildExpectation, aR as SignerRefusalCode, aS as SweepConfirmation, aT as SweepEip712Domain, aU as SweepEntry, aV as SweepExpectedAuth, aW as SweepPreparation, aX as SweepSubmitResult, aY as SweepTypedData, aZ as TRANSFER_WITH_AUTHORIZATION_TYPES, a_ as TYPED_DATA_NOT_ALLOWED, a$ as UnsupportedNodeVersionMessageOptions, b0 as X402AlreadySettledError, b1 as X402ExpectedAuth, b2 as X402ExpectedContext, b3 as X402PaymentHeaderContext, b4 as X402PaymentHeaderValidationError, b5 as X402PaymentOption, b6 as X402RequestSnapshot, b7 as X402SchemeSelection, b8 as X402UnexpectedStatusError, b9 as X402_LEGACY_PAYMENT_HEADER_NAME, ba as X402_MAX_AUTHORIZATION_WINDOW_SECONDS, bb as X402_PAYMENT_HEADER_NAME, bc as X402_PAYMENT_HEADER_NAMES_SENT, bd as X402_PAYMENT_REQUIRED_HEADER_NAME, be as X402_PAYMENT_RESPONSE_HEADER_NAME, bf as X402_SETTLEMENT_FORWARD_MARGIN_SECONDS, bg as assertBoundDirectPaymentUserOp, bh as assertUserOpTypedDataBinding, bi as buildSweepAuthorizationMessage, bj as buildSweepTypedData, bk as buildX402ExpectedMessage, bl as compareNodeVersions, bm as connectorRerunCommand, bn as connectorSpec, bo as createNextStepBuilder, bp as decodeBase64Json, bq as decodeBase64Utf8, br as defaultNextToolFor, bs as deriveDelegateAccountAddress, bt as encodeBase64Json, bu as encodeBase64Utf8, bv as encodePaymentProof, bw as havenClientIdentity, bx as isConnectorChannel, by as isErc7710Option, bz as isPackedUserOperationTypedData, bA as isSupportedNodeVersion, bB as isSweepableChain, bC as normalizePaymentRequired, bD as packedUserOperationHash, bE as parseNextTool, bF as parsePaymentRequired, bG as parsePaymentRequiredResponse, bH as readClientUpdate, bI as renderNextTool, bJ as resolveConnectorChannel, bK as resolveTokenFromAddress, bL as selectErc7710PaymentOption, bM as selectPaymentOption, bN as selectStandardPaymentOption, bO as selectX402SettlementScheme, bP as signerUpdateFallback, bQ as sweepUsdcAddress, bR as sweepUsdcDomain, bS as toStandardPaymentRequirements, bT as unsupportedNodeVersionMessage, bU as validateStandardX402PaymentHeader, bV as verifySettlementChild, bW as x402AssetTransferMethod, bX as x402AuthorizationAmount, bY as x402FacilitatorAddresses, bZ as x402V2PaymentEnvelope } from './base64-BUMXmruY.cjs';
3
+ import 'x402/types';
4
+ import 'viem';
1542
5
 
1543
6
  /**
1544
7
  * Verifiable payment receipts.
@@ -1602,186 +65,6 @@ type ReceiptVerification = {
1602
65
  */
1603
66
  declare function verifyPaymentReceipt(receipt: PaymentReceipt, recover?: (hash: string, signature: string) => string): ReceiptVerification;
1604
67
 
1605
- /**
1606
- * Gasless delegate-sweep primitives — the single source of truth shared by the
1607
- * edge signer (which signs) and the Haven backend (which relays).
1608
- *
1609
- * A stranded delegate EOA holds USDC but no ETH, so a raw ERC-20 transfer can't
1610
- * pay for its own gas. Instead the delegate signs an *off-chain* EIP-3009
1611
- * `TransferWithAuthorization` and the Haven relayer submits it on-chain and pays
1612
- * gas. The relayer is only a gas payer: it holds no allowance and is never a
1613
- * spender, so a relayer compromise cannot move user funds.
1614
- *
1615
- * Framework-neutral on purpose: `buildSweepTypedData` returns a plain
1616
- * `{ domain, types, primaryType, message }` that both viem
1617
- * (`signTypedData`/`recoverTypedDataAddress`) and ethers v6
1618
- * (`signTypedData`/`verifyTypedData`) accept, so the signer (viem) and backend
1619
- * (ethers) stay in lockstep without sharing a crypto library.
1620
- */
1621
- /** Base mainnet. The only chain Haven sweeps today. */
1622
- declare const SWEEP_BASE_CHAIN_ID = 8453;
1623
- /** Base Sepolia testnet — used by the dev environment / QA harness. */
1624
- declare const SWEEP_BASE_SEPOLIA_CHAIN_ID = 84532;
1625
- /** Canonical Circle USDC on Base (FiatTokenV2_2). */
1626
- declare const SWEEP_BASE_USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
1627
- /** Circle's canonical Base Sepolia testnet USDC. */
1628
- declare const SWEEP_BASE_SEPOLIA_USDC_ADDRESS = "0x036CbD53842c5426634e7929541eC2318f3dCF7e";
1629
- /** True when the gasless sweep supports a chain (its USDC domain + address are known). */
1630
- declare function isSweepableChain(chainId: number): boolean;
1631
- /** EIP-712 `TransferWithAuthorization` struct, per EIP-3009. */
1632
- declare const TRANSFER_WITH_AUTHORIZATION_TYPES: {
1633
- readonly TransferWithAuthorization: readonly [{
1634
- readonly name: "from";
1635
- readonly type: "address";
1636
- }, {
1637
- readonly name: "to";
1638
- readonly type: "address";
1639
- }, {
1640
- readonly name: "value";
1641
- readonly type: "uint256";
1642
- }, {
1643
- readonly name: "validAfter";
1644
- readonly type: "uint256";
1645
- }, {
1646
- readonly name: "validBefore";
1647
- readonly type: "uint256";
1648
- }, {
1649
- readonly name: "nonce";
1650
- readonly type: "bytes32";
1651
- }];
1652
- };
1653
- interface SweepEip712Domain {
1654
- name: string;
1655
- version: string;
1656
- chainId: number;
1657
- verifyingContract: string;
1658
- }
1659
- /**
1660
- * A fully-specified EIP-3009 authorization. All amounts/times are decimal
1661
- * strings (JSON-safe) and `nonce` is a 0x-prefixed 32-byte hex value. `token`
1662
- * and `chainId` are carried explicitly so the signer can assert they are
1663
- * canonical before signing.
1664
- */
1665
- interface SweepAuthorization {
1666
- /** Delegate EOA the funds are swept FROM. */
1667
- from: string;
1668
- /** Originating Safe the funds are swept TO. */
1669
- to: string;
1670
- /** Atomic USDC amount (decimal string). */
1671
- value: string;
1672
- /** Unix seconds the authorization becomes valid (decimal string, usually "0"). */
1673
- validAfter: string;
1674
- /** Unix seconds the authorization expires (decimal string). */
1675
- validBefore: string;
1676
- /** Random 0x-prefixed 32-byte hex nonce. */
1677
- nonce: string;
1678
- /** USDC contract address. */
1679
- token: string;
1680
- /** Chain id (8453 today). */
1681
- chainId: number;
1682
- }
1683
- /**
1684
- * Haven's signature over the sweep authorization context, signed with the same
1685
- * binding key the x402 expected-context uses. Lets the edge signer verify the
1686
- * authorization actually came from Haven (and wasn't crafted by a compromised
1687
- * hosted server pointing `to` at an attacker) before it signs.
1688
- */
1689
- interface SweepExpectedAuth {
1690
- /**
1691
- * Currently always 1. Typed as `number` for the same reason as
1692
- * `X402ExpectedAuth.version` (#1143): it is inbound, so a stale signer must be
1693
- * able to *receive* an unknown version in order to report it. The signer's
1694
- * `SUPPORTED_SWEEP_BINDING_VERSIONS` is the authority on what it will sign.
1695
- */
1696
- version: number;
1697
- message: string;
1698
- signature: string;
1699
- signer: string;
1700
- }
1701
- /** What `POST /machine-payments/sweep/prepare` returns when funds are stranded. */
1702
- interface SweepPreparation {
1703
- authorization: SweepAuthorization;
1704
- expectedAuth: SweepExpectedAuth;
1705
- }
1706
- /** Wire response from `POST /machine-payments/sweep/prepare` (snake_case). */
1707
- interface SweepPrepareResponse {
1708
- /** Present and true when the delegate holds nothing to recover. */
1709
- nothing_stranded?: boolean;
1710
- /**
1711
- * Present and true when the stranded balance is below the sweep floor (#700):
1712
- * it is left on the delegate as dust rather than recovered, because the gas to
1713
- * sweep it would exceed its value. `min_usdc` carries the configured floor. No
1714
- * `authorization` is built.
1715
- */
1716
- below_min?: boolean;
1717
- min_usdc?: string;
1718
- /** The authorization to sign — absent when nothing is stranded or below the floor. */
1719
- authorization?: SweepAuthorization;
1720
- /** Haven's binding over the authorization — absent when nothing is stranded. */
1721
- expected_auth?: SweepExpectedAuth;
1722
- asset?: string;
1723
- amount?: string;
1724
- amount_atomic?: string;
1725
- chain_id: number;
1726
- sign_instructions?: string;
1727
- message?: string;
1728
- }
1729
- /** Wire response from `POST /machine-payments/sweep/submit` (snake_case). */
1730
- interface SweepSubmitResponse {
1731
- tx_hash: string;
1732
- asset: string;
1733
- amount: string;
1734
- amount_atomic: string;
1735
- from_address: string;
1736
- to_address: string;
1737
- chain_id: number;
1738
- explorer_url: string;
1739
- idempotent_replay?: boolean;
1740
- }
1741
- /** Result of a submitted gasless sweep. */
1742
- interface SweepSubmitResult {
1743
- txHash: string;
1744
- amount: string;
1745
- amountAtomic: string;
1746
- asset: string;
1747
- fromAddress: string;
1748
- toAddress: string;
1749
- chainId: number;
1750
- explorerUrl: string;
1751
- }
1752
- interface SweepTypedData {
1753
- domain: SweepEip712Domain;
1754
- types: typeof TRANSFER_WITH_AUTHORIZATION_TYPES;
1755
- primaryType: 'TransferWithAuthorization';
1756
- message: {
1757
- from: string;
1758
- to: string;
1759
- value: bigint;
1760
- validAfter: bigint;
1761
- validBefore: bigint;
1762
- nonce: string;
1763
- };
1764
- }
1765
- /** Resolve the canonical USDC contract for a sweepable chain, or throw. */
1766
- declare function sweepUsdcAddress(chainId: number): string;
1767
- /** Resolve the USDC EIP-712 domain for a sweepable chain, or throw. */
1768
- declare function sweepUsdcDomain(chainId: number): SweepEip712Domain;
1769
- /**
1770
- * Build the EIP-712 typed data for an authorization, validating that the token
1771
- * and chain are canonical (the domain's `verifyingContract` must match the
1772
- * authorization's `token`). Returns bigint-valued fields so both viem and
1773
- * ethers v6 sign/recover identically.
1774
- */
1775
- declare function buildSweepTypedData(auth: SweepAuthorization): SweepTypedData;
1776
- /**
1777
- * Canonical, deterministic string the backend signs and the signer re-derives
1778
- * for the authorization binding. The `Haven sweep authorization v1` namespace
1779
- * (and `kind`) is distinct from the x402 expected-context namespace so an x402
1780
- * binding can never be replayed as a sweep authorization even though they share
1781
- * a signing key.
1782
- */
1783
- declare function buildSweepAuthorizationMessage(auth: SweepAuthorization): string;
1784
-
1785
68
  /**
1786
69
  * Merchant delivery and the evidence trail behind it (#1620, epic #1613).
1787
70
  *
@@ -1895,10 +178,18 @@ declare class HavenClient {
1895
178
  * context.
1896
179
  */
1897
180
  withRequestContext<T>(headers: Record<string, string>, fn: () => Promise<T>): Promise<T>;
181
+ /**
182
+ * The backend's newest `client_update` hint for this client (#3303): inside
183
+ * a `withRequestContext` dispatch, the one that dispatch's own requests
184
+ * received; outside one, the latest seen. Undefined when the client is
185
+ * current or the backend predates #3303.
186
+ */
187
+ clientUpdate(): HavenClientUpdate | undefined;
1898
188
  /**
1899
189
  * Send a payment in one call.
1900
190
  *
1901
- * Creates the intent, signs the hash, submits the signature,
191
+ * Creates the intent, signs its `sign_data` (a delegation-rail intent's
192
+ * EIP-712 typed data, after the #3271 UserOp binding check), submits the signature,
1902
193
  * and polls until confirmed (or throws on failure/timeout).
1903
194
  *
1904
195
  * Requires `delegateKey` to be set in the client config.
@@ -1978,11 +269,12 @@ declare class HavenClient {
1978
269
  */
1979
270
  getAgentSummary(): Promise<HavenAgentSummary>;
1980
271
  /**
1981
- * Sweep stranded USDC and ETH from the delegate EOA back to the originating Safe.
272
+ * Sweep stranded USDC and ETH from the delegate EOA back to the agent's Haven account.
1982
273
  *
1983
274
  * The delegate key held by this client signs and submits the transfer transactions
1984
275
  * directly — Haven's backend never handles the key or constructs signed txs
1985
- * (CASP/MiCA Red Line #2). Funds always go to the Safe linked to this agent.
276
+ * (CASP/MiCA Red Line #2). Funds always go to the Haven account linked to this agent
277
+ * (`accountAddress` from `getAgent()`).
1986
278
  *
1987
279
  * Requires `chainRpcs` to be set for the agent's chain in `HavenClientConfig`.
1988
280
  */
@@ -2296,10 +588,11 @@ declare class HavenClient {
2296
588
  resumeAuthorizedX402(input: ResumeAuthorizedX402Input): Promise<X402Receipt>;
2297
589
  resumeX402Payment(input: ResumeX402PaymentInput | X402ResumeState): Promise<Response>;
2298
590
  /**
2299
- * Fetch wrapper that automatically handles HTTP 402 responses.
591
+ * Fetch wrapper that automatically handles HTTP 402 responses — and, since
592
+ * #3118, a native-MCP payment-required tool result answered under HTTP 200.
2300
593
  *
2301
- * Works like the standard `fetch()` but intercepts 402 responses,
2302
- * pays via x402 through Haven, and retries the request.
594
+ * Works like the standard `fetch()` but intercepts 402 responses (or that
595
+ * tool-result challenge), pays via x402 through Haven, and retries the request.
2303
596
  *
2304
597
  * ```ts
2305
598
  * const response = await haven.fetch('https://paid-api.com/data')
@@ -2307,8 +600,9 @@ declare class HavenClient {
2307
600
  * ```
2308
601
  *
2309
602
  * **MCP-over-x402 auto-handshake (issue #315):** when the endpoint is
2310
- * MCP-shaped — the URL path ends in `/mcp`, or the 402 body carries a
2311
- * Coinbase Bazaar `extensions.bazaar` block — the SDK runs the MCP
603
+ * MCP-shaped — the URL path ends in `/mcp`, or the 402 body (or, since
604
+ * #3118, the tool-result challenge) carries a Coinbase Bazaar
605
+ * `extensions.bazaar` block — the SDK runs the MCP
2312
606
  * `initialize` handshake, threads the resulting `mcp-session-id`,
2313
607
  * `Accept: application/json, text/event-stream`, and `x402-wallet` headers
2314
608
  * through every request, and collapses SSE responses to the JSON-RPC
@@ -2338,7 +632,7 @@ declare class HavenClient {
2338
632
  * collapses an SSE JSON-RPC response to its `result`.
2339
633
  */
2340
634
  /**
2341
- * Wait for a payment's Safe→delegate funding tx to reach ≥1 on-chain
635
+ * Wait for a payment's account→delegate funding tx to reach ≥1 on-chain
2342
636
  * confirmation. The hosted x402 completion path MUST call this after funding
2343
637
  * and before delivering the merchant payment header, so the merchant's
2344
638
  * balanceOf(delegate) / transferWithAuthorization verification sees the funded
@@ -2512,7 +806,7 @@ declare const havenTools: {
2512
806
  /**
2513
807
  * Sign a hash using raw ECDSA (no Ethereum message prefix).
2514
808
  *
2515
- * This matches what Safe's AllowanceModule `checkSignature` expects —
809
+ * This matches what the retired Safe AllowanceModule rail's `checkSignature` expected —
2516
810
  * a direct ecrecover over the hash, NOT the "\x19Ethereum Signed Message" variant.
2517
811
  *
2518
812
  * Uses ethers.SigningKey.sign() instead of wallet.signMessage() to avoid the prefix.
@@ -2594,12 +888,12 @@ declare const toolDescriptions: {
2594
888
  readonly payX402OneShot: {
2595
889
  readonly summary: "Fetch an x402 paid HTTP resource in a single call. Handles the full probe -> pay -> retry round trip and returns the merchant response.";
2596
890
  readonly selectionGuidance: "Prefer this over the quote+pay split when the agent just wants the paid resource and does not need to inspect the price first. If you already have a quote from haven_quote_x402, use haven_pay_x402_quote instead. Do not use for read-only allowance, budget, spend-limit, remaining-amount, reset-period, or what-can-I-spend questions; use the allowance lookup tool instead.";
2597
- readonly behavior: "Calls the URL, parses any HTTP 402 x402 challenge, signs the payment locally, then retries the original request with the signed payment header (sent under PAYMENT-SIGNATURE, plus the legacy X-PAYMENT on the EIP-3009 path only) and returns the merchant response. Settlement is either direct account-to-merchant with no funding leg, or a bridge that first redeems the agent's budget delegation to fund the delegate wallet for an EIP-3009 authorization. A payment outside the on-chain budget is declined before any money moves; nothing is queued for a human to approve later. If the resource returns a non-402 status, returns it unchanged without contacting Haven.";
891
+ readonly behavior: "Calls the URL, parses any HTTP 402 x402 challenge (or, since #3118, a native-MCP payment-required tool result under HTTP 200), signs the payment locally, then retries the original request with the signed payment header (sent under PAYMENT-SIGNATURE, plus the legacy X-PAYMENT on the EIP-3009 path only) and returns the merchant response. Settlement is either direct account-to-merchant with no funding leg, or a bridge that first redeems the agent's budget delegation to fund the delegate wallet for an EIP-3009 authorization. A payment outside the on-chain budget is declined before any money moves; nothing is queued for a human to approve later. If the resource returns a non-402 status with no payment-required tool result, returns it unchanged without contacting Haven.";
2598
892
  readonly nextActionGuidance: string;
2599
893
  };
2600
894
  readonly resumeX402: {
2601
895
  readonly summary: "Resume an x402 payment whose Haven-side authorization already succeeded but whose merchant retry did not complete.";
2602
- readonly behavior: "Accepts either resume_state or payment_id, validates the original x402 details against the authorized Haven funding, and retries the merchant request with the signed payment header (sent under PAYMENT-SIGNATURE, plus the legacy X-PAYMENT on the EIP-3009 path only). No new Haven payment is created.";
896
+ readonly behavior: "Accepts either resume_state or payment_id, validates the x402 details against the authorized funding, and retries the merchant request with the signed payment header (PAYMENT-SIGNATURE, plus legacy X-PAYMENT on EIP-3009 only; also params._meta on an MCP tools/call body). No new Haven payment is created.";
2603
897
  readonly nextActionGuidance: string;
2604
898
  };
2605
899
  readonly getPaymentStatus: {
@@ -2632,8 +926,8 @@ declare const toolDescriptions: {
2632
926
  };
2633
927
  readonly listReceipts: {
2634
928
  readonly summary: "List machine-payment receipts, newest first, by page.";
2635
- readonly selectionGuidance: "For transaction history or payment evidence; use the allowance tool instead for remaining allowance or what-can-I-spend questions.";
2636
- readonly behavior: "Page: { receipts, total, hasMore, nextCursor }; total 0 = none exist (no indexing delay); hasMore = cut at limit, send nextCursor as cursor. parties.treasuryAccount is Haven's authoritative payer. protocolReceiptPayload is the merchant's PAYMENT-RESPONSE, relayed verbatim: merchant-controlled, unverified, not Haven's record; payer may differ from payerAddress. Proof header values are omitted.";
929
+ readonly selectionGuidance: "This agent's payment evidence, not the wallet's transaction history (sweeps, funding legs, other agents); use the allowance tool instead for remaining allowance or what-can-I-spend questions.";
930
+ readonly behavior: "Page { receipts, total, hasMore, nextCursor }; hasMore: pass nextCursor as cursor. parties.treasuryAccount is Haven's authoritative payer. protocolReceiptPayload is the merchant's PAYMENT-RESPONSE relayed verbatim: merchant-controlled, unverified, not Haven's record; payer may differ from payerAddress. Proof header values omitted.";
2637
931
  readonly nextActionGuidance: "";
2638
932
  };
2639
933
  readonly verifyReceipt: {
@@ -2935,271 +1229,6 @@ declare const HAVEN_AGENT_RUNBOOK_MD = "# Haven for agents \u2014 set your user
2935
1229
  */
2936
1230
  declare const AGENT_ONBOARDING_PROMPT = "I have a Haven account and I am signed in at {{HAVEN_ORIGIN}}. Please set up Haven so you can pay for things within a budget I approve.\n\nStart by reading {{HAVEN_ORIGIN}}/for-agents.md \u2014 it is written for you and explains which steps are mine.\n\nThen:\n\n1. Run `npx @haven_ai/cli@<channel> login`. The `<channel>` in that command is the tag your deployment names \u2014 read it from `/.well-known/haven.json` (`packages.cli.channel`), never a tag you pick. It prints a link and a code and does not need my password \u2014 it must never ask for it. Give me the link straight away and wait for me to approve it in my browser.\n2. Once I have approved, run `haven agents connect --name <a name you choose> --budget <amount> --token USDC --period <minutes>` with the budget I tell you. If I have not given you one, ask me before running it. Add `--run` to complete the connection in the same step.\n3. When a --json outcome reports approval.required: true, your first action must be to relay the approval instruction to me in your own reply \u2014 if the outcome carries approval.url, give me that link; otherwise tell me to return to Haven and approve this agent's budget \u2014 before verifying the connection, restarting anything, or any other step. Never build that link yourself: relay the one the outcome gave you or none at all. Any restart the outcome asks for is a separate instruction to give me afterwards, once the approval is done.\n4. Once I have approved the budget, verify with the `haven_get_agent` tool: `ready` means you can pay, `needs_approval` means my approval has not landed yet.\n\nTwo things only I can do: approving that budget with my passkey, and funding the account with USDC on Base \u2014 no ETH, Haven sponsors the gas. Tell me if either is missing rather than working around it.\n\nDo not print private keys, API keys, credential file contents, or config secrets in chat or logs.";
2937
1231
 
2938
- /**
2939
- * #3101 (epic #3105, slice 2/5): the typed next-step builder.
2940
- *
2941
- * Every hosted payment tool ends by naming the agent's next tool and its
2942
- * arguments (#1308). Until this module, the tool was a free string and the
2943
- * arguments a `Record<string, unknown>`, so nothing tied the keys to the tool
2944
- * named beside them — three sites handed `{ payment_id: null }` to a tool
2945
- * whose `payment_id` is a required string, and the compiler could not see it.
2946
- *
2947
- * The builder is generic over a TARGET MAP the caller supplies: bare tool
2948
- * name → { role, validate }. It is deliberately schema-library-agnostic (the
2949
- * SDK carries no zod): the hosted server derives each target's argument type
2950
- * from its own zod shape and passes a `validate` closure; this module only
2951
- * needs to know the role (to render `mcp__<server>__<tool>`) and how to say
2952
- * whether arguments parse. Keyed on the bare name + role (decision 1) so the
2953
- * namespaced string is rendered in exactly one place and the runtime-neutral
2954
- * `next_tool_server` / `next_tool_name` / `next_tool_server_role` fields are
2955
- * derived from the same input rather than parsed back out of a literal.
2956
- *
2957
- * Decisions 3 and 8: `nextTool` is REQUIRED on the input and may be `null` —
2958
- * a site that forgets it is a compile error; a site with no next tool says
2959
- * why, and the wire omits `next_tool` and carries `next_tool_omitted_reason`.
2960
- * `next_tool` is never null on the wire.
2961
- */
2962
- type NextToolServerRole = 'hosted' | 'signer';
2963
- /** The DEFAULT server name each role is wired under (#1588, #2550). */
2964
- declare const NEXT_TOOL_SERVER_NAMES: Record<NextToolServerRole, string>;
2965
- /** Default server name → role. An unknown server yields no role rather than a guess (#2550). */
2966
- declare const NEXT_TOOL_SERVER_ROLES: Record<string, NextToolServerRole>;
2967
- /** Renders the Claude-family namespaced tool name — the one string clients have followed since #1308. */
2968
- declare function renderNextTool(role: NextToolServerRole, name: string): string;
2969
- /** Parses a namespaced literal back into its parts; `role` is absent for an unknown server. */
2970
- declare function parseNextTool(literal: string): {
2971
- server: string;
2972
- name: string;
2973
- role?: NextToolServerRole;
2974
- } | null;
2975
- /**
2976
- * One target the builder may hand off to. `TArgs` is the argument type the
2977
- * caller derived from the tool's declared schema; `validate` is the runtime
2978
- * twin of that type and returns `null` when the arguments parse, else why not.
2979
- */
2980
- interface NextStepTarget<TArgs> {
2981
- role: NextToolServerRole;
2982
- validate: (input: unknown) => string | null;
2983
- /** Phantom carrier for the argument type; never read at runtime. */
2984
- readonly _args?: TArgs;
2985
- }
2986
- type NextStepTargets = Record<string, NextStepTarget<unknown>>;
2987
- /** The argument type a target carries. */
2988
- type NextStepArguments<Targets extends NextStepTargets, T extends keyof Targets> = Targets[T] extends NextStepTarget<infer A> ? A : never;
2989
- /**
2990
- * The handoff half of a next step: a registered tool with arguments that
2991
- * tool accepts, or no tool with the reason. A discriminated union over the
2992
- * target map's keys, so a wrong key, a missing required key, an unregistered
2993
- * tool name and an omitted `nextTool` are each a compile error at the site.
2994
- */
2995
- type NextStepHandoff<Targets extends NextStepTargets> = {
2996
- [T in keyof Targets & string]: {
2997
- nextTool: T;
2998
- nextArguments: NextStepArguments<Targets, T>;
2999
- };
3000
- }[keyof Targets & string] | {
3001
- nextTool: null;
3002
- nextToolOmittedReason: string;
3003
- };
3004
- type NextStepInput<Targets extends NextStepTargets> = NextStepHandoff<Targets> & {
3005
- nextAction: AgentPaymentNextAction;
3006
- safeToContinue: boolean;
3007
- reason: string;
3008
- };
3009
- /** The wire shape: `AgentNextStep` (its `next_tool` family) — never a null `next_tool`. */
3010
- type NextStep = AgentNextStep;
3011
- /**
3012
- * Per-`next_action` default tool (decision 9): the tool a site names unless it
3013
- * has a reason to override. Only actions with ONE sensible target are listed;
3014
- * `retry_original_x402_request` is absent because its only live emitter names
3015
- * no tool on purpose (the agent's own HTTP retry); `sign_and_submit_payment`
3016
- * is absent because the signer tool
3017
- * depends on the settlement scheme (`haven_sign` for erc7710 delegations,
3018
- * `haven_sign_x402` for the EIP-3009 bridge) and a wrong default there would be
3019
- * worse than none.
3020
- */
3021
- declare const DEFAULT_NEXT_TOOL_BY_ACTION: {
3022
- readonly check_status_later: "haven_get_payment_status";
3023
- readonly sweep_stranded_funds: "haven_sweep_delegate";
3024
- };
3025
- declare function defaultNextToolFor(action: AgentPaymentNextAction): string | undefined;
3026
- /**
3027
- * Builds a `nextStep` function bound to a target map. The returned function
3028
- * renders the wire fields from the bare name + role, and re-validates the
3029
- * arguments at runtime: on a mismatch it FAILS SAFE — omits the tool and says
3030
- * why in `next_tool_omitted_reason` — rather than throwing out of a handler
3031
- * that has already moved money. The compile-time twin makes that branch
3032
- * unreachable from typed sites; it exists for callers that bypass the types.
3033
- */
3034
- declare function createNextStepBuilder<Targets extends NextStepTargets>(targets: Targets): (input: NextStepInput<Targets>) => NextStep;
3035
-
3036
- /**
3037
- * The npm dist-tag the published Haven packages tell a user to re-run (#2423,
3038
- * slice 3 of epic #2420).
3039
- *
3040
- * ## Why a constant and not a literal
3041
- *
3042
- * Roughly a dozen user- and agent-facing strings across `@haven_ai/sdk`,
3043
- * `@haven_ai/signer`, `@haven_ai/connect` and the hosted MCP server say some
3044
- * form of "re-run `npx @haven_ai/connect@alpha`". Every one of them was a
3045
- * hard-coded literal, which is correct only for a build published under the
3046
- * `alpha` dist-tag. Once `dev`-branch snapshots publish under a `dev` tag
3047
- * (#2421), a snapshot build telling its tester to re-run `@alpha` would hand
3048
- * them the production connector — silently replacing the very build they are
3049
- * testing. So the tag becomes one build-time constant and every hint derives
3050
- * from it.
3051
- *
3052
- * ## Who writes it
3053
- *
3054
- * `scripts/release-bump.mjs` rewrites {@link HAVEN_CONNECTOR_CHANNEL} from the
3055
- * version it is bumping to, using exactly the rule `.github/workflows/publish.yml`
3056
- * uses to pick the `--tag` for that same version:
3057
- *
3058
- * | version | dist-tag / channel |
3059
- * |---|---|
3060
- * | `0.1.34-alpha.0` | `alpha` |
3061
- * | `0.0.0-dev.202609021200.abc1234` | `dev` |
3062
- * | `0.2.0` | `latest` |
3063
- *
3064
- * One rule, two consumers. `scripts/ci/connector-channel-agreement.test.mjs`
3065
- * executes the workflow's own shell and the bump script's own function over the
3066
- * same version table and fails if they ever disagree.
3067
- *
3068
- * ## Build-time here, run-time there
3069
- *
3070
- * A published tarball cannot read a deployment's environment, so for the
3071
- * published packages the channel is baked in at release time. A surface that is
3072
- * *deployed* rather than published has no release at which to bake anything in,
3073
- * so it reads the `HAVEN_CONNECTOR_CHANNEL` environment variable and falls back
3074
- * to this constant. Two surfaces do that: the hosted MCP server
3075
- * (`packages/mcp-server/src/connector-channel.ts`) and, since slice 2 (#2422),
3076
- * the backend's connector handout (`parseConnectorChannel` in
3077
- * `packages/backend/src/config.ts`). All three readers share one variable name,
3078
- * one default and one validation pattern, and that agreement is EXECUTED rather
3079
- * than asserted: `packages/backend/src/__tests__/connector-channel.test.ts`
3080
- * runs this module's `resolveConnectorChannel` and the backend's
3081
- * `parseConnectorChannel` over the same input table and fails if they ever
3082
- * diverge.
3083
- *
3084
- * **This says nothing about how any environment is configured.** Setting the
3085
- * variable anywhere is an operator action (epic #2420, operator step 3); no
3086
- * code here can observe it and none of this comment asserts it has happened.
3087
- */
3088
- /** The published connector package. Never varies; only its tag does. */
3089
- declare const CONNECTOR_PACKAGE_NAME = "@haven_ai/connect";
3090
- /**
3091
- * The npm dist-tag this build's re-run hints name.
3092
- *
3093
- * **Do not hand-edit.** `scripts/release-bump.mjs` owns this literal the same
3094
- * way it owns `CONNECTOR_VERSION` and its siblings, and
3095
- * `scripts/release-bump.test.mjs` fails if the two drift.
3096
- */
3097
- declare const HAVEN_CONNECTOR_CHANNEL = "alpha";
3098
- /** True when `value` is a well-formed dist-tag. */
3099
- declare function isConnectorChannel(value: string): boolean;
3100
- /**
3101
- * Resolve a channel from a deployment's `HAVEN_CONNECTOR_CHANNEL`.
3102
- *
3103
- * - unset, empty or whitespace ⇒ `fallback` (dashboards store a cleared
3104
- * variable as `""`, and that must land on the production-safe value);
3105
- * - well-formed ⇒ itself;
3106
- * - anything else ⇒ **throws**. It does not quietly fall back: a typo such as
3107
- * `dve` would then land on the production channel, and the environment would
3108
- * look fixed while reproducing the exact defect this slice removes.
3109
- *
3110
- * Well-formed-but-wrong (`dve` again) is *not* caught here and cannot be — it
3111
- * fails later at `npx`, where the error names the package. Stated rather than
3112
- * implied.
3113
- */
3114
- declare function resolveConnectorChannel(raw: string | undefined | null, fallback?: string): string;
3115
- /** `@haven_ai/connect@<channel>` — the spec an `npx` invocation names. */
3116
- declare function connectorSpec(channel?: string): string;
3117
- /**
3118
- * The re-run command every hint embeds.
3119
- *
3120
- * `connectorRerunCommand()` → `npx @haven_ai/connect@alpha`
3121
- * `connectorRerunCommand('--doctor')` → `npx @haven_ai/connect@alpha --doctor`
3122
- *
3123
- * `args` is appended verbatim so each call site keeps its own flags and its own
3124
- * surrounding sentence. The wording of those sentences is deliberately NOT
3125
- * moved here: several are inside signer refusal messages that users and agents
3126
- * pattern-match on, and this change is meant to move the channel token and
3127
- * nothing else.
3128
- */
3129
- declare function connectorRerunCommand(args?: string, options?: {
3130
- channel?: string;
3131
- npxFlags?: string;
3132
- }): string;
3133
-
3134
- /**
3135
- * The Node.js floor Haven's published packages support (#1161).
3136
- *
3137
- * ## Why this lives in the SDK
3138
- *
3139
- * Three packages need to enforce the same floor — `connect` (at setup),
3140
- * `signer` and `mcp` (at startup) — and `@haven_ai/sdk` is the only dependency
3141
- * all three already share. A copy per package is how the floor drifted in the
3142
- * first place: `engines` said `>=24` everywhere while connect's runtime manifest
3143
- * enforced `20.0.0`, so a connect run on Node v23 passed the guard, installed
3144
- * the signer, and signed a real payment. Two numbers for one fact is one number
3145
- * too many.
3146
- *
3147
- * Each consumer still owns its own refusal — the error type, the exit code, the
3148
- * wording of "what to do next" — because a library must never terminate its
3149
- * host process. This module only answers *is this version supported* and *what
3150
- * should we tell the user*.
3151
- *
3152
- * ## Why a floor is enforced at all
3153
- *
3154
- * `engines` is advisory: npm emits `EBADENGINE` and installs anyway unless the
3155
- * user happens to have `engine-strict` set. For a normal library that is a
3156
- * reasonable default. For the **signer** it is not — it holds the delegate key
3157
- * and produces every payment signature, so a subtle runtime incompatibility
3158
- * shows up as a wrong or missing signature on a money path. "It seemed to work"
3159
- * is precisely the evidence that cannot be relied on there.
3160
- */
3161
- /**
3162
- * The minimum supported Node.js version, as `major.minor.patch`.
3163
- *
3164
- * MUST equal the `engines.node` floor declared by every published Haven
3165
- * package. A guard test in each package asserts exactly that against its own
3166
- * `package.json`, so the two cannot drift again silently.
3167
- */
3168
- declare const HAVEN_MINIMUM_NODE_VERSION = "22.0.0";
3169
- /**
3170
- * Compare two Node versions. Negative when `left` is older.
3171
- *
3172
- * An unparseable version parses to `0.0.0` and therefore compares as older than
3173
- * any real floor — fail-closed. A version string Haven cannot read is not
3174
- * evidence of a supported runtime, and treating it as one would reopen exactly
3175
- * the hole this module closes.
3176
- */
3177
- declare function compareNodeVersions(left: string, right: string): number;
3178
- declare function isSupportedNodeVersion(nodeVersion?: string, minimumNodeVersion?: string): boolean;
3179
- interface UnsupportedNodeVersionMessageOptions {
3180
- /**
3181
- * What is being refused, in the user's terms — "Haven setup", "The Haven
3182
- * signer". Leads the message so the reader knows what just stopped.
3183
- */
3184
- subject: string;
3185
- nodeVersion?: string;
3186
- minimumNodeVersion?: string;
3187
- /** Appended verbatim as the closing line. Used for the re-run instruction. */
3188
- retryHint?: string;
3189
- }
3190
- /**
3191
- * The refusal text.
3192
- *
3193
- * Names the detected version, the required version, and **how to fix it** — the
3194
- * previous message stopped after the two version numbers, which tells a user
3195
- * they are stuck without telling them how to get unstuck. The version-manager
3196
- * lines are the fix for nearly everyone; the closing caveat is there because the
3197
- * runtime that *spawns* the signer is frequently not the shell that was
3198
- * upgraded, and a desktop app can keep launching the old Node long after
3199
- * `node -v` in a terminal says otherwise.
3200
- */
3201
- declare function unsupportedNodeVersionMessage(options: UnsupportedNodeVersionMessageOptions): string;
3202
-
3203
1232
  /**
3204
1233
  * #2914 (naming epic #2906, phase 5 — the CONTRACTION): the compatibility
3205
1234
  * window #2908 opened (read both server-response names, prefer the new;
@@ -3238,289 +1267,6 @@ declare function readX402ReceiptPayer(raw: {
3238
1267
  };
3239
1268
  }): string | undefined;
3240
1269
 
3241
- /**
3242
- * x402 protocol support for the Haven SDK.
3243
- *
3244
- * Provides:
3245
- * - parsePaymentRequired() — extract payment requirements from a 402 response
3246
- * - parsePaymentRequiredResponse() — async parser with JSON body fallback
3247
- * - encodePaymentProof() — encode a receipt as a PAYMENT-SIGNATURE header
3248
- *
3249
- * The main authorizeX402() and fetchWithPayment() are methods on HavenClient
3250
- * (see client.ts) since they need API access and signing.
3251
- */
3252
-
3253
- /**
3254
- * Persisted, agent-scoped facts used to preflight a signed standard x402
3255
- * payment header. This is an integrity comparison only: it never rebuilds,
3256
- * modifies, persists, or submits the supplied authorization.
3257
- */
3258
- interface X402PaymentHeaderContext {
3259
- merchantTo: string;
3260
- amountAtomic: string;
3261
- asset: string;
3262
- network: string;
3263
- resourceUrl: string;
3264
- payer: string;
3265
- chainId: number;
3266
- }
3267
- /** A deliberately value-free refusal for untrusted payment-header input. */
3268
- declare class X402PaymentHeaderValidationError extends Error {
3269
- constructor();
3270
- }
3271
- /**
3272
- * Upper bound on the MERCHANT-requested part of the EIP-3009 authorization
3273
- * window (#715, epic #713). The x402 library sets
3274
- * `validBefore = now + maxTimeoutSeconds` straight from the MERCHANT's 402
3275
- * challenge — without a cap, a malicious or sloppy merchant can request a
3276
- * year-long window and a leaked signed authorization stays spendable that
3277
- * whole time. 600 s is generous for any facilitator settle (typical is
3278
- * 30–60 s). This cap applies only to the signed authorization, never to the
3279
- * advertised requirements echoed in `accepted`. A merchant requiring more
3280
- * than the bounded lifetime can still reject at verification; preserving its
3281
- * offer does not widen Haven's signing policy.
3282
- */
3283
- declare const X402_MAX_AUTHORIZATION_WINDOW_SECONDS = 600;
3284
- /**
3285
- * Forward margin ADDED on top of the (clamped) merchant timeout when the
3286
- * authorization is actually signed (#1256). The x402 verify rule requires
3287
- * `validBefore ≥ now + maxTimeoutSeconds` AT THE FACILITATOR — but the
3288
- * upstream library computes `validBefore = now + maxTimeoutSeconds` at
3289
- * SIGNING time, leaving zero forward margin. Haven's flow guarantees elapsed
3290
- * time between the two (the funding UserOp confirms before the merchant
3291
- * retry, ~1 min plus latency), so every purchase against a merchant whose
3292
- * `maxTimeoutSeconds` exceeded that latency failed structurally — measured
3293
- * live on Base mainnet: Anchor requires 300 s, and 226 s remained at verify.
3294
- *
3295
- * 300 s covers funding + retry latency with room to spare. The #715 exposure
3296
- * ceiling becomes clamped-timeout + margin ≤ 900 s total forward — a
3297
- * deliberate widening from 600 s, recorded on #1256: an authorization that
3298
- * cannot pass verify protects no one, and 900 s is still bounded by the same
3299
- * clamp discipline.
3300
- */
3301
- declare const X402_SETTLEMENT_FORWARD_MARGIN_SECONDS = 300;
3302
- declare function normalizePaymentRequired(value: unknown): X402PaymentRequired | null;
3303
- /**
3304
- * The x402 wire header names, in one place (#2289).
3305
- *
3306
- * v2 renamed all three; v1's only name was `X-PAYMENT`, used in BOTH
3307
- * directions. Haven had adopted the v2 names for everything it *reads* and
3308
- * kept the v1 name for the one thing it *writes*, which is how a strict v2
3309
- * merchant came to never see a payment header at all.
3310
- *
3311
- * The 2026-08-31 owner decision was to send both outbound names on every
3312
- * retry rather than switch on `x402Version`: a v1 merchant ignores the name it
3313
- * does not know, a v2 merchant ignores the legacy one, and no version
3314
- * heuristic has to be right for a payment to land.
3315
- *
3316
- * **That is no longer unconditional (#2341).** It held while the cost of a
3317
- * spare header was zero, and on the EIP-3009 bridge it still is. On erc7710 it
3318
- * is not: that header carries a whole delegation chain, and duplicating it
3319
- * overflowed the merchant's header limit — HTTP 431, every erc7710 settlement
3320
- * refused. `x402PaymentHeaderNamesFor` below is the live rule; read it rather
3321
- * than this paragraph, which records why the simpler rule was right first.
3322
- */
3323
- /** v2 client→server payment payload. The name a strict v2 merchant reads. */
3324
- declare const X402_PAYMENT_HEADER_NAME = "PAYMENT-SIGNATURE";
3325
- /** v1 client→server payment payload; still accepted by most v2 merchants. */
3326
- declare const X402_LEGACY_PAYMENT_HEADER_NAME = "X-PAYMENT";
3327
- /** v2 server→client payment requirements. */
3328
- declare const X402_PAYMENT_REQUIRED_HEADER_NAME = "PAYMENT-REQUIRED";
3329
- /** v2 server→client settlement receipt. */
3330
- declare const X402_PAYMENT_RESPONSE_HEADER_NAME = "PAYMENT-RESPONSE";
3331
- /**
3332
- * Both wire names, v2 first — the value an EIP-3009 retry actually sends.
3333
- *
3334
- * **Not the general answer any more (#2341), and not what a recorder should
3335
- * reach for.** This was the evidence record's `paymentProofHeaderName` while
3336
- * both names always went on the wire; erc7710 now sends one, so a recorder
3337
- * still reading this constant would log a legacy header that was never sent —
3338
- * exactly the drift the previous wording promised it prevented. Use
3339
- * `x402PaymentHeaderNamesSent(paymentHeader)`. Kept exported because it is a
3340
- * published surface and removing it would break consumers.
3341
- */
3342
- declare const X402_PAYMENT_HEADER_NAMES_SENT = "PAYMENT-SIGNATURE, X-PAYMENT";
3343
- /**
3344
- * The x402 v2 payment envelope: `{x402Version, resource?, accepted, payload,
3345
- * extensions?}` per the spec's PaymentPayload (§5.2.2).
3346
- *
3347
- * The `resource` and `extensions` echoes are the #2361 fix, and they are not
3348
- * optional politeness: the spec makes the extensions echo a MUST ("the client
3349
- * must include at least the info received"), and CoinGecko's facilitator was
3350
- * live-bisected rejecting the echo-less envelope with a bare 400 while
3351
- * accepting the identical signature and `accepted`/`payload` bytes with the
3352
- * echoes added (#2360, Base mainnet, 2026-09-01). Both objects are echoed
3353
- * VERBATIM from the merchant's 402 — never reconstructed — and omitted when
3354
- * the challenge carries none, which keeps the envelope byte-identical to the
3355
- * pre-#2361 shape for echo-less merchants (Ampersend and Soundside settled
3356
- * that shape live, so omission is the proven-compatible default).
3357
- *
3358
- * The `accepted` wrap itself is #303's shape and predates this helper — see
3359
- * the #300/#303 history before "fixing" it: scheme/network live INSIDE
3360
- * `accepted` in v2, never at the top level.
3361
- */
3362
- declare function x402V2PaymentEnvelope(paymentRequired: Pick<X402PaymentRequired, 'x402Version' | 'resource' | 'extensions'>, accepted: X402PaymentOption, payload: unknown): Record<string, unknown>;
3363
- /**
3364
- * Parse an HTTP 402 response into x402 PaymentRequired data.
3365
- *
3366
- * Supports:
3367
- * - v2: PAYMENT-REQUIRED header (base64 JSON)
3368
- * - v1 fallback: X-PAYMENT header or response body
3369
- */
3370
- declare function parsePaymentRequired(response: Response): X402PaymentRequired;
3371
- /**
3372
- * Parse an HTTP 402 response into x402 PaymentRequired data.
3373
- *
3374
- * Soundside and other Bazaar-style MCP endpoints return the PaymentRequired
3375
- * object in the JSON body, while older Haven demos and many x402 examples use
3376
- * base64 headers. This keeps the synchronous header parser intact and adds the
3377
- * body fallback needed for those endpoints.
3378
- */
3379
- declare function parsePaymentRequiredResponse(response: Response): Promise<X402PaymentRequired>;
3380
- /**
3381
- * Select the best payment option from the x402 accepts array.
3382
- *
3383
- * Preference order:
3384
- * 1. Option on a Haven-supported network with a known token
3385
- * 2. Any option on a Haven-supported network
3386
- * 3. null — no compatible option
3387
- */
3388
- declare function selectPaymentOption(accepts: X402PaymentOption[]): X402PaymentOption | null;
3389
- /** The `extra.assetTransferMethod` value that marks an erc7710-settleable entry. */
3390
- declare const ERC7710_ASSET_TRANSFER_METHOD = "erc7710";
3391
- /**
3392
- * Read `extra.assetTransferMethod` defensively. `extra` is the merchant's own
3393
- * object, so it is untrusted shape: anything that is not the exact string is
3394
- * treated as "not erc7710" rather than coerced.
3395
- */
3396
- declare function x402AssetTransferMethod(option: X402PaymentOption): string | null;
3397
- /** True when the merchant advertises this entry as erc7710-settleable. */
3398
- declare function isErc7710Option(option: X402PaymentOption): boolean;
3399
- /**
3400
- * The facilitator addresses a merchant advertises for an erc7710 entry, for
3401
- * the #1058 redeemer pin — or `null` when it pins nothing.
3402
- *
3403
- * **An EMPTY array is `null`, not `[]`.** The backend rejects an empty
3404
- * `redeemers` list with a 400 (`routes/x402.ts`), and the QA scenario already
3405
- * treats empty as absent. Returning `[]` here would hand callers a value that
3406
- * means "pin to nobody" — which is not a narrower pin, it is an unbuildable
3407
- * delegation.
3408
- *
3409
- * Malformed entries are DROPPED rather than failing the whole option, and that
3410
- * asymmetry is deliberate. A pin narrowed by a merchant's typo means the
3411
- * facilitator that actually tries to redeem is not on the list, so redemption
3412
- * reverts — and erc7710 has no funding leg, so nothing moved and nothing is
3413
- * stranded. Refusing the option outright would instead deny a payment the
3414
- * remaining valid facilitators could have settled. Losing the payment is the
3415
- * worse outcome, precisely because the failure this issue closes (#1453) is the
3416
- * one where funds move BEFORE the rejection.
3417
- */
3418
- declare function x402FacilitatorAddresses(option: X402PaymentOption): string[] | null;
3419
- /**
3420
- * Select an option that can be paid with the official x402 EIP-3009 exact
3421
- * scheme. Haven's older tx-hash proof path can describe more networks; the
3422
- * merchant-verified path currently needs Base USDC.
3423
- *
3424
- * **Skips erc7710-tagged entries (#1453).** It used to return the first
3425
- * positional match and never look at `extra.assetTransferMethod`, so a merchant
3426
- * that listed its erc7710 entry first made a Haven client echo that option
3427
- * while signing a standard EIP-3009 authorization. The merchant rejects the
3428
- * mismatch cleanly — but on the legacy two-leg the Safe→delegate funding
3429
- * transfer has already executed, so the visible result is a stranded delegate
3430
- * balance for the sweep to reclaim. Only our own demo merchant's ordering was
3431
- * holding that shut, and that pin binds our merchant, not the ones we do not
3432
- * control.
3433
- */
3434
- declare function selectStandardPaymentOption(accepts: X402PaymentOption[]): X402PaymentOption | null;
3435
- /**
3436
- * Select the erc7710-settleable option, if the merchant advertises one.
3437
- */
3438
- declare function selectErc7710PaymentOption(accepts: X402PaymentOption[]): X402PaymentOption | null;
3439
- /** What a settlement-scheme decision resolved to. */
3440
- interface X402SchemeSelection {
3441
- scheme: 'erc7710' | 'eip3009';
3442
- option: X402PaymentOption;
3443
- /** Redeemer pin for the settlement child; only ever set on erc7710. */
3444
- facilitatorAddresses: string[] | null;
3445
- }
3446
- /**
3447
- * THE preference rule, in one place (#1450 owner decision, #1453).
3448
- *
3449
- * Prefer erc7710 whenever the account is on the delegation rail and the
3450
- * merchant advertises `extra.assetTransferMethod: "erc7710"`; fall back to
3451
- * the EIP-3009 bridge otherwise.
3452
- *
3453
- * Both halves of that condition are required, and the rail half is the
3454
- * caller's to supply — the SDK cannot see which rail an account is on from a
3455
- * 402 response alone. A legacy AllowanceModule account passing
3456
- * `delegationRail: true` would select a scheme its account cannot settle; the
3457
- * backend refuses that at authorize with the #1986 retired-rail 410 (#2245 —
3458
- * previously a scheme-specific 400 that wrongly implied the legacy rail could
3459
- * still settle via EIP-3009), which is where a rail mismatch SHOULD fail,
3460
- * on-chain-adjacent rather than in a client that could be lying to itself.
3461
- *
3462
- * Returns `null` when neither scheme has a payable entry — the caller decides
3463
- * whether that is an error or a reason to look elsewhere.
3464
- */
3465
- declare function selectX402SettlementScheme(accepts: X402PaymentOption[], opts: {
3466
- delegationRail: boolean;
3467
- }): X402SchemeSelection | null;
3468
- declare function x402AuthorizationAmount(option: X402PaymentOption): string;
3469
- /**
3470
- * Canonical Haven-authenticated x402 expected context, recomputed byte-for-byte
3471
- * by the edge signer before it signs anything.
3472
- *
3473
- * **Two versions, and the version is derived — never passed in (#1138).**
3474
- * `typedDataHash` present ⇒ v2, absent ⇒ v1. A v1 message is byte-identical to
3475
- * what shipped before, so existing signers keep verifying legacy-rail bindings
3476
- * unchanged.
3477
- *
3478
- * The version lives in both the header line and the payload so neither can be
3479
- * reinterpreted as the other: a v2 context cannot be replayed as a v1 one that
3480
- * drops the typed-data commitment, and a v1 context cannot be presented as v2.
3481
- * That downgrade is exactly the attack the digest exists to stop — see
3482
- * `assertExpectedBinding` in `@haven_ai/signer`, which refuses to raw-sign a
3483
- * hash under a v2 binding and refuses to sign typed data without one.
3484
- */
3485
- declare function buildX402ExpectedMessage(context: X402ExpectedContext): string;
3486
- declare function toStandardPaymentRequirements(paymentRequired: X402PaymentRequired, option: X402PaymentOption): PaymentRequirements;
3487
- /**
3488
- * Strictly validate an edge-signed EIP-3009 X-PAYMENT header against the
3489
- * persisted x402 intent context before a hosted relay can submit funding.
3490
- *
3491
- * The merchant/facilitator remains the final protocol verifier. This closes a
3492
- * separate hosted-relay integrity gap: malformed or context-mismatched input
3493
- * must never cause Haven to relay the funding signature first.
3494
- */
3495
- declare function validateStandardX402PaymentHeader(paymentHeader: string, context: X402PaymentHeaderContext): Promise<void>;
3496
- /**
3497
- * Encode a payment receipt as a base64 PAYMENT-SIGNATURE header value.
3498
- *
3499
- * This follows the x402 v2 protocol — the server's facilitator will
3500
- * verify the on-chain transaction referenced by tx_hash.
3501
- */
3502
- declare function encodePaymentProof(receipt: {
3503
- txHash: string;
3504
- paymentId: string;
3505
- token: string;
3506
- amount: string;
3507
- to: string;
3508
- resourceUrl?: string;
3509
- accepted?: X402PaymentOption;
3510
- payer?: string;
3511
- chainId?: number;
3512
- }): string;
3513
- /**
3514
- * Resolve a token symbol from a contract address.
3515
- *
3516
- * Checks all supported chains. For chain-specific resolution,
3517
- * pass the optional `network` CAIP-2 string (e.g. "eip155:100").
3518
- */
3519
- declare function resolveTokenFromAddress(address: string, network?: string): {
3520
- symbol: string;
3521
- decimals: number;
3522
- } | null;
3523
-
3524
1270
  /**
3525
1271
  * Where the PAID retry goes — and whether it may go there at all (#3097).
3526
1272
  *
@@ -3573,44 +1319,6 @@ declare class HavenInsecureRetryTargetError extends HavenError {
3573
1319
  }
3574
1320
  declare function assertSecureX402RetryTarget(url: string): void;
3575
1321
 
3576
- /**
3577
- * Runtime-agnostic base64 helpers — the single source of truth for the wire
3578
- * encoding shared by the SDK and the edge signer (#325).
3579
- *
3580
- * Why this module exists: the SDK used `atob`/`btoa` (Web globals) while the
3581
- * signer used `Buffer` (Node-only). Both worked because both currently run in
3582
- * Node ≥ 16, but the duplication was a latent wire-incompatibility — and the
3583
- * signer is headed for non-Node runtimes (browsers, Cloudflare Workers) where
3584
- * `Buffer` does not exist (#314).
3585
- *
3586
- * Encoding contract:
3587
- * - Output is ALWAYS standard base64 (`+`, `/`, padded). The x402 protocol's
3588
- * reference implementation validates headers against
3589
- * `/^[A-Za-z0-9+/]*={0,2}$/` — URL-safe output would be rejected.
3590
- * - Decoding is tolerant: URL-safe input (`-`, `_`, unpadded) is normalized
3591
- * before decoding, since third-party merchants are not guaranteed to be as
3592
- * strict as the reference implementation.
3593
- * - UTF-8 throughout. Naive `btoa(JSON.stringify(...))` throws on any
3594
- * non-Latin-1 character (e.g. a merchant description with an emoji or
3595
- * non-ASCII name); these helpers route through TextEncoder/TextDecoder on
3596
- * the Web path so multibyte characters round-trip identically on both
3597
- * runtimes.
3598
- */
3599
- /** Encode a UTF-8 string as standard base64. */
3600
- declare function encodeBase64Utf8(value: string): string;
3601
- /** Decode standard or URL-safe base64 to a UTF-8 string. */
3602
- declare function decodeBase64Utf8(value: string): string;
3603
- /** Encode a JSON-serializable value as a standard-base64 string. */
3604
- declare function encodeBase64Json(value: unknown): string;
3605
- /**
3606
- * Decode a base64 JSON payload.
3607
- *
3608
- * Pass a `label` to get a wrapped error message instead of the raw
3609
- * JSON/base64 error — call sites parsing untrusted merchant headers use this
3610
- * to produce actionable failures.
3611
- */
3612
- declare function decodeBase64Json<T>(value: string, label?: string): T;
3613
-
3614
1322
  /**
3615
1323
  * #1271 / #1301: bounded same-origin merchant MCP endpoint discovery.
3616
1324
  *
@@ -3639,4 +1347,4 @@ declare function discoverMerchantMcpUrl(inputUrl: string): Promise<string | null
3639
1347
  /** Trailing-slash/percent-case echoes compare equal; unparseable never does. */
3640
1348
  declare function sameUrl(a: string, b: string): boolean;
3641
1349
 
3642
- export { AGENT_APPROVAL_RELAY_JSON_SENTENCE, AGENT_APPROVAL_RELAY_PROSE_SENTENCE, AGENT_COMMAND_MODIFICATION_SENTENCE, AGENT_JSON_MODE_SENTENCE, AGENT_LOCAL_KEY_SENTENCE, AGENT_NETWORK_ACCESS_SENTENCE, AGENT_ONBOARDING_PROMPT, AGENT_PAYMENT_FAILURE_CODE_VALUES, AGENT_PAYMENT_NEXT_ACTION_VALUES, AGENT_PAYMENT_PHASE_VALUES, AGENT_PAYMENT_RAIL_VALUES, AGENT_README_SECTION_MD, AGENT_SECRET_HYGIENE_SENTENCE, AGENT_WIRING_COLLISION_RELAY_SENTENCE, type AgentNextStep, type AgentPaymentEnumSchema, AgentPaymentFailureCode, AgentPaymentFailureCodeDescriptions, AgentPaymentFailureCodeSchema, AgentPaymentNextAction, AgentPaymentNextActionDescriptions, AgentPaymentNextActionSchema, AgentPaymentPhase, AgentPaymentPhaseDescriptions, AgentPaymentPhaseSchema, AgentPaymentRail, AgentPaymentRailDescriptions, AgentPaymentRailSchema, type AgentPaymentSummary, type AgentPaymentWarning, AgentPaymentWarningCode, type AgentPurchaseSummary, CONNECTOR_PACKAGE_NAME, type CatalogSubmissionAccepted, type ClaudeTool, DEFAULT_CONFIRMATION_TIMEOUT_MS, DEFAULT_NEXT_TOOL_BY_ACTION, DISCOVERY_MAX_BYTES, ERC7710_ASSET_TRANSFER_METHOD, type EvidenceReportOutcome, HAVEN_AGENT_RUNBOOK_MD, HAVEN_CONNECTOR_CHANNEL, HAVEN_MINIMUM_NODE_VERSION, HAVEN_SKILL_BODY_MD, HAVEN_SKILL_MD, type HavenAgent, type HavenAgentAllowanceSummary, type HavenAgentReadiness, type HavenAgentSummary, type HavenAllowance, type HavenAllowanceSummary, HavenApiError, type HavenBalanceCoverage, type HavenCatalogEntry, type HavenCatalogMerchant, type HavenCatalogSubmission, HavenClient, type HavenClientConfig, HavenError, HavenInsecureRetryTargetError, type HavenPaymentReceipt, type HavenPaymentReceiptsPage, HavenPaymentStateError, HavenSigningError, HavenTimeoutError, HavenUnsupportedSignerVersionError, HavenZeroSettlementHashError, INSECURE_RETRY_TARGET_CODE, MERCHANT_DISCOVERY_PATHS, type MachinePaymentRail, MerchantTimeoutError, NEXT_TOOL_SERVER_NAMES, NEXT_TOOL_SERVER_ROLES, type NextStep, type NextStepArguments, type NextStepHandoff, type NextStepInput, type NextStepTarget, type NextStepTargets, type NextToolServerRole, type OpenAITool, type PaymentFee, type PaymentIntent, type PaymentNextAction, type PaymentPhase, type PaymentReceipt, type PaymentRequest, type PaymentResult, type PaymentResumeState, type PaymentStatus, type PaymentStatusResult, type PostPurchaseAllowanceSummary, RECEIPT_VERSION, type ReceiptVerification, type ResumeAuthorizedX402Input, type ResumeX402PaymentInput, SIGNER_UPDATE_FALLBACK, SKILL_FOLDER_NAME, SWEEP_BASE_CHAIN_ID, SWEEP_BASE_SEPOLIA_CHAIN_ID, SWEEP_BASE_SEPOLIA_USDC_ADDRESS, SWEEP_BASE_USDC_ADDRESS, type SharedToolKey, type SignData, SignerRefusalCode, type SweepAuthorization, type SweepConfirmation, type SweepEip712Domain, type SweepEntry, type SweepExpectedAuth, type SweepPreparation, type SweepPrepareResponse, type SweepResult, type SweepSubmitResponse, type SweepSubmitResult, type SweepTypedData, TRANSFER_WITH_AUTHORIZATION_TYPES, type ToolDescription, type UnsupportedNodeVersionMessageOptions, X402AlreadySettledError, type X402AuthorizationOptions, type X402Erc7710Settlement, type X402ExpectedAuth, type X402ExpectedContext, type X402Intent, type X402McpCallContext, type X402McpTransport, type X402MerchantCallContext, type X402MerchantOutcome, type X402MerchantOutcomeReport, type X402PaymentHeaderContext, X402PaymentHeaderValidationError, type X402PaymentOption, type X402PaymentRequired, type X402Quote, type X402Receipt, type X402RequestSnapshot, type X402ResumeState, type X402RetryTarget, type X402SchemeSelection, X402UnexpectedStatusError, X402_LEGACY_PAYMENT_HEADER_NAME, X402_MAX_AUTHORIZATION_WINDOW_SECONDS, X402_PAYMENT_HEADER_NAME, X402_PAYMENT_HEADER_NAMES_SENT, X402_PAYMENT_REQUIRED_HEADER_NAME, X402_PAYMENT_RESPONSE_HEADER_NAME, X402_SETTLEMENT_FORWARD_MARGIN_SECONDS, addressFromKey, assertSecureX402RetryTarget, buildSweepAuthorizationMessage, buildSweepTypedData, buildX402ExpectedMessage, compareNodeVersions, composeDescription, connectorRerunCommand, connectorSpec, createNextStepBuilder, decodeBase64Json, decodeBase64Utf8, defaultNextToolFor, discoverMerchantMcpUrl, encodeBase64Json, encodeBase64Utf8, encodePaymentProof, havenTools, isConnectorChannel, isErc7710Option, isSecureX402RetryTarget, isSupportedNodeVersion, isSweepableChain, isZeroSettlementTxHash, normalizePaymentRequired, parseNextTool, parsePaymentRequired, parsePaymentRequiredResponse, readX402ReceiptPayer, renderNextTool, resolveConnectorChannel, resolveTokenFromAddress, resolveX402RetryTarget, sameUrl, selectErc7710PaymentOption, selectPaymentOption, selectStandardPaymentOption, selectX402SettlementScheme, signHash, signUserOpTypedDataForDelegation, signerUpdateFallback, sweepUsdcAddress, sweepUsdcDomain, toStandardPaymentRequirements, toolDescriptions, unsupportedNodeVersionMessage, validateStandardX402PaymentHeader, verifyPaymentReceipt, verifySignature, x402AssetTransferMethod, x402AuthorizationAmount, x402FacilitatorAddresses, x402V2PaymentEnvelope };
1350
+ export { AGENT_APPROVAL_RELAY_JSON_SENTENCE, AGENT_APPROVAL_RELAY_PROSE_SENTENCE, AGENT_COMMAND_MODIFICATION_SENTENCE, AGENT_JSON_MODE_SENTENCE, AGENT_LOCAL_KEY_SENTENCE, AGENT_NETWORK_ACCESS_SENTENCE, AGENT_ONBOARDING_PROMPT, AGENT_README_SECTION_MD, AGENT_SECRET_HYGIENE_SENTENCE, AGENT_WIRING_COLLISION_RELAY_SENTENCE, AgentPaymentWarning, type ClaudeTool, DISCOVERY_MAX_BYTES, type EvidenceReportOutcome, HAVEN_AGENT_RUNBOOK_MD, HAVEN_SKILL_BODY_MD, HAVEN_SKILL_MD, HavenAgent, HavenAgentSummary, HavenAllowanceSummary, HavenBalanceCoverage, HavenCatalogEntry, HavenCatalogSubmission, HavenClient, HavenClientConfig, HavenClientUpdate, HavenError, HavenInsecureRetryTargetError, HavenPaymentReceipt, HavenPaymentReceiptsPage, INSECURE_RETRY_TARGET_CODE, MERCHANT_DISCOVERY_PATHS, type OpenAITool, PaymentIntent, type PaymentReceipt, PaymentRequest, PaymentResult, PaymentResumeState, PaymentStatusResult, PostPurchaseAllowanceSummary, RECEIPT_VERSION, type ReceiptVerification, ResumeAuthorizedX402Input, ResumeX402PaymentInput, SKILL_FOLDER_NAME, type SharedToolKey, SignData, SweepAuthorization, SweepPrepareResponse, SweepResult, SweepSubmitResponse, type ToolDescription, X402AuthorizationOptions, X402Erc7710Settlement, X402Intent, X402McpCallContext, X402McpTransport, X402MerchantCallContext, type X402MerchantOutcome, type X402MerchantOutcomeReport, X402PaymentRequired, X402Quote, X402Receipt, X402ResumeState, type X402RetryTarget, addressFromKey, assertSecureX402RetryTarget, composeDescription, discoverMerchantMcpUrl, havenTools, isSecureX402RetryTarget, isZeroSettlementTxHash, readX402ReceiptPayer, resolveX402RetryTarget, sameUrl, signHash, signUserOpTypedDataForDelegation, toolDescriptions, verifyPaymentReceipt, verifySignature };