@haven_ai/sdk 0.1.15-alpha.0 → 0.1.17-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
@@ -415,6 +415,44 @@ interface HavenAllowanceSummary {
415
415
  chainId: number;
416
416
  allowances: HavenAllowance[];
417
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
+ }
418
456
  interface HavenPaymentReceipt {
419
457
  id: string;
420
458
  paymentId: string;
@@ -967,6 +1005,14 @@ declare class HavenClient {
967
1005
  * Get the agent identity tied to this API key.
968
1006
  */
969
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>;
970
1016
  /**
971
1017
  * Sweep stranded USDC and ETH from the delegate EOA back to the originating Safe.
972
1018
  *
@@ -1124,6 +1170,18 @@ declare class HavenClient {
1124
1170
  * accepted), threads the session + wallet headers, sets `X-PAYMENT`, and
1125
1171
  * collapses an SSE JSON-RPC response to its `result`.
1126
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>;
1127
1185
  completeX402MerchantCall(input: {
1128
1186
  url: string;
1129
1187
  init?: RequestInit;
@@ -1364,8 +1422,9 @@ declare const toolDescriptions: {
1364
1422
  readonly nextActionGuidance: "";
1365
1423
  };
1366
1424
  readonly getAgent: {
1367
- readonly summary: "Return the authenticated agent identity, Haven wallet, delegate address, chain, and status.";
1368
- 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.";
1369
1428
  readonly nextActionGuidance: "";
1370
1429
  };
1371
1430
  readonly getAllowances: {
@@ -1412,10 +1471,12 @@ type SharedToolKey = keyof typeof toolDescriptions;
1412
1471
  *
1413
1472
  * This SDK file is the single source of truth for the generic, secret-free
1414
1473
  * skill content: no wallet address, no budget numbers, no per-agent values.
1415
- * The agent learns its identity and live budget at runtime via the
1416
- * `haven_get_agent` / `haven_get_allowances` MCP tools, so the same file works
1417
- * for every user. `packages/connect` imports this directly to auto-install the
1418
- * 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.
1419
1480
  *
1420
1481
  * `packages/frontend/src/lib/agent-skill-bundle.ts` keeps a deliberately
1421
1482
  * decoupled inline copy (the download fallback): frontend has zero
@@ -1424,7 +1485,7 @@ type SharedToolKey = keyof typeof toolDescriptions;
1424
1485
  * this canonical string and asserts byte-for-byte equality, so the two copies
1425
1486
  * cannot drift.
1426
1487
  */
1427
- 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 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:** `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";
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";
1428
1489
  /** Directory name for the installed skill folder. */
1429
1490
  declare const SKILL_FOLDER_NAME = "haven-pay";
1430
1491
 
@@ -1536,4 +1597,4 @@ declare function encodeBase64Json(value: unknown): string;
1536
1597
  */
1537
1598
  declare function decodeBase64Json<T>(value: string, label?: string): T;
1538
1599
 
1539
- 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 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 };
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 };
package/dist/index.d.ts CHANGED
@@ -415,6 +415,44 @@ interface HavenAllowanceSummary {
415
415
  chainId: number;
416
416
  allowances: HavenAllowance[];
417
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
+ }
418
456
  interface HavenPaymentReceipt {
419
457
  id: string;
420
458
  paymentId: string;
@@ -967,6 +1005,14 @@ declare class HavenClient {
967
1005
  * Get the agent identity tied to this API key.
968
1006
  */
969
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>;
970
1016
  /**
971
1017
  * Sweep stranded USDC and ETH from the delegate EOA back to the originating Safe.
972
1018
  *
@@ -1124,6 +1170,18 @@ declare class HavenClient {
1124
1170
  * accepted), threads the session + wallet headers, sets `X-PAYMENT`, and
1125
1171
  * collapses an SSE JSON-RPC response to its `result`.
1126
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>;
1127
1185
  completeX402MerchantCall(input: {
1128
1186
  url: string;
1129
1187
  init?: RequestInit;
@@ -1364,8 +1422,9 @@ declare const toolDescriptions: {
1364
1422
  readonly nextActionGuidance: "";
1365
1423
  };
1366
1424
  readonly getAgent: {
1367
- readonly summary: "Return the authenticated agent identity, Haven wallet, delegate address, chain, and status.";
1368
- 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.";
1369
1428
  readonly nextActionGuidance: "";
1370
1429
  };
1371
1430
  readonly getAllowances: {
@@ -1412,10 +1471,12 @@ type SharedToolKey = keyof typeof toolDescriptions;
1412
1471
  *
1413
1472
  * This SDK file is the single source of truth for the generic, secret-free
1414
1473
  * skill content: no wallet address, no budget numbers, no per-agent values.
1415
- * The agent learns its identity and live budget at runtime via the
1416
- * `haven_get_agent` / `haven_get_allowances` MCP tools, so the same file works
1417
- * for every user. `packages/connect` imports this directly to auto-install the
1418
- * 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.
1419
1480
  *
1420
1481
  * `packages/frontend/src/lib/agent-skill-bundle.ts` keeps a deliberately
1421
1482
  * decoupled inline copy (the download fallback): frontend has zero
@@ -1424,7 +1485,7 @@ type SharedToolKey = keyof typeof toolDescriptions;
1424
1485
  * this canonical string and asserts byte-for-byte equality, so the two copies
1425
1486
  * cannot drift.
1426
1487
  */
1427
- 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 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:** `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";
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";
1428
1489
  /** Directory name for the installed skill folder. */
1429
1490
  declare const SKILL_FOLDER_NAME = "haven-pay";
1430
1491
 
@@ -1536,4 +1597,4 @@ declare function encodeBase64Json(value: unknown): string;
1536
1597
  */
1537
1598
  declare function decodeBase64Json<T>(value: string, label?: string): T;
1538
1599
 
1539
- 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 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 };
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 };
package/dist/index.js CHANGED
@@ -529,6 +529,7 @@ function stableStringify(value) {
529
529
  const primitive = JSON.stringify(value);
530
530
  return primitive === void 0 ? "undefined" : primitive;
531
531
  }
532
+ if (value instanceof Date) return JSON.stringify(value.toISOString());
532
533
  if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(",")}]`;
533
534
  const object = value;
534
535
  return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(object[key])}`).join(",")}}`;
@@ -630,11 +631,24 @@ var DEFAULT_REQUEST_TIMEOUT = 3e4;
630
631
  var DEFAULT_CONFIRMATION_TIMEOUT = 9e4;
631
632
  var DEFAULT_POLLING_INTERVAL = 3e3;
632
633
  function formatAtomicAmount(atomic, decimals) {
634
+ if (atomic < 0n) return "0.0";
633
635
  const s = atomic.toString().padStart(decimals + 1, "0");
634
636
  const intPart = s.slice(0, s.length - decimals) || "0";
635
637
  const fracPart = s.slice(s.length - decimals).replace(/0+$/, "") || "0";
636
638
  return `${intPart}.${fracPart}`;
637
639
  }
640
+ function safeBigInt(value) {
641
+ try {
642
+ return BigInt(value);
643
+ } catch {
644
+ return 0n;
645
+ }
646
+ }
647
+ function deriveReadiness(status, allowances) {
648
+ if (status !== "active") return "revoked";
649
+ const hasSpendable = allowances.some((a) => safeBigInt(a.remainingAtomic) > 0n);
650
+ return hasSpendable ? "ready" : "needs_approval";
651
+ }
638
652
  var MCP_PROTOCOL_VERSION = "2025-06-18";
639
653
  var MCP_ACCEPT = "application/json, text/event-stream";
640
654
  var MCP_CLIENT_INFO = { name: "haven-sdk", version: "1" };
@@ -1001,6 +1015,32 @@ var HavenClient = class {
1001
1015
  chainId: raw.chain_id
1002
1016
  };
1003
1017
  }
1018
+ /**
1019
+ * One-shot "am I ready?" bootstrap: identity + live spend authority + a
1020
+ * readiness signal, in a single call. Folds {@link getAgent} and
1021
+ * {@link getAllowances} together and derives a {@link HavenAgentReadiness}
1022
+ * so an agent can answer "who am I and can I pay right now" at session start
1023
+ * without two round trips and manual assembly.
1024
+ */
1025
+ async getAgentSummary() {
1026
+ const [agent, allowanceSummary] = await Promise.all([
1027
+ this.getAgent(),
1028
+ this.getAllowances()
1029
+ ]);
1030
+ const allowances = allowanceSummary.allowances.map((a) => {
1031
+ const token = resolveTokenFromAddress(a.tokenAddress);
1032
+ const remainingDisplay = token ? `${formatAtomicAmount(safeBigInt(a.onchain.remaining), token.decimals)} ${a.tokenSymbol}` : `${a.onchain.remaining} ${a.tokenSymbol} (atomic; unknown decimals)`;
1033
+ return {
1034
+ tokenSymbol: a.tokenSymbol,
1035
+ remainingAtomic: a.onchain.remaining,
1036
+ remainingDisplay,
1037
+ configuredAmount: a.configuredAmount,
1038
+ resetPeriodMin: a.resetPeriodMin,
1039
+ isResetPending: a.onchain.isResetPending
1040
+ };
1041
+ });
1042
+ return { ...agent, readiness: deriveReadiness(agent.status, allowances), allowances };
1043
+ }
1004
1044
  /**
1005
1045
  * Sweep stranded USDC and ETH from the delegate EOA back to the originating Safe.
1006
1046
  *
@@ -1684,6 +1724,21 @@ var HavenClient = class {
1684
1724
  * accepted), threads the session + wallet headers, sets `X-PAYMENT`, and
1685
1725
  * collapses an SSE JSON-RPC response to its `result`.
1686
1726
  */
1727
+ /**
1728
+ * Wait for a payment's Safe→delegate funding tx to reach ≥1 on-chain
1729
+ * confirmation. The hosted x402 completion path MUST call this after funding
1730
+ * and before delivering the X-PAYMENT header, so the merchant's
1731
+ * balanceOf(delegate) / transferWithAuthorization verification sees the funded
1732
+ * balance — otherwise it rejects with "Payment verification failed". The
1733
+ * SDK's local path already does this (see authorizeStandardX402); the hosted
1734
+ * split flow regressed when the 5→3 collapse removed the incidental
1735
+ * inter-call latency that used to mask it. No-op when the funding tx hash or
1736
+ * a chain RPC (chainRpcs[chainId]) is unavailable.
1737
+ */
1738
+ async ensureFundingConfirmed(paymentId, fundingTxHash) {
1739
+ const status = await this.getPaymentStatus(paymentId);
1740
+ await this.waitForFundingTx(fundingTxHash ?? status.txHash ?? void 0, status.chainId);
1741
+ }
1687
1742
  async completeX402MerchantCall(input) {
1688
1743
  const evidenceContext = await this.resolveX402MerchantCompletionContext({
1689
1744
  paymentId: input.paymentId,
@@ -2959,8 +3014,9 @@ var toolDescriptions = {
2959
3014
  nextActionGuidance: ""
2960
3015
  },
2961
3016
  getAgent: {
2962
- summary: "Return the authenticated agent identity, Haven wallet, delegate address, chain, and status.",
2963
- behavior: "Read-only identity lookup. Useful for verifying which on-chain Safe and delegate the credential is bound to.",
3017
+ 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.",
3018
+ 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.",
3019
+ 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.',
2964
3020
  nextActionGuidance: ""
2965
3021
  },
2966
3022
  getAllowances: {
@@ -3261,12 +3317,28 @@ the \`mcp__haven-signer__\` namespace and keep the delegate key on this machine.
3261
3317
  - A request returns HTTP 402 (x402): use the Haven pay tools to settle it,
3262
3318
  then retry the original request.
3263
3319
 
3264
- ## Identity and budget come from the tools \u2014 never assume them
3320
+ ## Identity and budget
3321
+
3322
+ Do not guess the wallet address, network, or budget.
3323
+
3324
+ For instant orientation at the start of a session, read the non-secret
3325
+ \`agent.json\` the connector wrote to your Haven credential directory (typically
3326
+ \`~/.haven/agents/<agent-id>/agent.json\` \u2014 if you don't know the agent id, list
3327
+ \`~/.haven/agents/\` to find the folder). It
3328
+ holds your agent id, Haven wallet address, network, and *configured* per-token
3329
+ budget, and contains no keys \u2014 the fastest way to answer "who am I and what may
3330
+ I spend" with no round trip. If that file is absent (some setups don't write
3331
+ it), use the tools below instead.
3265
3332
 
3266
- Do not guess the wallet address, network, or budget. Read them live:
3333
+ Before any payment, confirm the *live remaining* budget with the tools \u2014
3334
+ \`agent.json\` shows the configured budget, not what is left after recent
3335
+ spending:
3267
3336
 
3268
- - \`haven_get_agent\` \u2014 agent identity, Haven wallet address, network.
3269
- - \`haven_get_allowances\` \u2014 current per-token budgets and what remains.
3337
+ - \`haven_get_agent\` \u2014 the recommended first call: identity (wallet, network)
3338
+ plus a readiness signal (\`ready\` / \`needs_approval\` / \`revoked\`) and live
3339
+ remaining per-token allowance, in one shot.
3340
+ - \`haven_get_allowances\` \u2014 detailed per-token breakdown (configured, spent,
3341
+ reset window) when you need more than the summary.
3270
3342
 
3271
3343
  Budgets reset on a period the user chose. If a payment exceeds the remaining
3272
3344
  budget it is queued for the user to approve in the Haven dashboard \u2014 this is