@agent-score/commerce 1.8.1 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +73 -9
  2. package/dist/{_response-9yp6Fit2.d.mts → _response-BFYN3b6i.d.mts} +17 -19
  3. package/dist/{_response-CC6jNb8q.d.ts → _response-_iPD5AIj.d.ts} +17 -19
  4. package/dist/challenge/index.d.mts +106 -198
  5. package/dist/challenge/index.d.ts +106 -198
  6. package/dist/challenge/index.js +238 -111
  7. package/dist/challenge/index.js.map +1 -1
  8. package/dist/challenge/index.mjs +238 -111
  9. package/dist/challenge/index.mjs.map +1 -1
  10. package/dist/checkout-B1JuEcbx.d.ts +939 -0
  11. package/dist/checkout-BN5i1Fi7.d.mts +939 -0
  12. package/dist/core.d.mts +2 -2
  13. package/dist/core.d.ts +2 -2
  14. package/dist/core.js +1 -1
  15. package/dist/core.js.map +1 -1
  16. package/dist/core.mjs +1 -1
  17. package/dist/core.mjs.map +1 -1
  18. package/dist/discovery/index.d.mts +453 -51
  19. package/dist/discovery/index.d.ts +453 -51
  20. package/dist/discovery/index.js +1092 -58
  21. package/dist/discovery/index.js.map +1 -1
  22. package/dist/discovery/index.mjs +1060 -57
  23. package/dist/discovery/index.mjs.map +1 -1
  24. package/dist/identity/express.d.mts +3 -3
  25. package/dist/identity/express.d.ts +3 -3
  26. package/dist/identity/express.js +30 -19
  27. package/dist/identity/express.js.map +1 -1
  28. package/dist/identity/express.mjs +30 -19
  29. package/dist/identity/express.mjs.map +1 -1
  30. package/dist/identity/fastify.d.mts +4 -4
  31. package/dist/identity/fastify.d.ts +4 -4
  32. package/dist/identity/fastify.js +30 -19
  33. package/dist/identity/fastify.js.map +1 -1
  34. package/dist/identity/fastify.mjs +30 -19
  35. package/dist/identity/fastify.mjs.map +1 -1
  36. package/dist/identity/hono.d.mts +3 -3
  37. package/dist/identity/hono.d.ts +3 -3
  38. package/dist/identity/hono.js +30 -19
  39. package/dist/identity/hono.js.map +1 -1
  40. package/dist/identity/hono.mjs +30 -19
  41. package/dist/identity/hono.mjs.map +1 -1
  42. package/dist/identity/nextjs.d.mts +6 -7
  43. package/dist/identity/nextjs.d.ts +6 -7
  44. package/dist/identity/nextjs.js +30 -19
  45. package/dist/identity/nextjs.js.map +1 -1
  46. package/dist/identity/nextjs.mjs +30 -19
  47. package/dist/identity/nextjs.mjs.map +1 -1
  48. package/dist/identity/policy.d.mts +41 -4
  49. package/dist/identity/policy.d.ts +41 -4
  50. package/dist/identity/policy.js +23307 -18
  51. package/dist/identity/policy.js.map +1 -1
  52. package/dist/identity/policy.mjs +23313 -3
  53. package/dist/identity/policy.mjs.map +1 -1
  54. package/dist/identity/web.d.mts +3 -3
  55. package/dist/identity/web.d.ts +3 -3
  56. package/dist/identity/web.js +30 -19
  57. package/dist/identity/web.js.map +1 -1
  58. package/dist/identity/web.mjs +30 -19
  59. package/dist/identity/web.mjs.map +1 -1
  60. package/dist/index.d.mts +72 -329
  61. package/dist/index.d.ts +72 -329
  62. package/dist/index.js +23301 -378
  63. package/dist/index.js.map +1 -1
  64. package/dist/index.mjs +23294 -362
  65. package/dist/index.mjs.map +1 -1
  66. package/dist/payment/index.d.mts +297 -265
  67. package/dist/payment/index.d.ts +297 -265
  68. package/dist/payment/index.js +605 -149
  69. package/dist/payment/index.js.map +1 -1
  70. package/dist/payment/index.mjs +590 -148
  71. package/dist/payment/index.mjs.map +1 -1
  72. package/dist/{agent_instructions-DiMSGkdm.d.mts → pricing-CQ9DIFaw.d.ts} +109 -56
  73. package/dist/{agent_instructions-DiMSGkdm.d.ts → pricing-CxzwyiO6.d.mts} +109 -56
  74. package/dist/rail_spec-XP0wKgJV.d.mts +132 -0
  75. package/dist/rail_spec-XP0wKgJV.d.ts +132 -0
  76. package/dist/{signer-CFVQsWjL.d.mts → signer-3FAit11j.d.mts} +27 -1
  77. package/dist/{signer-CFVQsWjL.d.ts → signer-3FAit11j.d.ts} +27 -1
  78. package/dist/solana-Cds87OTu.d.mts +67 -0
  79. package/dist/solana-Cds87OTu.d.ts +67 -0
  80. package/dist/stripe-multichain/index.d.mts +55 -66
  81. package/dist/stripe-multichain/index.d.ts +55 -66
  82. package/dist/stripe-multichain/index.js +68 -42
  83. package/dist/stripe-multichain/index.js.map +1 -1
  84. package/dist/stripe-multichain/index.mjs +68 -41
  85. package/dist/stripe-multichain/index.mjs.map +1 -1
  86. package/dist/{wwwauthenticate-CU1eNvMQ.d.mts → wwwauthenticate-D_FMnPgU.d.mts} +9 -10
  87. package/dist/{wwwauthenticate-CU1eNvMQ.d.ts → wwwauthenticate-D_FMnPgU.d.ts} +9 -10
  88. package/dist/x402_server-hgQzWQwB.d.mts +81 -0
  89. package/dist/x402_server-hgQzWQwB.d.ts +81 -0
  90. package/package.json +9 -7
@@ -0,0 +1,939 @@
1
+ import { T as TempoRailSpec, S as SolanaMppRailSpec, a as TempoSessionRailSpec, b as StripeRailSpec, X as X402BaseRailSpec } from './rail_spec-XP0wKgJV.js';
2
+ import { P as PricingBlock, R as RailKey } from './pricing-CQ9DIFaw.js';
3
+ import { CreateSessionOnMissing, AgentScoreCoreOptions, DenialReason } from './core.js';
4
+ import { X as X402Server } from './x402_server-hgQzWQwB.js';
5
+
6
+ /**
7
+ * UCP (Universal Commerce Protocol) profile builder.
8
+ *
9
+ * Compose the JSON payload published at `/.well-known/ucp` per the UCP spec.
10
+ * Output shape matches the spec example: top-level `{ ucp: {...}, signing_keys: [...] }`
11
+ * envelope, with `services` / `capabilities` / `payment_handlers` as MAPs keyed by
12
+ * reverse-DNS service / capability / handler name.
13
+ *
14
+ * AgentScore identity claims layer over UCP via the `sh.agentscore.identity` capability
15
+ * (vendor-namespaced; UCP doesn't define KYC/sanctions/age/jurisdiction natively). The
16
+ * capability extends `dev.ucp.shopping.checkout` AND `dev.ucp.shopping.cart` (multi-parent,
17
+ * the standard pattern UCP allows for capabilities that compose multiple parents).
18
+ *
19
+ * The unsigned profile body returned here is what merchants publish; pass it through
20
+ * `signUCPProfile` to attach the `agentscore-profile+jws` signature for trust-mode
21
+ * verifiers (vendor extension; UCP itself doesn't mandate profile-body signing).
22
+ *
23
+ * Spec reference: https://ucp.dev/
24
+ */
25
+ /**
26
+ * UCP per-element shape note: each binding interface (`UCPServiceBinding`,
27
+ * `UCPCapabilityBinding`, `UCPPaymentHandlerBinding`) carries the canonical UCP fields
28
+ * plus arbitrary vendor extras flat on the same object via `[k: string]: unknown`. The
29
+ * python sibling models these as dataclasses with an explicit `extras: dict` field. Both
30
+ * designs offer equivalent guarantees through different mechanisms.
31
+ */
32
+
33
+ /**
34
+ * Construct a UCPSigningKey from a public JWK dict (e.g. the `publicJWK` returned by
35
+ * `generateUCPSigningKey()`). Validates required fields and rejects symmetric keys that
36
+ * can't publicly verify a JWS in trust-mode UCP. Mirrors python's
37
+ * `UCPSigningKey.from_jwk(public_jwk)` classmethod via the `UCPSigningKey.fromJWK`
38
+ * static-method-style namespace export below.
39
+ */
40
+ declare function ucpSigningKeyFromJWKImpl(jwk: Record<string, unknown>): UCPSigningKey;
41
+ interface UCPSigningKey {
42
+ /** JWK kid (key id). */
43
+ kid: string;
44
+ /** JWK kty (key type) — `EC`, `RSA`, or `OKP`. */
45
+ kty: string;
46
+ /** JWK alg (signing algorithm) — `ES256`, `RS256`, or `EdDSA`. */
47
+ alg?: string;
48
+ /** JWK use, typically `sig`. */
49
+ use?: string;
50
+ /** JWK crv (curve) for EC / OKP keys. */
51
+ crv?: string;
52
+ /** JWK x / y / n / e / etc. The full key material; passed through verbatim. */
53
+ [k: string]: unknown;
54
+ }
55
+ /** Static-method-style namespace on the `UCPSigningKey` interface — mirrors python's
56
+ * `UCPSigningKey.from_jwk(jwk)` classmethod. Use as `UCPSigningKey.fromJWK(jwk)`. */
57
+ declare const UCPSigningKey: {
58
+ fromJWK: typeof ucpSigningKeyFromJWKImpl;
59
+ };
60
+ /** Transport binding — keyed under a service name (e.g., `dev.ucp.shopping`). */
61
+ interface UCPServiceBinding {
62
+ /** Spec version, YYYY-MM-DD per UCP convention. REQUIRED. */
63
+ version: string;
64
+ /** URL to human-readable specification. REQUIRED. */
65
+ spec: string;
66
+ /** Transport — `rest` / `mcp` / `a2a` / `embedded`. REQUIRED. */
67
+ transport: 'rest' | 'mcp' | 'a2a' | 'embedded';
68
+ /** Endpoint URL — required for rest/mcp; A2A points at the agent-card.json URL. */
69
+ endpoint?: string;
70
+ /** URL to JSON Schema — required for rest/mcp/embedded per spec. */
71
+ schema?: string;
72
+ /** Optional id for entity-instance disambiguation. */
73
+ id?: string;
74
+ /** Entity-specific config. */
75
+ config?: Record<string, unknown>;
76
+ /** Vendor-specific extras. */
77
+ [k: string]: unknown;
78
+ }
79
+ /** Capability binding — keyed under a capability name (e.g., `dev.ucp.shopping.checkout`). */
80
+ interface UCPCapabilityBinding {
81
+ /** Capability version, YYYY-MM-DD. REQUIRED. */
82
+ version: string;
83
+ /** URL to human-readable specification. REQUIRED. */
84
+ spec: string;
85
+ /** URL to JSON Schema. REQUIRED. */
86
+ schema: string;
87
+ /** Optional id for entity-instance disambiguation. */
88
+ id?: string;
89
+ /** Entity-specific config (feature flags, callback URLs, etc). */
90
+ config?: Record<string, unknown>;
91
+ /** Parent capability(ies) extended — single string or array for multi-parent. */
92
+ extends?: string | string[];
93
+ /** Optional version requirements per UCP §6.5. */
94
+ requires?: {
95
+ protocol?: {
96
+ min: string;
97
+ max?: string;
98
+ };
99
+ capabilities?: Record<string, {
100
+ min: string;
101
+ max?: string;
102
+ }>;
103
+ };
104
+ /** Vendor-specific extras allowed per UCP convention (e.g., the AgentScore identity
105
+ * capability adds a vendor-namespaced policy declaration here). */
106
+ [k: string]: unknown;
107
+ }
108
+ /** Payment handler binding — keyed under a handler reverse-DNS name (e.g., `com.google.pay`). */
109
+ interface UCPPaymentHandlerBinding {
110
+ /** Handler instance id (short, human-readable, e.g., `gpay`, `tempo`, `x402`). REQUIRED. */
111
+ id: string;
112
+ /** Handler spec version, YYYY-MM-DD. REQUIRED. */
113
+ version: string;
114
+ /** URL to handler spec. REQUIRED. */
115
+ spec: string;
116
+ /** URL to handler config schema. REQUIRED. */
117
+ schema: string;
118
+ /** Available instruments — type + per-type constraints (cards, wallets, etc.). */
119
+ available_instruments?: Array<{
120
+ type: string;
121
+ constraints?: Record<string, unknown>;
122
+ [k: string]: unknown;
123
+ }>;
124
+ /** Handler config — gateway IDs, merchant IDs, public keys, etc. */
125
+ config?: Record<string, unknown>;
126
+ /** Vendor-specific extras. */
127
+ [k: string]: unknown;
128
+ }
129
+ /** UCP body — nested under the `ucp` key of the published profile. */
130
+ interface UCPProfileBody {
131
+ /** UCP spec version (YYYY-MM-DD). */
132
+ version: string;
133
+ /** Display name for the merchant / agent surface. */
134
+ name?: string;
135
+ /** Services — keyed by service name (e.g., `dev.ucp.shopping`). Each value is an
136
+ * array of transport bindings (one merchant typically advertises multiple transports
137
+ * under one service name). */
138
+ services: Record<string, UCPServiceBinding[]>;
139
+ /** Capabilities — keyed by capability name (e.g., `dev.ucp.shopping.checkout`). */
140
+ capabilities: Record<string, UCPCapabilityBinding[]>;
141
+ /** Payment handlers — keyed by handler reverse-DNS name (e.g., `com.google.pay`). */
142
+ payment_handlers: Record<string, UCPPaymentHandlerBinding[]>;
143
+ /** Optional `supported_versions` map linking historical version-specific profile URLs.
144
+ * Pattern: `{ "2026-01-23": "https://merchant/.well-known/ucp/2026-01-23", ... }`. */
145
+ supported_versions?: Record<string, string>;
146
+ /** Vendor-specific extras inside the `ucp` envelope. */
147
+ [k: string]: unknown;
148
+ }
149
+ /** Full UCP profile body as published at `/.well-known/ucp`. Top-level shape:
150
+ * `{ ucp: {...}, signing_keys: [...], signature?: "..." }`. */
151
+ interface UCPProfile {
152
+ /** UCP body. ALL UCP-spec fields nest here per spec. */
153
+ ucp: UCPProfileBody;
154
+ /** JWKS — public keys at the OUTER level per UCP spec. Verifiers fetch this profile,
155
+ * match the kid from a JWS / RFC 9421 signature header against this list, and validate. */
156
+ signing_keys: UCPSigningKey[];
157
+ /** Set when JWS-signed via `signUCPProfile` — JWS Compact Serialization with detached
158
+ * payload (header..signature; payload is the canonicalized body minus this field). */
159
+ signature?: string;
160
+ /** Top-level vendor-specific extras (outside the `ucp` envelope). */
161
+ [k: string]: unknown;
162
+ }
163
+ interface BuildUCPProfileInput {
164
+ /** UCP spec version. Default `'2026-04-08'` (the latest published UCP spec date). MUST match a published UCP spec version, not a free-form date. */
165
+ version?: string;
166
+ /** Display name for the merchant / agent surface. */
167
+ name?: string;
168
+ /** Services map, keyed by service name. UCP-shopping merchants typically advertise
169
+ * bindings under `'dev.ucp.shopping'`. */
170
+ services?: Record<string, UCPServiceBinding[]>;
171
+ /** Capabilities map, keyed by capability name. The `sh.agentscore.identity` capability
172
+ * is auto-added when `agentscore_gate` is provided. */
173
+ capabilities?: Record<string, UCPCapabilityBinding[]>;
174
+ /** Payment handlers map, keyed by handler reverse-DNS name. */
175
+ payment_handlers?: Record<string, UCPPaymentHandlerBinding[]>;
176
+ /** JWKS — public keys the merchant signs with. REQUIRED by spec. */
177
+ signing_keys: UCPSigningKey[];
178
+ /** Merchant gate policy declaration. When provided, the SDK auto-injects an
179
+ * `sh.agentscore.identity` capability binding into `capabilities`, with the
180
+ * policy as the binding's `config`. Static merchant declaration only — no
181
+ * per-operator data ever ends up on the public profile. Per-operator identity
182
+ * attestation lives on the AP2 risk-signal endpoint, not here. */
183
+ agentscore_gate?: AgentScoreGatePolicy;
184
+ /** Optional override for the AgentScore capability schema URL. Field is snake_cased
185
+ * for cross-language parity with the Python sibling. */
186
+ agentscore_schema_url?: string;
187
+ /** Optional override for the AgentScore capability spec URL. */
188
+ agentscore_spec_url?: string;
189
+ /** `supported_versions` map at the profile root for backwards-compat across
190
+ * spec dates. Pattern: `{ "<date>": "<base>/.well-known/ucp/<date>" }`. */
191
+ supported_versions?: Record<string, string>;
192
+ /** Vendor-specific extras at the OUTER level (alongside `ucp` + `signing_keys`). */
193
+ extras?: Record<string, unknown>;
194
+ /** Vendor-specific extras INSIDE the `ucp` envelope (alongside `version`, `services`, etc.). */
195
+ ucp_extras?: Record<string, unknown>;
196
+ }
197
+ /** Merchant gate policy declared on the UCP profile via `sh.agentscore.identity` capability config.
198
+ * All fields optional; merchant declares which AgentScore checks the gate enforces. Snake-case
199
+ * field names match the AgentScore API's `/v1/assess` policy contract verbatim — no conversion
200
+ * layer between this declaration and what the gate actually enforces at runtime. */
201
+ interface AgentScoreGatePolicy {
202
+ /** Gate denies if the operator/account behind the agent is not Stripe-Identity-verified. */
203
+ require_kyc?: boolean;
204
+ /** Gate denies if the operator/account is flagged by OpenSanctions screening. */
205
+ require_sanctions_clear?: boolean;
206
+ /** Gate denies if the verified age (from KYC) is below this threshold. Common values: 18, 21. */
207
+ min_age?: number;
208
+ /** ISO-3166-1 alpha-2 country codes the gate accepts. Empty/absent allows any. Mutually exclusive
209
+ * with `blocked_jurisdictions` (set one or the other, not both). */
210
+ allowed_jurisdictions?: string[];
211
+ /** ISO-3166-1 alpha-2 country codes the gate denies. Empty/absent denies none. Mutually exclusive
212
+ * with `allowed_jurisdictions`. */
213
+ blocked_jurisdictions?: string[];
214
+ }
215
+ /**
216
+ * Compose a UCP profile body for `/.well-known/ucp` publication. Returns the spec-
217
+ * compliant shape: `{ ucp: { version, services, capabilities, payment_handlers, ... },
218
+ * signing_keys: [...] }`. Pass through `signUCPProfile` to attach a JWS signature for
219
+ * trust-mode verifiers.
220
+ *
221
+ * Auto-injects `sh.agentscore.identity` as a vendor capability extending both
222
+ * `dev.ucp.shopping.checkout` and `dev.ucp.shopping.cart` when `agentscore_gate`
223
+ * is provided. The capability's `config` carries the merchant's static gate
224
+ * policy declaration (require_kyc / require_sanctions_clear / min_age /
225
+ * allowed_jurisdictions / blocked_jurisdictions). NO per-operator data is ever
226
+ * placed on the public profile — per-operator identity attestation flows through
227
+ * the AP2 risk-signal endpoint, not here.
228
+ *
229
+ * Example:
230
+ * ```ts
231
+ * import { buildUCPProfile } from '@agent-score/commerce';
232
+ *
233
+ * const profile = buildUCPProfile({
234
+ * name: 'Example Merchant',
235
+ * services: {
236
+ * 'dev.ucp.shopping': [
237
+ * { version: '2026-04-08', spec: 'https://ucp.dev/2026-04-08/specification/overview',
238
+ * transport: 'mcp', endpoint: 'https://merchant.example/api/ucp/mcp',
239
+ * schema: 'https://ucp.dev/services/shopping/mcp.openrpc.json' },
240
+ * ],
241
+ * },
242
+ * payment_handlers: {
243
+ * ...mppPaymentHandler({ networks: [{ network: 'tempo-mainnet', chain_id: 4217, recipient: TEMPO_ADDR }] }),
244
+ * },
245
+ * signing_keys: [signingKey],
246
+ * agentscore_gate: { require_kyc: true, min_age: 21, allowed_jurisdictions: ['US'] },
247
+ * });
248
+ * ```
249
+ */
250
+ declare function buildUCPProfile(input: BuildUCPProfileInput): UCPProfile;
251
+ declare const AGENTSCORE_UCP_CAPABILITY = "sh.agentscore.identity";
252
+ type MppRailSpec = TempoRailSpec | SolanaMppRailSpec | TempoSessionRailSpec;
253
+ /**
254
+ * Build the `sh.agentscore.payment.mpp` payment handler block for a UCP profile.
255
+ *
256
+ * Pass any mix of `TempoRailSpec`, `SolanaMppRailSpec`, and `TempoSessionRailSpec`.
257
+ *
258
+ * @example
259
+ * ```ts
260
+ * buildUCPProfile({
261
+ * ...,
262
+ * payment_handlers: {
263
+ * ...mppPaymentHandler({
264
+ * networks: [
265
+ * { recipient: '0xtempo' }, // TempoRailSpec
266
+ * { recipient: 'solanaaddr', network: 'solana:5eykt4...' }, // SolanaMppRailSpec
267
+ * ],
268
+ * }),
269
+ * },
270
+ * });
271
+ * ```
272
+ */
273
+ declare function mppPaymentHandler({ networks, }: {
274
+ networks: MppRailSpec[];
275
+ }): Record<string, UCPPaymentHandlerBinding[]>;
276
+ /**
277
+ * Build the `sh.agentscore.payment.x402` payment handler block for a UCP profile.
278
+ *
279
+ * @example
280
+ * ```ts
281
+ * buildUCPProfile({
282
+ * ...,
283
+ * payment_handlers: {
284
+ * ...x402PaymentHandler({ networks: [{ recipient: '0xabc...' }] }),
285
+ * },
286
+ * });
287
+ * ```
288
+ */
289
+ declare function x402PaymentHandler({ networks, }: {
290
+ networks: X402BaseRailSpec[];
291
+ }): Record<string, UCPPaymentHandlerBinding[]>;
292
+ /**
293
+ * Build the `sh.agentscore.payment.stripe_spt` payment handler block for a UCP profile.
294
+ *
295
+ * @example
296
+ * ```ts
297
+ * buildUCPProfile({
298
+ * ...,
299
+ * payment_handlers: {
300
+ * ...stripeSptPaymentHandler({ spec: { profileId: 'profile_5xKvNqM9BaH' } }),
301
+ * },
302
+ * });
303
+ * ```
304
+ */
305
+ declare function stripeSptPaymentHandler({ spec, }: {
306
+ spec: StripeRailSpec;
307
+ }): Record<string, UCPPaymentHandlerBinding[]>;
308
+
309
+ /**
310
+ * High-level Checkout orchestrator — composes 402-emit + verify+settle.
311
+ *
312
+ * The Checkout primitive collapses the agent-commerce dance (emit 402 →
313
+ * verify+settle on retry → respond) into a single `await checkout.handle(request)`
314
+ * call. It services every merchant shape:
315
+ *
316
+ * - **Goods sellers** wire inventory hooks (`onSettled` persists the order;
317
+ * `mintRecipients` mints per-order Stripe-multichain addresses).
318
+ * - **API sellers** wire per-call billing (`computePricing` returns a fixed
319
+ * amount; `onSettled` returns the inline API response body).
320
+ * - **Self-custody-only merchants** configure chain rails (Tempo / Base / Solana)
321
+ * via `X402BaseRailSpec` / `TempoRailSpec` / `SolanaMppRailSpec`.
322
+ * - **Custodial-only merchants** configure `StripeRailSpec` and skip the chain
323
+ * rails — Stripe SPT settles via the same `composeMppx` hook.
324
+ * - **Multi-rail merchants** configure all of the above; the agent picks the rail.
325
+ *
326
+ * Three flexibility axes — every combination is supported:
327
+ *
328
+ * - **x402 only / MPP only / both** — Checkout works with `x402Server` alone,
329
+ * `composeMppx` alone, or both. Whichever payment header arrives is dispatched
330
+ * to the configured handler; the other path is simply absent.
331
+ * - **Self-custody / Stripe / mixed** — rails dict is the single source of truth.
332
+ * Listing `StripeRailSpec` makes Stripe SPT an acceptable rail; omitting it
333
+ * makes the merchant chain-only. Mixing freely is the default.
334
+ * - **Gated / ungated identity** — `CheckoutRequest.assess` is optional. Merchants
335
+ * who run AgentScoreGate upstream pass its result through; merchants running
336
+ * anonymous leave it `null`.
337
+ *
338
+ * Domain-neutral by design: every per-request value is keyed by `referenceId`
339
+ * (a UUID minted on first contact). Goods merchants persist this as their order
340
+ * id; API merchants treat it as a per-call request id.
341
+ */
342
+
343
+ type CheckoutRailSpec = TempoRailSpec | X402BaseRailSpec | SolanaMppRailSpec | StripeRailSpec | TempoSessionRailSpec;
344
+ /**
345
+ * Framework-neutral HTTP request input to `Checkout.handle`.
346
+ *
347
+ * Merchants build this from their framework's request object once; the
348
+ * Checkout layer then runs the same flow regardless of Hono / Express / Next /
349
+ * Fastify / raw Web Fetch.
350
+ */
351
+ interface CheckoutRequest {
352
+ method: string;
353
+ url: string;
354
+ headers: Record<string, string>;
355
+ /** Parsed JSON body. For non-JSON endpoints, pass `{}` and stash the raw bytes elsewhere. */
356
+ body: Record<string, unknown>;
357
+ /** Optional assess block from the gate (operator/wallet identity, signer verdicts).
358
+ *
359
+ * When present, hooks can branch on identity (e.g. KYC-only pricing). When absent,
360
+ * the merchant is either running pre-gate (anonymous discovery) or chose to skip
361
+ * the gate for this endpoint. */
362
+ assess?: Record<string, unknown> | null;
363
+ /** Optional escape hatch for the framework's native request object. Pass when
364
+ * your `composeMppx` hook needs to call `mppx.compose(...)(rawRequest)` — mppx's
365
+ * compose binds to the raw HTTP request, so the orchestrator forwards this
366
+ * through unchanged. */
367
+ raw?: unknown;
368
+ }
369
+ /** Output of `Checkout.computePricing` — per-request pricing. */
370
+ interface PricingResult {
371
+ /** Total to charge in USD (or the upper bound, for `mode: 'upto'` rails). */
372
+ amountUsd: number;
373
+ currency?: string;
374
+ /** Optional pre-built `PricingBlock`. When omitted, Checkout builds a minimal
375
+ * block from `amountUsd` so the 402 body always carries pricing metadata. */
376
+ block?: PricingBlock;
377
+ /** Optional product block surfaced in the 402 body's `product` field. Goods
378
+ * merchants populate `{id, name, slug, list_price_usd, ...}`; API sellers leave
379
+ * this absent since per-call billing has no product concept. */
380
+ product?: Record<string, string>;
381
+ /** Optional merchant-specific fields merged into the 402 body alongside the
382
+ * standard `accepted_methods` / `agent_instructions` / `pricing` blocks.
383
+ * Useful for `redemption_code_applied`, coupon hints, or any other field the
384
+ * merchant wants the agent to see in the challenge body. */
385
+ bodyExtras?: Record<string, unknown>;
386
+ }
387
+ /**
388
+ * Build a {@link PricingResult} from cents-denominated inputs.
389
+ *
390
+ * Saves the `{ amountUsd: ..., block: buildPricingBlock({...}) }` dance every
391
+ * US-commerce merchant repeats. When `subtotalCents` is set:
392
+ *
393
+ * - `subtotalCents` is the list price (pre-discount). `discountCents` is the
394
+ * deduction applied (redemption code / coupon / promo).
395
+ * - `amountUsd` is derived from `(subtotal + tax + shipping - discount) / 100`
396
+ * (floored at 0) unless explicitly provided.
397
+ * - A {@link PricingBlock} is built via {@link buildPricingBlock} and attached
398
+ * to the result's `block` field. `discount` is surfaced as a dollar-string
399
+ * when `discountCents` is supplied.
400
+ *
401
+ * When `subtotalCents` is omitted, the function passes through to the raw
402
+ * `PricingResult` shape; `amountUsd` is then required.
403
+ *
404
+ * Use this in `computePricing` hooks instead of hand-rolling:
405
+ *
406
+ * @example
407
+ * computePricing: async (ctx) => pricingResult({
408
+ * subtotalCents: 25000,
409
+ * taxCents: 2000,
410
+ * taxRate: 0.08,
411
+ * taxState: 'CA',
412
+ * }),
413
+ *
414
+ * @example
415
+ * // Redemption-code applied (free order, agent sees the savings line):
416
+ * computePricing: async (ctx) => pricingResult({
417
+ * subtotalCents: 7500,
418
+ * discountCents: 7500,
419
+ * }),
420
+ */
421
+ declare function pricingResult(opts: {
422
+ subtotalCents?: number;
423
+ taxCents?: number;
424
+ shippingCents?: number;
425
+ discountCents?: number;
426
+ taxRate?: number;
427
+ taxState?: string;
428
+ currency?: string;
429
+ amountUsd?: number;
430
+ product?: Record<string, string>;
431
+ bodyExtras?: Record<string, unknown>;
432
+ }): PricingResult;
433
+ /**
434
+ * Per-route discovery-probe config. When passed to {@link Checkout}, any
435
+ * empty-body POST without a payment credential short-circuits with a sample
436
+ * 402 advertising the merchant's payment shape — the canonical pattern x402
437
+ * crawlers (`awal x402 details`, `x402-proxy`, `x402scan`) rely on.
438
+ *
439
+ * Mirrors python's `DiscoveryProbeConfig` dataclass.
440
+ */
441
+ interface DiscoveryProbeConfig {
442
+ realm: string;
443
+ sampleRail: 'tempo' | 'base' | 'solana' | 'stripe';
444
+ sampleAmountUsd: number;
445
+ sampleRecipient: string;
446
+ intent?: 'charge' | 'authorize' | 'session.open';
447
+ ttlSeconds?: number;
448
+ docsUrl?: string;
449
+ message?: string;
450
+ x402Sample?: {
451
+ version?: 1 | 2;
452
+ networks?: string[];
453
+ accepts?: unknown[];
454
+ amountAtomic?: string;
455
+ resourceUrl?: string;
456
+ };
457
+ }
458
+ /** In-flight state passed to every hook in the Checkout flow. */
459
+ interface CheckoutContext {
460
+ request: CheckoutRequest;
461
+ /** UUID minted on first contact. Goods merchants persist as order id; API
462
+ * merchants treat as request id. */
463
+ referenceId: string;
464
+ /** Set after `computePricing` runs. */
465
+ pricing: PricingResult | null;
466
+ /** rail-key → recipient address, after `mintRecipients` runs (if provided).
467
+ * Static rails inherit recipients from the RailSpec. */
468
+ recipients: Record<string, string>;
469
+ /** Merchant-supplied per-request state, populated by `preValidate`. Other
470
+ * hooks read from here (e.g. `ctx.state.product` after preValidate
471
+ * resolved it). Stays empty when no `preValidate` is configured. */
472
+ state: Record<string, unknown>;
473
+ /** Capture the signer wallet under the operator credential the gate resolved
474
+ * for this request. Set by Checkout's internal gate after a successful allow
475
+ * when an operator_token is present; `undefined` for wallet-authenticated
476
+ * requests (no operator_token to associate) or anonymous discovery legs.
477
+ * Fire-and-forget — invoke from `onSettled` with the recovered signer. */
478
+ captureWallet?: (opts: {
479
+ walletAddress: string;
480
+ network: 'evm' | 'solana';
481
+ idempotencyKey?: string;
482
+ }) => Promise<void>;
483
+ }
484
+ /**
485
+ * Derive a coarse identity status (`'verified' | 'unverified' | 'anonymous'`)
486
+ * from the assess block on a CheckoutContext. Goods merchants persist this on
487
+ * the order row so audit logs distinguish gated buyers from anonymous ones.
488
+ */
489
+ declare function getIdentityStatus(ctx: CheckoutContext): 'verified' | 'unverified' | 'anonymous';
490
+ /**
491
+ * Raised from a `preValidate` hook to short-circuit Checkout with a canonical
492
+ * 4xx envelope.
493
+ *
494
+ * Checkout catches this and emits the canonical `{ error, next_steps }` envelope
495
+ * via `buildValidationError` so merchants don't construct response bodies
496
+ * themselves in the pre-validate path.
497
+ */
498
+ declare class CheckoutValidationError extends Error {
499
+ readonly code: string;
500
+ readonly action: string;
501
+ readonly status: number;
502
+ readonly extra: Record<string, unknown> | undefined;
503
+ constructor(opts: {
504
+ code: string;
505
+ message: string;
506
+ action?: string;
507
+ status?: number;
508
+ extra?: Record<string, unknown>;
509
+ });
510
+ }
511
+ /**
512
+ * Hook that runs once per request before pricing/settle. Returns a state dict
513
+ * that Checkout merges into `ctx.state` so downstream hooks (`computePricing`,
514
+ * `onSettled`) can read merchant-resolved values like the product row,
515
+ * redemption code, post-discount cents, etc.
516
+ *
517
+ * Throw {@link CheckoutValidationError} to short-circuit with a 4xx envelope.
518
+ */
519
+ type PreValidateFn = (ctx: CheckoutContext) => Record<string, unknown> | Promise<Record<string, unknown>>;
520
+ /** Denial returned by a `CheckoutGateConfig.runGate` function. */
521
+ interface GateDenial {
522
+ status: number;
523
+ body: Record<string, unknown>;
524
+ headers?: Record<string, string>;
525
+ }
526
+ /**
527
+ * Function the merchant supplies (or builds via a Checkout-gate helper) to run
528
+ * the per-request AgentScore gate. Returns `null` on accept, a `GateDenial`
529
+ * on deny.
530
+ */
531
+ type RunGateFn = (ctx: CheckoutContext) => Promise<GateDenial | null>;
532
+ /**
533
+ * Wires the AgentScore gate into Checkout.
534
+ *
535
+ * The SDK constructs an `AgentScoreCore` from the policy fields (KYC, age,
536
+ * sanctions, jurisdiction allowlist) and evaluates it after `preValidate`
537
+ * populates state. Supports the full `createSessionOnMissing` hook surface so
538
+ * merchants can pre-create pending orders before the verification session is
539
+ * minted (set `onBeforeSession` to upsert state keyed by `ctx.referenceId` or
540
+ * `ctx.state.*`, returning extras that the SDK folds into `reason.extra`).
541
+ *
542
+ * Three customization layers, in order of precedence:
543
+ *
544
+ * 1. ``runGate`` — full escape hatch. Replaces the SDK's gate flow entirely.
545
+ * Merchants implement assess + denial body construction themselves. Useful
546
+ * only for non-standard auth (e.g. shared signing keys, non-AgentScore IdP).
547
+ * 2. ``perRequestPolicy`` — reads `ctx.state` (populated by preValidate) and
548
+ * returns a partial policy override applied per request (e.g. product-level
549
+ * KYC requirement). When omitted, the static fields below apply uniformly.
550
+ * 3. ``onDenied`` — invoked AFTER the SDK builds the canonical DenialReason.
551
+ * Return a `GateDenial` to override the response body shape, or null to
552
+ * fall back to the canonical body from `denialReasonToBody`.
553
+ *
554
+ * Static policy fields mirror `AgentScoreCoreOptions` — see that interface
555
+ * for field semantics.
556
+ */
557
+ interface CheckoutGateConfig {
558
+ /** AgentScore API key. Required when `runGate` is omitted. */
559
+ apiKey?: string;
560
+ /** Override the default `https://api.agentscore.sh` base URL. */
561
+ baseUrl?: string;
562
+ /** Prepended to the default User-Agent on API calls. */
563
+ userAgent?: string;
564
+ /** Require KYC verification. */
565
+ requireKyc?: boolean;
566
+ /** Require operator clear of sanctions. */
567
+ requireSanctionsClear?: boolean;
568
+ /** Minimum operator age bracket (18 or 21). */
569
+ minAge?: number;
570
+ /** Blocked jurisdiction list. */
571
+ blockedJurisdictions?: string[];
572
+ /** Allowed jurisdiction allowlist; only these pass. */
573
+ allowedJurisdictions?: string[];
574
+ /** Fail-open posture for AgentScore-side infra failures. Default false. */
575
+ failOpen?: boolean;
576
+ /** How long to cache results in seconds. Default 300. */
577
+ cacheSeconds?: number;
578
+ /** Optional chain filter for scoring. */
579
+ chain?: string;
580
+ /** Session-mint config for missing-identity bootstrap. Hooks receive the
581
+ * CheckoutContext so `getSessionOptions` and `onBeforeSession` can read
582
+ * state populated by `preValidate`. */
583
+ createSessionOnMissing?: CreateSessionOnMissing<CheckoutContext>;
584
+ /** Surfaced in `agent_memory` hints and audit logs. */
585
+ merchantName?: string;
586
+ /** Free-form context label (e.g. `"purchase"`, `"orders"`). */
587
+ context?: string;
588
+ /** Per-request policy override. Returns the partial fields to merge over
589
+ * the static config above. Return `null` to skip the gate. */
590
+ perRequestPolicy?: (ctx: CheckoutContext) => Partial<AgentScoreCoreOptions> | null | Promise<Partial<AgentScoreCoreOptions> | null>;
591
+ /** Customize the denial response body. Called after the SDK resolves a
592
+ * DenialReason. Return a `GateDenial` to override the canonical body, or
593
+ * null to use `denialReasonToBody`. */
594
+ onDenied?: (ctx: CheckoutContext, reason: DenialReason) => GateDenial | null | Promise<GateDenial | null>;
595
+ /** Full escape hatch — replaces the SDK gate flow. */
596
+ runGate?: RunGateFn;
597
+ }
598
+ /** Surface passed to `Checkout.onSettled` after a payment lands. */
599
+ interface SettleOutcome {
600
+ /** Protocol family that handled the settle. */
601
+ rail: 'x402' | 'mpp';
602
+ /** The `PAYMENT-RESPONSE` header to echo (x402 success path). `null` for MPP. */
603
+ paymentResponseHeader: string | null;
604
+ /** The `Payment-Receipt` header to echo (MPP success path, paymentauth.org §5).
605
+ * `null` for x402 and for the MPP zero-settle carve-out (no receipt minted). */
606
+ paymentReceiptHeader: string | null;
607
+ /** The underlying settle result for merchants that need to inspect tx hash / etc. */
608
+ raw: unknown;
609
+ /** On-chain transaction hash where applicable; `null` for the zero-settle carve-out
610
+ * (no on-chain settle) and for Stripe SPT. */
611
+ txHash?: string | null;
612
+ /** Verified signer address (EVM lowercased; Solana base58 verbatim). */
613
+ signerAddress?: string | null;
614
+ /** Network family of the signer; `'evm'` or `'solana'`. */
615
+ signerNetwork?: string | null;
616
+ /** The merchant's `rails`-dict key that handled this settle (e.g. `'tempo'`,
617
+ * `'x402_base'`). Use to label rails in audit logs and persisted orders. */
618
+ railKey?: string;
619
+ }
620
+ /** Result a `composeMppx` hook returns when handling an MPP credential.
621
+ *
622
+ * `status: 200` means mppx validated the `Authorization: Payment` credential
623
+ * and the settlement landed; Checkout runs `onSettled` and returns success.
624
+ *
625
+ * `status: 402` means mppx emitted a 402 (no credential / invalid credential).
626
+ * Checkout layers its rich body on top of mppx's WWW-Authenticate header and
627
+ * optional x402 PAYMENT-REQUIRED, returning the composed 402.
628
+ */
629
+ interface MppxComposeOutcome {
630
+ status: 200 | 402;
631
+ /** For `status: 402`: the WWW-Authenticate (+ any other) headers mppx's compose
632
+ * emitted. Checkout merges these into the final 402 response. */
633
+ headers?: Record<string, string>;
634
+ /** For `status: 200`: optional PAYMENT-RESPONSE header echoed to the agent. */
635
+ paymentResponseHeader?: string | null;
636
+ /** For `status: 200`: serialized `Payment-Receipt` header (base64url-encoded
637
+ * receipt struct per mppx's `Receipt.serialize`). Echoed to the agent so
638
+ * spec-strict MPP clients (tempo CLI, etc.) can lift tx_hash + source from
639
+ * headers without parsing the JSON body. */
640
+ paymentReceiptHeader?: string | null;
641
+ /** The underlying mppx compose result for `onSettled` introspection. */
642
+ raw?: unknown;
643
+ /** On-chain tx hash from the mppx Receipt (when status=200 and on-chain). */
644
+ txHash?: string | null;
645
+ /** Verified signer recovered from the credential (when status=200). */
646
+ signerAddress?: string | null;
647
+ /** Network family of the signer; `'evm'` or `'solana'`. */
648
+ signerNetwork?: string | null;
649
+ /** The merchant's `rails`-dict key that handled this settle. Defaults to
650
+ * `"tempo"` when unset by the hook. */
651
+ railKey?: string;
652
+ }
653
+ /** Framework-neutral output of `Checkout.handle`. */
654
+ interface CheckoutResult {
655
+ status: number;
656
+ body: Record<string, unknown>;
657
+ headers: Record<string, string>;
658
+ referenceId: string;
659
+ settled: boolean;
660
+ /** `null` on settlement success; otherwise the failure phase
661
+ * (`'verify_failed'`, `'settle_failed'`, ...) for diagnostics. */
662
+ settlePhase?: string | null;
663
+ }
664
+ type PricingFn = (ctx: CheckoutContext) => PricingResult | Promise<PricingResult>;
665
+ type RecipientsFn = (ctx: CheckoutContext) => Record<string, string> | Promise<Record<string, string>>;
666
+ type ReferenceIdFn = (ctx: CheckoutContext) => string | Promise<string>;
667
+ type OnSettledFn = (ctx: CheckoutContext, outcome: SettleOutcome) => Record<string, unknown> | null | Promise<Record<string, unknown> | null>;
668
+ type ComposeMppxFn = (ctx: CheckoutContext) => MppxComposeOutcome | Promise<MppxComposeOutcome>;
669
+ type IsCachedAddressFn = (address: string) => boolean | Promise<boolean>;
670
+ /**
671
+ * Build the canonical `composeMppx` hook for pympp/mppx-backed MPP rails.
672
+ *
673
+ * Lazily resolves the server via the supplied `serverGetter` (typically the
674
+ * output of `lazyMppxServer`). Forwards the request's `Authorization: Payment`
675
+ * header and the current pricing amount to `mpp.charge`. Maps the three pympp
676
+ * outcomes to `MppxComposeOutcome`:
677
+ *
678
+ * - `Challenge` (no/invalid credential) → `status: 402` with the
679
+ * `www-authenticate` header pympp issued.
680
+ * - `(Credential, Receipt)` tuple → `status: 200` with the tx hash lifted from
681
+ * `receipt.reference` / `receipt.transaction` and the signer lifted from the
682
+ * credential's `did:pkh:...` source.
683
+ * - Any unexpected exception → `status: 402` (no headers; Checkout falls back
684
+ * to its standard 402 emit).
685
+ */
686
+ declare function makeMppxComposeHook(opts: {
687
+ serverGetter: () => Promise<unknown>;
688
+ }): ComposeMppxFn;
689
+ /**
690
+ * Framework-neutral 4xx envelope (`{ error, next_steps, agent_instructions }`).
691
+ *
692
+ * Returns the body dict; merchants wrap in their framework's JSON response.
693
+ * The per-framework `validationResponse*` helpers do this for you.
694
+ */
695
+ declare function validationEnvelope(opts: {
696
+ code: string;
697
+ message: string;
698
+ action?: string;
699
+ extra?: Record<string, unknown>;
700
+ }): Record<string, unknown>;
701
+ interface ValidationResponseInput {
702
+ code: string;
703
+ message: string;
704
+ action?: string;
705
+ status?: number;
706
+ extra?: Record<string, unknown>;
707
+ }
708
+ /** Hono one-liner; returns a `Response` via `c.json`-equivalent semantics. */
709
+ declare function validationResponseHono(input: ValidationResponseInput): Response;
710
+ /**
711
+ * Express helper; writes the response on the supplied `res`. Returns `void`
712
+ * to match Express convention.
713
+ */
714
+ declare function validationResponseExpress(res: {
715
+ status: (code: number) => unknown;
716
+ json: (body: unknown) => unknown;
717
+ }, input: ValidationResponseInput): void;
718
+ /** Fastify helper; writes on the supplied `reply` and returns it for chaining. */
719
+ declare function validationResponseFastify(reply: {
720
+ code: (code: number) => unknown;
721
+ send: (body: unknown) => unknown;
722
+ }, input: ValidationResponseInput): unknown;
723
+ /** Next.js helper; returns a `Response` (interchangeable with NextResponse.json). */
724
+ declare function validationResponseNextjs(input: ValidationResponseInput): Response;
725
+ /** Web Fetch helper; returns a standard `Response`. */
726
+ declare function validationResponseWeb(input: ValidationResponseInput): Response;
727
+ declare module './checkout' {
728
+ }
729
+ /**
730
+ * High-level agent-commerce orchestrator.
731
+ *
732
+ * @example
733
+ * ```ts
734
+ * const checkout = new Checkout({
735
+ * rails: { tempo: ..., x402_base: ..., stripe: ... },
736
+ * url: APP_URL,
737
+ * computePricing: (ctx) => ({ amountUsd: cartTotal(ctx.request.body) }),
738
+ * mintRecipients: (ctx) => stripeMultichainAddressesFor(ctx),
739
+ * onSettled: (ctx, outcome) => persistOrder(ctx.referenceId, ctx.request.body, outcome),
740
+ * composeMppx: (ctx) => mppxCompose(mppx, ctx.request),
741
+ * x402Server: x402,
742
+ * });
743
+ * const result = await checkout.handle(buildCheckoutRequest(request));
744
+ * return new Response(JSON.stringify(result.body), { status: result.status, headers: result.headers });
745
+ * ```
746
+ */
747
+ declare class Checkout {
748
+ readonly rails: Record<string, CheckoutRailSpec>;
749
+ readonly url: string;
750
+ readonly merchantName: string | undefined;
751
+ readonly computePricing: PricingFn;
752
+ readonly preValidate: PreValidateFn | undefined;
753
+ x402Server: X402Server | undefined;
754
+ composeMppx: ComposeMppxFn | undefined;
755
+ readonly mintRecipients: RecipientsFn | undefined;
756
+ readonly mintReferenceId: ReferenceIdFn | undefined;
757
+ readonly onSettled: OnSettledFn | undefined;
758
+ readonly isCachedAddress: IsCachedAddressFn | undefined;
759
+ readonly zeroSettleCarveOut: boolean;
760
+ readonly gate: CheckoutGateConfig | undefined;
761
+ readonly discoveryExtensions: Record<string, unknown> | undefined;
762
+ readonly discoveryProbe: DiscoveryProbeConfig | undefined;
763
+ private _x402ServerGetter;
764
+ constructor(opts: {
765
+ rails: Record<string, CheckoutRailSpec>;
766
+ url: string;
767
+ computePricing: PricingFn;
768
+ /** Per-request validation hook. Runs before pricing/gate/settle. Throw
769
+ * `CheckoutValidationError` to short-circuit with a 4xx envelope. Returns
770
+ * a state dict merged into `ctx.state` for downstream hooks. */
771
+ preValidate?: PreValidateFn;
772
+ /** Built via `createX402Server`. Pair it with an `X402BaseRailSpec` in
773
+ * `rails['x402_base']`; the CAIP-2 network is read from `rail.network`.
774
+ * When omitted, Checkout auto-derives via `lazyX402Server` from the flat
775
+ * `cdpApiKeyId` / `cdpApiKeySecret` kwargs. */
776
+ x402Server?: X402Server;
777
+ /** Required when the merchant accepts `Authorization: Payment` credentials.
778
+ * When omitted and `mppxSecretKey` is supplied, Checkout auto-derives via
779
+ * `lazyMppxServer` + the canonical compose hook (see `makeMppxComposeHook`). */
780
+ composeMppx?: ComposeMppxFn;
781
+ /** Flat-config: when `x402Server` is omitted and any X402BaseRailSpec is in
782
+ * `rails`, Checkout lazy-builds the x402 server. Pair `cdpApiKeyId` +
783
+ * `cdpApiKeySecret` to use Coinbase's facilitator; omit both for the
784
+ * public HTTP facilitator. */
785
+ cdpApiKeyId?: string;
786
+ cdpApiKeySecret?: string;
787
+ /** Flat-config: when `composeMppx` is omitted and an MPP rail is in `rails`,
788
+ * Checkout lazy-builds the mppx server. */
789
+ mppxSecretKey?: string;
790
+ /** Per-order deposit address minting (e.g. Stripe-multichain). */
791
+ mintRecipients?: RecipientsFn;
792
+ /** Default is `randomUUID()`. */
793
+ mintReferenceId?: ReferenceIdFn;
794
+ /** Runs after a settle lands; can return an inline response body for API sellers. */
795
+ onSettled?: OnSettledFn;
796
+ /** Pass when the merchant mints per-order addresses so `verifyX402Request` can
797
+ * confirm the `payTo` was minted by this merchant. Defaults to permissive. */
798
+ isCachedAddress?: IsCachedAddressFn;
799
+ /** Engage the EIP-3009 value=0 + pympp `proof` carve-out when pricing
800
+ * resolves to $0. Goods merchants offering free redemption codes set this
801
+ * to `true` so the credential parses without an on-chain settle. */
802
+ zeroSettleCarveOut?: boolean;
803
+ /** Per-request gate config. When set, the gate runs after `preValidate`
804
+ * populates `ctx.state` and before pricing/settle. Denials short-circuit
805
+ * with the gate's body verbatim. */
806
+ gate?: CheckoutGateConfig;
807
+ /** Per-endpoint x402 `extensions` block emitted on the 402 body. Merge
808
+ * outputs of `createBazaarDiscovery({...})` (or other extension declarers)
809
+ * here — Checkout forwards verbatim into the 402 response body's
810
+ * `extensions` field so Bazaar crawlers and other spec-compliant clients
811
+ * read the route's declared input/output schema. */
812
+ discoveryExtensions?: Record<string, unknown>;
813
+ /** Optional discovery-probe config: auto-route empty-body POSTs without a
814
+ * payment header to a sample 402 advertising the merchant's shape for
815
+ * crawlers (`awal x402 details`, x402-proxy, x402scan, ...). */
816
+ discoveryProbe?: DiscoveryProbeConfig;
817
+ });
818
+ /** Canonical `RailKey` list derived from the configured rails dict. Each
819
+ * `*RailSpec` type maps to one `RailKey` (Tempo and TempoSession both fold
820
+ * to `"tempo_mpp"`). Dedupes so listing is per protocol, not per recipient.
821
+ * Use in `.well-known/mpp.json`, skill.md / llms.txt discovery responses. */
822
+ get acceptedRails(): RailKey[];
823
+ /** Protocol-shaped method-name list (`"tempo/charge"`, `"x402/exact (base)"`).
824
+ * Suitable for the `methods: [...]` array of `.well-known/mpp.json`. */
825
+ get acceptedMethodNames(): string[];
826
+ /** Resolve the x402 server, awaiting the lazy getter on first use. */
827
+ private getX402Server;
828
+ private x402ServerAvailable;
829
+ /** Return the rails-dict key for the X402BaseRailSpec entry. Defaults to
830
+ * `"x402_base"` when no match found. */
831
+ private x402RailKey;
832
+ /** Return the rails-dict key for the primary MPP rail. */
833
+ private mppRailKey;
834
+ /** CAIP-2 read from `rails['x402_base'].network` (or its default).
835
+ * Defined only when an `X402BaseRailSpec` is present in rails AND a server
836
+ * is configured (explicit or auto-derived); otherwise `null`. */
837
+ get x402BaseNetwork(): string | null;
838
+ handle(request: CheckoutRequest): Promise<CheckoutResult>;
839
+ private validationErrorResult;
840
+ private runGate;
841
+ private handleZeroSettle;
842
+ private mintRefId;
843
+ private resolveRecipientsForCtx;
844
+ private asyncIsCachedAddress;
845
+ private handleX402;
846
+ private handleMppx;
847
+ private emit402;
848
+ private buildSuccess;
849
+ }
850
+ interface Checkout {
851
+ handleHono(c: {
852
+ req: {
853
+ method: string;
854
+ url: string;
855
+ raw?: Request;
856
+ header: (name?: string) => string | Record<string, string> | undefined;
857
+ json: () => Promise<unknown>;
858
+ };
859
+ json: (body: unknown, status?: number, headers?: Record<string, string>) => Response;
860
+ body: (body: string, status?: number, headers?: Record<string, string>) => Response;
861
+ }, body?: Record<string, unknown>): Promise<Response>;
862
+ handleExpress(req: {
863
+ method: string;
864
+ originalUrl?: string;
865
+ url?: string;
866
+ headers: Record<string, string | string[] | undefined>;
867
+ body?: unknown;
868
+ }, res: {
869
+ status: (code: number) => unknown;
870
+ setHeader: (name: string, value: string) => unknown;
871
+ json: (body: unknown) => unknown;
872
+ }, body?: Record<string, unknown>): Promise<void>;
873
+ handleFastify(request: {
874
+ method: string;
875
+ url: string;
876
+ headers: Record<string, string | string[] | undefined>;
877
+ body?: unknown;
878
+ }, reply: {
879
+ code: (code: number) => unknown;
880
+ header: (name: string, value: string) => unknown;
881
+ send: (body: unknown) => unknown;
882
+ }, body?: Record<string, unknown>): Promise<unknown>;
883
+ handleNextjs(request: Request, body?: Record<string, unknown>): Promise<Response>;
884
+ handleWeb(request: Request, body?: Record<string, unknown>): Promise<Response>;
885
+ mountUcpRoutesHono(app: {
886
+ get: (path: string, handler: (c: {
887
+ req: {
888
+ raw: Request;
889
+ };
890
+ }) => Promise<Response> | Response) => unknown;
891
+ options: (path: string, handler: (c: {
892
+ req: {
893
+ raw: Request;
894
+ };
895
+ }) => Promise<Response> | Response) => unknown;
896
+ }, opts: MountUcpRoutesOptions): void;
897
+ mountUcpRoutesExpress(app: {
898
+ get: (path: string, handler: (req: {
899
+ headers: Record<string, string | string[] | undefined>;
900
+ }, res: ExpressLikeRes) => Promise<void> | void) => unknown;
901
+ options: (path: string, handler: (req: {
902
+ headers: Record<string, string | string[] | undefined>;
903
+ }, res: ExpressLikeRes) => Promise<void> | void) => unknown;
904
+ }, opts: MountUcpRoutesOptions): void;
905
+ mountUcpRoutesFastify(app: {
906
+ get: (path: string, handler: (request: {
907
+ headers: Record<string, string | string[] | undefined>;
908
+ }, reply: FastifyLikeReply) => Promise<unknown> | unknown) => unknown;
909
+ options: (path: string, handler: (request: {
910
+ headers: Record<string, string | string[] | undefined>;
911
+ }, reply: FastifyLikeReply) => Promise<unknown> | unknown) => unknown;
912
+ }, opts: MountUcpRoutesOptions): void;
913
+ }
914
+ interface ExpressLikeRes {
915
+ status: (code: number) => unknown;
916
+ set: (headers: Record<string, string>) => unknown;
917
+ type: (mt: string) => unknown;
918
+ send: (body: string) => unknown;
919
+ }
920
+ interface FastifyLikeReply {
921
+ code: (code: number) => unknown;
922
+ header: (k: string, v: string) => unknown;
923
+ type: (mt: string) => unknown;
924
+ send: (body: string) => unknown;
925
+ }
926
+ /** Options for the `mountUcpRoutes<Framework>` helpers — one shape used by all
927
+ * three adapters. Saves merchants from copy-pasting the same 3-route block
928
+ * (GET ucp + GET jwks + OPTIONS preflights) every time. */
929
+ interface MountUcpRoutesOptions {
930
+ name: string;
931
+ wellKnownUcpUrl: string;
932
+ services: Record<string, unknown[]>;
933
+ signingKid?: string;
934
+ agentscoreGate?: unknown;
935
+ ucpPath?: string;
936
+ jwksPath?: string;
937
+ }
938
+
939
+ export { AGENTSCORE_UCP_CAPABILITY as A, validationResponseFastify as B, Checkout as C, type DiscoveryProbeConfig as D, validationResponseHono as E, validationResponseNextjs as F, type GateDenial as G, validationResponseWeb as H, type IsCachedAddressFn as I, x402PaymentHandler as J, type MountUcpRoutesOptions as M, type OnSettledFn as O, type PreValidateFn as P, type RecipientsFn as R, type SettleOutcome as S, UCPSigningKey as U, type UCPProfile as a, type AgentScoreGatePolicy as b, type CheckoutContext as c, type CheckoutGateConfig as d, type CheckoutRailSpec as e, type CheckoutRequest as f, type CheckoutResult as g, CheckoutValidationError as h, type ComposeMppxFn as i, type MppxComposeOutcome as j, type PricingFn as k, type PricingResult as l, type ReferenceIdFn as m, type RunGateFn as n, type UCPCapabilityBinding as o, type UCPPaymentHandlerBinding as p, type UCPProfileBody as q, type UCPServiceBinding as r, buildUCPProfile as s, getIdentityStatus as t, makeMppxComposeHook as u, mppPaymentHandler as v, pricingResult as w, stripeSptPaymentHandler as x, validationEnvelope as y, validationResponseExpress as z };