@agent-score/commerce 1.3.2 → 1.5.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/payment/networks.ts","../../src/payment/usdc.ts","../../src/payment/rails.ts","../../src/payment/directive.ts","../../src/payment/wwwauthenticate.ts","../../src/discovery/probe.ts","../../src/discovery/bazaar.ts","../../src/discovery/well_known_mpp.ts","../../src/discovery/well_known_x402.ts","../../src/discovery/llms_txt.ts","../../src/discovery/openapi.ts","../../src/discovery/robots_tag.ts","../../src/challenge/agent_instructions.ts","../../src/discovery/skill_md.ts"],"sourcesContent":["/**\n * Named network registry. Vendors reference symbolic names (`networks.base.mainnet.caip2`)\n * instead of magic strings. Lifted from agentscore-pay's constants.\n */\nexport const networks = {\n base: {\n mainnet: { caip2: 'eip155:8453' as const, chainId: 8453 },\n sepolia: { caip2: 'eip155:84532' as const, chainId: 84532 },\n },\n solana: {\n mainnet: { caip2: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp' as const },\n devnet: { caip2: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1' as const },\n },\n tempo: {\n mainnet: { caip2: 'eip155:4217' as const, chainId: 4217 },\n testnet: { caip2: 'eip155:42431' as const, chainId: 42431 },\n },\n} as const;\n\nexport type NetworkFamily = keyof typeof networks;\n\n/**\n * Returns the family name (base/solana/tempo) for a given CAIP-2 network string,\n * or null if the network isn't in the registry. Useful for routing settlement\n * by network.\n */\nexport function networkFamily(caip2: string): NetworkFamily | null {\n if (caip2 === networks.base.mainnet.caip2 || caip2 === networks.base.sepolia.caip2) return 'base';\n if (caip2 === networks.solana.mainnet.caip2 || caip2 === networks.solana.devnet.caip2) return 'solana';\n if (caip2 === networks.tempo.mainnet.caip2 || caip2 === networks.tempo.testnet.caip2) return 'tempo';\n if (caip2.startsWith('solana:')) return 'solana';\n return null;\n}\n","/**\n * USDC token registry per network. Used by paymentDirective and rail definitions.\n * Lifted from agentscore-pay's constants.\n */\nexport const USDC = {\n base: {\n mainnet: { address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' as const, decimals: 6 },\n sepolia: { address: '0x036CbD53842c5426634e7929541eC2318f3dCF7e' as const, decimals: 6 },\n },\n solana: {\n mainnet: { mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', decimals: 6 },\n devnet: { mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', decimals: 6 },\n },\n tempo: {\n mainnet: { address: '0x20C000000000000000000000b9537d11c60E8b50' as const, decimals: 6 },\n testnet: { address: '0x20c0000000000000000000000000000000000000' as const, decimals: 6 },\n },\n} as const;\n","import { networks } from './networks';\nimport { USDC } from './usdc';\n\n/**\n * Symbolic rail names mapped to their protocol details. Vendors pass `rail: 'tempo-mainnet'`\n * to the directive builder and the SDK fills in method/network/decimals/currency from this\n * registry. Custom rails not in this registry can be passed by setting the lower-level\n * fields directly on the directive builder.\n */\nexport const rails = {\n 'tempo-mainnet': {\n method: 'tempo',\n network: networks.tempo.mainnet.caip2,\n chainId: networks.tempo.mainnet.chainId,\n currency: USDC.tempo.mainnet.address,\n decimals: USDC.tempo.mainnet.decimals,\n asset: USDC.tempo.mainnet.address,\n },\n 'tempo-testnet': {\n method: 'tempo',\n network: networks.tempo.testnet.caip2,\n chainId: networks.tempo.testnet.chainId,\n currency: USDC.tempo.testnet.address,\n decimals: USDC.tempo.testnet.decimals,\n asset: USDC.tempo.testnet.address,\n },\n 'x402-base-mainnet': {\n method: 'x402',\n network: networks.base.mainnet.caip2,\n chainId: networks.base.mainnet.chainId,\n currency: USDC.base.mainnet.address,\n decimals: USDC.base.mainnet.decimals,\n asset: USDC.base.mainnet.address,\n },\n 'x402-base-sepolia': {\n method: 'x402',\n network: networks.base.sepolia.caip2,\n chainId: networks.base.sepolia.chainId,\n currency: USDC.base.sepolia.address,\n decimals: USDC.base.sepolia.decimals,\n asset: USDC.base.sepolia.address,\n },\n // Upto rails — pay UP TO a max amount (Permit2-based, vs EIP-3009 for exact). Use for\n // variable-cost APIs where the actual cost depends on output (LLM tokens, bandwidth, etc.).\n // Only available on EVM networks; Solana svm doesn't ship an upto scheme yet.\n 'x402-base-mainnet-upto': {\n method: 'x402-upto',\n network: networks.base.mainnet.caip2,\n chainId: networks.base.mainnet.chainId,\n currency: USDC.base.mainnet.address,\n decimals: USDC.base.mainnet.decimals,\n asset: USDC.base.mainnet.address,\n },\n 'x402-base-sepolia-upto': {\n method: 'x402-upto',\n network: networks.base.sepolia.caip2,\n chainId: networks.base.sepolia.chainId,\n currency: USDC.base.sepolia.address,\n decimals: USDC.base.sepolia.decimals,\n asset: USDC.base.sepolia.address,\n },\n 'mpp-solana-mainnet': {\n method: 'solana',\n network: networks.solana.mainnet.caip2,\n currency: USDC.solana.mainnet.mint,\n decimals: USDC.solana.mainnet.decimals,\n asset: USDC.solana.mainnet.mint,\n },\n 'mpp-solana-devnet': {\n method: 'solana',\n network: networks.solana.devnet.caip2,\n currency: USDC.solana.devnet.mint,\n decimals: USDC.solana.devnet.decimals,\n asset: USDC.solana.devnet.mint,\n },\n 'stripe-spt': {\n method: 'stripe',\n currency: 'usd',\n decimals: 2,\n },\n} as const;\n\nexport type RailName = keyof typeof rails;\n\nexport interface RailDefinition {\n method: string;\n network?: string;\n chainId?: number;\n currency: string;\n decimals: number;\n asset?: string;\n}\n\n/**\n * Lookup a rail definition by symbolic name. Returns undefined if the rail isn't in\n * the registry — vendors with custom rails should pass the low-level fields directly.\n */\nexport function lookupRail(name: string): RailDefinition | undefined {\n return rails[name as RailName] as RailDefinition | undefined;\n}\n","import { lookupRail } from './rails';\n\nexport interface PaymentRequestInput {\n /** Symbolic rail name (e.g., 'tempo-mainnet', 'x402-base-mainnet') — fills in defaults */\n rail?: string;\n /** Amount in USD as a number or string. Converted to raw integer using `decimals`. */\n amountUsd: string | number;\n /** Token contract address or currency code. Defaults from rail. */\n currency?: string;\n /** Decimal precision for the amount. Defaults from rail (6 for USDC, 2 for USD). */\n decimals?: number;\n /** Recipient address (on-chain). Optional for stripe-style rails. */\n recipient?: string;\n /** EVM chain ID (goes into methodDetails.chainId). Defaults from rail. */\n chainId?: number;\n /** Stripe profile_id or similar (goes into methodDetails.networkId — note camelCase per link-cli's mpp decode validator). */\n networkId?: string;\n}\n\n/**\n * Build the base64-encoded `request` blob for an MPP Payment directive (per the\n * paymentauth.org spec). Output shape matches what link-cli `mpp decode` expects:\n *\n * { amount: \"<raw_integer>\", currency: \"<token>\", recipient?: \"<addr>\",\n * methodDetails?: { chainId?: number, networkId?: string } }\n */\nexport function buildPaymentRequestBlob(input: PaymentRequestInput): string {\n const railDef = input.rail ? lookupRail(input.rail) : undefined;\n const decimals = input.decimals ?? railDef?.decimals ?? 6;\n const currency = input.currency ?? railDef?.currency ?? 'usd';\n const chainId = input.chainId ?? railDef?.chainId;\n\n const amountNum = typeof input.amountUsd === 'string' ? Number(input.amountUsd) : input.amountUsd;\n const amountRaw = BigInt(Math.round(amountNum * 10 ** decimals)).toString();\n const blob: Record<string, unknown> = { amount: amountRaw, currency, decimals };\n if (input.recipient) blob.recipient = input.recipient;\n const methodDetails: Record<string, unknown> = {};\n if (chainId !== undefined) methodDetails.chainId = chainId;\n if (input.networkId) methodDetails.networkId = input.networkId;\n if (Object.keys(methodDetails).length > 0) blob.methodDetails = methodDetails;\n return Buffer.from(JSON.stringify(blob)).toString('base64url');\n}\n\nexport interface PaymentDirectiveInput {\n /** Symbolic rail name — sets `method` automatically */\n rail?: string;\n /** Challenge id (unique per request, used to correlate retries) */\n id: string;\n /** Realm — the host of the merchant URL (e.g., \"agents.merchant.example\") */\n realm: string;\n /** MPP method name. Defaults from rail (e.g., 'tempo', 'stripe'). */\n method?: string;\n /** MPP intent. Defaults to 'charge'. */\n intent?: string;\n /** ISO-8601 expiry timestamp. Defaults to now + 5 minutes. */\n expires?: string;\n /** Base64-encoded request blob. Pass the result of buildPaymentRequestBlob. */\n request: string;\n}\n\n/**\n * Format an MPP Payment directive string for the WWW-Authenticate header.\n * Output shape: `Payment id=\"...\", realm=\"...\", method=\"...\", intent=\"charge\",\n * expires=\"...\", request=\"<base64>\"`\n */\nexport function paymentDirective(input: PaymentDirectiveInput): string {\n const railDef = input.rail ? lookupRail(input.rail) : undefined;\n const method = input.method ?? railDef?.method ?? 'unknown';\n const intent = input.intent ?? 'charge';\n const expires = input.expires ?? new Date(Date.now() + 5 * 60 * 1000).toISOString();\n return `Payment id=\"${input.id}\", realm=\"${input.realm}\", method=\"${method}\", intent=\"${intent}\", expires=\"${expires}\", request=\"${input.request}\"`;\n}\n\nexport interface BuildPaymentDirectiveInput\n extends Omit<PaymentRequestInput, 'rail'>,\n Omit<PaymentDirectiveInput, 'request'> {\n rail: string;\n}\n\n/**\n * Convenience: build the request blob and the directive in one call. Most vendors\n * want this rather than the two-step form.\n */\nexport function buildPaymentDirective(input: BuildPaymentDirectiveInput): string {\n const request = buildPaymentRequestBlob({\n rail: input.rail,\n amountUsd: input.amountUsd,\n currency: input.currency,\n decimals: input.decimals,\n recipient: input.recipient,\n chainId: input.chainId,\n networkId: input.networkId,\n });\n return paymentDirective({\n rail: input.rail,\n id: input.id,\n realm: input.realm,\n method: input.method,\n intent: input.intent,\n expires: input.expires,\n request,\n });\n}\n","/**\n * Joins multiple Payment directives into a single WWW-Authenticate header value.\n * Per RFC 7235, multiple challenges are comma-separated.\n */\nexport function wwwAuthenticateHeader(directives: string[]): string {\n return directives.join(', ');\n}\n\nexport interface PaymentRequiredHeaderInput {\n x402Version: 1 | 2;\n accepts: unknown[];\n resource?: { url: string; mimeType?: string };\n}\n\n/**\n * Add the v1↔v2 amount-field alias to each accepts entry. Idempotent. Used by both\n * `paymentRequiredHeader` (header emit) and `build402Body` (body emit) so every\n * x402 entry on the wire carries BOTH `amount` (v2 spec) AND `maxAmountRequired`\n * (v1 spec) — strict v1-only parsers (e.g. Coinbase awal at `payments-mcp.coinbase.com`,\n * which is hardcoded to read `maxAmountRequired`) work alongside strict v2 parsers,\n * which ignore the alias.\n */\nexport function aliasAmountFields(accepts: unknown[]): unknown[] {\n return accepts.map((entry) => {\n if (entry === null || typeof entry !== 'object') return entry;\n const e = entry as Record<string, unknown>;\n const hasAmount = e.amount !== undefined;\n const hasMaxAmount = e.maxAmountRequired !== undefined;\n if (hasAmount && !hasMaxAmount) return { ...e, maxAmountRequired: e.amount };\n if (hasMaxAmount && !hasAmount) return { ...e, amount: e.maxAmountRequired };\n return e;\n });\n}\n\n/**\n * Encode the standard x402 PAYMENT-REQUIRED header (base64-encoded JSON of the\n * PaymentRequired object). Clients that recognize the header (`@x402/fetch`,\n * `@x402/core` HTTPClient, `agentscore-pay`) prefer it over body fields.\n *\n * Note: do NOT add a v1↔v2 amount-field alias here. `@x402/core`'s\n * `findMatchingRequirements` uses `deepEqual` against the agent's signed\n * `accepted` payload — any field present on one side and missing on the other\n * (e.g. `maxAmountRequired` on the wire body but not in `buildPaymentRequirements`'s\n * output) makes the match silently fail at settle time. Keep `accepts` shape\n * identical to whatever `buildPaymentRequirements` produces server-side.\n */\nexport function paymentRequiredHeader(input: PaymentRequiredHeaderInput): string {\n return Buffer.from(JSON.stringify(input)).toString('base64');\n}\n","import { buildPaymentRequestBlob, paymentDirective } from '../payment/directive';\nimport { networks } from '../payment/networks';\nimport { USDC } from '../payment/usdc';\nimport { paymentRequiredHeader } from '../payment/wwwauthenticate';\n\n/** Placeholder payTo for x402 sample accepts in the discovery probe — the probe\n * exists for crawlers to find that we support x402, not for actual payment. The\n * real 402 (returned on a fully-formed request body) carries real deposit\n * addresses minted from a Stripe PaymentIntent. */\nconst ZERO_EVM_PAYTO = '0x0000000000000000000000000000000000000000';\nconst ZERO_SOLANA_PAYTO = '11111111111111111111111111111111';\n\n/**\n * Build a sample x402 accepts entry for a CAIP-2 network. Looks up the USDC asset\n * for the network from the `USDC` registry and uses a placeholder payTo. Used by\n * the discovery probe to advertise x402 support without exposing real deposit\n * addresses.\n *\n * Returns null when the network isn't in the registry — vendors with custom\n * networks should construct accepts entries by hand and pass them via\n * `x402Sample.accepts` directly.\n */\nexport function sampleX402AcceptForNetwork(\n caip2: string,\n amountAtomic: string = '1000000',\n): Record<string, unknown> | null {\n if (caip2 === networks.base.mainnet.caip2) {\n return {\n scheme: 'exact',\n network: caip2,\n amount: amountAtomic,\n asset: USDC.base.mainnet.address,\n payTo: ZERO_EVM_PAYTO,\n maxTimeoutSeconds: 300,\n // ``extra.name`` mirrors the on-chain USDC contract's ``name()`` because\n // EIP-712 domain hashes include this string. Wrong name → every signed\n // payload fails facilitator verify with ``invalid_exact_evm_payload_signature``.\n // Base mainnet USDC returns \"USD Coin\"; base sepolia USDC returns \"USDC\".\n extra: { name: 'USD Coin', version: '2' },\n };\n }\n if (caip2 === networks.base.sepolia.caip2) {\n return {\n scheme: 'exact',\n network: caip2,\n amount: amountAtomic,\n asset: USDC.base.sepolia.address,\n payTo: ZERO_EVM_PAYTO,\n maxTimeoutSeconds: 300,\n extra: { name: 'USDC', version: '2' },\n };\n }\n if (caip2 === networks.solana.mainnet.caip2) {\n return {\n scheme: 'exact',\n network: caip2,\n amount: amountAtomic,\n asset: USDC.solana.mainnet.mint,\n payTo: ZERO_SOLANA_PAYTO,\n maxTimeoutSeconds: 300,\n };\n }\n if (caip2 === networks.solana.devnet.caip2) {\n return {\n scheme: 'exact',\n network: caip2,\n amount: amountAtomic,\n asset: USDC.solana.devnet.mint,\n payTo: ZERO_SOLANA_PAYTO,\n maxTimeoutSeconds: 300,\n };\n }\n return null;\n}\n\nexport interface DiscoveryProbeOptions {\n /** Realm — typically the host of your merchant URL (e.g., \"agents.merchant.example\"). */\n realm: string;\n /** Symbolic rail name to advertise in the sample challenge (e.g., 'tempo-mainnet'). */\n sampleRail: string;\n /** Sample amount in USD for the probe (e.g., 1.00). Crawlers use this as an example. */\n sampleAmountUsd: number;\n /** A recipient address to use in the sample directive (your real or zero address is fine). */\n sampleRecipient: string;\n /** MPP intent. Defaults to 'charge'. */\n intent?: string;\n /** TTL for the probe challenge in seconds. Defaults to 300 (5 minutes). */\n ttlSeconds?: number;\n /** Optional URL to include in the body for further docs (e.g., your llms.txt). */\n docsUrl?: string;\n /** Optional human-readable message in the body. */\n message?: string;\n /** Optional sample x402 accepts entries. When provided, the probe response also\n * carries the standard x402 `payment-required` header (base64 PaymentRequired) AND\n * an `accepts` array in the body — so x402 crawlers (e.g. Coinbase awal's\n * `x402 details`/`x402 pay`) can discover the endpoint's x402 support without\n * needing to send a fully-formed business request. Each entry is run through\n * `aliasAmountFields` so v1-only parsers can read `maxAmountRequired` too.\n *\n * Pass `networks` (shorthand) for the common case — the helper looks up USDC\n * per network from the registry and uses placeholder payTo addresses. Or pass\n * `accepts` directly for full control over the sample shape. */\n x402Sample?: {\n /** Spec version to declare. Defaults to 2. */\n version?: 1 | 2;\n /** Shorthand: array of CAIP-2 network strings. Each is mapped to a sample\n * USDC accepts entry via `sampleX402AcceptForNetwork`. Networks not in the\n * USDC registry are silently skipped. Use `accepts` for custom shapes. */\n networks?: string[];\n /** Sample accepts entries. Used when `networks` shorthand isn't enough.\n * Supplied entries are NOT merged with `networks`-derived entries — pick\n * one or the other. */\n accepts?: unknown[];\n /** Sample atomic amount used by the `networks` shorthand. Defaults to\n * `'1000000'` ($1.00 USDC at 6 decimals). Ignored when `accepts` is set. */\n amountAtomic?: string;\n /** Resource URL the probe is responding for. Used in the PAYMENT-REQUIRED header. */\n resourceUrl?: string;\n };\n}\n\nexport interface DiscoveryProbeResponse {\n status: 402;\n headers: Record<string, string>;\n body: string;\n}\n\n/**\n * Build a 402 response advertising a sample Payment challenge. MPP crawlers\n * (mppscan, link-cli mpp decode) probe with empty bodies; merchants need to answer\n * with a properly-formatted Payment directive so the realm can be indexed.\n *\n * Returns a framework-agnostic response shape. Wrap in your framework's response:\n *\n * const probe = buildDiscoveryProbeResponse({...});\n * return new Response(probe.body, { status: probe.status, headers: probe.headers });\n */\nexport function buildDiscoveryProbeResponse(opts: DiscoveryProbeOptions): DiscoveryProbeResponse {\n const probeId = `probe_${Date.now()}`;\n const expires = new Date(Date.now() + (opts.ttlSeconds ?? 300) * 1000).toISOString();\n const request = buildPaymentRequestBlob({\n rail: opts.sampleRail,\n amountUsd: opts.sampleAmountUsd,\n recipient: opts.sampleRecipient,\n });\n const directive = paymentDirective({\n rail: opts.sampleRail,\n id: probeId,\n realm: opts.realm,\n intent: opts.intent,\n expires,\n request,\n });\n\n const bodyObj: Record<string, unknown> = {\n error: {\n code: 'payment_required',\n message: opts.message ?? 'This endpoint requires payment. Send a valid request body to receive a full challenge.',\n },\n discovery: true,\n ...(opts.docsUrl ? { docs: opts.docsUrl } : {}),\n };\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n 'www-authenticate': directive,\n };\n\n if (opts.x402Sample) {\n const x402Version = opts.x402Sample.version ?? 2;\n const sampleAccepts = opts.x402Sample.accepts\n ?? (opts.x402Sample.networks ?? [])\n .map((n) => sampleX402AcceptForNetwork(n, opts.x402Sample!.amountAtomic ?? '1000000'))\n .filter((e): e is Record<string, unknown> => e !== null);\n // paymentRequiredHeader applies aliasAmountFields internally; do the same for\n // the body's `accepts` so v1-only parsers (Coinbase awal at payments-mcp.coinbase.com)\n // and v2-strict parsers can both read either field name.\n headers['payment-required'] = paymentRequiredHeader({\n x402Version,\n accepts: sampleAccepts,\n ...(opts.x402Sample.resourceUrl\n ? { resource: { url: opts.x402Sample.resourceUrl, mimeType: 'application/json' } }\n : {}),\n });\n // Also embed in body for clients that read body-level accepts (e.g. awal x402 details\n // falls back from header → body when the header isn't present).\n bodyObj.x402Version = x402Version;\n // Reuse the header's already-aliased accepts so the body matches.\n const headerJson = JSON.parse(Buffer.from(headers['payment-required'], 'base64').toString('utf-8'));\n bodyObj.accepts = headerJson.accepts;\n }\n\n return {\n status: 402,\n headers,\n body: JSON.stringify(bodyObj),\n };\n}\n\nexport interface RequestLike {\n method: string;\n headers: { get(name: string): string | null };\n clone(): { text(): Promise<string> };\n}\n\n/**\n * Returns true when the request is an empty-body POST without a payment credential —\n * the canonical MPP discovery probe pattern. Vendors compose this with\n * buildDiscoveryProbeResponse to short-circuit crawler requests before any business\n * logic runs.\n */\nexport async function isDiscoveryProbeRequest(req: RequestLike): Promise<boolean> {\n if (req.method !== 'POST') return false;\n const auth = req.headers.get('authorization');\n if (auth?.startsWith('Payment ')) return false;\n const body = await req.clone().text();\n return !body || body === '{}';\n}\n","/**\n * Bazaar discovery extension wrapper. Vendors pass their merchant config and we wrap\n * `declareDiscoveryExtension` from `@x402/extensions/bazaar`. The returned value is\n * registered on the x402 server (e.g., via `createX402Server({bazaar: true})` or\n * `server.registerExtension(...)`).\n *\n * `@x402/extensions` is an optional peer dependency.\n */\nexport interface BazaarDiscoveryConfig {\n bodyType?: 'json' | 'form';\n input?: Record<string, unknown>;\n output?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\ninterface BazaarModule {\n declareDiscoveryExtension?: (config: BazaarDiscoveryConfig) => unknown;\n}\n\nexport async function createBazaarDiscovery(config: BazaarDiscoveryConfig): Promise<unknown> {\n const bazaar = await dynamicImport<BazaarModule>('@x402/extensions/bazaar');\n /* v8 ignore start -- peer-dep-absence guard; @x402/extensions is installed in test env */\n if (!bazaar?.declareDiscoveryExtension) {\n throw new Error(\n '@x402/extensions not installed — `npm install @x402/extensions` for createBazaarDiscovery.',\n );\n }\n /* v8 ignore stop */\n return bazaar.declareDiscoveryExtension(config);\n}\n\nasync function dynamicImport<T>(moduleName: string): Promise<T | null> {\n try {\n return (await import(moduleName)) as T;\n } catch {\n /* v8 ignore next -- catch fires only when peer dep is missing; installed in test env */\n return null;\n }\n}\n","export interface PaymentMethodConfig {\n /** MPP payment methods accepted, e.g., ['tempo', 'x402', 'stripe']. */\n methods: string[];\n /** x402-specific config (when 'x402' is in methods). */\n x402?: {\n networks: string[];\n scheme?: string;\n asset?: string;\n facilitator?: string;\n client_tooling?: string;\n };\n /** Identity headers accepted (e.g., ['X-Operator-Token', 'X-Wallet-Address']). */\n identity?: string[];\n /** Per-identity-path metadata for agents. */\n identity_paths?: {\n wallet?: { header: string; applies_to_rails: string[]; note?: string };\n operator_token?: { header: string; applies_to_rails: string[]; note?: string };\n };\n /** Compliance policy summary for agents to know what they need before purchasing. */\n compliance?: {\n require_kyc?: boolean;\n min_age?: number;\n allowed_jurisdictions?: string[];\n require_sanctions_clear?: boolean;\n };\n /** Required fields in the request body. */\n required_fields?: string[];\n /** Optional fields in the request body. */\n optional_fields?: string[];\n /** Vendor-specific extras merged into the purchase block (e.g., gift_note metadata). */\n extra?: Record<string, unknown>;\n}\n\nexport interface WellKnownMppInput {\n /** Merchant display name. */\n name: string;\n /** Short description (1-2 sentences). */\n description?: string;\n /** Canonical merchant URL. */\n url: string;\n /** OpenAPI doc URL (typically `${url}/openapi.json`). */\n openapi?: string;\n /** Endpoints map: path → {method, url}. */\n endpoints: Record<string, { method: string; url: string }>;\n /** Catalog metadata (categories, etc). Optional. */\n catalog?: Record<string, unknown>;\n /** Purchase flow details (payment methods, identity, compliance). */\n purchase: PaymentMethodConfig;\n /** Shipping policy (countries, restrictions). */\n shipping?: Record<string, unknown>;\n /** Vendor-specific extra fields merged at the top level. */\n extra?: Record<string, unknown>;\n}\n\n/**\n * Build the standard `.well-known/mpp.json` discovery document. Lift the boilerplate\n * (payment.methods, payment.identity_paths, payment.compliance) into a typed config so\n * vendors get spec-compliance \"for free\"; merchant-specific fields (catalog, shipping)\n * pass through.\n *\n * Wire it in your framework like:\n * app.get('/.well-known/mpp.json', (c) => c.json(buildWellKnownMpp({...})));\n */\nexport function buildWellKnownMpp(input: WellKnownMppInput): Record<string, unknown> {\n return {\n name: input.name,\n ...(input.description ? { description: input.description } : {}),\n url: input.url,\n ...(input.openapi ? { openapi: input.openapi } : {}),\n endpoints: input.endpoints,\n ...(input.catalog ? { catalog: input.catalog } : {}),\n purchase: {\n ...(input.purchase.required_fields ? { required_fields: input.purchase.required_fields } : {}),\n ...(input.purchase.optional_fields ? { optional_fields: input.purchase.optional_fields } : {}),\n ...(input.purchase.extra ?? {}),\n ...(input.purchase.identity ? { identity: input.purchase.identity } : {}),\n ...(input.purchase.identity_paths ? { identity_paths: input.purchase.identity_paths } : {}),\n payment_methods: input.purchase.methods,\n ...(input.purchase.x402 ? { x402: input.purchase.x402 } : {}),\n ...(input.purchase.compliance ? { compliance: input.purchase.compliance } : {}),\n },\n ...(input.shipping ? { shipping: input.shipping } : {}),\n ...(input.extra ?? {}),\n };\n}\n","/**\n * `buildWellKnownX402`: emits the x402scan v1 `/.well-known/x402` discovery shape.\n *\n * x402scan accepts three discovery strategies (OpenAPI > `/.well-known/x402` > endpoint\n * probe). Most AgentScore merchants already publish a richer `/.well-known/mpp.json`,\n * but x402scan's strict parser only reads the v1 shape, so we emit both. The two\n * coexist on different paths.\n *\n * Spec (verbatim, x402scan):\n *\n * {\n * \"version\": 1,\n * \"resources\": [\"POST /api/route\", ...]\n * }\n *\n * Resource entries are `\"METHOD /path\"` strings, not objects. Runtime 402 behavior\n * is authoritative over this static metadata.\n */\n\nexport interface WellKnownX402Resource {\n /** HTTP method, uppercase: `'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'`. */\n method: string;\n /** Path, leading slash: `'/purchase'`. */\n path: string;\n}\n\nexport interface BuildWellKnownX402Input {\n /** Invocable, payment-required routes. Each entry becomes `\"METHOD /path\"`. */\n resources: WellKnownX402Resource[];\n}\n\nexport interface WellKnownX402Document {\n version: 1;\n resources: string[];\n}\n\nexport function buildWellKnownX402(input: BuildWellKnownX402Input): WellKnownX402Document {\n return {\n version: 1,\n resources: input.resources.map((r) => `${r.method.toUpperCase()} ${r.path}`),\n };\n}\n","export interface LlmsTxtIdentitySectionInput {\n /** When true, include the AgentScore identity-paths explanation (wallet vs operator-token). */\n agentscore?: boolean;\n /** Compliance policy to mention (KYC, age, jurisdiction). */\n compliance?: {\n require_kyc?: boolean;\n min_age?: number;\n allowed_jurisdictions?: string[];\n require_sanctions_clear?: boolean;\n };\n}\n\n/**\n * Generate the standard \"Choose your identity header\" section for an AgentScore-gated\n * merchant's llms.txt. Explains wallet-auth vs operator-token paths + the cross-merchant\n * memory contract so agents know how to authenticate without reading the API docs.\n */\nexport function llmsTxtIdentitySection(input: LlmsTxtIdentitySectionInput = {}): string {\n if (!input.agentscore) {\n return '';\n }\n const compliance = input.compliance;\n const complianceNote = compliance\n ? `\\n\\nCompliance: ${[\n compliance.require_kyc ? 'KYC required' : null,\n compliance.min_age ? `age ${compliance.min_age}+` : null,\n compliance.allowed_jurisdictions?.length\n ? `${compliance.allowed_jurisdictions.join('/')} only`\n : null,\n compliance.require_sanctions_clear ? 'sanctions clear' : null,\n ]\n .filter(Boolean)\n .join(', ')}.`\n : '';\n return `## Identity\n\nAgentScore identity is reusable across every AgentScore-gated merchant — one KYC, no re-verification per site. Pick a header:\n\n- **\\`X-Wallet-Address: 0x...\\` or base58** — works on signing rails (Tempo, x402, Solana MPP). The wallet you claim must sign the payment.\n- **\\`X-Operator-Token: opc_...\\`** — works on every rail, including Stripe SPT. Reusable across AgentScore merchants until expiry.\n- **Neither** — you get a 403 with \\`verify_url\\`. Complete the session flow once and reuse the resulting \\`opc_...\\` everywhere.${complianceNote}`;\n}\n\nexport interface LlmsTxtPaymentSectionInput {\n /** Symbolic rail names supported. */\n rails: ('tempo-mainnet' | 'tempo-testnet' | 'x402-base-mainnet' | 'x402-base-sepolia' | 'mpp-solana-mainnet' | 'mpp-solana-devnet' | 'stripe-spt' | string)[];\n /** Merchant URL — used in the example commands. */\n appUrl: string;\n /**\n * When true, emit the verbose multi-step variant: setup commands per rail, full per-rail\n * payment-command examples, and warnings about footguns. Default false (one-line bullet per rail).\n * Use this when llms.txt is the primary integration doc the agent reads.\n */\n verbose?: boolean;\n /** When verbose, the Tempo network name to mention in the prerequisites. Default 'tempo-mainnet'. */\n tempoNetworkName?: string;\n /** When verbose, the Tempo chain id to mention in the prerequisites. Default 4217. */\n tempoChainId?: number;\n}\n\n/**\n * Generate the standard \"## Payment\" section for a merchant's llms.txt. Documents the\n * supported rails with concrete CLI examples (tempo request, agentscore-pay, link-cli)\n * per the configured rail set.\n *\n * Pass `verbose: true` for the rich variant — multi-step setup + multi-line command examples +\n * exact-amount warnings. Default is the compact one-bullet-per-rail form.\n */\nexport function llmsTxtPaymentSection(input: LlmsTxtPaymentSectionInput): string {\n return input.verbose ? llmsTxtPaymentSectionVerbose(input) : llmsTxtPaymentSectionCompact(input);\n}\n\nfunction hasRailFamily(rails: string[], prefix: string): boolean {\n return rails.some(r => r.startsWith(prefix));\n}\n\nfunction isTestnetRail(rails: string[], prefix: string): boolean {\n return rails.some(r => r.startsWith(prefix) && /(sepolia|devnet|moderato|testnet)/.test(r));\n}\n\nfunction llmsTxtPaymentSectionCompact(input: LlmsTxtPaymentSectionInput): string {\n const lines: string[] = ['## Payment', ''];\n const rails = input.rails;\n if (hasRailFamily(rails, 'tempo-')) {\n lines.push('- **Tempo USDC via MPP** — `tempo request -X POST -H \"X-Operator-Token: opc_...\" --json \\'{...}\\' --max-spend N ' + input.appUrl + '`');\n }\n if (hasRailFamily(rails, 'x402-base-')) {\n lines.push('- **x402 USDC on Base** (EIP-3009) — `agentscore-pay pay POST ' + input.appUrl + ' --chain base -H \"X-Operator-Token: opc_...\" -d \\'{...}\\'`');\n }\n if (hasRailFamily(rails, 'mpp-solana-')) {\n lines.push('- **USDC on Solana** — `agentscore-pay pay POST ' + input.appUrl + ' --chain solana -H \"X-Operator-Token: opc_...\" -d \\'{...}\\'`');\n }\n if (rails.includes('stripe-spt')) {\n lines.push('- **Stripe Shared Payment Token** — agent mints SPT (own Stripe account scoped to networkId, OR `link-cli spend-request create --credential-type shared_payment_token --network-id <profileId> ...`)');\n }\n lines.push('');\n lines.push('IMPORTANT: Do NOT use raw on-chain transfers. Use the CLI commands above so the payment credential is signed and submitted via the protocol handshake.');\n lines.push('');\n return lines.join('\\n');\n}\n\nfunction llmsTxtPaymentSectionVerbose(input: LlmsTxtPaymentSectionInput): string {\n const rails = input.rails;\n const tempoNetwork = input.tempoNetworkName ?? 'tempo-mainnet';\n const tempoChain = input.tempoChainId ?? 4217;\n const hasTempo = hasRailFamily(rails, 'tempo-');\n const hasBase = hasRailFamily(rails, 'x402-base-');\n const hasSolana = hasRailFamily(rails, 'mpp-solana-');\n const hasStripe = rails.includes('stripe-spt');\n const baseNetworkName = isTestnetRail(rails, 'x402-base-') ? 'Base Sepolia' : 'Base';\n const solanaNetworkName = isTestnetRail(rails, 'mpp-solana-') ? 'Solana devnet' : 'Solana';\n\n const lines: string[] = ['## Payment', ''];\n lines.push('Accepted rails:');\n lines.push('');\n if (hasTempo) lines.push('- **USDC on Tempo**');\n if (hasBase) lines.push(`- **USDC on ${baseNetworkName}**`);\n if (hasSolana) lines.push(`- **USDC on ${solanaNetworkName}**`);\n if (hasStripe) lines.push('- **Stripe Shared Payment Token**');\n lines.push('');\n\n if (hasTempo) {\n lines.push('### Pay with Tempo');\n lines.push('');\n lines.push('```bash');\n lines.push('curl -fsSL https://tempo.xyz/install | bash');\n lines.push('tempo wallet login');\n lines.push(`tempo wallet whoami # need USDC.e on ${tempoNetwork} (chain ${tempoChain})`);\n lines.push('tempo wallet fund # if zero');\n lines.push('');\n lines.push('tempo request -X POST \\\\');\n lines.push(' -H \"X-Operator-Token: opc_...\" \\\\');\n lines.push(\" --json '{...}' \\\\\");\n lines.push(' --max-spend N \\\\');\n lines.push(` ${input.appUrl}`);\n lines.push('```');\n lines.push('');\n }\n\n if (hasBase || hasSolana) {\n const chainsLabel = [hasBase && baseNetworkName, hasSolana && solanaNetworkName].filter(Boolean).join(' or ');\n const flags = [hasBase && '`--chain base`', hasSolana && '`--chain solana`'].filter(Boolean).join(' or ');\n lines.push(`### Pay with ${chainsLabel}`);\n lines.push('');\n lines.push('```bash');\n lines.push('npm install -g @agent-score/pay');\n lines.push(`agentscore-pay wallet create ${flags}`);\n lines.push(`agentscore-pay balance ${flags} # fund the printed address with USDC`);\n lines.push('');\n lines.push(`agentscore-pay pay POST ${input.appUrl} \\\\`);\n lines.push(` ${hasBase ? '--chain base' : '--chain solana'} \\\\`);\n lines.push(' -H \"X-Operator-Token: opc_...\" \\\\');\n lines.push(\" -d '{...}' \\\\\");\n lines.push(' --max-spend N');\n lines.push('```');\n lines.push('');\n }\n\n if (hasStripe) {\n lines.push('### Pay with Stripe SPT');\n lines.push('');\n lines.push('Mint a SharedPaymentToken scoped to the `profile_id` from the 402 body, then submit via `Authorization: Payment` with `method=stripe/charge`. Either your own Stripe account or `link-cli spend-request create --credential-type shared_payment_token --network-id <profileId> ...` for Stripe Link wallets.');\n lines.push('');\n }\n\n lines.push('IMPORTANT: Use the CLIs above. Raw on-chain transfers (e.g. `tempo wallet transfer`, sending USDC manually to deposit addresses) bypass the protocol handshake and the order will not complete.');\n if (hasBase || hasSolana) {\n lines.push('IMPORTANT: Pay the exact amount in the 402 challenge. Overpayments and underpayments cannot be matched.');\n }\n lines.push('');\n return lines.join('\\n');\n}\n\nexport interface BuildLlmsTxtInput {\n merchantName: string;\n /** Optional 1-line summary under the title. */\n tagline?: string;\n /** Custom merchant-written sections (intro, endpoints, terms, etc.). */\n sections: { heading: string; content: string }[];\n /** Append the AgentScore identity section. */\n agentscoreIdentity?: LlmsTxtIdentitySectionInput;\n /** Append the standard payment section. */\n payment?: LlmsTxtPaymentSectionInput;\n}\n\n/**\n * Assemble a complete llms.txt document. Vendor passes their merchant-specific sections\n * (intro, catalog, endpoints, gift orders, shipping, etc.); the helper adds the AgentScore\n * identity + payment boilerplate at the end. Returns the full markdown string.\n */\nexport function buildLlmsTxt(input: BuildLlmsTxtInput): string {\n const parts: string[] = [`# ${input.merchantName}`];\n if (input.tagline) {\n parts.push(`> ${input.tagline}`);\n }\n parts.push('');\n for (const s of input.sections) {\n parts.push(`## ${s.heading}`);\n parts.push('');\n parts.push(s.content);\n parts.push('');\n }\n if (input.agentscoreIdentity) {\n parts.push(llmsTxtIdentitySection(input.agentscoreIdentity));\n parts.push('');\n }\n if (input.payment) {\n parts.push(llmsTxtPaymentSection(input.payment));\n }\n return parts.join('\\n');\n}\n","/**\n * OpenAPI snippets for AgentScore-related concepts. Vendors plug these into their own\n * OpenAPI 3.1 document (typically /openapi.json) so MPPScan and similar agent registries\n * can validate the merchant's auth + denial schemas correctly.\n *\n * Each helper returns a piece of an OpenAPI document — vendors compose them into their\n * full spec.\n */\n\n/**\n * Standard AgentScore identity security schemes. Plug into `components.securitySchemes`.\n *\n * Includes `siwx` (Sign-In With X) per the x402scan discovery spec so identity-gated\n * operations can declare `security: [{ siwx: [] }]` and stay classified as identity-only,\n * not paid.\n */\nexport function agentscoreSecuritySchemes(): Record<string, unknown> {\n return {\n OperatorToken: {\n type: 'apiKey',\n in: 'header',\n name: 'X-Operator-Token',\n description:\n 'Operator-token-path identity (opc_...). Works on every payment rail; reusable across AgentScore merchants. If both X-Operator-Token and X-Wallet-Address are sent, this one wins.',\n },\n WalletAddress: {\n type: 'apiKey',\n in: 'header',\n name: 'X-Wallet-Address',\n description:\n 'Wallet-path identity (0x... or base58). Only works on rails that carry a wallet signature (Tempo MPP, x402 EIP-3009, x402 SPL Token). The wallet you claim MUST sign the payment.',\n },\n siwx: siwxSecurityScheme(),\n };\n}\n\n/**\n * Sign-In With X security scheme entry, per the x402scan discovery spec.\n *\n * Reference it on identity-gated (but free) operations as\n * `security: [{ siwx: [] }]`. Do NOT also attach `x-payment-info` to those routes,\n * x402scan will misclassify them as paid.\n */\nexport function siwxSecurityScheme(): Record<string, unknown> {\n return {\n type: 'http',\n scheme: 'bearer',\n bearerFormat: 'SIWX',\n description:\n 'Sign-In With X wallet authentication. Agent signs a challenge with their wallet (any supported chain) and presents the proof in the Authorization header. Used for identity-gated free endpoints; payment-required endpoints declare x-payment-info instead.',\n };\n}\n\n/**\n * Standard AgentScore denial response schemas. Plug into `components.schemas` so OpenAPI\n * validators understand the 403 body shape across denial codes.\n */\nexport function agentscoreDenialSchemas(): Record<string, unknown> {\n return {\n AgentScoreDenialReason: {\n type: 'string',\n enum: [\n 'missing_identity',\n 'identity_verification_required',\n 'token_expired',\n 'invalid_credential',\n 'wallet_signer_mismatch',\n 'wallet_auth_requires_wallet_signing',\n 'wallet_not_trusted',\n 'api_error',\n 'payment_required',\n ],\n description:\n \"Denial code emitted by AgentScore's gate middleware in 403 responses. Every code carries a structured agent_instructions block describing recovery actions (per-code action: missing_identity → probe_identity_then_session, identity_verification_required / token_expired → deliver_verify_url_and_poll, invalid_credential → switch_token_or_restart_session, wallet_signer_mismatch → resign_or_switch_to_operator_token, wallet_auth_requires_wallet_signing → switch_to_operator_token, wallet_not_trusted → contact_support — UNFIXABLE compliance only (sanctions/age/jurisdiction_restricted); fixable reasons re-route to identity_verification_required, payment_required → contact_merchant).\",\n },\n AgentScoreDenialBody: {\n type: 'object',\n properties: {\n error: { $ref: '#/components/schemas/AgentScoreDenialReason' },\n agent_instructions: {\n type: 'string',\n description:\n 'JSON-encoded { action, steps, user_message } block. Always present on every denial; agents parse this to learn how to recover (e.g., poll verify_url, switch headers, re-sign).',\n },\n verify_url: { type: 'string', format: 'uri', description: \"Present for missing_identity / identity_verification_required / token_expired denials. Agent shares this with the user to complete KYC or claim a wallet. Not present on wallet_not_trusted (UNFIXABLE compliance — re-verification won't change the outcome).\" },\n session_id: { type: 'string' },\n poll_url: { type: 'string', format: 'uri' },\n poll_secret: { type: 'string' },\n agent_memory: { type: 'object', description: 'Cross-merchant pattern hint emitted on first-encounter denials.' },\n },\n required: ['error', 'agent_instructions'],\n },\n };\n}\n\n/**\n * Standard 402 PaymentRequired body schema (for AgentScore-extended 402 responses).\n * Includes the rails, identity metadata, agent_instructions, pricing, and x402-compliance\n * fields a typical merchant emits via build402Body.\n */\nexport function agentscorePaymentRequiredSchema(): Record<string, unknown> {\n return {\n AgentScorePaymentRequired: {\n type: 'object',\n properties: {\n payment_required: { type: 'boolean', enum: [true] },\n x402Version: { type: 'integer', enum: [1, 2] },\n accepts: { type: 'array', items: { type: 'object' }, description: 'x402 PaymentRequired.accepts entries.' },\n accepted_methods: {\n type: 'array',\n items: { type: 'object' },\n description: 'MPP method entries (tempo/charge, x402/exact, stripe/charge, ...).',\n },\n amount_usd: { type: 'string' },\n currency: { type: 'string' },\n pricing: {\n type: 'object',\n properties: {\n subtotal: { type: 'string' },\n tax: { type: 'string' },\n tax_rate: { type: 'number' },\n tax_state: { type: 'string' },\n total: { type: 'string' },\n },\n },\n identity_mode: { type: 'string', enum: ['wallet', 'operator_token'] },\n required_signer: { type: 'string' },\n linked_wallets: { type: 'array', items: { type: 'string' } },\n signer_constraint: { type: 'string' },\n agent_instructions: { type: 'object' },\n agent_memory: { type: 'object' },\n },\n },\n };\n}\n\n/**\n * Per-operation `x-payment-info` extension, per the x402scan discovery spec.\n *\n * Every payment-required OpenAPI operation should carry this block alongside a\n * 402 response. Tells discovery crawlers (x402scan, agent CLIs) the static price\n * and which protocols the route accepts. Runtime 402 behavior is authoritative\n * over this static metadata; the static side is for indexability.\n *\n * @example fixed price across x402 + MPP Tempo\n * ```ts\n * Object.assign(operation, {\n * ...xPaymentInfoExtension({\n * price: { mode: 'fixed', currency: 'USD', amount: '0.10' },\n * protocols: [\n * { x402: {} },\n * { mpp: { method: 'tempo/charge', intent: 'pay', currency: 'USD' } },\n * ],\n * }),\n * responses: {\n * '200': {...},\n * '402': { description: 'Payment Required' },\n * },\n * });\n * ```\n */\nexport interface XPaymentInfoFixedPrice {\n mode: 'fixed';\n currency: string;\n amount: string;\n}\n\nexport interface XPaymentInfoDynamicPrice {\n mode: 'dynamic';\n currency: string;\n min: string;\n max: string;\n}\n\nexport type XPaymentInfoPrice = XPaymentInfoFixedPrice | XPaymentInfoDynamicPrice;\n\nexport interface XPaymentInfoX402Protocol {\n x402: Record<string, unknown>;\n}\n\nexport interface XPaymentInfoMppProtocol {\n mpp: { method: string; intent: string; currency: string };\n}\n\nexport type XPaymentInfoProtocol = XPaymentInfoX402Protocol | XPaymentInfoMppProtocol;\n\nexport interface XPaymentInfoInput {\n price: XPaymentInfoPrice;\n protocols: XPaymentInfoProtocol[];\n}\n\nexport function xPaymentInfoExtension(\n input: XPaymentInfoInput,\n): { 'x-payment-info': { price: XPaymentInfoPrice; protocols: XPaymentInfoProtocol[] } } {\n return { 'x-payment-info': { price: input.price, protocols: input.protocols } };\n}\n\n/**\n * `info.x-guidance` extension, per the x402scan discovery spec. Spread into your\n * OpenAPI document's `info` block to give agents a high-level prose description\n * of how to use the API. Discovery crawlers surface this on the listing page.\n *\n * @example\n * ```ts\n * const spec = {\n * openapi: '3.1.0',\n * info: {\n * title: 'My Merchant API',\n * version: '1.0',\n * ...xGuidanceExtension('Wine merchant. POST /purchase with a verified operator token...'),\n * },\n * };\n * ```\n */\nexport function xGuidanceExtension(text: string): { 'x-guidance': string } {\n return { 'x-guidance': text };\n}\n\nexport interface BuildAgentScoreOpenApiSnippetsInput {\n /** Include security schemes in the snippet. Default true. */\n security?: boolean;\n /** Include denial schemas in the snippet. Default true. */\n denials?: boolean;\n /** Include the 402 PaymentRequired schema in the snippet. Default true. */\n paymentRequired?: boolean;\n}\n\n/**\n * Convenience: returns a `components` snippet ready to merge into an OpenAPI document.\n *\n * const spec = {\n * openapi: '3.1.0',\n * info: { title: 'My Merchant API', version: '1.0' },\n * paths: {...},\n * components: { ...agentscoreOpenApiSnippets(), schemas: { ...mySchemas, ...agentscoreOpenApiSnippets().schemas } },\n * };\n *\n * Or more idiomatically: `Object.assign(spec.components, agentscoreOpenApiSnippets())`.\n */\nexport function agentscoreOpenApiSnippets(\n opts: BuildAgentScoreOpenApiSnippetsInput = {},\n): { securitySchemes?: Record<string, unknown>; schemas?: Record<string, unknown> } {\n const out: { securitySchemes?: Record<string, unknown>; schemas?: Record<string, unknown> } = {};\n if (opts.security !== false) {\n out.securitySchemes = agentscoreSecuritySchemes();\n }\n if (opts.denials !== false || opts.paymentRequired !== false) {\n out.schemas = {\n ...(opts.denials !== false ? agentscoreDenialSchemas() : {}),\n ...(opts.paymentRequired !== false ? agentscorePaymentRequiredSchema() : {}),\n };\n }\n return out;\n}\n","/**\n * Default discovery paths emitted by `@agent-score/commerce` builders. These are\n * the public-by-design endpoints agents and crawlers fetch to learn the\n * merchant's shape: OpenAPI, llms.txt, MPP well-known, A2A agent card, UCP profile.\n * They should NOT carry `X-Robots-Tag: noindex` since the whole point is for\n * agents (and search/discovery crawlers) to find them.\n *\n * Everything else on an agent-only API should noindex by default — there's no\n * human-shaped HTML to surface to general search engines, and accidental\n * indexing leaks transactional endpoints into noisy SERPs.\n */\nexport const defaultDiscoveryPaths: ReadonlySet<string> = new Set([\n '/openapi.json',\n '/llms.txt',\n '/skill.md',\n '/SKILL.md',\n '/.well-known/mpp.json',\n '/.well-known/x402',\n '/.well-known/agent-card.json',\n '/.well-known/ucp',\n '/favicon.png',\n '/favicon.ico',\n]);\n\n/**\n * Pure predicate for \"is this path a known discovery surface?\". Compose this\n * into your own framework's middleware when you don't want the bundled Hono\n * wrapper. Custom paths are the union with the defaults — pass `replace: true`\n * to skip the defaults.\n */\nexport function isDiscoveryPath(\n path: string,\n options?: { customPaths?: Iterable<string>; replace?: boolean },\n): boolean {\n if (options?.replace) {\n return new Set(options.customPaths ?? []).has(path);\n }\n if (defaultDiscoveryPaths.has(path)) return true;\n if (options?.customPaths) {\n for (const p of options.customPaths) if (p === path) return true;\n }\n return false;\n}\n\nexport interface NoindexNonDiscoveryOptions {\n /** Additional discovery paths beyond the defaults (e.g. `/sitemap.xml`,\n * `/.well-known/foo`). Merged with the defaults unless `replacePaths: true`. */\n customPaths?: Iterable<string>;\n /** When true, ignore the bundled defaults and only treat `customPaths` as\n * discovery surfaces. Use when the merchant deliberately chooses a different\n * set (e.g. omits `/openapi.json` from a closed API). */\n replacePaths?: boolean;\n /** Override the X-Robots-Tag value applied to non-discovery paths. Defaults to\n * the standard \"noindex, nofollow, noarchive, nosnippet\" tuple — change only\n * if you have a very specific crawl-shape requirement. */\n robotsTag?: string;\n}\n\nconst DEFAULT_ROBOTS_TAG = 'noindex, nofollow, noarchive, nosnippet';\n\n/** Predicate the per-framework wrappers share. Pulled out so non-listed frameworks\n * can compose it directly (`if (!shouldNoindex(path, opts)) ...`). */\nfunction shouldNoindex(path: string, customSet: Set<string> | undefined, replacePaths: boolean | undefined): boolean {\n const isDiscovery = replacePaths\n ? (customSet?.has(path) ?? false)\n : defaultDiscoveryPaths.has(path) || (customSet?.has(path) ?? false);\n return !isDiscovery;\n}\n\n/**\n * Hono middleware. Mount globally near the top of your middleware stack:\n *\n * app.use('*', noindexNonDiscoveryPaths());\n * app.use('*', noindexNonDiscoveryPaths({ customPaths: ['/sitemap.xml'] }));\n *\n * Per-framework variants (`noindexNonDiscoveryPathsExpress`,\n * `noindexNonDiscoveryPathsFastify`, `noindexNonDiscoveryPathsWeb`) ship below.\n * For Next.js Route Handlers, use `applyNoindexHeader(response, path, opts)`\n * inline since route handlers don't have a global mount point.\n */\nexport function noindexNonDiscoveryPaths(options?: NoindexNonDiscoveryOptions) {\n const customSet = options?.customPaths ? new Set(options.customPaths) : undefined;\n const robotsTag = options?.robotsTag ?? DEFAULT_ROBOTS_TAG;\n return async (c: { req: { path: string }; header: (k: string, v: string) => void }, next: () => Promise<void>) => {\n await next();\n if (shouldNoindex(c.req.path, customSet, options?.replacePaths)) {\n c.header('X-Robots-Tag', robotsTag);\n }\n };\n}\n\n/** Express middleware. Sets the header before `next()` so route handlers can\n * override per-response if they need to. */\nexport function noindexNonDiscoveryPathsExpress(options?: NoindexNonDiscoveryOptions) {\n const customSet = options?.customPaths ? new Set(options.customPaths) : undefined;\n const robotsTag = options?.robotsTag ?? DEFAULT_ROBOTS_TAG;\n return (\n req: { path: string },\n res: { setHeader: (name: string, value: string) => void },\n next: () => void,\n ) => {\n if (shouldNoindex(req.path, customSet, options?.replacePaths)) {\n res.setHeader('X-Robots-Tag', robotsTag);\n }\n next();\n };\n}\n\n/** Fastify plugin (use as `app.register(noindexNonDiscoveryPathsFastify, opts)`).\n * Registers an `onRequest` hook so the header lands on every response. */\ninterface FastifyReqLike { url?: string; routerPath?: string }\ninterface FastifyReplyLike { header: (name: string, value: string) => void }\ninterface FastifyAppLike {\n addHook(event: 'onRequest', handler: (req: FastifyReqLike, reply: FastifyReplyLike, done: () => void) => void): void;\n}\nexport function noindexNonDiscoveryPathsFastify(\n app: FastifyAppLike,\n options: NoindexNonDiscoveryOptions | undefined,\n done: () => void,\n): void {\n const customSet = options?.customPaths ? new Set(options.customPaths) : undefined;\n const robotsTag = options?.robotsTag ?? DEFAULT_ROBOTS_TAG;\n app.addHook('onRequest', (req, reply, hookDone) => {\n const path = (req.url ?? req.routerPath ?? '').split('?')[0];\n if (shouldNoindex(path, customSet, options?.replacePaths)) {\n reply.header('X-Robots-Tag', robotsTag);\n }\n hookDone();\n });\n done();\n}\n\n/** Web Fetch / Cloudflare Workers / Deno / Bun helper. Returns a wrapped\n * Response that carries `X-Robots-Tag` on non-discovery paths. Pair with the\n * request's URL pathname:\n *\n * return wrapNoindexResponse(new URL(req.url).pathname, response);\n */\nexport function wrapNoindexResponse(\n path: string,\n response: Response,\n options?: NoindexNonDiscoveryOptions,\n): Response {\n const customSet = options?.customPaths ? new Set(options.customPaths) : undefined;\n const robotsTag = options?.robotsTag ?? DEFAULT_ROBOTS_TAG;\n if (!shouldNoindex(path, customSet, options?.replacePaths)) return response;\n const headers = new Headers(response.headers);\n headers.set('X-Robots-Tag', robotsTag);\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\n/** Next.js Route Handler helper. Call inline before returning the Response:\n *\n * export async function POST(req: Request) {\n * const path = new URL(req.url).pathname;\n * const res = Response.json({...});\n * return applyNoindexHeader(res, path);\n * }\n *\n * Same wrapper shape as the Web Fetch helper — exported separately for clarity\n * in Next.js docs/examples. */\nexport const applyNoindexHeader = wrapNoindexResponse;\n","import type { HowToPayBlock } from './how_to_pay';\n\n/** Map of rail key (e.g. 'x402_base', 'tempo_mpp', 'stripe') → list of client identifiers\n * that have been smoke-verified by the merchant against the protocol shape they emit.\n * Strings are display labels, not install commands — agents already get install commands\n * via `how_to_pay.<rail>.setup`. Use these as a \"what's known to work\" hint. */\nexport type CompatibleClients = Record<string, string[]>;\n\nexport interface BuildAgentInstructionsInput {\n /** Per-rail commands. Build with `buildHowToPay`. */\n howToPay: HowToPayBlock;\n /** Tool recommendations as human-readable strings. Defaults to a sensible set covering tempo + agentscore-pay. */\n recommendedTools?: string[];\n /** Wallet-stack compatibility note for the agent. Default: rail-neutral, no specific wallet stack required. */\n walletCompatibility?: string;\n /** How long the merchant will wait for payment after the 402. Default 300 (5 minutes). */\n timeoutSeconds?: number;\n /** Warnings about common footguns. Defaults include tempo wallet transfer + raw on-chain x402 deposits. */\n warnings?: string[];\n /** Additional warnings appended to the default protocol-footgun set. Use this when you want\n * to keep the SDK's protocol warnings AND add merchant-specific notes (e.g., a per-order\n * rail-availability message). Ignored when `warnings` is set explicitly. */\n extraWarnings?: string[];\n /** Recommended rail (e.g., 'tempo', 'x402_base'). Surfaced for agents to default to. */\n recommended?: string;\n /** Per-rail list of client names the merchant has verified work end-to-end. Vendors set\n * this from their own smoke matrix — defaults to none (avoids vouching for clients the\n * merchant has not tested). When omitted, the field is not emitted. */\n compatibleClients?: CompatibleClients;\n /** Arbitrary additional fields the vendor wants merged into the agent_instructions object. */\n extra?: Record<string, unknown>;\n}\n\nexport interface AgentInstructions {\n how_to_pay: HowToPayBlock;\n recommended_tools: string[];\n wallet_compatibility: string;\n timeout_seconds: number;\n warnings: string[];\n recommended?: string;\n compatible_clients?: CompatibleClients;\n [key: string]: unknown;\n}\n\nconst TEMPO_WARNING =\n 'Do NOT use `tempo wallet transfer`. That moves USDC on-chain without completing the protocol handshake, so the order will not complete. Use `tempo request` instead.';\n\nconst X402_WARNING =\n 'Do NOT send USDC manually to the deposit addresses. Use `agentscore-pay pay` so the credential is signed and submitted; otherwise the order will not complete even though the deposit lands.';\n\nconst TEMPO_TOOL = '`tempo request` for Tempo USDC';\nconst AGENTSCORE_PAY_TOOL = '`agentscore-pay` — Base + Solana + Tempo from one CLI';\n\nconst DEFAULT_WALLET_COMPATIBILITY =\n 'Any client that can produce a valid MPP credential (Authorization: Payment) or x402 X-Payment header. Use the CLI commands above; sign-it-yourself is also fine.';\n\nfunction defaultRecommendedTools(howToPay: HowToPayBlock): string[] {\n const tools: string[] = [];\n if (howToPay.tempo) tools.push(TEMPO_TOOL);\n if (howToPay.tempo || howToPay.x402_base || howToPay.solana_mpp) tools.push(AGENTSCORE_PAY_TOOL);\n return tools;\n}\n\nfunction defaultWarnings(howToPay: HowToPayBlock): string[] {\n const w: string[] = [];\n if (howToPay.tempo) w.push(TEMPO_WARNING);\n if (howToPay.x402_base) w.push(X402_WARNING);\n return w;\n}\n\n/**\n * Default `compatible_clients` derived from the rails declared in `howToPay`. Lists\n * clients the AgentScore team has smoke-verified end-to-end against an `@agent-score/commerce`\n * merchant; entries appear only for rails the vendor actually offers. Vendors override\n * this in `buildAgentInstructions({compatibleClients: {...}})` to add their own tested\n * clients or remove entries that don't fit their endpoint.\n *\n * Verified state as of the SDK release. The same data is also published as a docs page\n * for humans (rationale, per-rail commands, why some clients don't fully work, last\n * verified date) — this default keeps the merchant-side surface in sync.\n */\n/** Symbolic rail keys agent-facing surfaces use to talk about a rail without spelling out\n * network/scheme details. Same keys as `CompatibleClients` map keys. */\nexport type RailKey = 'tempo_mpp' | 'x402_base' | 'solana_mpp' | 'stripe';\n\nconst RAIL_CLIENTS: Record<RailKey, readonly string[]> = {\n tempo_mpp: ['agentscore-pay', 'tempo request', 'x402-proxy'],\n x402_base: ['agentscore-pay', 'x402-proxy', 'purl (omit --network flag)'],\n solana_mpp: ['agentscore-pay'],\n stripe: ['link-cli'],\n};\n\n/** Returns the smoke-verified client list for a set of rail keys. The single source of\n * truth for \"which CLIs we've verified end-to-end on each rail\" — consumed both by the\n * 402-body builder (`defaultCompatibleClients`) and by discovery surfaces (skill.md,\n * llms.txt, etc.). Update here, every surface inherits. */\nexport function compatibleClientsByRails(rails: readonly RailKey[]): CompatibleClients | undefined {\n const out: CompatibleClients = {};\n for (const r of rails) out[r] = [...RAIL_CLIENTS[r]];\n return Object.keys(out).length === 0 ? undefined : out;\n}\n\nfunction defaultCompatibleClients(howToPay: HowToPayBlock): CompatibleClients | undefined {\n const rails: RailKey[] = [];\n if (howToPay.tempo) rails.push('tempo_mpp');\n if (howToPay.x402_base) rails.push('x402_base');\n if (howToPay.solana_mpp) rails.push('solana_mpp');\n if (howToPay.stripe) rails.push('stripe');\n return compatibleClientsByRails(rails);\n}\n\n/**\n * Build the agent_instructions object for the 402 body. Combines how_to_pay with\n * recommended tools, warnings, wallet-compatibility note, and timeout.\n *\n * Defaults adapt to the rails declared in `howToPay`: only tempo-relevant warnings/tools\n * appear if `howToPay.tempo` is set, only x402-relevant ones if `x402_base` is set.\n * Stripe-only merchants get neither rail-specific warning. Vendors override\n * `warnings`/`recommendedTools` for full control.\n */\nexport function buildAgentInstructions(input: BuildAgentInstructionsInput): AgentInstructions {\n const compatibleClients = input.compatibleClients ?? defaultCompatibleClients(input.howToPay);\n return {\n how_to_pay: input.howToPay,\n recommended_tools: input.recommendedTools ?? defaultRecommendedTools(input.howToPay),\n wallet_compatibility: input.walletCompatibility ?? DEFAULT_WALLET_COMPATIBILITY,\n timeout_seconds: input.timeoutSeconds ?? 300,\n warnings: input.warnings ?? [...defaultWarnings(input.howToPay), ...(input.extraWarnings ?? [])],\n ...(input.recommended ? { recommended: input.recommended } : {}),\n ...(compatibleClients ? { compatible_clients: compatibleClients } : {}),\n ...(input.extra ?? {}),\n };\n}\n","import { compatibleClientsByRails } from '../challenge/agent_instructions';\nimport type { CompatibleClients, RailKey } from '../challenge/agent_instructions';\n\nexport type { CompatibleClients, RailKey } from '../challenge/agent_instructions';\nexport { compatibleClientsByRails } from '../challenge/agent_instructions';\n\nexport interface SkillMdEndpoint {\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n path: string;\n authRequired: boolean;\n description: string;\n}\n\nexport interface SkillMdIdentityRequirements {\n /** Whether KYC is required for gated routes. */\n kycRequired?: boolean;\n /** Minimum age (e.g. 21 for alcohol). */\n minAge?: number;\n /** Allowed-jurisdictions list (ISO 3166-1 alpha-2 country codes). */\n allowedJurisdictions?: string[];\n /** Whether sanctions screening is enforced. */\n sanctionsClear?: boolean;\n}\n\nexport interface SkillMdShippingPolicy {\n /** Allowed shipping countries (ISO 3166-1 alpha-2). */\n allowedCountries?: string[];\n /** Blocked US states (2-letter codes). */\n blockedStates?: string[];\n}\n\nexport interface SkillMdLink {\n label: string;\n url: string;\n}\n\nexport interface BuildSkillMdInput {\n /** Skill manifest identifier — kebab-case per agentskills.io spec: 1-64 chars, lowercase\n * alphanumeric + hyphens, no leading/trailing/consecutive hyphens. Validated at build\n * time; invalid names throw. e.g. 'example-merchant-commerce'. */\n name: string;\n /** Skill description — agentskills.io spec: 1-1024 chars, non-empty. Should describe both\n * what the skill does AND when to use it; imperative phrasing recommended (\"Use when…\").\n * Validated at build time; over-length throws. */\n description: string;\n /** Merchant homepage (or domain root). Emitted as `metadata.homepage` per spec\n * (top-level non-spec fields go under metadata). */\n homepage: string;\n /** Skill schema version — increment when the skill body materially changes. Emitted as\n * a quoted string under `metadata.version` per agentskills.io spec (metadata values\n * must be strings). Accepts string or number; numbers are converted. Default \"1\". */\n version?: string | number;\n\n /** Optional license name or path to a bundled license file. Emitted as top-level\n * frontmatter `license:` per spec. */\n license?: string;\n /** Optional environment-requirements note (max 500 chars). e.g. \"Requires Node 20+\".\n * Emitted as top-level frontmatter `compatibility:` per spec. */\n compatibility?: string;\n /** Optional space-separated string of pre-approved tools (experimental per spec). */\n allowedTools?: string;\n /** Additional caller-defined metadata entries — flat key/value strings nested under\n * `metadata:`. Spec requires string values. */\n metadata?: Record<string, string | number>;\n\n /** Human display name (e.g. \"Example Merchant\"). */\n merchantName: string;\n /** Optional one-line tagline appearing under the title. */\n tagline?: string;\n /** Optional short prose intro describing what the merchant offers. Renders below the title. */\n intro?: string;\n\n /** Files / well-known URLs surfaced under the \"Important Files\" table. The skill.md URL\n * itself is added automatically — list other discovery surfaces (llms.txt, mpp.json,\n * openapi.json, agent-card.json). */\n files?: SkillMdLink[];\n\n /** Rails the merchant accepts. Drives the Payment + Compatible Clients sections. Order\n * is preserved in render. Default to the rails actually declared on the merchant's\n * `respond402` config — keep these in sync. */\n acceptedRails: RailKey[];\n /** Override the per-rail compatible-clients matrix. When omitted, derives from\n * `acceptedRails` via the SDK's smoke-verified default. Override keys not in\n * `acceptedRails` are dropped (the rail isn't accepted, so the row isn't rendered). */\n compatibleClients?: CompatibleClients;\n\n /** Identity requirements as agent-observable outcomes (kyc / age / jurisdiction /\n * sanctions). Internal posture (`failOpen`, mount strategy, KYC vendor) is intentionally\n * not part of this shape — agents act on outcomes, not implementation. */\n identity?: SkillMdIdentityRequirements;\n /** URL to the identity-bootstrap skill. Linked from the Identity Prerequisite section\n * so an agent without a Passport can follow the bootstrap before attempting purchase. */\n identityBootstrapUrl?: string;\n\n /** Shipping policy, for physical-goods merchants. Omit for digital merchants. */\n shipping?: SkillMdShippingPolicy;\n\n /** Agent-facing endpoints — path, method, whether auth is required, brief purpose. */\n endpoints: SkillMdEndpoint[];\n\n /** When this skill should fire (skill loader uses for trigger matching). */\n triggers: string[];\n\n /** Optional numbered onboarding steps. Each entry renders as a numbered list item;\n * may include shell snippets in markdown code fences. */\n onboardingSteps?: string[];\n\n /** Support / homepage / docs links rendered in the \"Support\" section. */\n supportLinks?: SkillMdLink[];\n\n /** When true (default), append a footer noting clients can refresh skill.md to pick\n * up new endpoints. Set to false to suppress. */\n refreshFooter?: boolean;\n}\n\nconst RAIL_LABELS: Record<RailKey, string> = {\n tempo_mpp: 'MPP on Tempo',\n x402_base: 'x402 on Base',\n solana_mpp: 'MPP on Solana',\n stripe: 'Stripe Shared Payment Token',\n};\n\nconst RAIL_NOTES: Record<RailKey, string> = {\n tempo_mpp: 'USDC. Use `agentscore-pay --chain tempo` (or `tempo request`); MPP credential goes in `Authorization: Payment`.',\n x402_base: 'USDC (EIP-3009). Use `agentscore-pay`; X-Payment header carries the signed credential.',\n solana_mpp: 'USDC (SPL). Use `agentscore-pay --chain solana`; MPP credential goes in `Authorization: Payment`.',\n stripe: 'Card via Link wallet. Use `@stripe/link-cli` — `agentscore-pay` emits the handoff hint when this rail is picked.',\n};\n\nconst NAME_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;\nconst NAME_MAX = 64;\nconst DESCRIPTION_MAX = 1024;\nconst COMPATIBILITY_MAX = 500;\n\nfunction validateInput(input: BuildSkillMdInput): void {\n if (!input.name || input.name.length === 0 || input.name.length > NAME_MAX) {\n throw new Error(`buildSkillMd: name must be 1-${NAME_MAX} characters (got ${input.name?.length ?? 0})`);\n }\n if (!NAME_RE.test(input.name)) {\n throw new Error(\n `buildSkillMd: name \"${input.name}\" is invalid — must be lowercase alphanumeric and hyphens, no leading/trailing/consecutive hyphens (agentskills.io spec)`,\n );\n }\n if (!input.description || input.description.length === 0) {\n throw new Error('buildSkillMd: description is required and must be non-empty (agentskills.io spec)');\n }\n if (input.description.length > DESCRIPTION_MAX) {\n throw new Error(\n `buildSkillMd: description must be ≤${DESCRIPTION_MAX} characters (got ${input.description.length})`,\n );\n }\n if (input.compatibility && input.compatibility.length > COMPATIBILITY_MAX) {\n throw new Error(\n `buildSkillMd: compatibility must be ≤${COMPATIBILITY_MAX} characters (got ${input.compatibility.length})`,\n );\n }\n}\n\n/** Quote a value as a YAML double-quoted scalar — escape `\\\\`, `\"`, and newlines. The\n * agentskills.io spec calls out unquoted colons in `description` as the most common\n * parse failure across clients; emit every user-supplied scalar quoted to be safe. */\nfunction quoteYaml(value: string): string {\n return `\"${value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/\\n/g, '\\\\n')}\"`;\n}\n\n/** Sanitize a string for inclusion in a markdown table cell — escape backslashes first\n * (so existing `\\` aren't treated as escapes), then escape pipes (which would otherwise\n * terminate the cell). */\nfunction tableCell(value: string): string {\n return value.replace(/\\\\/g, '\\\\\\\\').replace(/\\|/g, '\\\\|');\n}\n\nfunction frontmatter(input: BuildSkillMdInput): string {\n const lines: string[] = ['---'];\n lines.push(`name: ${input.name}`);\n lines.push(`description: ${quoteYaml(input.description)}`);\n if (input.license) lines.push(`license: ${quoteYaml(input.license)}`);\n if (input.compatibility) lines.push(`compatibility: ${quoteYaml(input.compatibility)}`);\n if (input.allowedTools) lines.push(`allowed-tools: ${quoteYaml(input.allowedTools)}`);\n\n const meta: Array<[string, string]> = [];\n meta.push(['version', String(input.version ?? '1')]);\n meta.push(['homepage', input.homepage]);\n for (const [k, v] of Object.entries(input.metadata ?? {})) {\n if (k === 'version' || k === 'homepage') continue;\n meta.push([k, String(v)]);\n }\n lines.push('metadata:');\n for (const [k, v] of meta) {\n lines.push(` ${k}: ${quoteYaml(v)}`);\n }\n lines.push('---');\n return lines.join('\\n');\n}\n\nfunction importantFiles(input: BuildSkillMdInput): string {\n const skillUrl = `${input.homepage.replace(/\\/$/, '')}/skill.md`;\n const rows: string[] = [\n '| File | URL |',\n '|------|-----|',\n `| **SKILL.md** (this file) | \\`${skillUrl}\\` |`,\n ];\n for (const f of input.files ?? []) {\n rows.push(`| ${tableCell(f.label)} | \\`${tableCell(f.url)}\\` |`);\n }\n return ['## Important Files', '', ...rows].join('\\n');\n}\n\nfunction paymentSection(input: BuildSkillMdInput): string {\n const override = input.compatibleClients;\n const defaults = compatibleClientsByRails(input.acceptedRails) ?? {};\n // Override entries only apply to rails actually accepted; ignore stragglers.\n const clients: CompatibleClients = {};\n for (const r of input.acceptedRails) {\n clients[r] = override?.[r] ?? defaults[r] ?? [];\n }\n const rows: string[] = ['| Rail | Notes | Compatible clients |', '|---|---|---|'];\n for (const r of input.acceptedRails) {\n const list = (clients[r] ?? []).join(', ') || '—';\n rows.push(`| **${RAIL_LABELS[r]}** | ${RAIL_NOTES[r]} | ${list} |`);\n }\n return [\n '## Payment',\n '',\n 'Each gated route returns a 402 with `WWW-Authenticate` + `PAYMENT-REQUIRED` body listing the rails below with current pricing. Pick whichever your wallet is funded for.',\n '',\n ...rows,\n ].join('\\n');\n}\n\nfunction identitySection(input: BuildSkillMdInput): string {\n const id = input.identity;\n if (!id) return '';\n const reqs: string[] = [];\n if (id.kycRequired) reqs.push('KYC verified Passport');\n if (id.minAge) reqs.push(`age ${id.minAge}+`);\n if (id.allowedJurisdictions?.length) reqs.push(`${id.allowedJurisdictions.join('/')} only`);\n if (id.sanctionsClear) reqs.push('sanctions clear');\n if (reqs.length === 0) return '';\n const bootstrap = input.identityBootstrapUrl\n ? `\\n\\nIf you don't have a Passport, fetch \\`${input.identityBootstrapUrl}\\` and follow the onboarding there first. Bring back the \\`opc_...\\` operator token in \\`X-Operator-Token\\` on every gated request.`\n : '';\n return [\n '## Identity Prerequisite',\n '',\n `This merchant uses AgentScore identity. Required: ${reqs.join(', ')}.${bootstrap}`,\n '',\n 'Denial bodies carry an `agent_instructions` block describing the recovery action — read the `action` field and follow it. See the identity-bootstrap skill for the canonical denial-code → action table.',\n ].join('\\n');\n}\n\nfunction shippingSection(input: BuildSkillMdInput): string {\n const s = input.shipping;\n if (!s || (!s.allowedCountries?.length && !s.blockedStates?.length)) return '';\n const lines: string[] = ['## Shipping', ''];\n if (s.allowedCountries?.length) {\n lines.push(`Ships to: ${s.allowedCountries.join(', ')}.`);\n }\n if (s.blockedStates?.length) {\n if (lines.length > 2) lines.push('');\n lines.push(`Blocked US states: ${s.blockedStates.join(', ')}.`);\n }\n return lines.join('\\n');\n}\n\nfunction endpointsSection(input: BuildSkillMdInput): string {\n if (input.endpoints.length === 0) return '';\n const rows = ['| Method | Path | Auth | Purpose |', '|---|---|---|---|'];\n for (const e of input.endpoints) {\n rows.push(\n `| ${e.method} | \\`${tableCell(e.path)}\\` | ${e.authRequired ? 'identity required' : 'anonymous'} | ${tableCell(e.description)} |`,\n );\n }\n return ['## Endpoints', '', ...rows].join('\\n');\n}\n\nfunction onboardingSection(input: BuildSkillMdInput): string {\n if (!input.onboardingSteps?.length) return '';\n const rows = input.onboardingSteps.map((step, i) => `${i + 1}. ${step}`);\n return ['## Onboarding Flow', '', ...rows].join('\\n');\n}\n\nfunction triggersSection(input: BuildSkillMdInput): string {\n if (input.triggers.length === 0) return '';\n const rows = input.triggers.map((t) => `- ${t}`);\n return ['## Triggers', '', 'Use this skill when the user wants to:', '', ...rows].join('\\n');\n}\n\nfunction supportSection(input: BuildSkillMdInput): string {\n if (!input.supportLinks?.length) return '';\n const rows = input.supportLinks.map((l) => `- **${l.label}**: ${l.url}`);\n return ['## Support', '', ...rows].join('\\n');\n}\n\nfunction refreshFooter(input: BuildSkillMdInput): string {\n if (input.refreshFooter === false) return '';\n return '_Re-fetch this file periodically to pick up new endpoints, rails, or policies._';\n}\n\nfunction titleBlock(input: BuildSkillMdInput): string {\n const parts: string[] = [`# ${input.merchantName}`];\n if (input.tagline) parts.push(`_${input.tagline}_`);\n if (input.intro) parts.push(input.intro);\n return parts.join('\\n\\n');\n}\n\n/**\n * Render an agentskills.io-compatible `skill.md` for an agent-commerce merchant.\n *\n * Output is YAML frontmatter (`name` / `description` / optional `license` /\n * `compatibility` / `allowed-tools` / `metadata`) followed by markdown sections\n * describing payment rails, identity requirements, endpoints, triggers, and support\n * links — strictly the agent-facing contract, with no internal posture (no `failOpen`,\n * no mount-strategy names, no KYC vendor, no defense parameters).\n *\n * Spec compliance:\n * - `name` validated against the agentskills.io regex (lowercase alphanumeric + hyphens,\n * no leading/trailing/consecutive hyphens, ≤64 chars).\n * - `description` length capped at 1024.\n * - `metadata` values always emitted as quoted strings.\n * - `description` (and other user scalars) double-quoted to defuse the colon /\n * newline / quote pitfall the spec explicitly warns about.\n *\n * The compatible-clients-per-rail table sources from the same SDK constant\n * (`compatibleClientsByRails`) that drives the live 402 body's `compatible_clients`\n * field, so updating a smoke-verified client in one place propagates to every surface.\n */\nexport function buildSkillMd(input: BuildSkillMdInput): string {\n validateInput(input);\n const sections = [\n frontmatter(input),\n titleBlock(input),\n importantFiles(input),\n identitySection(input),\n paymentSection(input),\n shippingSection(input),\n onboardingSection(input),\n endpointsSection(input),\n triggersSection(input),\n supportSection(input),\n refreshFooter(input),\n ].filter((s) => s !== '');\n return sections.join('\\n\\n').replace(/\\n{3,}/g, '\\n\\n').trim() + '\\n';\n}\n"],"mappings":";AAIO,IAAM,WAAW;AAAA,EACtB,MAAM;AAAA,IACJ,SAAS,EAAE,OAAO,eAAwB,SAAS,KAAK;AAAA,IACxD,SAAS,EAAE,OAAO,gBAAyB,SAAS,MAAM;AAAA,EAC5D;AAAA,EACA,QAAQ;AAAA,IACN,SAAS,EAAE,OAAO,0CAAmD;AAAA,IACrE,QAAQ,EAAE,OAAO,0CAAmD;AAAA,EACtE;AAAA,EACA,OAAO;AAAA,IACL,SAAS,EAAE,OAAO,eAAwB,SAAS,KAAK;AAAA,IACxD,SAAS,EAAE,OAAO,gBAAyB,SAAS,MAAM;AAAA,EAC5D;AACF;;;ACbO,IAAM,OAAO;AAAA,EAClB,MAAM;AAAA,IACJ,SAAS,EAAE,SAAS,8CAAuD,UAAU,EAAE;AAAA,IACvF,SAAS,EAAE,SAAS,8CAAuD,UAAU,EAAE;AAAA,EACzF;AAAA,EACA,QAAQ;AAAA,IACN,SAAS,EAAE,MAAM,gDAAgD,UAAU,EAAE;AAAA,IAC7E,QAAQ,EAAE,MAAM,gDAAgD,UAAU,EAAE;AAAA,EAC9E;AAAA,EACA,OAAO;AAAA,IACL,SAAS,EAAE,SAAS,8CAAuD,UAAU,EAAE;AAAA,IACvF,SAAS,EAAE,SAAS,8CAAuD,UAAU,EAAE;AAAA,EACzF;AACF;;;ACRO,IAAM,QAAQ;AAAA,EACnB,iBAAiB;AAAA,IACf,QAAQ;AAAA,IACR,SAAS,SAAS,MAAM,QAAQ;AAAA,IAChC,SAAS,SAAS,MAAM,QAAQ;AAAA,IAChC,UAAU,KAAK,MAAM,QAAQ;AAAA,IAC7B,UAAU,KAAK,MAAM,QAAQ;AAAA,IAC7B,OAAO,KAAK,MAAM,QAAQ;A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AO,MAAM,SAAS,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE;AAC/C,SAAO,CAAC,eAAe,IAAI,0CAA0C,IAAI,GAAG,IAAI,EAAE,KAAK,IAAI;AAC7F;AAEA,SAAS,eAAe,OAAkC;AACxD,MAAI,CAAC,MAAM,cAAc,OAAQ,QAAO;AACxC,QAAM,OAAO,MAAM,aAAa,IAAI,CAAC,MAAM,OAAO,EAAE,KAAK,OAAO,EAAE,GAAG,EAAE;AACvE,SAAO,CAAC,cAAc,IAAI,GAAG,IAAI,EAAE,KAAK,IAAI;AAC9C;AAEA,SAAS,cAAc,OAAkC;AACvD,MAAI,MAAM,kBAAkB,MAAO,QAAO;AAC1C,SAAO;AACT;AAEA,SAAS,WAAW,OAAkC;AACpD,QAAM,QAAkB,CAAC,KAAK,MAAM,YAAY,EAAE;AAClD,MAAI,MAAM,QAAS,OAAM,KAAK,IAAI,MAAM,OAAO,GAAG;AAClD,MAAI,MAAM,MAAO,OAAM,KAAK,MAAM,KAAK;AACvC,SAAO,MAAM,KAAK,MAAM;AAC1B;AAuBO,SAAS,aAAa,OAAkC;AAC7D,gBAAc,KAAK;AACnB,QAAM,WAAW;AAAA,IACf,YAAY,KAAK;AAAA,IACjB,WAAW,KAAK;AAAA,IAChB,eAAe,KAAK;AAAA,IACpB,gBAAgB,KAAK;AAAA,IACrB,eAAe,KAAK;AAAA,IACpB,gBAAgB,KAAK;AAAA,IACrB,kBAAkB,KAAK;AAAA,IACvB,iBAAiB,KAAK;AAAA,IACtB,gBAAgB,KAAK;AAAA,IACrB,eAAe,KAAK;AAAA,IACpB,cAAc,KAAK;AAAA,EACrB,EAAE,OAAO,CAAC,MAAM,MAAM,EAAE;AACxB,SAAO,SAAS,KAAK,MAAM,EAAE,QAAQ,WAAW,MAAM,EAAE,KAAK,IAAI;AACnE;","names":["rails","rails"]}
1
+ {"version":3,"sources":["../../src/payment/networks.ts","../../src/payment/usdc.ts","../../src/payment/rails.ts","../../src/payment/directive.ts","../../src/payment/wwwauthenticate.ts","../../src/discovery/probe.ts","../../src/discovery/bazaar.ts","../../src/discovery/well_known_mpp.ts","../../src/discovery/well_known_x402.ts","../../src/discovery/llms_txt.ts","../../src/discovery/openapi.ts","../../src/discovery/robots_tag.ts","../../src/challenge/agent_instructions.ts","../../src/discovery/skill_md.ts"],"sourcesContent":["/**\n * Named network registry. Vendors reference symbolic names (`networks.base.mainnet.caip2`)\n * instead of magic strings. Lifted from agentscore-pay's constants.\n */\nexport const networks = {\n base: {\n mainnet: { caip2: 'eip155:8453' as const, chainId: 8453 },\n sepolia: { caip2: 'eip155:84532' as const, chainId: 84532 },\n },\n solana: {\n mainnet: { caip2: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp' as const },\n devnet: { caip2: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1' as const },\n },\n tempo: {\n mainnet: { caip2: 'eip155:4217' as const, chainId: 4217 },\n testnet: { caip2: 'eip155:42431' as const, chainId: 42431 },\n },\n} as const;\n\nexport type NetworkFamily = keyof typeof networks;\n\n/**\n * Returns the family name (base/solana/tempo) for a given CAIP-2 network string,\n * or null if the network isn't in the registry. Useful for routing settlement\n * by network.\n */\nexport function networkFamily(caip2: string): NetworkFamily | null {\n if (caip2 === networks.base.mainnet.caip2 || caip2 === networks.base.sepolia.caip2) return 'base';\n if (caip2 === networks.solana.mainnet.caip2 || caip2 === networks.solana.devnet.caip2) return 'solana';\n if (caip2 === networks.tempo.mainnet.caip2 || caip2 === networks.tempo.testnet.caip2) return 'tempo';\n if (caip2.startsWith('solana:')) return 'solana';\n return null;\n}\n","/**\n * USDC token registry per network. Used by paymentDirective and rail definitions.\n * Lifted from agentscore-pay's constants.\n */\nexport const USDC = {\n base: {\n mainnet: { address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' as const, decimals: 6 },\n sepolia: { address: '0x036CbD53842c5426634e7929541eC2318f3dCF7e' as const, decimals: 6 },\n },\n solana: {\n mainnet: { mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', decimals: 6 },\n devnet: { mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', decimals: 6 },\n },\n tempo: {\n mainnet: { address: '0x20C000000000000000000000b9537d11c60E8b50' as const, decimals: 6 },\n testnet: { address: '0x20c0000000000000000000000000000000000000' as const, decimals: 6 },\n },\n} as const;\n","import { networks } from './networks';\nimport { USDC } from './usdc';\n\n/**\n * Symbolic rail names mapped to their protocol details. Vendors pass `rail: 'tempo-mainnet'`\n * to the directive builder and the SDK fills in method/network/decimals/currency from this\n * registry. Custom rails not in this registry can be passed by setting the lower-level\n * fields directly on the directive builder.\n */\nexport const rails = {\n 'tempo-mainnet': {\n method: 'tempo',\n network: networks.tempo.mainnet.caip2,\n chainId: networks.tempo.mainnet.chainId,\n currency: USDC.tempo.mainnet.address,\n decimals: USDC.tempo.mainnet.decimals,\n asset: USDC.tempo.mainnet.address,\n },\n 'tempo-testnet': {\n method: 'tempo',\n network: networks.tempo.testnet.caip2,\n chainId: networks.tempo.testnet.chainId,\n currency: USDC.tempo.testnet.address,\n decimals: USDC.tempo.testnet.decimals,\n asset: USDC.tempo.testnet.address,\n },\n 'x402-base-mainnet': {\n method: 'x402',\n network: networks.base.mainnet.caip2,\n chainId: networks.base.mainnet.chainId,\n currency: USDC.base.mainnet.address,\n decimals: USDC.base.mainnet.decimals,\n asset: USDC.base.mainnet.address,\n },\n 'x402-base-sepolia': {\n method: 'x402',\n network: networks.base.sepolia.caip2,\n chainId: networks.base.sepolia.chainId,\n currency: USDC.base.sepolia.address,\n decimals: USDC.base.sepolia.decimals,\n asset: USDC.base.sepolia.address,\n },\n // Upto rails — pay UP TO a max amount (Permit2-based, vs EIP-3009 for exact). Use for\n // variable-cost APIs where the actual cost depends on output (LLM tokens, bandwidth, etc.).\n // Only available on EVM networks; Solana svm doesn't ship an upto scheme yet.\n 'x402-base-mainnet-upto': {\n method: 'x402-upto',\n network: networks.base.mainnet.caip2,\n chainId: networks.base.mainnet.chainId,\n currency: USDC.base.mainnet.address,\n decimals: USDC.base.mainnet.decimals,\n asset: USDC.base.mainnet.address,\n },\n 'x402-base-sepolia-upto': {\n method: 'x402-upto',\n network: networks.base.sepolia.caip2,\n chainId: networks.base.sepolia.chainId,\n currency: USDC.base.sepolia.address,\n decimals: USDC.base.sepolia.decimals,\n asset: USDC.base.sepolia.address,\n },\n 'mpp-solana-mainnet': {\n method: 'solana',\n network: networks.solana.mainnet.caip2,\n currency: USDC.solana.mainnet.mint,\n decimals: USDC.solana.mainnet.decimals,\n asset: USDC.solana.mainnet.mint,\n },\n 'mpp-solana-devnet': {\n method: 'solana',\n network: networks.solana.devnet.caip2,\n currency: USDC.solana.devnet.mint,\n decimals: USDC.solana.devnet.decimals,\n asset: USDC.solana.devnet.mint,\n },\n 'stripe-spt': {\n method: 'stripe',\n currency: 'usd',\n decimals: 2,\n },\n} as const;\n\nexport type RailName = keyof typeof rails;\n\nexport interface RailDefinition {\n method: string;\n network?: string;\n chainId?: number;\n currency: string;\n decimals: number;\n asset?: string;\n}\n\n/**\n * Lookup a rail definition by symbolic name. Returns undefined if the rail isn't in\n * the registry — vendors with custom rails should pass the low-level fields directly.\n */\nexport function lookupRail(name: string): RailDefinition | undefined {\n return rails[name as RailName] as RailDefinition | undefined;\n}\n","import { lookupRail } from './rails';\n\nexport interface PaymentRequestInput {\n /** Symbolic rail name (e.g., 'tempo-mainnet', 'x402-base-mainnet') — fills in defaults */\n rail?: string;\n /** Amount in USD as a number or string. Converted to raw integer using `decimals`. */\n amountUsd: string | number;\n /** Token contract address or currency code. Defaults from rail. */\n currency?: string;\n /** Decimal precision for the amount. Defaults from rail (6 for USDC, 2 for USD). */\n decimals?: number;\n /** Recipient address (on-chain). Optional for stripe-style rails. */\n recipient?: string;\n /** EVM chain ID (goes into methodDetails.chainId). Defaults from rail. */\n chainId?: number;\n /** Stripe profile_id or similar (goes into methodDetails.networkId — note camelCase per link-cli's mpp decode validator). */\n networkId?: string;\n}\n\n/**\n * Build the base64-encoded `request` blob for an MPP Payment directive (per the\n * paymentauth.org spec). Output shape matches what link-cli `mpp decode` expects:\n *\n * { amount: \"<raw_integer>\", currency: \"<token>\", recipient?: \"<addr>\",\n * methodDetails?: { chainId?: number, networkId?: string } }\n */\nexport function buildPaymentRequestBlob(input: PaymentRequestInput): string {\n const railDef = input.rail ? lookupRail(input.rail) : undefined;\n const decimals = input.decimals ?? railDef?.decimals ?? 6;\n const currency = input.currency ?? railDef?.currency ?? 'usd';\n const chainId = input.chainId ?? railDef?.chainId;\n\n const amountNum = typeof input.amountUsd === 'string' ? Number(input.amountUsd) : input.amountUsd;\n const amountRaw = BigInt(Math.round(amountNum * 10 ** decimals)).toString();\n const blob: Record<string, unknown> = { amount: amountRaw, currency, decimals };\n if (input.recipient) blob.recipient = input.recipient;\n const methodDetails: Record<string, unknown> = {};\n if (chainId !== undefined) methodDetails.chainId = chainId;\n if (input.networkId) methodDetails.networkId = input.networkId;\n if (Object.keys(methodDetails).length > 0) blob.methodDetails = methodDetails;\n return Buffer.from(JSON.stringify(blob)).toString('base64url');\n}\n\nexport interface PaymentDirectiveInput {\n /** Symbolic rail name — sets `method` automatically */\n rail?: string;\n /** Challenge id (unique per request, used to correlate retries) */\n id: string;\n /** Realm — the host of the merchant URL (e.g., \"agents.merchant.example\") */\n realm: string;\n /** MPP method name. Defaults from rail (e.g., 'tempo', 'stripe'). */\n method?: string;\n /** MPP intent. Defaults to 'charge'. */\n intent?: string;\n /** ISO-8601 expiry timestamp. Defaults to now + 5 minutes. */\n expires?: string;\n /** Base64-encoded request blob. Pass the result of buildPaymentRequestBlob. */\n request: string;\n}\n\n/**\n * Format an MPP Payment directive string for the WWW-Authenticate header.\n * Output shape: `Payment id=\"...\", realm=\"...\", method=\"...\", intent=\"charge\",\n * expires=\"...\", request=\"<base64>\"`\n */\nexport function paymentDirective(input: PaymentDirectiveInput): string {\n const railDef = input.rail ? lookupRail(input.rail) : undefined;\n const method = input.method ?? railDef?.method ?? 'unknown';\n const intent = input.intent ?? 'charge';\n const expires = input.expires ?? new Date(Date.now() + 5 * 60 * 1000).toISOString();\n return `Payment id=\"${input.id}\", realm=\"${input.realm}\", method=\"${method}\", intent=\"${intent}\", expires=\"${expires}\", request=\"${input.request}\"`;\n}\n\nexport interface BuildPaymentDirectiveInput\n extends Omit<PaymentRequestInput, 'rail'>,\n Omit<PaymentDirectiveInput, 'request'> {\n rail: string;\n}\n\n/**\n * Convenience: build the request blob and the directive in one call. Most vendors\n * want this rather than the two-step form.\n */\nexport function buildPaymentDirective(input: BuildPaymentDirectiveInput): string {\n const request = buildPaymentRequestBlob({\n rail: input.rail,\n amountUsd: input.amountUsd,\n currency: input.currency,\n decimals: input.decimals,\n recipient: input.recipient,\n chainId: input.chainId,\n networkId: input.networkId,\n });\n return paymentDirective({\n rail: input.rail,\n id: input.id,\n realm: input.realm,\n method: input.method,\n intent: input.intent,\n expires: input.expires,\n request,\n });\n}\n","/**\n * Joins multiple Payment directives into a single WWW-Authenticate header value.\n * Per RFC 7235, multiple challenges are comma-separated.\n */\nexport function wwwAuthenticateHeader(directives: string[]): string {\n return directives.join(', ');\n}\n\nexport interface PaymentRequiredHeaderInput {\n x402Version: 1 | 2;\n accepts: unknown[];\n resource?: { url: string; mimeType?: string };\n}\n\n/**\n * Add the v1↔v2 amount-field alias to each accepts entry. Idempotent. Used by both\n * `paymentRequiredHeader` (header emit) and `build402Body` (body emit) so every\n * x402 entry on the wire carries BOTH `amount` (v2 spec) AND `maxAmountRequired`\n * (v1 spec) — strict v1-only parsers (e.g. Coinbase awal at `payments-mcp.coinbase.com`,\n * which is hardcoded to read `maxAmountRequired`) work alongside strict v2 parsers,\n * which ignore the alias.\n */\nexport function aliasAmountFields(accepts: unknown[]): unknown[] {\n return accepts.map((entry) => {\n if (entry === null || typeof entry !== 'object') return entry;\n const e = entry as Record<string, unknown>;\n const hasAmount = e.amount !== undefined;\n const hasMaxAmount = e.maxAmountRequired !== undefined;\n if (hasAmount && !hasMaxAmount) return { ...e, maxAmountRequired: e.amount };\n if (hasMaxAmount && !hasAmount) return { ...e, amount: e.maxAmountRequired };\n return e;\n });\n}\n\n/**\n * Encode the standard x402 PAYMENT-REQUIRED header (base64-encoded JSON of the\n * PaymentRequired object). Clients that recognize the header (`@x402/fetch`,\n * `@x402/core` HTTPClient, `agentscore-pay`) prefer it over body fields.\n *\n * Note: do NOT add a v1↔v2 amount-field alias here. `@x402/core`'s\n * `findMatchingRequirements` uses `deepEqual` against the agent's signed\n * `accepted` payload — any field present on one side and missing on the other\n * (e.g. `maxAmountRequired` on the wire body but not in `buildPaymentRequirements`'s\n * output) makes the match silently fail at settle time. Keep `accepts` shape\n * identical to whatever `buildPaymentRequirements` produces server-side.\n */\nexport function paymentRequiredHeader(input: PaymentRequiredHeaderInput): string {\n return Buffer.from(JSON.stringify(input)).toString('base64');\n}\n","import { buildPaymentRequestBlob, paymentDirective } from '../payment/directive';\nimport { networks } from '../payment/networks';\nimport { USDC } from '../payment/usdc';\nimport { paymentRequiredHeader } from '../payment/wwwauthenticate';\n\n/** Placeholder payTo for x402 sample accepts in the discovery probe — the probe\n * exists for crawlers to find that we support x402, not for actual payment. The\n * real 402 (returned on a fully-formed request body) carries real deposit\n * addresses minted from a Stripe PaymentIntent. */\nconst ZERO_EVM_PAYTO = '0x0000000000000000000000000000000000000000';\nconst ZERO_SOLANA_PAYTO = '11111111111111111111111111111111';\n\n/**\n * Build a sample x402 accepts entry for a CAIP-2 network. Looks up the USDC asset\n * for the network from the `USDC` registry and uses a placeholder payTo. Used by\n * the discovery probe to advertise x402 support without exposing real deposit\n * addresses.\n *\n * Returns null when the network isn't in the registry — vendors with custom\n * networks should construct accepts entries by hand and pass them via\n * `x402Sample.accepts` directly.\n */\nexport function sampleX402AcceptForNetwork(\n caip2: string,\n amountAtomic: string = '1000000',\n): Record<string, unknown> | null {\n if (caip2 === networks.base.mainnet.caip2) {\n return {\n scheme: 'exact',\n network: caip2,\n amount: amountAtomic,\n asset: USDC.base.mainnet.address,\n payTo: ZERO_EVM_PAYTO,\n maxTimeoutSeconds: 300,\n // ``extra.name`` mirrors the on-chain USDC contract's ``name()`` because\n // EIP-712 domain hashes include this string. Wrong name → every signed\n // payload fails facilitator verify with ``invalid_exact_evm_payload_signature``.\n // Base mainnet USDC returns \"USD Coin\"; base sepolia USDC returns \"USDC\".\n extra: { name: 'USD Coin', version: '2' },\n };\n }\n if (caip2 === networks.base.sepolia.caip2) {\n return {\n scheme: 'exact',\n network: caip2,\n amount: amountAtomic,\n asset: USDC.base.sepolia.address,\n payTo: ZERO_EVM_PAYTO,\n maxTimeoutSeconds: 300,\n extra: { name: 'USDC', version: '2' },\n };\n }\n if (caip2 === networks.solana.mainnet.caip2) {\n return {\n scheme: 'exact',\n network: caip2,\n amount: amountAtomic,\n asset: USDC.solana.mainnet.mint,\n payTo: ZERO_SOLANA_PAYTO,\n maxTimeoutSeconds: 300,\n };\n }\n if (caip2 === networks.solana.devnet.caip2) {\n return {\n scheme: 'exact',\n network: caip2,\n amount: amountAtomic,\n asset: USDC.solana.devnet.mint,\n payTo: ZERO_SOLANA_PAYTO,\n maxTimeoutSeconds: 300,\n };\n }\n return null;\n}\n\nexport interface DiscoveryProbeOptions {\n /** Realm — typically the host of your merchant URL (e.g., \"agents.merchant.example\"). */\n realm: string;\n /** Symbolic rail name to advertise in the sample challenge (e.g., 'tempo-mainnet'). */\n sampleRail: string;\n /** Sample amount in USD for the probe (e.g., 1.00). Crawlers use this as an example. */\n sampleAmountUsd: number;\n /** A recipient address to use in the sample directive (your real or zero address is fine). */\n sampleRecipient: string;\n /** MPP intent. Defaults to 'charge'. */\n intent?: string;\n /** TTL for the probe challenge in seconds. Defaults to 300 (5 minutes). */\n ttlSeconds?: number;\n /** Optional URL to include in the body for further docs (e.g., your llms.txt). */\n docsUrl?: string;\n /** Optional human-readable message in the body. */\n message?: string;\n /** Optional sample x402 accepts entries. When provided, the probe response also\n * carries the standard x402 `payment-required` header (base64 PaymentRequired) AND\n * an `accepts` array in the body — so x402 crawlers (e.g. Coinbase awal's\n * `x402 details`/`x402 pay`) can discover the endpoint's x402 support without\n * needing to send a fully-formed business request. Each entry is run through\n * `aliasAmountFields` so v1-only parsers can read `maxAmountRequired` too.\n *\n * Pass `networks` (shorthand) for the common case — the helper looks up USDC\n * per network from the registry and uses placeholder payTo addresses. Or pass\n * `accepts` directly for full control over the sample shape. */\n x402Sample?: {\n /** Spec version to declare. Defaults to 2. */\n version?: 1 | 2;\n /** Shorthand: array of CAIP-2 network strings. Each is mapped to a sample\n * USDC accepts entry via `sampleX402AcceptForNetwork`. Networks not in the\n * USDC registry are silently skipped. Use `accepts` for custom shapes. */\n networks?: string[];\n /** Sample accepts entries. Used when `networks` shorthand isn't enough.\n * Supplied entries are NOT merged with `networks`-derived entries — pick\n * one or the other. */\n accepts?: unknown[];\n /** Sample atomic amount used by the `networks` shorthand. Defaults to\n * `'1000000'` ($1.00 USDC at 6 decimals). Ignored when `accepts` is set. */\n amountAtomic?: string;\n /** Resource URL the probe is responding for. Used in the PAYMENT-REQUIRED header. */\n resourceUrl?: string;\n };\n}\n\nexport interface DiscoveryProbeResponse {\n status: 402;\n headers: Record<string, string>;\n body: string;\n}\n\n/**\n * Build a 402 response advertising a sample Payment challenge. MPP crawlers\n * (mppscan, link-cli mpp decode) probe with empty bodies; merchants need to answer\n * with a properly-formatted Payment directive so the realm can be indexed.\n *\n * Returns a framework-agnostic response shape. Wrap in your framework's response:\n *\n * const probe = buildDiscoveryProbeResponse({...});\n * return new Response(probe.body, { status: probe.status, headers: probe.headers });\n */\nexport function buildDiscoveryProbeResponse(opts: DiscoveryProbeOptions): DiscoveryProbeResponse {\n const probeId = `probe_${Date.now()}`;\n const expires = new Date(Date.now() + (opts.ttlSeconds ?? 300) * 1000).toISOString();\n const request = buildPaymentRequestBlob({\n rail: opts.sampleRail,\n amountUsd: opts.sampleAmountUsd,\n recipient: opts.sampleRecipient,\n });\n const directive = paymentDirective({\n rail: opts.sampleRail,\n id: probeId,\n realm: opts.realm,\n intent: opts.intent,\n expires,\n request,\n });\n\n const bodyObj: Record<string, unknown> = {\n error: {\n code: 'payment_required',\n message: opts.message ?? 'This endpoint requires payment. Send a valid request body to receive a full challenge.',\n },\n discovery: true,\n ...(opts.docsUrl ? { docs: opts.docsUrl } : {}),\n };\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n 'www-authenticate': directive,\n };\n\n if (opts.x402Sample) {\n const x402Version = opts.x402Sample.version ?? 2;\n const sampleAccepts = opts.x402Sample.accepts\n ?? (opts.x402Sample.networks ?? [])\n .map((n) => sampleX402AcceptForNetwork(n, opts.x402Sample!.amountAtomic ?? '1000000'))\n .filter((e): e is Record<string, unknown> => e !== null);\n // paymentRequiredHeader applies aliasAmountFields internally; do the same for\n // the body's `accepts` so v1-only parsers (Coinbase awal at payments-mcp.coinbase.com)\n // and v2-strict parsers can both read either field name.\n headers['payment-required'] = paymentRequiredHeader({\n x402Version,\n accepts: sampleAccepts,\n ...(opts.x402Sample.resourceUrl\n ? { resource: { url: opts.x402Sample.resourceUrl, mimeType: 'application/json' } }\n : {}),\n });\n // Also embed in body for clients that read body-level accepts (e.g. awal x402 details\n // falls back from header → body when the header isn't present).\n bodyObj.x402Version = x402Version;\n // Reuse the header's already-aliased accepts so the body matches.\n const headerJson = JSON.parse(Buffer.from(headers['payment-required'], 'base64').toString('utf-8'));\n bodyObj.accepts = headerJson.accepts;\n }\n\n return {\n status: 402,\n headers,\n body: JSON.stringify(bodyObj),\n };\n}\n\nexport interface RequestLike {\n method: string;\n headers: { get(name: string): string | null };\n clone(): { text(): Promise<string> };\n}\n\n/**\n * Returns true when the request is an empty-body POST without a payment credential —\n * the canonical MPP discovery probe pattern. Vendors compose this with\n * buildDiscoveryProbeResponse to short-circuit crawler requests before any business\n * logic runs.\n */\nexport async function isDiscoveryProbeRequest(req: RequestLike): Promise<boolean> {\n if (req.method !== 'POST') return false;\n const auth = req.headers.get('authorization');\n if (auth?.startsWith('Payment ')) return false;\n const body = await req.clone().text();\n return !body || body === '{}';\n}\n","/**\n * Bazaar discovery extension wrapper. Vendors pass their merchant config and we wrap\n * `declareDiscoveryExtension` from `@x402/extensions/bazaar`. The returned value is\n * registered on the x402 server (e.g., via `createX402Server({bazaar: true})` or\n * `server.registerExtension(...)`).\n *\n * `@x402/extensions` is an optional peer dependency.\n */\nexport interface BazaarDiscoveryConfig {\n bodyType?: 'json' | 'form';\n input?: Record<string, unknown>;\n output?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\ninterface BazaarModule {\n declareDiscoveryExtension?: (config: BazaarDiscoveryConfig) => unknown;\n}\n\nexport async function createBazaarDiscovery(config: BazaarDiscoveryConfig): Promise<unknown> {\n const bazaar = await dynamicImport<BazaarModule>('@x402/extensions/bazaar');\n /* v8 ignore start -- peer-dep-absence guard; @x402/extensions is installed in test env */\n if (!bazaar?.declareDiscoveryExtension) {\n throw new Error(\n '@x402/extensions not installed — `npm install @x402/extensions` for createBazaarDiscovery.',\n );\n }\n /* v8 ignore stop */\n return bazaar.declareDiscoveryExtension(config);\n}\n\nasync function dynamicImport<T>(moduleName: string): Promise<T | null> {\n try {\n return (await import(moduleName)) as T;\n } catch {\n /* v8 ignore next -- catch fires only when peer dep is missing; installed in test env */\n return null;\n }\n}\n","export interface PaymentMethodConfig {\n /** MPP payment methods accepted, e.g., ['tempo', 'x402', 'stripe']. */\n methods: string[];\n /** x402-specific config (when 'x402' is in methods). */\n x402?: {\n networks: string[];\n scheme?: string;\n asset?: string;\n facilitator?: string;\n client_tooling?: string;\n };\n /** Identity headers accepted (e.g., ['X-Operator-Token', 'X-Wallet-Address']). */\n identity?: string[];\n /** Per-identity-path metadata for agents. */\n identity_paths?: {\n wallet?: { header: string; applies_to_rails: string[]; note?: string };\n operator_token?: { header: string; applies_to_rails: string[]; note?: string };\n };\n /** Compliance policy summary for agents to know what they need before purchasing. */\n compliance?: {\n require_kyc?: boolean;\n min_age?: number;\n allowed_jurisdictions?: string[];\n require_sanctions_clear?: boolean;\n };\n /** Required fields in the request body. */\n required_fields?: string[];\n /** Optional fields in the request body. */\n optional_fields?: string[];\n /** Vendor-specific extras merged into the purchase block (e.g., gift_note metadata). */\n extra?: Record<string, unknown>;\n}\n\nexport interface WellKnownMppInput {\n /** Merchant display name. */\n name: string;\n /** Short description (1-2 sentences). */\n description?: string;\n /** Canonical merchant URL. */\n url: string;\n /** OpenAPI doc URL (typically `${url}/openapi.json`). */\n openapi?: string;\n /** Endpoints map: path → {method, url}. */\n endpoints: Record<string, { method: string; url: string }>;\n /** Catalog metadata (categories, etc). Optional. */\n catalog?: Record<string, unknown>;\n /** Purchase flow details (payment methods, identity, compliance). */\n purchase: PaymentMethodConfig;\n /** Shipping policy (countries, restrictions). */\n shipping?: Record<string, unknown>;\n /** Vendor-specific extra fields merged at the top level. */\n extra?: Record<string, unknown>;\n}\n\n/**\n * Build the standard `.well-known/mpp.json` discovery document. Lift the boilerplate\n * (payment.methods, payment.identity_paths, payment.compliance) into a typed config so\n * vendors get spec-compliance \"for free\"; merchant-specific fields (catalog, shipping)\n * pass through.\n *\n * Wire it in your framework like:\n * app.get('/.well-known/mpp.json', (c) => c.json(buildWellKnownMpp({...})));\n */\nexport function buildWellKnownMpp(input: WellKnownMppInput): Record<string, unknown> {\n return {\n name: input.name,\n ...(input.description ? { description: input.description } : {}),\n url: input.url,\n ...(input.openapi ? { openapi: input.openapi } : {}),\n endpoints: input.endpoints,\n ...(input.catalog ? { catalog: input.catalog } : {}),\n purchase: {\n ...(input.purchase.required_fields ? { required_fields: input.purchase.required_fields } : {}),\n ...(input.purchase.optional_fields ? { optional_fields: input.purchase.optional_fields } : {}),\n ...(input.purchase.extra ?? {}),\n ...(input.purchase.identity ? { identity: input.purchase.identity } : {}),\n ...(input.purchase.identity_paths ? { identity_paths: input.purchase.identity_paths } : {}),\n payment_methods: input.purchase.methods,\n ...(input.purchase.x402 ? { x402: input.purchase.x402 } : {}),\n ...(input.purchase.compliance ? { compliance: input.purchase.compliance } : {}),\n },\n ...(input.shipping ? { shipping: input.shipping } : {}),\n ...(input.extra ?? {}),\n };\n}\n","/**\n * `buildWellKnownX402`: emits the x402scan v1 `/.well-known/x402` discovery shape.\n *\n * x402scan accepts three discovery strategies (OpenAPI > `/.well-known/x402` > endpoint\n * probe). Most AgentScore merchants already publish a richer `/.well-known/mpp.json`,\n * but x402scan's strict parser only reads the v1 shape, so we emit both. The two\n * coexist on different paths.\n *\n * Spec (verbatim, x402scan):\n *\n * {\n * \"version\": 1,\n * \"resources\": [\"POST /api/route\", ...]\n * }\n *\n * Resource entries are `\"METHOD /path\"` strings, not objects. Runtime 402 behavior\n * is authoritative over this static metadata.\n */\n\nexport interface WellKnownX402Resource {\n /** HTTP method, uppercase: `'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'`. */\n method: string;\n /** Path, leading slash: `'/purchase'`. */\n path: string;\n}\n\nexport interface BuildWellKnownX402Input {\n /** Invocable, payment-required routes. Each entry becomes `\"METHOD /path\"`. */\n resources: WellKnownX402Resource[];\n}\n\nexport interface WellKnownX402Document {\n version: 1;\n resources: string[];\n}\n\nexport function buildWellKnownX402(input: BuildWellKnownX402Input): WellKnownX402Document {\n return {\n version: 1,\n resources: input.resources.map((r) => `${r.method.toUpperCase()} ${r.path}`),\n };\n}\n","export interface LlmsTxtIdentitySectionInput {\n /** When true, include the AgentScore identity-paths explanation (wallet vs operator-token). */\n agentscore?: boolean;\n /** Compliance policy to mention (KYC, age, jurisdiction). */\n compliance?: {\n require_kyc?: boolean;\n min_age?: number;\n allowed_jurisdictions?: string[];\n require_sanctions_clear?: boolean;\n };\n}\n\n/**\n * Generate the standard \"Choose your identity header\" section for an AgentScore-gated\n * merchant's llms.txt. Explains wallet-auth vs operator-token paths + the cross-merchant\n * memory contract so agents know how to authenticate without reading the API docs.\n */\nexport function llmsTxtIdentitySection(input: LlmsTxtIdentitySectionInput = {}): string {\n if (!input.agentscore) {\n return '';\n }\n const compliance = input.compliance;\n const complianceNote = compliance\n ? `\\n\\nCompliance: ${[\n compliance.require_kyc ? 'KYC required' : null,\n compliance.min_age ? `age ${compliance.min_age}+` : null,\n compliance.allowed_jurisdictions?.length\n ? `${compliance.allowed_jurisdictions.join('/')} only`\n : null,\n compliance.require_sanctions_clear ? 'sanctions clear' : null,\n ]\n .filter(Boolean)\n .join(', ')}.`\n : '';\n return `## Identity\n\nAgentScore identity is reusable across every AgentScore-gated merchant — one KYC, no re-verification per site. Pick a header:\n\n- **\\`X-Wallet-Address: 0x...\\` or base58** — works on signing rails (Tempo, x402, Solana MPP). The wallet you claim must sign the payment.\n- **\\`X-Operator-Token: opc_...\\`** — works on every rail, including Stripe SPT. Reusable across AgentScore merchants until expiry.\n- **Neither** — you get a 403 with \\`verify_url\\`. Complete the session flow once and reuse the resulting \\`opc_...\\` everywhere.${complianceNote}`;\n}\n\nexport interface LlmsTxtPaymentSectionInput {\n /** Symbolic rail names supported. */\n rails: ('tempo-mainnet' | 'tempo-testnet' | 'x402-base-mainnet' | 'x402-base-sepolia' | 'mpp-solana-mainnet' | 'mpp-solana-devnet' | 'stripe-spt' | string)[];\n /** Merchant URL — used in the example commands. */\n appUrl: string;\n /**\n * When true, emit the verbose multi-step variant: setup commands per rail, full per-rail\n * payment-command examples, and warnings about footguns. Default false (one-line bullet per rail).\n * Use this when llms.txt is the primary integration doc the agent reads.\n */\n verbose?: boolean;\n /** When verbose, the Tempo network name to mention in the prerequisites. Default 'tempo-mainnet'. */\n tempoNetworkName?: string;\n /** When verbose, the Tempo chain id to mention in the prerequisites. Default 4217. */\n tempoChainId?: number;\n}\n\n/**\n * Generate the standard \"## Payment\" section for a merchant's llms.txt. Documents the\n * supported rails with concrete CLI examples (tempo request, agentscore-pay, link-cli)\n * per the configured rail set.\n *\n * Pass `verbose: true` for the rich variant — multi-step setup + multi-line command examples +\n * exact-amount warnings. Default is the compact one-bullet-per-rail form.\n */\nexport function llmsTxtPaymentSection(input: LlmsTxtPaymentSectionInput): string {\n return input.verbose ? llmsTxtPaymentSectionVerbose(input) : llmsTxtPaymentSectionCompact(input);\n}\n\nfunction hasRailFamily(rails: string[], prefix: string): boolean {\n return rails.some(r => r.startsWith(prefix));\n}\n\nfunction isTestnetRail(rails: string[], prefix: string): boolean {\n return rails.some(r => r.startsWith(prefix) && /(sepolia|devnet|moderato|testnet)/.test(r));\n}\n\nfunction llmsTxtPaymentSectionCompact(input: LlmsTxtPaymentSectionInput): string {\n const lines: string[] = ['## Payment', ''];\n const rails = input.rails;\n if (hasRailFamily(rails, 'tempo-')) {\n lines.push('- **Tempo USDC via MPP** — `tempo request -X POST -H \"X-Operator-Token: opc_...\" --json \\'{...}\\' --max-spend N ' + input.appUrl + '`');\n }\n if (hasRailFamily(rails, 'x402-base-')) {\n lines.push('- **x402 USDC on Base** (EIP-3009) — `agentscore-pay pay POST ' + input.appUrl + ' --chain base -H \"X-Operator-Token: opc_...\" -d \\'{...}\\'`');\n }\n if (hasRailFamily(rails, 'mpp-solana-')) {\n lines.push('- **USDC on Solana** — `agentscore-pay pay POST ' + input.appUrl + ' --chain solana -H \"X-Operator-Token: opc_...\" -d \\'{...}\\'`');\n }\n if (rails.includes('stripe-spt')) {\n lines.push('- **Stripe Shared Payment Token** — agent mints SPT (own Stripe account scoped to networkId, OR `link-cli spend-request create --credential-type shared_payment_token --network-id <profileId> ...`)');\n }\n lines.push('');\n lines.push('IMPORTANT: Do NOT use raw on-chain transfers. Use the CLI commands above so the payment credential is signed and submitted via the protocol handshake.');\n lines.push('');\n return lines.join('\\n');\n}\n\nfunction llmsTxtPaymentSectionVerbose(input: LlmsTxtPaymentSectionInput): string {\n const rails = input.rails;\n const tempoNetwork = input.tempoNetworkName ?? 'tempo-mainnet';\n const tempoChain = input.tempoChainId ?? 4217;\n const hasTempo = hasRailFamily(rails, 'tempo-');\n const hasBase = hasRailFamily(rails, 'x402-base-');\n const hasSolana = hasRailFamily(rails, 'mpp-solana-');\n const hasStripe = rails.includes('stripe-spt');\n const baseNetworkName = isTestnetRail(rails, 'x402-base-') ? 'Base Sepolia' : 'Base';\n const solanaNetworkName = isTestnetRail(rails, 'mpp-solana-') ? 'Solana devnet' : 'Solana';\n\n const lines: string[] = ['## Payment', ''];\n lines.push('Accepted rails:');\n lines.push('');\n if (hasTempo) lines.push('- **USDC on Tempo**');\n if (hasBase) lines.push(`- **USDC on ${baseNetworkName}**`);\n if (hasSolana) lines.push(`- **USDC on ${solanaNetworkName}**`);\n if (hasStripe) lines.push('- **Stripe Shared Payment Token**');\n lines.push('');\n\n if (hasTempo) {\n lines.push('### Pay with Tempo');\n lines.push('');\n lines.push('```bash');\n lines.push('curl -fsSL https://tempo.xyz/install | bash');\n lines.push('tempo wallet login');\n lines.push(`tempo wallet whoami # need USDC.e on ${tempoNetwork} (chain ${tempoChain})`);\n lines.push('tempo wallet fund # if zero');\n lines.push('');\n lines.push('tempo request -X POST \\\\');\n lines.push(' -H \"X-Operator-Token: opc_...\" \\\\');\n lines.push(\" --json '{...}' \\\\\");\n lines.push(' --max-spend N \\\\');\n lines.push(` ${input.appUrl}`);\n lines.push('```');\n lines.push('');\n }\n\n if (hasBase || hasSolana) {\n const chainsLabel = [hasBase && baseNetworkName, hasSolana && solanaNetworkName].filter(Boolean).join(' or ');\n const flags = [hasBase && '`--chain base`', hasSolana && '`--chain solana`'].filter(Boolean).join(' or ');\n lines.push(`### Pay with ${chainsLabel}`);\n lines.push('');\n lines.push('```bash');\n lines.push('npm install -g @agent-score/pay');\n lines.push(`agentscore-pay wallet create ${flags}`);\n lines.push(`agentscore-pay balance ${flags} # fund the printed address with USDC`);\n lines.push('');\n lines.push(`agentscore-pay pay POST ${input.appUrl} \\\\`);\n lines.push(` ${hasBase ? '--chain base' : '--chain solana'} \\\\`);\n lines.push(' -H \"X-Operator-Token: opc_...\" \\\\');\n lines.push(\" -d '{...}' \\\\\");\n lines.push(' --max-spend N');\n lines.push('```');\n lines.push('');\n }\n\n if (hasStripe) {\n lines.push('### Pay with Stripe SPT');\n lines.push('');\n lines.push('Mint a SharedPaymentToken scoped to the `profile_id` from the 402 body, then submit via `Authorization: Payment` with `method=stripe/charge`. Either your own Stripe account or `link-cli spend-request create --credential-type shared_payment_token --network-id <profileId> ...` for Stripe Link wallets.');\n lines.push('');\n }\n\n lines.push('IMPORTANT: Use the CLIs above. Raw on-chain transfers (e.g. `tempo wallet transfer`, sending USDC manually to deposit addresses) bypass the protocol handshake and the order will not complete.');\n if (hasBase || hasSolana) {\n lines.push('IMPORTANT: Pay the exact amount in the 402 challenge. Overpayments and underpayments cannot be matched.');\n }\n lines.push('');\n return lines.join('\\n');\n}\n\nexport interface BuildLlmsTxtInput {\n merchantName: string;\n /** Optional 1-line summary under the title. */\n tagline?: string;\n /** Custom merchant-written sections (intro, endpoints, terms, etc.). */\n sections: { heading: string; content: string }[];\n /** Append the AgentScore identity section. */\n agentscoreIdentity?: LlmsTxtIdentitySectionInput;\n /** Append the standard payment section. */\n payment?: LlmsTxtPaymentSectionInput;\n}\n\n/**\n * Assemble a complete llms.txt document. Vendor passes their merchant-specific sections\n * (intro, catalog, endpoints, gift orders, shipping, etc.); the helper adds the AgentScore\n * identity + payment boilerplate at the end. Returns the full markdown string.\n */\nexport function buildLlmsTxt(input: BuildLlmsTxtInput): string {\n const parts: string[] = [`# ${input.merchantName}`];\n if (input.tagline) {\n parts.push(`> ${input.tagline}`);\n }\n parts.push('');\n for (const s of input.sections) {\n parts.push(`## ${s.heading}`);\n parts.push('');\n parts.push(s.content);\n parts.push('');\n }\n if (input.agentscoreIdentity) {\n parts.push(llmsTxtIdentitySection(input.agentscoreIdentity));\n parts.push('');\n }\n if (input.payment) {\n parts.push(llmsTxtPaymentSection(input.payment));\n }\n return parts.join('\\n');\n}\n","/**\n * OpenAPI snippets for AgentScore-related concepts. Vendors plug these into their own\n * OpenAPI 3.1 document (typically /openapi.json) so MPPScan and similar agent registries\n * can validate the merchant's auth + denial schemas correctly.\n *\n * Each helper returns a piece of an OpenAPI document — vendors compose them into their\n * full spec.\n */\n\n/**\n * Standard AgentScore identity security schemes. Plug into `components.securitySchemes`.\n *\n * Includes `siwx` (Sign-In With X) per the x402scan discovery spec so identity-gated\n * operations can declare `security: [{ siwx: [] }]` and stay classified as identity-only,\n * not paid.\n */\nexport function agentscoreSecuritySchemes(): Record<string, unknown> {\n return {\n OperatorToken: {\n type: 'apiKey',\n in: 'header',\n name: 'X-Operator-Token',\n description:\n 'Operator-token-path identity (opc_...). Works on every payment rail; reusable across AgentScore merchants. If both X-Operator-Token and X-Wallet-Address are sent, this one wins.',\n },\n WalletAddress: {\n type: 'apiKey',\n in: 'header',\n name: 'X-Wallet-Address',\n description:\n 'Wallet-path identity (0x... or base58). Only works on rails that carry a wallet signature (Tempo MPP, x402 EIP-3009, x402 SPL Token). The wallet you claim MUST sign the payment.',\n },\n siwx: siwxSecurityScheme(),\n };\n}\n\n/**\n * Sign-In With X security scheme entry, per the x402scan discovery spec.\n *\n * Reference it on identity-gated (but free) operations as\n * `security: [{ siwx: [] }]`. Do NOT also attach `x-payment-info` to those routes,\n * x402scan will misclassify them as paid.\n */\nexport function siwxSecurityScheme(): Record<string, unknown> {\n return {\n type: 'http',\n scheme: 'bearer',\n bearerFormat: 'SIWX',\n description:\n 'Sign-In With X wallet authentication. Agent signs a challenge with their wallet (any supported chain) and presents the proof in the Authorization header. Used for identity-gated free endpoints; payment-required endpoints declare x-payment-info instead.',\n };\n}\n\n/**\n * Standard AgentScore denial response schemas. Plug into `components.schemas` so OpenAPI\n * validators understand the 403 body shape across denial codes.\n */\nexport function agentscoreDenialSchemas(): Record<string, unknown> {\n return {\n AgentScoreDenialReason: {\n type: 'string',\n enum: [\n 'missing_identity',\n 'identity_verification_required',\n 'token_expired',\n 'invalid_credential',\n 'wallet_signer_mismatch',\n 'wallet_auth_requires_wallet_signing',\n 'wallet_not_trusted',\n 'api_error',\n 'payment_required',\n ],\n description:\n \"Denial code emitted by AgentScore's gate middleware in 403 responses. Every code carries a structured agent_instructions block describing recovery actions (per-code action: missing_identity → probe_identity_then_session, identity_verification_required / token_expired → deliver_verify_url_and_poll, invalid_credential → switch_token_or_restart_session, wallet_signer_mismatch → resign_or_switch_to_operator_token, wallet_auth_requires_wallet_signing → switch_to_operator_token, wallet_not_trusted → contact_support — UNFIXABLE compliance only (sanctions/age/jurisdiction_restricted); fixable reasons re-route to identity_verification_required, payment_required → contact_merchant).\",\n },\n AgentScoreDenialBody: {\n type: 'object',\n properties: {\n error: { $ref: '#/components/schemas/AgentScoreDenialReason' },\n agent_instructions: {\n type: 'string',\n description:\n 'JSON-encoded { action, steps, user_message } block. Always present on every denial; agents parse this to learn how to recover (e.g., poll verify_url, switch headers, re-sign).',\n },\n verify_url: { type: 'string', format: 'uri', description: \"Present for missing_identity / identity_verification_required / token_expired denials. Agent shares this with the user to complete KYC or claim a wallet. Not present on wallet_not_trusted (UNFIXABLE compliance — re-verification won't change the outcome).\" },\n session_id: { type: 'string' },\n poll_url: { type: 'string', format: 'uri' },\n poll_secret: { type: 'string' },\n agent_memory: { type: 'object', description: 'Cross-merchant pattern hint emitted on first-encounter denials.' },\n },\n required: ['error', 'agent_instructions'],\n },\n };\n}\n\n/**\n * Standard 402 PaymentRequired body schema (for AgentScore-extended 402 responses).\n * Includes the rails, identity metadata, agent_instructions, pricing, and x402-compliance\n * fields a typical merchant emits via build402Body.\n */\nexport function agentscorePaymentRequiredSchema(): Record<string, unknown> {\n return {\n AgentScorePaymentRequired: {\n type: 'object',\n properties: {\n payment_required: { type: 'boolean', enum: [true] },\n x402Version: { type: 'integer', enum: [1, 2] },\n accepts: { type: 'array', items: { type: 'object' }, description: 'x402 PaymentRequired.accepts entries.' },\n accepted_methods: {\n type: 'array',\n items: { type: 'object' },\n description: 'MPP method entries (tempo/charge, x402/exact, stripe/charge, ...).',\n },\n amount_usd: { type: 'string' },\n currency: { type: 'string' },\n pricing: {\n type: 'object',\n properties: {\n subtotal: { type: 'string' },\n tax: { type: 'string' },\n tax_rate: { type: 'number' },\n tax_state: { type: 'string' },\n total: { type: 'string' },\n },\n },\n identity_mode: { type: 'string', enum: ['wallet', 'operator_token'] },\n required_signer: { type: 'string' },\n linked_wallets: { type: 'array', items: { type: 'string' } },\n signer_constraint: { type: 'string' },\n agent_instructions: { type: 'object' },\n agent_memory: { type: 'object' },\n },\n },\n };\n}\n\n/**\n * Per-operation `x-payment-info` extension, per the x402scan discovery spec.\n *\n * Every payment-required OpenAPI operation should carry this block alongside a\n * 402 response. Tells discovery crawlers (x402scan, agent CLIs) the static price\n * and which protocols the route accepts. Runtime 402 behavior is authoritative\n * over this static metadata; the static side is for indexability.\n *\n * @example fixed price across x402 + MPP Tempo\n * ```ts\n * Object.assign(operation, {\n * ...xPaymentInfoExtension({\n * price: { mode: 'fixed', currency: 'USD', amount: '0.10' },\n * protocols: [\n * { x402: {} },\n * { mpp: { method: 'tempo/charge', intent: 'pay', currency: 'USD' } },\n * ],\n * }),\n * responses: {\n * '200': {...},\n * '402': { description: 'Payment Required' },\n * },\n * });\n * ```\n */\nexport interface XPaymentInfoFixedPrice {\n mode: 'fixed';\n currency: string;\n amount: string;\n}\n\nexport interface XPaymentInfoDynamicPrice {\n mode: 'dynamic';\n currency: string;\n min: string;\n max: string;\n}\n\nexport type XPaymentInfoPrice = XPaymentInfoFixedPrice | XPaymentInfoDynamicPrice;\n\nexport interface XPaymentInfoX402Protocol {\n x402: Record<string, unknown>;\n}\n\nexport interface XPaymentInfoMppProtocol {\n mpp: { method: string; intent: string; currency: string };\n}\n\nexport type XPaymentInfoProtocol = XPaymentInfoX402Protocol | XPaymentInfoMppProtocol;\n\nexport interface XPaymentInfoInput {\n price: XPaymentInfoPrice;\n protocols: XPaymentInfoProtocol[];\n}\n\nexport function xPaymentInfoExtension(\n input: XPaymentInfoInput,\n): { 'x-payment-info': { price: XPaymentInfoPrice; protocols: XPaymentInfoProtocol[] } } {\n return { 'x-payment-info': { price: input.price, protocols: input.protocols } };\n}\n\n/**\n * `info.x-guidance` extension, per the x402scan discovery spec. Spread into your\n * OpenAPI document's `info` block to give agents a high-level prose description\n * of how to use the API. Discovery crawlers surface this on the listing page.\n *\n * @example\n * ```ts\n * const spec = {\n * openapi: '3.1.0',\n * info: {\n * title: 'My Merchant API',\n * version: '1.0',\n * ...xGuidanceExtension('Wine merchant. POST /purchase with a verified operator token...'),\n * },\n * };\n * ```\n */\nexport function xGuidanceExtension(text: string): { 'x-guidance': string } {\n return { 'x-guidance': text };\n}\n\nexport interface BuildAgentScoreOpenApiSnippetsInput {\n /** Include security schemes in the snippet. Default true. */\n security?: boolean;\n /** Include denial schemas in the snippet. Default true. */\n denials?: boolean;\n /** Include the 402 PaymentRequired schema in the snippet. Default true. */\n paymentRequired?: boolean;\n}\n\n/**\n * Convenience: returns a `components` snippet ready to merge into an OpenAPI document.\n *\n * const spec = {\n * openapi: '3.1.0',\n * info: { title: 'My Merchant API', version: '1.0' },\n * paths: {...},\n * components: { ...agentscoreOpenApiSnippets(), schemas: { ...mySchemas, ...agentscoreOpenApiSnippets().schemas } },\n * };\n *\n * Or more idiomatically: `Object.assign(spec.components, agentscoreOpenApiSnippets())`.\n */\nexport function agentscoreOpenApiSnippets(\n opts: BuildAgentScoreOpenApiSnippetsInput = {},\n): { securitySchemes?: Record<string, unknown>; schemas?: Record<string, unknown> } {\n const out: { securitySchemes?: Record<string, unknown>; schemas?: Record<string, unknown> } = {};\n if (opts.security !== false) {\n out.securitySchemes = agentscoreSecuritySchemes();\n }\n if (opts.denials !== false || opts.paymentRequired !== false) {\n out.schemas = {\n ...(opts.denials !== false ? agentscoreDenialSchemas() : {}),\n ...(opts.paymentRequired !== false ? agentscorePaymentRequiredSchema() : {}),\n };\n }\n return out;\n}\n","/**\n * Default discovery paths emitted by `@agent-score/commerce` builders. These are\n * the public-by-design endpoints agents and crawlers fetch to learn the\n * merchant's shape: OpenAPI, llms.txt, MPP well-known, A2A agent card, UCP profile.\n * They should NOT carry `X-Robots-Tag: noindex` since the whole point is for\n * agents (and search/discovery crawlers) to find them.\n *\n * Everything else on an agent-only API should noindex by default — there's no\n * human-shaped HTML to surface to general search engines, and accidental\n * indexing leaks transactional endpoints into noisy SERPs.\n */\nexport const defaultDiscoveryPaths: ReadonlySet<string> = new Set([\n '/openapi.json',\n '/llms.txt',\n '/skill.md',\n '/SKILL.md',\n '/.well-known/mpp.json',\n '/.well-known/x402',\n '/.well-known/agent-card.json',\n '/.well-known/ucp',\n '/.well-known/jwks.json',\n '/favicon.png',\n '/favicon.ico',\n]);\n\n/**\n * Pure predicate for \"is this path a known discovery surface?\". Compose this\n * into your own framework's middleware when you don't want the bundled Hono\n * wrapper. Custom paths are the union with the defaults — pass `replace: true`\n * to skip the defaults.\n */\nexport function isDiscoveryPath(\n path: string,\n options?: { customPaths?: Iterable<string>; replace?: boolean },\n): boolean {\n if (options?.replace) {\n return new Set(options.customPaths ?? []).has(path);\n }\n if (defaultDiscoveryPaths.has(path)) return true;\n if (options?.customPaths) {\n for (const p of options.customPaths) if (p === path) return true;\n }\n return false;\n}\n\nexport interface NoindexNonDiscoveryOptions {\n /** Additional discovery paths beyond the defaults (e.g. `/sitemap.xml`,\n * `/.well-known/foo`). Merged with the defaults unless `replacePaths: true`. */\n customPaths?: Iterable<string>;\n /** When true, ignore the bundled defaults and only treat `customPaths` as\n * discovery surfaces. Use when the merchant deliberately chooses a different\n * set (e.g. omits `/openapi.json` from a closed API). */\n replacePaths?: boolean;\n /** Override the X-Robots-Tag value applied to non-discovery paths. Defaults to\n * the standard \"noindex, nofollow, noarchive, nosnippet\" tuple — change only\n * if you have a very specific crawl-shape requirement. */\n robotsTag?: string;\n}\n\nconst DEFAULT_ROBOTS_TAG = 'noindex, nofollow, noarchive, nosnippet';\n\n/** Predicate the per-framework wrappers share. Pulled out so non-listed frameworks\n * can compose it directly (`if (!shouldNoindex(path, opts)) ...`). */\nfunction shouldNoindex(path: string, customSet: Set<string> | undefined, replacePaths: boolean | undefined): boolean {\n const isDiscovery = replacePaths\n ? (customSet?.has(path) ?? false)\n : defaultDiscoveryPaths.has(path) || (customSet?.has(path) ?? false);\n return !isDiscovery;\n}\n\n/**\n * Hono middleware. Mount globally near the top of your middleware stack:\n *\n * app.use('*', noindexNonDiscoveryPaths());\n * app.use('*', noindexNonDiscoveryPaths({ customPaths: ['/sitemap.xml'] }));\n *\n * Per-framework variants (`noindexNonDiscoveryPathsExpress`,\n * `noindexNonDiscoveryPathsFastify`, `noindexNonDiscoveryPathsWeb`) ship below.\n * For Next.js Route Handlers, use `applyNoindexHeader(response, path, opts)`\n * inline since route handlers don't have a global mount point.\n */\nexport function noindexNonDiscoveryPaths(options?: NoindexNonDiscoveryOptions) {\n const customSet = options?.customPaths ? new Set(options.customPaths) : undefined;\n const robotsTag = options?.robotsTag ?? DEFAULT_ROBOTS_TAG;\n return async (c: { req: { path: string }; header: (k: string, v: string) => void }, next: () => Promise<void>) => {\n await next();\n if (shouldNoindex(c.req.path, customSet, options?.replacePaths)) {\n c.header('X-Robots-Tag', robotsTag);\n }\n };\n}\n\n/** Express middleware. Sets the header before `next()` so route handlers can\n * override per-response if they need to. */\nexport function noindexNonDiscoveryPathsExpress(options?: NoindexNonDiscoveryOptions) {\n const customSet = options?.customPaths ? new Set(options.customPaths) : undefined;\n const robotsTag = options?.robotsTag ?? DEFAULT_ROBOTS_TAG;\n return (\n req: { path: string },\n res: { setHeader: (name: string, value: string) => void },\n next: () => void,\n ) => {\n if (shouldNoindex(req.path, customSet, options?.replacePaths)) {\n res.setHeader('X-Robots-Tag', robotsTag);\n }\n next();\n };\n}\n\n/** Fastify plugin (use as `app.register(noindexNonDiscoveryPathsFastify, opts)`).\n * Registers an `onRequest` hook so the header lands on every response. */\ninterface FastifyReqLike { url?: string; routerPath?: string }\ninterface FastifyReplyLike { header: (name: string, value: string) => void }\ninterface FastifyAppLike {\n addHook(event: 'onRequest', handler: (req: FastifyReqLike, reply: FastifyReplyLike, done: () => void) => void): void;\n}\nexport function noindexNonDiscoveryPathsFastify(\n app: FastifyAppLike,\n options: NoindexNonDiscoveryOptions | undefined,\n done: () => void,\n): void {\n const customSet = options?.customPaths ? new Set(options.customPaths) : undefined;\n const robotsTag = options?.robotsTag ?? DEFAULT_ROBOTS_TAG;\n app.addHook('onRequest', (req, reply, hookDone) => {\n const path = (req.url ?? req.routerPath ?? '').split('?')[0];\n if (shouldNoindex(path, customSet, options?.replacePaths)) {\n reply.header('X-Robots-Tag', robotsTag);\n }\n hookDone();\n });\n done();\n}\n\n/** Web Fetch / Cloudflare Workers / Deno / Bun helper. Returns a wrapped\n * Response that carries `X-Robots-Tag` on non-discovery paths. Pair with the\n * request's URL pathname:\n *\n * return wrapNoindexResponse(new URL(req.url).pathname, response);\n */\nexport function wrapNoindexResponse(\n path: string,\n response: Response,\n options?: NoindexNonDiscoveryOptions,\n): Response {\n const customSet = options?.customPaths ? new Set(options.customPaths) : undefined;\n const robotsTag = options?.robotsTag ?? DEFAULT_ROBOTS_TAG;\n if (!shouldNoindex(path, customSet, options?.replacePaths)) return response;\n const headers = new Headers(response.headers);\n headers.set('X-Robots-Tag', robotsTag);\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\n/** Next.js Route Handler helper. Call inline before returning the Response:\n *\n * export async function POST(req: Request) {\n * const path = new URL(req.url).pathname;\n * const res = Response.json({...});\n * return applyNoindexHeader(res, path);\n * }\n *\n * Same wrapper shape as the Web Fetch helper — exported separately for clarity\n * in Next.js docs/examples. */\nexport const applyNoindexHeader = wrapNoindexResponse;\n","import type { HowToPayBlock } from './how_to_pay';\n\n/** Map of rail key (e.g. 'x402_base', 'tempo_mpp', 'stripe') → list of client identifiers\n * that have been smoke-verified by the merchant against the protocol shape they emit.\n * Strings are display labels, not install commands — agents already get install commands\n * via `how_to_pay.<rail>.setup`. Use these as a \"what's known to work\" hint. */\nexport type CompatibleClients = Record<string, string[]>;\n\nexport interface BuildAgentInstructionsInput {\n /** Per-rail commands. Build with `buildHowToPay`. */\n howToPay: HowToPayBlock;\n /** Tool recommendations as human-readable strings. Defaults to a sensible set covering tempo + agentscore-pay. */\n recommendedTools?: string[];\n /** Wallet-stack compatibility note for the agent. Default: rail-neutral, no specific wallet stack required. */\n walletCompatibility?: string;\n /** How long the merchant will wait for payment after the 402. Default 300 (5 minutes). */\n timeoutSeconds?: number;\n /** Warnings about common footguns. Defaults include tempo wallet transfer + raw on-chain x402 deposits. */\n warnings?: string[];\n /** Additional warnings appended to the default protocol-footgun set. Use this when you want\n * to keep the SDK's protocol warnings AND add merchant-specific notes (e.g., a per-order\n * rail-availability message). Ignored when `warnings` is set explicitly. */\n extraWarnings?: string[];\n /** Recommended rail (e.g., 'tempo', 'x402_base'). Surfaced for agents to default to. */\n recommended?: string;\n /** Per-rail list of client names the merchant has verified work end-to-end. Vendors set\n * this from their own smoke matrix — defaults to none (avoids vouching for clients the\n * merchant has not tested). When omitted, the field is not emitted. */\n compatibleClients?: CompatibleClients;\n /** Arbitrary additional fields the vendor wants merged into the agent_instructions object. */\n extra?: Record<string, unknown>;\n}\n\nexport interface AgentInstructions {\n how_to_pay: HowToPayBlock;\n recommended_tools: string[];\n wallet_compatibility: string;\n timeout_seconds: number;\n warnings: string[];\n recommended?: string;\n compatible_clients?: CompatibleClients;\n [key: string]: unknown;\n}\n\nconst TEMPO_WARNING =\n 'Do NOT use `tempo wallet transfer`. That moves USDC on-chain without completing the protocol handshake, so the order will not complete. Use `tempo request` instead.';\n\nconst X402_WARNING =\n 'Do NOT send USDC manually to the deposit addresses. Use `agentscore-pay pay` so the credential is signed and submitted; otherwise the order will not complete even though the deposit lands.';\n\nconst TEMPO_TOOL = '`tempo request` for Tempo USDC';\nconst AGENTSCORE_PAY_TOOL = '`agentscore-pay` — Base + Solana + Tempo from one CLI';\n\nconst DEFAULT_WALLET_COMPATIBILITY =\n 'Any client that can produce a valid MPP credential (Authorization: Payment) or x402 X-Payment header. Use the CLI commands above; sign-it-yourself is also fine.';\n\nfunction defaultRecommendedTools(howToPay: HowToPayBlock): string[] {\n const tools: string[] = [];\n if (howToPay.tempo) tools.push(TEMPO_TOOL);\n if (howToPay.tempo || howToPay.x402_base || howToPay.solana_mpp) tools.push(AGENTSCORE_PAY_TOOL);\n return tools;\n}\n\nfunction defaultWarnings(howToPay: HowToPayBlock): string[] {\n const w: string[] = [];\n if (howToPay.tempo) w.push(TEMPO_WARNING);\n if (howToPay.x402_base) w.push(X402_WARNING);\n return w;\n}\n\n/**\n * Default `compatible_clients` derived from the rails declared in `howToPay`. Lists\n * clients the AgentScore team has smoke-verified end-to-end against an `@agent-score/commerce`\n * merchant; entries appear only for rails the vendor actually offers. Vendors override\n * this in `buildAgentInstructions({compatibleClients: {...}})` to add their own tested\n * clients or remove entries that don't fit their endpoint.\n *\n * Verified state as of the SDK release. The same data is also published as a docs page\n * for humans (rationale, per-rail commands, why some clients don't fully work, last\n * verified date) — this default keeps the merchant-side surface in sync.\n */\n/** Symbolic rail keys agent-facing surfaces use to talk about a rail without spelling out\n * network/scheme details. Same keys as `CompatibleClients` map keys. */\nexport type RailKey = 'tempo_mpp' | 'x402_base' | 'solana_mpp' | 'stripe';\n\nconst RAIL_CLIENTS: Record<RailKey, readonly string[]> = {\n tempo_mpp: ['agentscore-pay', 'tempo request', 'x402-proxy'],\n x402_base: ['agentscore-pay', 'x402-proxy', 'purl (omit --network flag)'],\n solana_mpp: ['agentscore-pay'],\n stripe: ['link-cli'],\n};\n\n/** Returns the smoke-verified client list for a set of rail keys. The single source of\n * truth for \"which CLIs we've verified end-to-end on each rail\" — consumed both by the\n * 402-body builder (`defaultCompatibleClients`) and by discovery surfaces (skill.md,\n * llms.txt, etc.). Update here, every surface inherits. */\nexport function compatibleClientsByRails(rails: readonly RailKey[]): CompatibleClients | undefined {\n const out: CompatibleClients = {};\n for (const r of rails) out[r] = [...RAIL_CLIENTS[r]];\n return Object.keys(out).length === 0 ? undefined : out;\n}\n\nfunction defaultCompatibleClients(howToPay: HowToPayBlock): CompatibleClients | undefined {\n const rails: RailKey[] = [];\n if (howToPay.tempo) rails.push('tempo_mpp');\n if (howToPay.x402_base) rails.push('x402_base');\n if (howToPay.solana_mpp) rails.push('solana_mpp');\n if (howToPay.stripe) rails.push('stripe');\n return compatibleClientsByRails(rails);\n}\n\n/**\n * Build the agent_instructions object for the 402 body. Combines how_to_pay with\n * recommended tools, warnings, wallet-compatibility note, and timeout.\n *\n * Defaults adapt to the rails declared in `howToPay`: only tempo-relevant warnings/tools\n * appear if `howToPay.tempo` is set, only x402-relevant ones if `x402_base` is set.\n * Stripe-only merchants get neither rail-specific warning. Vendors override\n * `warnings`/`recommendedTools` for full control.\n */\nexport function buildAgentInstructions(input: BuildAgentInstructionsInput): AgentInstructions {\n const compatibleClients = input.compatibleClients ?? defaultCompatibleClients(input.howToPay);\n return {\n how_to_pay: input.howToPay,\n recommended_tools: input.recommendedTools ?? defaultRecommendedTools(input.howToPay),\n wallet_compatibility: input.walletCompatibility ?? DEFAULT_WALLET_COMPATIBILITY,\n timeout_seconds: input.timeoutSeconds ?? 300,\n warnings: input.warnings ?? [...defaultWarnings(input.howToPay), ...(input.extraWarnings ?? [])],\n ...(input.recommended ? { recommended: input.recommended } : {}),\n ...(compatibleClients ? { compatible_clients: compatibleClients } : {}),\n ...(input.extra ?? {}),\n };\n}\n","import { compatibleClientsByRails } from '../challenge/agent_instructions';\nimport type { CompatibleClients, RailKey } from '../challenge/agent_instructions';\n\nexport type { CompatibleClients, RailKey } from '../challenge/agent_instructions';\nexport { compatibleClientsByRails } from '../challenge/agent_instructions';\n\nexport interface SkillMdEndpoint {\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n path: string;\n authRequired: boolean;\n description: string;\n}\n\nexport interface SkillMdIdentityRequirements {\n /** Whether KYC is required for gated routes. */\n kycRequired?: boolean;\n /** Minimum age (e.g. 21 for alcohol). */\n minAge?: number;\n /** Allowed-jurisdictions list (ISO 3166-1 alpha-2 country codes). */\n allowedJurisdictions?: string[];\n /** Whether sanctions screening is enforced. */\n sanctionsClear?: boolean;\n}\n\nexport interface SkillMdShippingPolicy {\n /** Allowed shipping countries (ISO 3166-1 alpha-2). */\n allowedCountries?: string[];\n /** Blocked US states (2-letter codes). */\n blockedStates?: string[];\n}\n\nexport interface SkillMdLink {\n label: string;\n url: string;\n}\n\nexport interface BuildSkillMdInput {\n /** Skill manifest identifier — kebab-case per agentskills.io spec: 1-64 chars, lowercase\n * alphanumeric + hyphens, no leading/trailing/consecutive hyphens. Validated at build\n * time; invalid names throw. e.g. 'example-merchant-commerce'. */\n name: string;\n /** Skill description — agentskills.io spec: 1-1024 chars, non-empty. Should describe both\n * what the skill does AND when to use it; imperative phrasing recommended (\"Use when…\").\n * Validated at build time; over-length throws. */\n description: string;\n /** Merchant homepage (or domain root). Emitted as `metadata.homepage` per spec\n * (top-level non-spec fields go under metadata). */\n homepage: string;\n /** Skill schema version — increment when the skill body materially changes. Emitted as\n * a quoted string under `metadata.version` per agentskills.io spec (metadata values\n * must be strings). Accepts string or number; numbers are converted. Default \"1\". */\n version?: string | number;\n\n /** Optional license name or path to a bundled license file. Emitted as top-level\n * frontmatter `license:` per spec. */\n license?: string;\n /** Optional environment-requirements note (max 500 chars). e.g. \"Requires Node 20+\".\n * Emitted as top-level frontmatter `compatibility:` per spec. */\n compatibility?: string;\n /** Optional space-separated string of pre-approved tools (experimental per spec). */\n allowedTools?: string;\n /** Additional caller-defined metadata entries — flat key/value strings nested under\n * `metadata:`. Spec requires string values. */\n metadata?: Record<string, string | number>;\n\n /** Human display name (e.g. \"Example Merchant\"). */\n merchantName: string;\n /** Optional one-line tagline appearing under the title. */\n tagline?: string;\n /** Optional short prose intro describing what the merchant offers. Renders below the title. */\n intro?: string;\n\n /** Files / well-known URLs surfaced under the \"Important Files\" table. The skill.md URL\n * itself is added automatically — list other discovery surfaces (llms.txt, mpp.json,\n * openapi.json, agent-card.json). */\n files?: SkillMdLink[];\n\n /** Rails the merchant accepts. Drives the Payment + Compatible Clients sections. Order\n * is preserved in render. Default to the rails actually declared on the merchant's\n * `respond402` config — keep these in sync. */\n acceptedRails: RailKey[];\n /** Override the per-rail compatible-clients matrix. When omitted, derives from\n * `acceptedRails` via the SDK's smoke-verified default. Override keys not in\n * `acceptedRails` are dropped (the rail isn't accepted, so the row isn't rendered). */\n compatibleClients?: CompatibleClients;\n\n /** Identity requirements as agent-observable outcomes (kyc / age / jurisdiction /\n * sanctions). Internal posture (`failOpen`, mount strategy, KYC vendor) is intentionally\n * not part of this shape — agents act on outcomes, not implementation. */\n identity?: SkillMdIdentityRequirements;\n /** URL to the identity-bootstrap skill. Linked from the Identity Prerequisite section\n * so an agent without a Passport can follow the bootstrap before attempting purchase. */\n identityBootstrapUrl?: string;\n\n /** Shipping policy, for physical-goods merchants. Omit for digital merchants. */\n shipping?: SkillMdShippingPolicy;\n\n /** Agent-facing endpoints — path, method, whether auth is required, brief purpose. */\n endpoints: SkillMdEndpoint[];\n\n /** When this skill should fire (skill loader uses for trigger matching). */\n triggers: string[];\n\n /** Optional numbered onboarding steps. Each entry renders as a numbered list item;\n * may include shell snippets in markdown code fences. */\n onboardingSteps?: string[];\n\n /** Support / homepage / docs links rendered in the \"Support\" section. */\n supportLinks?: SkillMdLink[];\n\n /** When true (default), append a footer noting clients can refresh skill.md to pick\n * up new endpoints. Set to false to suppress. */\n refreshFooter?: boolean;\n}\n\nconst RAIL_LABELS: Record<RailKey, string> = {\n tempo_mpp: 'MPP on Tempo',\n x402_base: 'x402 on Base',\n solana_mpp: 'MPP on Solana',\n stripe: 'Stripe Shared Payment Token',\n};\n\nconst RAIL_NOTES: Record<RailKey, string> = {\n tempo_mpp: 'USDC. Use `agentscore-pay pay --chain tempo` (or `tempo request`); MPP credential goes in `Authorization: Payment`.',\n x402_base: 'USDC (EIP-3009). Use `agentscore-pay pay --chain base`; X-Payment header carries the signed credential.',\n solana_mpp: 'USDC (SPL). Use `agentscore-pay pay --chain solana`; MPP credential goes in `Authorization: Payment`.',\n stripe: 'Card via Link wallet. Use `@stripe/link-cli` — `agentscore-pay` emits the handoff hint when this rail is picked.',\n};\n\nconst NAME_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;\nconst NAME_MAX = 64;\nconst DESCRIPTION_MAX = 1024;\nconst COMPATIBILITY_MAX = 500;\n\nfunction validateInput(input: BuildSkillMdInput): void {\n if (!input.name || input.name.length === 0 || input.name.length > NAME_MAX) {\n throw new Error(`buildSkillMd: name must be 1-${NAME_MAX} characters (got ${input.name?.length ?? 0})`);\n }\n if (!NAME_RE.test(input.name)) {\n throw new Error(\n `buildSkillMd: name \"${input.name}\" is invalid — must be lowercase alphanumeric and hyphens, no leading/trailing/consecutive hyphens (agentskills.io spec)`,\n );\n }\n if (!input.description || input.description.length === 0) {\n throw new Error('buildSkillMd: description is required and must be non-empty (agentskills.io spec)');\n }\n if (input.description.length > DESCRIPTION_MAX) {\n throw new Error(\n `buildSkillMd: description must be ≤${DESCRIPTION_MAX} characters (got ${input.description.length})`,\n );\n }\n if (input.compatibility && input.compatibility.length > COMPATIBILITY_MAX) {\n throw new Error(\n `buildSkillMd: compatibility must be ≤${COMPATIBILITY_MAX} characters (got ${input.compatibility.length})`,\n );\n }\n}\n\n/** Quote a value as a YAML double-quoted scalar — escape `\\\\`, `\"`, and newlines. The\n * agentskills.io spec calls out unquoted colons in `description` as the most common\n * parse failure across clients; emit every user-supplied scalar quoted to be safe. */\nfunction quoteYaml(value: string): string {\n return `\"${value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/\\n/g, '\\\\n')}\"`;\n}\n\n/** Sanitize a string for inclusion in a markdown table cell — escape backslashes first\n * (so existing `\\` aren't treated as escapes), then escape pipes (which would otherwise\n * terminate the cell). */\nfunction tableCell(value: string): string {\n return value.replace(/\\\\/g, '\\\\\\\\').replace(/\\|/g, '\\\\|');\n}\n\nfunction frontmatter(input: BuildSkillMdInput): string {\n const lines: string[] = ['---'];\n lines.push(`name: ${input.name}`);\n lines.push(`description: ${quoteYaml(input.description)}`);\n if (input.license) lines.push(`license: ${quoteYaml(input.license)}`);\n if (input.compatibility) lines.push(`compatibility: ${quoteYaml(input.compatibility)}`);\n if (input.allowedTools) lines.push(`allowed-tools: ${quoteYaml(input.allowedTools)}`);\n\n const meta: Array<[string, string]> = [];\n meta.push(['version', String(input.version ?? '1')]);\n meta.push(['homepage', input.homepage]);\n for (const [k, v] of Object.entries(input.metadata ?? {})) {\n if (k === 'version' || k === 'homepage') continue;\n meta.push([k, String(v)]);\n }\n lines.push('metadata:');\n for (const [k, v] of meta) {\n lines.push(` ${k}: ${quoteYaml(v)}`);\n }\n lines.push('---');\n return lines.join('\\n');\n}\n\nfunction importantFiles(input: BuildSkillMdInput): string {\n const skillUrl = `${input.homepage.replace(/\\/$/, '')}/skill.md`;\n const rows: string[] = [\n '| File | URL |',\n '|------|-----|',\n `| **SKILL.md** (this file) | \\`${skillUrl}\\` |`,\n ];\n for (const f of input.files ?? []) {\n rows.push(`| ${tableCell(f.label)} | \\`${tableCell(f.url)}\\` |`);\n }\n return ['## Important Files', '', ...rows].join('\\n');\n}\n\nfunction paymentSection(input: BuildSkillMdInput): string {\n const override = input.compatibleClients;\n const defaults = compatibleClientsByRails(input.acceptedRails) ?? {};\n // Override entries only apply to rails actually accepted; ignore stragglers.\n const clients: CompatibleClients = {};\n for (const r of input.acceptedRails) {\n clients[r] = override?.[r] ?? defaults[r] ?? [];\n }\n const rows: string[] = ['| Rail | Notes | Compatible clients |', '|---|---|---|'];\n for (const r of input.acceptedRails) {\n const list = (clients[r] ?? []).join(', ') || '—';\n rows.push(`| **${RAIL_LABELS[r]}** | ${RAIL_NOTES[r]} | ${list} |`);\n }\n return [\n '## Payment',\n '',\n 'Each gated route returns a 402 with `WWW-Authenticate` + `PAYMENT-REQUIRED` body listing the rails below with current pricing. Pick whichever your wallet is funded for.',\n '',\n ...rows,\n ].join('\\n');\n}\n\nfunction identitySection(input: BuildSkillMdInput): string {\n const id = input.identity;\n if (!id) return '';\n const reqs: string[] = [];\n if (id.kycRequired) reqs.push('KYC verified Passport');\n if (id.minAge) reqs.push(`age ${id.minAge}+`);\n if (id.allowedJurisdictions?.length) reqs.push(`${id.allowedJurisdictions.join('/')} only`);\n if (id.sanctionsClear) reqs.push('sanctions clear');\n if (reqs.length === 0) return '';\n const bootstrap = input.identityBootstrapUrl\n ? `\\n\\nIf you don't have a Passport, fetch \\`${input.identityBootstrapUrl}\\` and follow the onboarding there first. Bring back the \\`opc_...\\` operator token in \\`X-Operator-Token\\` on every gated request.`\n : '';\n return [\n '## Identity Prerequisite',\n '',\n `This merchant uses AgentScore identity. Required: ${reqs.join(', ')}.${bootstrap}`,\n '',\n 'Denial bodies carry an `agent_instructions` block describing the recovery action — read the `action` field and follow it. See the identity-bootstrap skill for the canonical denial-code → action table.',\n ].join('\\n');\n}\n\nfunction shippingSection(input: BuildSkillMdInput): string {\n const s = input.shipping;\n if (!s || (!s.allowedCountries?.length && !s.blockedStates?.length)) return '';\n const lines: string[] = ['## Shipping', ''];\n if (s.allowedCountries?.length) {\n lines.push(`Ships to: ${s.allowedCountries.join(', ')}.`);\n }\n if (s.blockedStates?.length) {\n if (lines.length > 2) lines.push('');\n lines.push(`Blocked US states: ${s.blockedStates.join(', ')}.`);\n }\n return lines.join('\\n');\n}\n\nfunction endpointsSection(input: BuildSkillMdInput): string {\n if (input.endpoints.length === 0) return '';\n const rows = ['| Method | Path | Auth | Purpose |', '|---|---|---|---|'];\n for (const e of input.endpoints) {\n rows.push(\n `| ${e.method} | \\`${tableCell(e.path)}\\` | ${e.authRequired ? 'identity required' : 'anonymous'} | ${tableCell(e.description)} |`,\n );\n }\n return ['## Endpoints', '', ...rows].join('\\n');\n}\n\nfunction onboardingSection(input: BuildSkillMdInput): string {\n if (!input.onboardingSteps?.length) return '';\n const rows = input.onboardingSteps.map((step, i) => `${i + 1}. ${step}`);\n return ['## Onboarding Flow', '', ...rows].join('\\n');\n}\n\nfunction triggersSection(input: BuildSkillMdInput): string {\n if (input.triggers.length === 0) return '';\n const rows = input.triggers.map((t) => `- ${t}`);\n return ['## Triggers', '', 'Use this skill when the user wants to:', '', ...rows].join('\\n');\n}\n\nfunction supportSection(input: BuildSkillMdInput): string {\n if (!input.supportLinks?.length) return '';\n const rows = input.supportLinks.map((l) => `- **${l.label}**: ${l.url}`);\n return ['## Support', '', ...rows].join('\\n');\n}\n\nfunction refreshFooter(input: BuildSkillMdInput): string {\n if (input.refreshFooter === false) return '';\n return '_Re-fetch this file periodically to pick up new endpoints, rails, or policies._';\n}\n\nfunction titleBlock(input: BuildSkillMdInput): string {\n const parts: string[] = [`# ${input.merchantName}`];\n if (input.tagline) parts.push(`_${input.tagline}_`);\n if (input.intro) parts.push(input.intro);\n return parts.join('\\n\\n');\n}\n\n/**\n * Render an agentskills.io-compatible `skill.md` for an agent-commerce merchant.\n *\n * Output is YAML frontmatter (`name` / `description` / optional `license` /\n * `compatibility` / `allowed-tools` / `metadata`) followed by markdown sections\n * describing payment rails, identity requirements, endpoints, triggers, and support\n * links — strictly the agent-facing contract, with no internal posture (no `failOpen`,\n * no mount-strategy names, no KYC vendor, no defense parameters).\n *\n * Spec compliance:\n * - `name` validated against the agentskills.io regex (lowercase alphanumeric + hyphens,\n * no leading/trailing/consecutive hyphens, ≤64 chars).\n * - `description` length capped at 1024.\n * - `metadata` values always emitted as quoted strings.\n * - `description` (and other user scalars) double-quoted to defuse the colon /\n * newline / quote pitfall the spec explicitly warns about.\n *\n * The compatible-clients-per-rail table sources from the same SDK constant\n * (`compatibleClientsByRails`) that drives the live 402 body's `compatible_clients`\n * field, so updating a smoke-verified client in one place propagates to every surface.\n */\nexport function buildSkillMd(input: BuildSkillMdInput): string {\n validateInput(input);\n const sections = [\n frontmatter(input),\n titleBlock(input),\n importantFiles(input),\n identitySection(input),\n paymentSection(input),\n shippingSection(input),\n onboardingSection(input),\n endpointsSection(input),\n triggersSection(input),\n supportSection(input),\n refreshFooter(input),\n ].filter((s) => s !== '');\n return sections.join('\\n\\n').replace(/\\n{3,}/g, '\\n\\n').trim() + '\\n';\n}\n"],"mappings":";AAIO,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AI,CAAC,MAAM,cAAc,OAAQ,QAAO;AACxC,QAAM,OAAO,MAAM,aAAa,IAAI,CAAC,MAAM,OAAO,EAAE,KAAK,OAAO,EAAE,GAAG,EAAE;AACvE,SAAO,CAAC,cAAc,IAAI,GAAG,IAAI,EAAE,KAAK,IAAI;AAC9C;AAEA,SAAS,cAAc,OAAkC;AACvD,MAAI,MAAM,kBAAkB,MAAO,QAAO;AAC1C,SAAO;AACT;AAEA,SAAS,WAAW,OAAkC;AACpD,QAAM,QAAkB,CAAC,KAAK,MAAM,YAAY,EAAE;AAClD,MAAI,MAAM,QAAS,OAAM,KAAK,IAAI,MAAM,OAAO,GAAG;AAClD,MAAI,MAAM,MAAO,OAAM,KAAK,MAAM,KAAK;AACvC,SAAO,MAAM,KAAK,MAAM;AAC1B;AAuBO,SAAS,aAAa,OAAkC;AAC7D,gBAAc,KAAK;AACnB,QAAM,WAAW;AAAA,IACf,YAAY,KAAK;AAAA,IACjB,WAAW,KAAK;AAAA,IAChB,eAAe,KAAK;AAAA,IACpB,gBAAgB,KAAK;AAAA,IACrB,eAAe,KAAK;AAAA,IACpB,gBAAgB,KAAK;AAAA,IACrB,kBAAkB,KAAK;AAAA,IACvB,iBAAiB,KAAK;AAAA,IACtB,gBAAgB,KAAK;AAAA,IACrB,eAAe,KAAK;AAAA,IACpB,cAAc,KAAK;AAAA,EACrB,EAAE,OAAO,CAAC,MAAM,MAAM,EAAE;AACxB,SAAO,SAAS,KAAK,MAAM,EAAE,QAAQ,WAAW,MAAM,EAAE,KAAK,IAAI;AACnE;","names":["rails","rails"]}
@@ -365,7 +365,7 @@ function createAgentScoreCore(options) {
365
365
  } = options;
366
366
  const baseUrl = stripTrailingSlashes(rawBaseUrl);
367
367
  const agentMemoryHint = buildAgentMemoryHint();
368
- const defaultUa = `@agent-score/commerce@${"1.3.2"}`;
368
+ const defaultUa = `@agent-score/commerce@${"1.5.0"}`;
369
369
  const userAgentHeader = userAgent ? `${userAgent} (${defaultUa})` : defaultUa;
370
370
  const sdk = new import_sdk.AgentScore({ apiKey, baseUrl, userAgent: userAgentHeader });
371
371
  const sessionSdkCache = /* @__PURE__ */ new Map();
@@ -332,7 +332,7 @@ function createAgentScoreCore(options) {
332
332
  } = options;
333
333
  const baseUrl = stripTrailingSlashes(rawBaseUrl);
334
334
  const agentMemoryHint = buildAgentMemoryHint();
335
- const defaultUa = `@agent-score/commerce@${"1.3.2"}`;
335
+ const defaultUa = `@agent-score/commerce@${"1.5.0"}`;
336
336
  const userAgentHeader = userAgent ? `${userAgent} (${defaultUa})` : defaultUa;
337
337
  const sdk = new AgentScore({ apiKey, baseUrl, userAgent: userAgentHeader });
338
338
  const sessionSdkCache = /* @__PURE__ */ new Map();
@@ -366,7 +366,7 @@ function createAgentScoreCore(options) {
366
366
  } = options;
367
367
  const baseUrl = stripTrailingSlashes(rawBaseUrl);
368
368
  const agentMemoryHint = buildAgentMemoryHint();
369
- const defaultUa = `@agent-score/commerce@${"1.3.2"}`;
369
+ const defaultUa = `@agent-score/commerce@${"1.5.0"}`;
370
370
  const userAgentHeader = userAgent ? `${userAgent} (${defaultUa})` : defaultUa;
371
371
  const sdk = new import_sdk.AgentScore({ apiKey, baseUrl, userAgent: userAgentHeader });
372
372
  const sessionSdkCache = /* @__PURE__ */ new Map();
@@ -332,7 +332,7 @@ function createAgentScoreCore(options) {
332
332
  } = options;
333
333
  const baseUrl = stripTrailingSlashes(rawBaseUrl);
334
334
  const agentMemoryHint = buildAgentMemoryHint();
335
- const defaultUa = `@agent-score/commerce@${"1.3.2"}`;
335
+ const defaultUa = `@agent-score/commerce@${"1.5.0"}`;
336
336
  const userAgentHeader = userAgent ? `${userAgent} (${defaultUa})` : defaultUa;
337
337
  const sdk = new AgentScore({ apiKey, baseUrl, userAgent: userAgentHeader });
338
338
  const sessionSdkCache = /* @__PURE__ */ new Map();
@@ -365,7 +365,7 @@ function createAgentScoreCore(options) {
365
365
  } = options;
366
366
  const baseUrl = stripTrailingSlashes(rawBaseUrl);
367
367
  const agentMemoryHint = buildAgentMemoryHint();
368
- const defaultUa = `@agent-score/commerce@${"1.3.2"}`;
368
+ const defaultUa = `@agent-score/commerce@${"1.5.0"}`;
369
369
  const userAgentHeader = userAgent ? `${userAgent} (${defaultUa})` : defaultUa;
370
370
  const sdk = new import_sdk.AgentScore({ apiKey, baseUrl, userAgent: userAgentHeader });
371
371
  const sessionSdkCache = /* @__PURE__ */ new Map();
@@ -332,7 +332,7 @@ function createAgentScoreCore(options) {
332
332
  } = options;
333
333
  const baseUrl = stripTrailingSlashes(rawBaseUrl);
334
334
  const agentMemoryHint = buildAgentMemoryHint();
335
- const defaultUa = `@agent-score/commerce@${"1.3.2"}`;
335
+ const defaultUa = `@agent-score/commerce@${"1.5.0"}`;
336
336
  const userAgentHeader = userAgent ? `${userAgent} (${defaultUa})` : defaultUa;
337
337
  const sdk = new AgentScore({ apiKey, baseUrl, userAgent: userAgentHeader });
338
338
  const sessionSdkCache = /* @__PURE__ */ new Map();
@@ -361,7 +361,7 @@ function createAgentScoreCore(options) {
361
361
  } = options;
362
362
  const baseUrl = stripTrailingSlashes(rawBaseUrl);
363
363
  const agentMemoryHint = buildAgentMemoryHint();
364
- const defaultUa = `@agent-score/commerce@${"1.3.2"}`;
364
+ const defaultUa = `@agent-score/commerce@${"1.5.0"}`;
365
365
  const userAgentHeader = userAgent ? `${userAgent} (${defaultUa})` : defaultUa;
366
366
  const sdk = new import_sdk.AgentScore({ apiKey, baseUrl, userAgent: userAgentHeader });
367
367
  const sessionSdkCache = /* @__PURE__ */ new Map();
@@ -332,7 +332,7 @@ function createAgentScoreCore(options) {
332
332
  } = options;
333
333
  const baseUrl = stripTrailingSlashes(rawBaseUrl);
334
334
  const agentMemoryHint = buildAgentMemoryHint();
335
- const defaultUa = `@agent-score/commerce@${"1.3.2"}`;
335
+ const defaultUa = `@agent-score/commerce@${"1.5.0"}`;
336
336
  const userAgentHeader = userAgent ? `${userAgent} (${defaultUa})` : defaultUa;
337
337
  const sdk = new AgentScore({ apiKey, baseUrl, userAgent: userAgentHeader });
338
338
  const sessionSdkCache = /* @__PURE__ */ new Map();
@@ -361,7 +361,7 @@ function createAgentScoreCore(options) {
361
361
  } = options;
362
362
  const baseUrl = stripTrailingSlashes(rawBaseUrl);
363
363
  const agentMemoryHint = buildAgentMemoryHint();
364
- const defaultUa = `@agent-score/commerce@${"1.3.2"}`;
364
+ const defaultUa = `@agent-score/commerce@${"1.5.0"}`;
365
365
  const userAgentHeader = userAgent ? `${userAgent} (${defaultUa})` : defaultUa;
366
366
  const sdk = new import_sdk.AgentScore({ apiKey, baseUrl, userAgent: userAgentHeader });
367
367
  const sessionSdkCache = /* @__PURE__ */ new Map();
@@ -332,7 +332,7 @@ function createAgentScoreCore(options) {
332
332
  } = options;
333
333
  const baseUrl = stripTrailingSlashes(rawBaseUrl);
334
334
  const agentMemoryHint = buildAgentMemoryHint();
335
- const defaultUa = `@agent-score/commerce@${"1.3.2"}`;
335
+ const defaultUa = `@agent-score/commerce@${"1.5.0"}`;
336
336
  const userAgentHeader = userAgent ? `${userAgent} (${defaultUa})` : defaultUa;
337
337
  const sdk = new AgentScore({ apiKey, baseUrl, userAgent: userAgentHeader });
338
338
  const sessionSdkCache = /* @__PURE__ */ new Map();