@haven_ai/sdk 0.1.14-alpha.0 → 0.1.16-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -109,6 +109,7 @@ interface X402PaymentRequired {
109
109
  };
110
110
  accepts: X402PaymentOption[];
111
111
  error?: string;
112
+ extensions?: Record<string, unknown>;
112
113
  }
113
114
  /** A single payment option from x402 PaymentRequired. */
114
115
  interface X402PaymentOption {
@@ -173,6 +174,8 @@ interface X402AuthorizationOptions {
173
174
  interface X402Intent {
174
175
  /** Haven payment id for the funding transfer. */
175
176
  paymentId: string;
177
+ /** Stable key used to create or refresh this x402 funding intent. */
178
+ idempotencyKey: string;
176
179
  status: 'pending_signature';
177
180
  /** ISO 8601 expiry of the funding intent, if returned. */
178
181
  expiresAt?: string;
@@ -203,6 +206,8 @@ interface X402ExpectedContext {
203
206
  amount: string;
204
207
  asset: string;
205
208
  network: string;
209
+ /** Optional ISO expiry for the funding/quote window. When present, it is bound into the Haven-authenticated context. */
210
+ expiresAt?: string;
206
211
  }
207
212
  interface X402ExpectedAuth {
208
213
  version: 1;
@@ -217,6 +222,10 @@ interface X402RequestSnapshot {
217
222
  headers: [string, string][];
218
223
  body?: string;
219
224
  }
225
+ interface X402McpTransport {
226
+ handshakeRequired: boolean;
227
+ source: 'path' | 'bazaar';
228
+ }
220
229
  /** Quote parsed from an HTTP 402 response without creating a Haven payment. */
221
230
  interface X402Quote {
222
231
  rail: 'x402';
@@ -224,6 +233,7 @@ interface X402Quote {
224
233
  paymentRequired: X402PaymentRequired;
225
234
  accepted: X402PaymentOption;
226
235
  request: X402RequestSnapshot;
236
+ mcpTransport?: X402McpTransport;
227
237
  resourceUrl: string;
228
238
  description: string | null;
229
239
  mimeType: string | null;
@@ -405,6 +415,44 @@ interface HavenAllowanceSummary {
405
415
  chainId: number;
406
416
  allowances: HavenAllowance[];
407
417
  }
418
+ /**
419
+ * Affirmative spend-readiness for the authenticated agent, derived from the raw
420
+ * agent status plus the on-chain remaining allowance:
421
+ * - `ready` — active and at least one token has remaining on-chain allowance.
422
+ * - `needs_approval`— active but no remaining allowance to auto-spend; payments
423
+ * will be queued for the wallet owner to approve in Haven.
424
+ * - `revoked` — the agent's status is not `active`; nothing auto-executes.
425
+ *
426
+ * Note: a hard-paused/disabled credential is rejected by the API before this
427
+ * call returns, so it surfaces as an API error rather than `revoked`. `revoked`
428
+ * is reached when the request authenticates but the agent status is non-active.
429
+ *
430
+ * Wallet token balance is intentionally NOT folded in here: the on-chain
431
+ * remaining allowance is the gate Haven enforces, and insufficient wallet
432
+ * funding surfaces at pay time as INSUFFICIENT_FUNDS.
433
+ */
434
+ type HavenAgentReadiness = 'ready' | 'needs_approval' | 'revoked';
435
+ /** Compact, agent-facing per-token spend authority for the bootstrap summary. */
436
+ interface HavenAgentAllowanceSummary {
437
+ tokenSymbol: string;
438
+ /** Live on-chain remaining allowance in atomic units. */
439
+ remainingAtomic: string;
440
+ /** Human-readable remaining, e.g. "4.96 USDC". */
441
+ remainingDisplay: string;
442
+ /** Configured allowance amount (atomic) the owner granted. */
443
+ configuredAmount: string;
444
+ resetPeriodMin: number;
445
+ isResetPending: boolean;
446
+ }
447
+ /**
448
+ * One-shot "am I ready?" bootstrap: identity + live spend authority + a
449
+ * readiness signal, so an agent can answer "who am I and can I pay right now"
450
+ * from a single call at session start. Superset of {@link HavenAgent}.
451
+ */
452
+ interface HavenAgentSummary extends HavenAgent {
453
+ readiness: HavenAgentReadiness;
454
+ allowances: HavenAgentAllowanceSummary[];
455
+ }
408
456
  interface HavenPaymentReceipt {
409
457
  id: string;
410
458
  paymentId: string;
@@ -520,6 +568,11 @@ declare const AgentPaymentNextAction: {
520
568
  readonly StopAndTellUser: "stop_and_tell_user";
521
569
  /** Ask again only if the user still wants the payment after expiry. */
522
570
  readonly RequestAgainIfUserStillWantsIt: "request_again_if_user_still_wants_it";
571
+ /**
572
+ * The x402 funding/quote window expired. Re-quote the same logical merchant
573
+ * operation with the same idempotency key to stay double-charge-safe.
574
+ */
575
+ readonly PaymentWindowExpired: "payment_window_expired";
523
576
  /**
524
577
  * Stop and tell the user that the originating Safe needs to be funded or
525
578
  * the agent's per-token allowance needs to be raised before the payment
@@ -534,6 +587,15 @@ declare const AgentPaymentNextAction: {
534
587
  readonly SweepStrandedFunds: "sweep_stranded_funds";
535
588
  };
536
589
  type AgentPaymentNextAction = (typeof AgentPaymentNextAction)[keyof typeof AgentPaymentNextAction];
590
+ declare const AgentPaymentFailureCode: {
591
+ /** A merchant-authoritative x402 price exceeds the caller's pre-funding max_amount cap. */
592
+ readonly PriceExceedsMax: "PRICE_EXCEEDS_MAX";
593
+ /** The x402 funding/quote window expired before the signer or hosted settle step could finish. */
594
+ readonly PaymentWindowExpired: "PAYMENT_WINDOW_EXPIRED";
595
+ /** The Haven funding leg succeeded, but the merchant rejected the paid retry. */
596
+ readonly MerchantRejectedAfterFunding: "MERCHANT_REJECTED_AFTER_FUNDING";
597
+ };
598
+ type AgentPaymentFailureCode = (typeof AgentPaymentFailureCode)[keyof typeof AgentPaymentFailureCode];
537
599
  /**
538
600
  * Stable rail identifier carried on Haven agent payment responses and resume
539
601
  * state.
@@ -572,13 +634,16 @@ type AgentPaymentRail = (typeof AgentPaymentRail)[keyof typeof AgentPaymentRail]
572
634
  type PaymentPhase = AgentPaymentPhase;
573
635
  type PaymentNextAction = AgentPaymentNextAction;
574
636
  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")[];
575
- 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" | "fund_safe_or_raise_allowance" | "sweep_stranded_funds")[];
637
+ 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" | "payment_window_expired" | "fund_safe_or_raise_allowance" | "sweep_stranded_funds")[];
638
+ declare const AGENT_PAYMENT_FAILURE_CODE_VALUES: ("PRICE_EXCEEDS_MAX" | "PAYMENT_WINDOW_EXPIRED" | "MERCHANT_REJECTED_AFTER_FUNDING")[];
576
639
  declare const AGENT_PAYMENT_RAIL_VALUES: ("x402" | "mpp" | "mpp_demo" | "mpp_crypto" | "stripe_deposit" | "spt" | "direct")[];
577
640
  declare const AgentPaymentPhaseDescriptions: Record<AgentPaymentPhase, string>;
578
641
  declare const AgentPaymentNextActionDescriptions: Record<AgentPaymentNextAction, string>;
642
+ declare const AgentPaymentFailureCodeDescriptions: Record<AgentPaymentFailureCode, string>;
579
643
  declare const AgentPaymentRailDescriptions: Record<AgentPaymentRail, string>;
580
644
  declare const AgentPaymentPhaseSchema: AgentPaymentEnumSchema;
581
645
  declare const AgentPaymentNextActionSchema: AgentPaymentEnumSchema;
646
+ declare const AgentPaymentFailureCodeSchema: AgentPaymentEnumSchema;
582
647
  declare const AgentPaymentRailSchema: AgentPaymentEnumSchema;
583
648
  interface PaymentStatusResult {
584
649
  paymentId: string;
@@ -671,6 +736,166 @@ declare class HavenTimeoutError extends HavenError {
671
736
  constructor(paymentId: string);
672
737
  }
673
738
 
739
+ /**
740
+ * Gasless delegate-sweep primitives — the single source of truth shared by the
741
+ * edge signer (which signs) and the Haven backend (which relays).
742
+ *
743
+ * A stranded delegate EOA holds USDC but no ETH, so a raw ERC-20 transfer can't
744
+ * pay for its own gas. Instead the delegate signs an *off-chain* EIP-3009
745
+ * `TransferWithAuthorization` and the Haven relayer submits it on-chain and pays
746
+ * gas. The relayer is only a gas payer: it holds no allowance and is never a
747
+ * spender, so a relayer compromise cannot move user funds.
748
+ *
749
+ * Framework-neutral on purpose: `buildSweepTypedData` returns a plain
750
+ * `{ domain, types, primaryType, message }` that both viem
751
+ * (`signTypedData`/`recoverTypedDataAddress`) and ethers v6
752
+ * (`signTypedData`/`verifyTypedData`) accept, so the signer (viem) and backend
753
+ * (ethers) stay in lockstep without sharing a crypto library.
754
+ */
755
+ /** Base mainnet. The only chain Haven sweeps today. */
756
+ declare const SWEEP_BASE_CHAIN_ID = 8453;
757
+ /** Canonical Circle USDC on Base (FiatTokenV2_2). */
758
+ declare const SWEEP_BASE_USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
759
+ /** EIP-712 `TransferWithAuthorization` struct, per EIP-3009. */
760
+ declare const TRANSFER_WITH_AUTHORIZATION_TYPES: {
761
+ readonly TransferWithAuthorization: readonly [{
762
+ readonly name: "from";
763
+ readonly type: "address";
764
+ }, {
765
+ readonly name: "to";
766
+ readonly type: "address";
767
+ }, {
768
+ readonly name: "value";
769
+ readonly type: "uint256";
770
+ }, {
771
+ readonly name: "validAfter";
772
+ readonly type: "uint256";
773
+ }, {
774
+ readonly name: "validBefore";
775
+ readonly type: "uint256";
776
+ }, {
777
+ readonly name: "nonce";
778
+ readonly type: "bytes32";
779
+ }];
780
+ };
781
+ interface SweepEip712Domain {
782
+ name: string;
783
+ version: string;
784
+ chainId: number;
785
+ verifyingContract: string;
786
+ }
787
+ /**
788
+ * A fully-specified EIP-3009 authorization. All amounts/times are decimal
789
+ * strings (JSON-safe) and `nonce` is a 0x-prefixed 32-byte hex value. `token`
790
+ * and `chainId` are carried explicitly so the signer can assert they are
791
+ * canonical before signing.
792
+ */
793
+ interface SweepAuthorization {
794
+ /** Delegate EOA the funds are swept FROM. */
795
+ from: string;
796
+ /** Originating Safe the funds are swept TO. */
797
+ to: string;
798
+ /** Atomic USDC amount (decimal string). */
799
+ value: string;
800
+ /** Unix seconds the authorization becomes valid (decimal string, usually "0"). */
801
+ validAfter: string;
802
+ /** Unix seconds the authorization expires (decimal string). */
803
+ validBefore: string;
804
+ /** Random 0x-prefixed 32-byte hex nonce. */
805
+ nonce: string;
806
+ /** USDC contract address. */
807
+ token: string;
808
+ /** Chain id (8453 today). */
809
+ chainId: number;
810
+ }
811
+ /**
812
+ * Haven's signature over the sweep authorization context, signed with the same
813
+ * binding key the x402 expected-context uses. Lets the edge signer verify the
814
+ * authorization actually came from Haven (and wasn't crafted by a compromised
815
+ * hosted server pointing `to` at an attacker) before it signs.
816
+ */
817
+ interface SweepExpectedAuth {
818
+ version: 1;
819
+ message: string;
820
+ signature: string;
821
+ signer: string;
822
+ }
823
+ /** What `POST /machine-payments/sweep/prepare` returns when funds are stranded. */
824
+ interface SweepPreparation {
825
+ authorization: SweepAuthorization;
826
+ expectedAuth: SweepExpectedAuth;
827
+ }
828
+ /** Wire response from `POST /machine-payments/sweep/prepare` (snake_case). */
829
+ interface SweepPrepareResponse {
830
+ /** Present and true when the delegate holds nothing to recover. */
831
+ nothing_stranded?: boolean;
832
+ /** The authorization to sign — absent when nothing is stranded. */
833
+ authorization?: SweepAuthorization;
834
+ /** Haven's binding over the authorization — absent when nothing is stranded. */
835
+ expected_auth?: SweepExpectedAuth;
836
+ asset?: string;
837
+ amount?: string;
838
+ amount_atomic?: string;
839
+ chain_id: number;
840
+ sign_instructions?: string;
841
+ message?: string;
842
+ }
843
+ /** Wire response from `POST /machine-payments/sweep/submit` (snake_case). */
844
+ interface SweepSubmitResponse {
845
+ tx_hash: string;
846
+ asset: string;
847
+ amount: string;
848
+ amount_atomic: string;
849
+ from_address: string;
850
+ to_address: string;
851
+ chain_id: number;
852
+ explorer_url: string;
853
+ idempotent_replay?: boolean;
854
+ }
855
+ /** Result of a submitted gasless sweep. */
856
+ interface SweepSubmitResult {
857
+ txHash: string;
858
+ amount: string;
859
+ amountAtomic: string;
860
+ asset: string;
861
+ fromAddress: string;
862
+ toAddress: string;
863
+ chainId: number;
864
+ explorerUrl: string;
865
+ }
866
+ interface SweepTypedData {
867
+ domain: SweepEip712Domain;
868
+ types: typeof TRANSFER_WITH_AUTHORIZATION_TYPES;
869
+ primaryType: 'TransferWithAuthorization';
870
+ message: {
871
+ from: string;
872
+ to: string;
873
+ value: bigint;
874
+ validAfter: bigint;
875
+ validBefore: bigint;
876
+ nonce: string;
877
+ };
878
+ }
879
+ /** Resolve the canonical USDC contract for a sweepable chain, or throw. */
880
+ declare function sweepUsdcAddress(chainId: number): string;
881
+ /** Resolve the USDC EIP-712 domain for a sweepable chain, or throw. */
882
+ declare function sweepUsdcDomain(chainId: number): SweepEip712Domain;
883
+ /**
884
+ * Build the EIP-712 typed data for an authorization, validating that the token
885
+ * and chain are canonical (the domain's `verifyingContract` must match the
886
+ * authorization's `token`). Returns bigint-valued fields so both viem and
887
+ * ethers v6 sign/recover identically.
888
+ */
889
+ declare function buildSweepTypedData(auth: SweepAuthorization): SweepTypedData;
890
+ /**
891
+ * Canonical, deterministic string the backend signs and the signer re-derives
892
+ * for the authorization binding. The `Haven sweep authorization v1` namespace
893
+ * (and `kind`) is distinct from the x402 expected-context namespace so an x402
894
+ * binding can never be replayed as a sweep authorization even though they share
895
+ * a signing key.
896
+ */
897
+ declare function buildSweepAuthorizationMessage(auth: SweepAuthorization): string;
898
+
674
899
  declare class HavenClient {
675
900
  private readonly apiKey;
676
901
  private readonly delegateKey;
@@ -780,6 +1005,14 @@ declare class HavenClient {
780
1005
  * Get the agent identity tied to this API key.
781
1006
  */
782
1007
  getAgent(): Promise<HavenAgent>;
1008
+ /**
1009
+ * One-shot "am I ready?" bootstrap: identity + live spend authority + a
1010
+ * readiness signal, in a single call. Folds {@link getAgent} and
1011
+ * {@link getAllowances} together and derives a {@link HavenAgentReadiness}
1012
+ * so an agent can answer "who am I and can I pay right now" at session start
1013
+ * without two round trips and manual assembly.
1014
+ */
1015
+ getAgentSummary(): Promise<HavenAgentSummary>;
783
1016
  /**
784
1017
  * Sweep stranded USDC and ETH from the delegate EOA back to the originating Safe.
785
1018
  *
@@ -790,6 +1023,23 @@ declare class HavenClient {
790
1023
  * Requires `chainRpcs` to be set for the agent's chain in `HavenClientConfig`.
791
1024
  */
792
1025
  sweepDelegate(): Promise<SweepResult>;
1026
+ /**
1027
+ * Hosted (keyless) split-signer sweep — step 1 of 2.
1028
+ *
1029
+ * Asks the backend to build a gasless EIP-3009 sweep authorization for the
1030
+ * delegate's stranded USDC. Returns `nothing_stranded` when the delegate is
1031
+ * empty, otherwise an `authorization` + Haven `expected_auth` to hand to the
1032
+ * edge signer's `haven_sign_sweep_delegate`. No key is required on this client.
1033
+ */
1034
+ prepareSweep(): Promise<SweepPrepareResponse>;
1035
+ /**
1036
+ * Hosted (keyless) split-signer sweep — step 2 of 2.
1037
+ *
1038
+ * Relays the delegate-signed authorization. The Haven relayer submits the
1039
+ * on-chain `transferWithAuthorization` and pays gas; this client never holds
1040
+ * the key.
1041
+ */
1042
+ submitSweep(authorization: SweepAuthorization, signature: string): Promise<SweepSubmitResponse>;
793
1043
  /**
794
1044
  * Get configured and on-chain allowances for the authenticated agent.
795
1045
  */
@@ -913,27 +1163,39 @@ declare class HavenClient {
913
1163
  * amount/merchant/nonce-bound EIP-3009 authorization the edge signer already
914
1164
  * produced — the hosted server cannot mint or reuse signing authority.
915
1165
  *
916
- * When the URL is MCP-shaped (`/mcp` path), runs a fresh `initialize`
1166
+ * When the URL is MCP-shaped (`/mcp` path) or the quote-time transport context
1167
+ * says the merchant was Bazaar-discoverable, runs a fresh `initialize`
917
1168
  * handshake (the quote-time session is gone once funding confirms; the x402
918
1169
  * challenge is stateless w.r.t. the MCP session, so a fresh session is
919
1170
  * accepted), threads the session + wallet headers, sets `X-PAYMENT`, and
920
1171
  * collapses an SSE JSON-RPC response to its `result`.
921
- *
922
- * Limitation: detects MCP only by the `/mcp` path convention, not the
923
- * Coinbase Bazaar `extensions.bazaar` 402 signal that `fetch()` also honors.
924
- * A Bazaar-discoverable merchant on a non-`/mcp` URL would need the standard
925
- * `fetch()` path. All current MCP-tool merchants use the `/mcp` convention.
926
1172
  */
1173
+ /**
1174
+ * Wait for a payment's Safe→delegate funding tx to reach ≥1 on-chain
1175
+ * confirmation. The hosted x402 completion path MUST call this after funding
1176
+ * and before delivering the X-PAYMENT header, so the merchant's
1177
+ * balanceOf(delegate) / transferWithAuthorization verification sees the funded
1178
+ * balance — otherwise it rejects with "Payment verification failed". The
1179
+ * SDK's local path already does this (see authorizeStandardX402); the hosted
1180
+ * split flow regressed when the 5→3 collapse removed the incidental
1181
+ * inter-call latency that used to mask it. No-op when the funding tx hash or
1182
+ * a chain RPC (chainRpcs[chainId]) is unavailable.
1183
+ */
1184
+ ensureFundingConfirmed(paymentId: string, fundingTxHash?: string): Promise<void>;
927
1185
  completeX402MerchantCall(input: {
928
1186
  url: string;
929
1187
  init?: RequestInit;
1188
+ paymentId: string;
930
1189
  paymentHeader: string;
1190
+ mcpTransport?: X402McpTransport;
931
1191
  }): Promise<{
932
1192
  status: number;
933
1193
  ok: boolean;
934
1194
  body: unknown;
935
1195
  settlementTxHash?: string;
936
1196
  }>;
1197
+ private resolveX402MerchantCompletionContext;
1198
+ private resolveX402WalletForMerchantCall;
937
1199
  authorizeMachinePayment(challenge: MachinePaymentChallenge, options?: MppAuthorizationOptions): Promise<MachinePaymentReceipt>;
938
1200
  private authorizeMppDemoPayment;
939
1201
  resumeAuthorizedMpp(input: ResumeAuthorizedMppInput): Promise<MachinePaymentReceipt>;
@@ -970,6 +1232,7 @@ declare class HavenClient {
970
1232
  private requestInitFromSnapshot;
971
1233
  private withX402Wallet;
972
1234
  private buildX402Quote;
1235
+ private detectX402McpTransport;
973
1236
  private buildX402ResumeState;
974
1237
  private buildMppQuote;
975
1238
  private buildMppResumeState;
@@ -1159,8 +1422,9 @@ declare const toolDescriptions: {
1159
1422
  readonly nextActionGuidance: "";
1160
1423
  };
1161
1424
  readonly getAgent: {
1162
- readonly summary: "Return the authenticated agent identity, Haven wallet, delegate address, chain, and status.";
1163
- readonly behavior: "Read-only identity lookup. Useful for verifying which on-chain Safe and delegate the credential is bound to.";
1425
+ readonly summary: "Return the authenticated agent identity AND its live spend authority in one call: Haven wallet, delegate, chain, raw status, a readiness signal, and per-token remaining allowance (atomic + human-readable). The recommended first call in a new session to confirm who you are and whether you can pay right now.";
1426
+ readonly selectionGuidance: "Use this as the one-shot orientation/bootstrap at the start of a session, or whenever you need to confirm identity together with whether the agent can spend right now. For a detailed per-token breakdown (configured vs spent vs reset window) use haven_get_allowances.";
1427
+ readonly behavior: "Reads identity plus the on-chain AllowanceModule snapshot in one shot. readiness is \"ready\" when at least one token has remaining on-chain allowance, \"needs_approval\" when the agent is active but has no remaining allowance to auto-spend (payments will be queued for the wallet owner to approve in Haven), and \"revoked\" when the credential is not active. allowances[] carries remainingAtomic and remainingDisplay per token. Identity fields (id, name, status, safeAddress, delegateAddress, chainId) are unchanged from before.";
1164
1428
  readonly nextActionGuidance: "";
1165
1429
  };
1166
1430
  readonly getAllowances: {
@@ -1185,7 +1449,7 @@ declare const toolDescriptions: {
1185
1449
  readonly summary: "Discover payable services from Haven's curated merchant catalog — names, prices, and which pay tool to use.";
1186
1450
  readonly selectionGuidance: string;
1187
1451
  readonly behavior: string;
1188
- readonly nextActionGuidance: "Pick an entry, confirm the price with the user if it is non-trivial, and pay it with the tool named in suggested_tool, passing the entry's resource_url (and tool_name for MCP merchants).";
1452
+ readonly nextActionGuidance: "Pick an entry and pay it with the tool named in suggested_tool, passing the entry's resource_url (and tool_name for MCP merchants). Confirm the price from the live pay-tool result (not the catalog), and pass max_amount when the user has a cap.";
1189
1453
  };
1190
1454
  readonly sweep_delegate: {
1191
1455
  readonly summary: "Sweep stranded USDC and/or ETH from the delegate wallet back to the originating Safe.";
@@ -1207,10 +1471,12 @@ type SharedToolKey = keyof typeof toolDescriptions;
1207
1471
  *
1208
1472
  * This SDK file is the single source of truth for the generic, secret-free
1209
1473
  * skill content: no wallet address, no budget numbers, no per-agent values.
1210
- * The agent learns its identity and live budget at runtime via the
1211
- * `haven_get_agent` / `haven_get_allowances` MCP tools, so the same file works
1212
- * for every user. `packages/connect` imports this directly to auto-install the
1213
- * skill into runtime skills folders.
1474
+ * The agent learns its live budget at runtime via the `haven_get_agent` /
1475
+ * `haven_get_allowances` MCP tools, and can read identity + configured budget
1476
+ * for fast first-turn orientation from the non-secret `agent.json` the
1477
+ * connector writes (see `packages/connect/src/storage.ts`), so the same file
1478
+ * works for every user. `packages/connect` imports this directly to
1479
+ * auto-install the skill into runtime skills folders.
1214
1480
  *
1215
1481
  * `packages/frontend/src/lib/agent-skill-bundle.ts` keeps a deliberately
1216
1482
  * decoupled inline copy (the download fallback): frontend has zero
@@ -1219,7 +1485,7 @@ type SharedToolKey = keyof typeof toolDescriptions;
1219
1485
  * this canonical string and asserts byte-for-byte equality, so the two copies
1220
1486
  * cannot drift.
1221
1487
  */
1222
- declare const HAVEN_SKILL_MD = "---\nname: haven-pay\ndescription: Pay for things from the user's Haven wallet within their agent rules. Use when the user asks to send, pay, tip, or transfer crypto \u2014 or when a request hits an HTTP 402 (x402) paywall.\n---\n\n# Haven: pay from a Haven wallet\n\nThis skill lets the agent make payments from the user's Haven wallet through\nthe Haven MCP tools. Every payment is checked against the agent's on-chain\nbudget before money moves; payments above the remaining budget wait for the\nuser's approval in Haven.\n\n## When to use this skill\n\n- The user asks to send money, pay someone, tip, donate, or transfer tokens.\n- A request returns HTTP 402 (x402): use the Haven pay tools to settle it,\n then retry the original request.\n\n## Identity and budget come from the tools \u2014 never assume them\n\nDo not guess the wallet address, network, or budget. Read them live:\n\n- `haven_get_agent` \u2014 agent identity, Haven wallet address, network.\n- `haven_get_allowances` \u2014 current per-token budgets and what remains.\n\nBudgets reset on a period the user chose. If a payment exceeds the remaining\nbudget it is queued for the user to approve in the Haven dashboard \u2014 this is\nnormal, not an error.\n\n## Paying\n\n- **Direct transfer:** `haven_pay` with recipient, amount, and token.\n- **x402 paywall:** `haven_quote_x402` to get a quote, then\n `haven_pay_x402_quote`. In the hosted setup the signing step happens in\n the local Haven signer; follow the tool results \u2014 they tell you the next\n action at every step. Retry the original request only when the result says\n `retry_original_x402_request`.\n- **Paid MCP tool call:** `haven_pay_mcp_tool` with the merchant URL, tool\n name, and arguments. Then follow the returned steps: `haven_sign` the\n funding hash, `haven_submit` the signature, `haven_x402_sign_header` to\n build the payment header, and finally `haven_complete_mcp_tool` to settle\n with the merchant and get the tool result. Pass `payment_required` and\n `arguments` through verbatim from the `haven_pay_mcp_tool` result. Do not\n call the merchant yourself \u2014 Haven completes the merchant leg for you.\n- **Status:** `haven_get_payment_status` with a `payment_id` to check on\n queued or in-flight payments. Do not poll in a tight loop.\n\n## Approval semantics\n\n- A result with `pending_approval` means the payment exceeded the remaining\n budget and is waiting for the user in Haven. Tell the user, then check\n status later.\n- Never ask the user for private keys and never try to sign anything\n yourself \u2014 Haven signs. If a tool reports a missing or invalid credential,\n tell the user to re-run the Haven setup command.\n\n## Failure handling\n\nHaven errors are shaped `{ error, status, details? }` and written for\nhumans \u2014 surface the message verbatim. Common cases:\n\n- `pending_approval`: queued for the user's approval (see above).\n- `insufficient_funds`: the Haven wallet doesn't hold enough of that token.\n Suggest the user add funds in the Haven dashboard.\n- Budget exceeded: tell the user how much remains (from\n `haven_get_allowances`) and that they can raise the budget in Haven.\n\n## Revoke\n\nIf this agent's credential may have leaked, tell the user to pause or revoke\nthe agent in the Haven dashboard under Agents. New requests stop immediately\nfor that credential.\n";
1488
+ declare const HAVEN_SKILL_MD = "---\nname: haven-pay\ndescription: Pay for things from the user's Haven wallet within their agent rules. Use when the user asks to send, pay, tip, or transfer crypto \u2014 or when a request hits an HTTP 402 (x402) paywall.\n---\n\n# Haven: pay from a Haven wallet\n\nThis skill lets the agent make payments from the user's Haven wallet through\nthe Haven MCP tools. Every payment is checked against the agent's on-chain\nbudget before money moves; payments above the remaining budget wait for the\nuser's approval in Haven.\n\nHosted tools run in the `mcp__haven__` namespace. Local signing tools run in\nthe `mcp__haven-signer__` namespace and keep the delegate key on this machine.\n\n## When to use this skill\n\n- The user asks to send money, pay someone, tip, donate, or transfer tokens.\n- A request returns HTTP 402 (x402): use the Haven pay tools to settle it,\n then retry the original request.\n\n## Identity and budget\n\nDo not guess the wallet address, network, or budget.\n\nFor instant orientation at the start of a session, read the non-secret\n`agent.json` the connector wrote to your Haven credential directory (typically\n`~/.haven/agents/<agent-id>/agent.json` \u2014 if you don't know the agent id, list\n`~/.haven/agents/` to find the folder). It\nholds your agent id, Haven wallet address, network, and *configured* per-token\nbudget, and contains no keys \u2014 the fastest way to answer \"who am I and what may\nI spend\" with no round trip. If that file is absent (some setups don't write\nit), use the tools below instead.\n\nBefore any payment, confirm the *live remaining* budget with the tools \u2014\n`agent.json` shows the configured budget, not what is left after recent\nspending:\n\n- `haven_get_agent` \u2014 the recommended first call: identity (wallet, network)\n plus a readiness signal (`ready` / `needs_approval` / `revoked`) and live\n remaining per-token allowance, in one shot.\n- `haven_get_allowances` \u2014 detailed per-token breakdown (configured, spent,\n reset window) when you need more than the summary.\n\nBudgets reset on a period the user chose. If a payment exceeds the remaining\nbudget it is queued for the user to approve in the Haven dashboard \u2014 this is\nnormal, not an error.\n\n## Paying\n\n- **Direct transfer:** `haven_pay` with recipient, amount, and token.\n- **x402 paywall:** `haven_quote_x402` to get a quote, then\n `haven_pay_x402_quote`. In the hosted setup the signing step happens in\n the local Haven signer; follow the tool results \u2014 they tell you the next\n action at every step. Retry the original request only when the result says\n `retry_original_x402_request`.\n- **Paid MCP tool call:** `mcp__haven__haven_pay_mcp_tool` with the merchant\n URL, tool name, and arguments, then finish in two calls (fast path):\n `mcp__haven-signer__haven_sign_x402` on the local signer (pass\n `payload_hash`, `x402_expected` as the nested `x402.expected` object, and\n `payment_required`) returns `{ signature, payment_header }`; then\n `mcp__haven__haven_settle_mcp_tool` (pass `payment_id`, `signature`,\n `payment_header`, `merchant_url`, `tool_name`, `arguments`,\n `mcp_transport`) funds and settles in one step and returns the tool result.\n If it returns `settled: false`, funding is queued for the user's approval \u2014\n tell them and check status later, do not re-pay. Step-by-step alternative:\n `mcp__haven-signer__haven_sign` \u2192 `mcp__haven__haven_submit` \u2192\n `mcp__haven-signer__haven_x402_sign_header` \u2192\n `mcp__haven__haven_complete_mcp_tool`. Pass `payment_required`,\n `arguments`, and `mcp_transport` verbatim from the\n `mcp__haven__haven_pay_mcp_tool` result. The returned `expires_at` is the\n signing window; if a tool returns `PAYMENT_WINDOW_EXPIRED`, re-run\n `mcp__haven__haven_pay_mcp_tool` with the same\n `idempotency_key`. Do not call the merchant yourself \u2014 Haven completes the\n merchant leg for you.\n- **Prices:** show the user the live price from the pay-tool result, never a\n catalog price. `haven_discover_tools` prices are indicative\n (`price_is_indicative`) and can be stale. The pay-tool result's `amount` /\n `amount_atomic` is the amount Haven authorizes for the call \u2014 a ceiling the\n merchant settles at or below \u2014 so present it as the most the user will pay.\n Pass `max_amount` (atomic units) to `haven_pay_mcp_tool` /\n `haven_pay_x402_quote` to reject a quote whose authorized amount is above the\n user's cap, before any funds move.\n- **Status:** `haven_get_payment_status` with a `payment_id` to check on\n queued or in-flight payments. Do not poll in a tight loop.\n\n## Approval semantics\n\n- A result with `pending_approval` means the payment exceeded the remaining\n budget and is waiting for the user in Haven. Tell the user, then check\n status later.\n- Never ask the user for private keys. Signing happens only in the local Haven\n signer; the hosted Haven tools never receive the signing key. If a tool\n reports a missing or invalid credential, tell the user to re-run the Haven\n setup command.\n\n## Failure handling\n\nHaven tool failures are shaped like `{ success: false, code, message, ... }`\nor older `{ error, status, details? }` responses. Branch on `code` when\npresent and surface `message` or `error` verbatim. Common cases:\n\n- `pending_approval`: queued for the user's approval (see above).\n- `insufficient_funds`: the Haven wallet doesn't hold enough of that token.\n Suggest the user add funds in the Haven dashboard.\n- `PRICE_EXCEEDS_MAX`: the live merchant price exceeded your `max_amount`.\n No funds moved; ask the user before retrying with a higher cap.\n- `PAYMENT_WINDOW_EXPIRED`: re-run `mcp__haven__haven_pay_mcp_tool` with the same\n `idempotency_key`, then sign the fresh `payload_hash`.\n- `MERCHANT_REJECTED_AFTER_FUNDING`: stop retrying the merchant and use\n `mcp__haven__haven_sweep_delegate` to recover stranded delegate funds.\n- Budget exceeded: tell the user how much remains (from\n `haven_get_allowances`) and that they can raise the budget in Haven.\n\n## Revoke\n\nIf this agent's credential may have leaked, tell the user to pause or revoke\nthe agent in the Haven dashboard under Agents. New requests stop immediately\nfor that credential.\n";
1223
1489
  /** Directory name for the installed skill folder. */
1224
1490
  declare const SKILL_FOLDER_NAME = "haven-pay";
1225
1491
 
@@ -1331,4 +1597,4 @@ declare function encodeBase64Json(value: unknown): string;
1331
1597
  */
1332
1598
  declare function decodeBase64Json<T>(value: string, label?: string): T;
1333
1599
 
1334
- export { AGENT_PAYMENT_NEXT_ACTION_VALUES, AGENT_PAYMENT_PHASE_VALUES, AGENT_PAYMENT_RAIL_VALUES, type AgentPaymentEnumSchema, AgentPaymentNextAction, AgentPaymentNextActionDescriptions, AgentPaymentNextActionSchema, AgentPaymentPhase, AgentPaymentPhaseDescriptions, AgentPaymentPhaseSchema, AgentPaymentRail, AgentPaymentRailDescriptions, AgentPaymentRailSchema, type ClaudeTool, HAVEN_SKILL_MD, type HavenAgent, type HavenAllowance, type HavenAllowanceSummary, HavenApiError, type HavenCatalogEntry, HavenClient, type HavenClientConfig, HavenError, type HavenPaymentReceipt, HavenPaymentStateError, HavenSigningError, HavenTimeoutError, type MachinePaymentChallenge, type MachinePaymentRail, type MachinePaymentReceipt, type MppAuthorizationOptions, type MppQuote, type MppResumeState, type OpenAITool, type PaymentIntent, type PaymentNextAction, type PaymentPhase, type PaymentRequest, type PaymentResult, type PaymentResumeState, type PaymentStatus, type PaymentStatusResult, type PendingApproval, type ResumeAuthorizedMppInput, type ResumeAuthorizedX402Input, type ResumeMppPaymentInput, type ResumeX402PaymentInput, SKILL_FOLDER_NAME, type SharedToolKey, type SignData, type SweepEntry, type SweepResult, type ToolDescription, type X402AuthorizationOptions, type X402ExpectedAuth, type X402ExpectedContext, type X402Intent, type X402PaymentOption, type X402PaymentRequired, type X402Quote, type X402Receipt, type X402RequestSnapshot, type X402ResumeState, addressFromKey, buildMachinePaymentIdempotencyKey, buildX402ExpectedMessage, composeDescription, decodeBase64Json, decodeBase64Utf8, encodeBase64Json, encodeBase64Utf8, encodeMachinePaymentProof, encodePaymentProof, havenTools, parseMachinePaymentChallenge, parseMachinePaymentChallengeResponse, parsePaymentRequired, parsePaymentRequiredResponse, selectPaymentOption, selectStandardPaymentOption, signHash, toStandardPaymentRequirements, toolDescriptions, verifySignature, x402AuthorizationAmount };
1600
+ export { AGENT_PAYMENT_FAILURE_CODE_VALUES, AGENT_PAYMENT_NEXT_ACTION_VALUES, AGENT_PAYMENT_PHASE_VALUES, AGENT_PAYMENT_RAIL_VALUES, type AgentPaymentEnumSchema, AgentPaymentFailureCode, AgentPaymentFailureCodeDescriptions, AgentPaymentFailureCodeSchema, AgentPaymentNextAction, AgentPaymentNextActionDescriptions, AgentPaymentNextActionSchema, AgentPaymentPhase, AgentPaymentPhaseDescriptions, AgentPaymentPhaseSchema, AgentPaymentRail, AgentPaymentRailDescriptions, AgentPaymentRailSchema, type ClaudeTool, HAVEN_SKILL_MD, type HavenAgent, type HavenAgentAllowanceSummary, type HavenAgentReadiness, type HavenAgentSummary, type HavenAllowance, type HavenAllowanceSummary, HavenApiError, type HavenCatalogEntry, HavenClient, type HavenClientConfig, HavenError, type HavenPaymentReceipt, HavenPaymentStateError, HavenSigningError, HavenTimeoutError, type MachinePaymentChallenge, type MachinePaymentRail, type MachinePaymentReceipt, type MppAuthorizationOptions, type MppQuote, type MppResumeState, type OpenAITool, type PaymentIntent, type PaymentNextAction, type PaymentPhase, type PaymentRequest, type PaymentResult, type PaymentResumeState, type PaymentStatus, type PaymentStatusResult, type PendingApproval, type ResumeAuthorizedMppInput, type ResumeAuthorizedX402Input, type ResumeMppPaymentInput, type ResumeX402PaymentInput, SKILL_FOLDER_NAME, SWEEP_BASE_CHAIN_ID, SWEEP_BASE_USDC_ADDRESS, type SharedToolKey, type SignData, type SweepAuthorization, 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 X402AuthorizationOptions, type X402ExpectedAuth, type X402ExpectedContext, type X402Intent, type X402McpTransport, type X402PaymentOption, type X402PaymentRequired, type X402Quote, type X402Receipt, type X402RequestSnapshot, type X402ResumeState, addressFromKey, buildMachinePaymentIdempotencyKey, buildSweepAuthorizationMessage, buildSweepTypedData, buildX402ExpectedMessage, composeDescription, decodeBase64Json, decodeBase64Utf8, encodeBase64Json, encodeBase64Utf8, encodeMachinePaymentProof, encodePaymentProof, havenTools, parseMachinePaymentChallenge, parseMachinePaymentChallengeResponse, parsePaymentRequired, parsePaymentRequiredResponse, selectPaymentOption, selectStandardPaymentOption, signHash, sweepUsdcAddress, sweepUsdcDomain, toStandardPaymentRequirements, toolDescriptions, verifySignature, x402AuthorizationAmount };