@agent-score/commerce 1.0.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.
Files changed (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +306 -0
  3. package/dist/_response-DmziuJz6.d.mts +137 -0
  4. package/dist/_response-rbK0zM7y.d.ts +137 -0
  5. package/dist/api/index.d.mts +1 -0
  6. package/dist/api/index.d.ts +1 -0
  7. package/dist/api/index.js +37 -0
  8. package/dist/api/index.js.map +1 -0
  9. package/dist/api/index.mjs +14 -0
  10. package/dist/api/index.mjs.map +1 -0
  11. package/dist/challenge/index.d.mts +523 -0
  12. package/dist/challenge/index.d.ts +523 -0
  13. package/dist/challenge/index.js +354 -0
  14. package/dist/challenge/index.js.map +1 -0
  15. package/dist/challenge/index.mjs +318 -0
  16. package/dist/challenge/index.mjs.map +1 -0
  17. package/dist/core.d.mts +252 -0
  18. package/dist/core.d.ts +252 -0
  19. package/dist/core.js +500 -0
  20. package/dist/core.js.map +1 -0
  21. package/dist/core.mjs +472 -0
  22. package/dist/core.mjs.map +1 -0
  23. package/dist/discovery/index.d.mts +382 -0
  24. package/dist/discovery/index.d.ts +382 -0
  25. package/dist/discovery/index.js +675 -0
  26. package/dist/discovery/index.js.map +1 -0
  27. package/dist/discovery/index.mjs +630 -0
  28. package/dist/discovery/index.mjs.map +1 -0
  29. package/dist/identity/express.d.mts +44 -0
  30. package/dist/identity/express.d.ts +44 -0
  31. package/dist/identity/express.js +777 -0
  32. package/dist/identity/express.js.map +1 -0
  33. package/dist/identity/express.mjs +738 -0
  34. package/dist/identity/express.mjs.map +1 -0
  35. package/dist/identity/fastify.d.mts +63 -0
  36. package/dist/identity/fastify.d.ts +63 -0
  37. package/dist/identity/fastify.js +780 -0
  38. package/dist/identity/fastify.js.map +1 -0
  39. package/dist/identity/fastify.mjs +741 -0
  40. package/dist/identity/fastify.mjs.map +1 -0
  41. package/dist/identity/hono.d.mts +83 -0
  42. package/dist/identity/hono.d.ts +83 -0
  43. package/dist/identity/hono.js +779 -0
  44. package/dist/identity/hono.js.map +1 -0
  45. package/dist/identity/hono.mjs +740 -0
  46. package/dist/identity/hono.mjs.map +1 -0
  47. package/dist/identity/nextjs.d.mts +62 -0
  48. package/dist/identity/nextjs.d.ts +62 -0
  49. package/dist/identity/nextjs.js +784 -0
  50. package/dist/identity/nextjs.js.map +1 -0
  51. package/dist/identity/nextjs.mjs +747 -0
  52. package/dist/identity/nextjs.mjs.map +1 -0
  53. package/dist/identity/policy.d.mts +115 -0
  54. package/dist/identity/policy.d.ts +115 -0
  55. package/dist/identity/policy.js +81 -0
  56. package/dist/identity/policy.js.map +1 -0
  57. package/dist/identity/policy.mjs +53 -0
  58. package/dist/identity/policy.mjs.map +1 -0
  59. package/dist/identity/web.d.mts +82 -0
  60. package/dist/identity/web.d.ts +82 -0
  61. package/dist/identity/web.js +775 -0
  62. package/dist/identity/web.js.map +1 -0
  63. package/dist/identity/web.mjs +738 -0
  64. package/dist/identity/web.mjs.map +1 -0
  65. package/dist/index.d.mts +252 -0
  66. package/dist/index.d.ts +252 -0
  67. package/dist/index.js +432 -0
  68. package/dist/index.js.map +1 -0
  69. package/dist/index.mjs +388 -0
  70. package/dist/index.mjs.map +1 -0
  71. package/dist/payment/index.d.mts +716 -0
  72. package/dist/payment/index.d.ts +716 -0
  73. package/dist/payment/index.js +691 -0
  74. package/dist/payment/index.js.map +1 -0
  75. package/dist/payment/index.mjs +639 -0
  76. package/dist/payment/index.mjs.map +1 -0
  77. package/dist/signer-Cvdwn6Cs.d.mts +48 -0
  78. package/dist/signer-Cvdwn6Cs.d.ts +48 -0
  79. package/dist/stripe-multichain/index.d.mts +221 -0
  80. package/dist/stripe-multichain/index.d.ts +221 -0
  81. package/dist/stripe-multichain/index.js +243 -0
  82. package/dist/stripe-multichain/index.js.map +1 -0
  83. package/dist/stripe-multichain/index.mjs +199 -0
  84. package/dist/stripe-multichain/index.mjs.map +1 -0
  85. package/dist/wwwauthenticate-CU1eNvMQ.d.mts +37 -0
  86. package/dist/wwwauthenticate-CU1eNvMQ.d.ts +37 -0
  87. package/package.json +172 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/_denial.ts","../../src/_response.ts","../../src/address.ts","../../src/cache.ts","../../src/core.ts","../../src/signer.ts","../../src/identity/web.ts"],"sourcesContent":["/**\n * Universal denial helpers shared across every adapter.\n *\n * What lives here:\n * - `FIXABLE_DENIAL_REASONS` / `isFixableDenial` — classifier for compliance reasons that can\n * be resolved by re-completing KYC (vs sanctions / age failures which are permanent).\n * - `denialReasonStatus` — picks the right HTTP status code per denial code (401 for credential\n * problems, 503 for transient API errors, 403 for everything else).\n * - `buildSignerMismatchBody` — produces the standard 403 body for a `verifyWalletSignerMatch`\n * non-pass result.\n * - `buildContactSupportNextSteps` — standard `next_steps.action: \"contact_support\"` shape for\n * unfixable compliance denials.\n * - `verificationAgentInstructions` — the canned `agent_instructions` block for\n * identity-verification 403s. Vendors can override individual fields.\n *\n * Adapters use `denialReasonStatus` inside their default `onDenied` so vendors get the right\n * status code for free. The body builders are exported from each adapter so vendors who write\n * a custom `onDenied` can compose them without copy-paste.\n */\n\nimport type { DenialReason, VerifyWalletSignerResult } from './core';\n\n/**\n * Compliance denial reasons that can be resolved by re-completing KYC. Sanctions hits and\n * age-not-verified are NOT in this set — they're permanent policy failures on an\n * otherwise-verified identity and require contact-support, not retry.\n */\nexport const FIXABLE_DENIAL_REASONS: ReadonlySet<string> = new Set([\n 'kyc_required',\n 'kyc_pending',\n 'kyc_failed',\n 'jurisdiction_restricted',\n]);\n\n/**\n * Returns true when a `wallet_not_trusted` denial's reasons are all \"fixable\" (the user can\n * re-verify and retry). False when any reason is permanent (sanctions, age).\n *\n * Empty reasons array is treated as fixable on the assumption that an empty-reason denial\n * means a generic policy fail that's worth retrying — vendors can override by checking the\n * specific reasons themselves.\n */\nexport function isFixableDenial(reasons: readonly string[] | undefined): boolean {\n if (!reasons || reasons.length === 0) return true;\n return reasons.every((r) => FIXABLE_DENIAL_REASONS.has(r));\n}\n\n/**\n * The right HTTP status code for a denial. `defaultOnDenied` in every adapter uses this so\n * vendors get correct status codes without writing per-code branches.\n *\n * - 401 for credential problems the agent can recover from (`token_expired`, `invalid_credential`)\n * - 503 for transient `api_error`\n * - 403 for everything else (identity required, compliance fail, signer mismatch, etc.)\n */\nexport function denialReasonStatus(reason: DenialReason): 401 | 403 | 503 {\n if (reason.code === 'token_expired' || reason.code === 'invalid_credential') return 401;\n if (reason.code === 'api_error') return 503;\n return 403;\n}\n\nexport interface SignerMismatchBodyInput {\n /** Result from `verifyWalletSignerMatch`. The function only emits a body for non-pass results. */\n result: VerifyWalletSignerResult;\n /** Optional override for the human-facing `next_steps.user_message`. */\n userMessage?: string;\n /** Optional override for `next_steps.learn_more_url`. Default: AgentScore agent-identity guide. */\n learnMoreUrl?: string;\n}\n\n/**\n * Standard 403 body for a non-pass `verifyWalletSignerMatch` result. Returns null for `pass` /\n * `api_error` so vendors can call it unconditionally:\n *\n * const result = await verifyWalletSignerMatch(c);\n * const mismatchBody = buildSignerMismatchBody({ result });\n * if (mismatchBody) return c.json(mismatchBody, 403);\n *\n * Body shape mirrors the gate's denial bodies: top-level error.code, all signer-match fields\n * (`claimed_operator`, `actual_signer_operator`, `expected_signer`, `actual_signer`,\n * `linked_wallets`), plus a `next_steps` action describing the recovery path.\n */\nexport function buildSignerMismatchBody(input: SignerMismatchBodyInput): Record<string, unknown> | null {\n const { result } = input;\n if (result.kind === 'pass' || result.kind === 'api_error') return null;\n\n const learnMoreUrl = input.learnMoreUrl ?? 'https://docs.agentscore.sh/guides/agent-identity';\n\n if (result.kind === 'wallet_signer_mismatch') {\n const linkedWallets = result.linkedWallets ?? [];\n const userMessage = input.userMessage ?? (linkedWallets.length > 0\n ? `Sign the payment with one of the wallets linked to this operator: ${linkedWallets.join(', ')}. Then retry.`\n : 'Sign the payment with the same wallet you claimed via X-Wallet-Address, or switch to X-Operator-Token for rail-independent identity.');\n return {\n error: {\n code: 'wallet_signer_mismatch',\n message:\n 'Payment signer does not match the wallet claimed via X-Wallet-Address. The signer and the claimed wallet must both resolve to the same AgentScore operator.',\n },\n claimed_operator: result.claimedOperator,\n actual_signer_operator: result.actualSignerOperator ?? null,\n expected_signer: result.expectedSigner,\n actual_signer: result.actualSigner,\n linked_wallets: linkedWallets,\n next_steps: {\n action: 'regenerate_payment_from_linked_wallet',\n user_message: userMessage,\n learn_more_url: learnMoreUrl,\n },\n };\n }\n\n // wallet_auth_requires_wallet_signing\n return {\n error: {\n code: 'wallet_auth_requires_wallet_signing',\n message:\n 'Wallet-auth requires a payment rail that carries a wallet signature (Tempo MPP, x402). Stripe SPT and card rails have no wallet signer; switch to X-Operator-Token to use those.',\n },\n next_steps: {\n action: 'switch_to_operator_token',\n user_message:\n input.userMessage ??\n 'Drop the X-Wallet-Address header and retry with X-Operator-Token (works on every payment rail).',\n learn_more_url: learnMoreUrl,\n },\n };\n}\n\n/**\n * Standard `next_steps` block for unfixable compliance denials (sanctions, age, etc.). Vendors\n * spread this into a 403 body alongside the usual `error`/`reasons` fields.\n *\n * return c.json({\n * error: { code: 'compliance_denied', message: '...' },\n * reasons,\n * next_steps: buildContactSupportNextSteps('support@martinestate.com'),\n * }, 403);\n */\nexport function buildContactSupportNextSteps(\n supportEmail: string,\n message?: string,\n): { action: 'contact_support'; support_email: string; user_message: string } {\n return {\n action: 'contact_support',\n support_email: supportEmail,\n user_message:\n message ??\n `If you believe this denial is in error, contact support at ${supportEmail} with your order details.`,\n };\n}\n\nexport interface VerificationAgentInstructionsInput {\n /** Override the user-facing message. */\n userAction?: string;\n /** Replace the generic \"Retry the original merchant request...\" step with a merchant-specific\n * one (e.g. \"Retry POST /purchase with X-Operator-Token AND include order_id...\"). When set,\n * this REPLACES baseSteps[4] rather than appending — use it instead of `extraSteps[0]` when\n * your retry instruction is a refinement of the canonical retry, not an additional step. */\n retryStep?: string;\n /** Append additional steps after the retry step. Use this for genuinely additional steps\n * (e.g. \"After payment the same call returns 200 with the order\"), not for re-stating the\n * retry — use `retryStep` for that. */\n extraSteps?: string[];\n /** Override the poll cadence. Default 5 seconds. */\n pollIntervalSeconds?: number;\n /** Override how long the agent should keep polling. Default 3600 seconds (1 hour). */\n timeoutSeconds?: number;\n /** Optional `order_ttl` note describing how long pending orders survive. */\n orderTtl?: string;\n /** Arbitrary additional fields merged into the instructions object. */\n extra?: Record<string, unknown>;\n}\n\n/**\n * The canonical `agent_instructions` block for identity-verification 403s. Tells the agent how to\n * present the verify_url, poll for the operator_token, and retry the original request. Universal\n * across every AgentScore-gated merchant — overrides let vendors add merchant-specific steps\n * (e.g. \"include order_id when retrying\").\n */\nexport function verificationAgentInstructions(input: VerificationAgentInstructionsInput = {}): {\n action: 'poll_for_credential';\n user_action: string;\n steps: string[];\n poll_interval_seconds: number;\n poll_secret_header: 'X-Poll-Secret';\n retry_token_header: 'X-Operator-Token';\n timeout_seconds: number;\n order_ttl?: string;\n [key: string]: unknown;\n} {\n const baseSteps = [\n 'Present the verify_url directly to the user — it is a complete, ready-to-open URL with the session token already embedded (e.g. https://agentscore.sh/verify?session=sess_...). Do NOT modify or construct the URL yourself.',\n `Immediately begin polling poll_url every ${input.pollIntervalSeconds ?? 5} seconds with header X-Poll-Secret set to poll_secret. The user will complete verification in their browser while you poll in the background.`,\n 'The user visits the URL, signs in, completes identity verification (photo ID + selfie via Stripe Identity), and closes the tab. They do NOT need to copy or paste anything back to you.',\n 'When your poll returns status \"verified\", extract operator_token from the response. This is a one-time value — save it immediately. Subsequent polls return status \"consumed\" without the token.',\n input.retryStep ?? 'Retry the original merchant request with header X-Operator-Token set to the operator_token value.',\n ];\n\n return {\n action: 'poll_for_credential',\n user_action:\n input.userAction ??\n 'The user must visit verify_url to complete identity verification before this request can proceed',\n steps: input.extraSteps ? [...baseSteps, ...input.extraSteps] : baseSteps,\n poll_interval_seconds: input.pollIntervalSeconds ?? 5,\n poll_secret_header: 'X-Poll-Secret',\n retry_token_header: 'X-Operator-Token',\n timeout_seconds: input.timeoutSeconds ?? 3600,\n ...(input.orderTtl ? { order_ttl: input.orderTtl } : {}),\n ...(input.extra ?? {}),\n };\n}\n","/**\n * Shared DenialReason → response body serialization for all adapters.\n *\n * Keeps Hono / Express / Fastify / Web / Next.js defaults aligned — a field added\n * here shows up in every adapter's 403 body automatically, and there's one place\n * to test the marshaling.\n *\n * Body shape: `{ error: { code, message }, ... }` — matches the canonical AgentScore\n * core API response shape (`core/api/src/lib/auth.ts`, `lib/rate-limit.ts`, etc.) and\n * martin-estate's pre-commerce shape, so downstream agents see one consistent\n * `error.code` + `error.message` pair regardless of which layer produced the denial.\n */\n\nimport type { DenialCode, DenialReason } from './core.js';\n\nconst DEFAULT_MESSAGES: Record<DenialCode, string> = {\n missing_identity:\n 'No identity provided. Send X-Wallet-Address (wallet) or X-Operator-Token (credential).',\n identity_verification_required:\n 'Identity verification is required to access this resource. Visit verify_url to complete KYC.',\n wallet_not_trusted:\n 'The wallet does not meet the merchant compliance policy.',\n api_error:\n 'AgentScore is unreachable. This is transient — retry in a few seconds.',\n payment_required:\n 'AgentScore tier does not support assess. Contact support.',\n wallet_signer_mismatch:\n 'Payment signer does not match the wallet claimed via X-Wallet-Address. The signer and the claimed wallet must both resolve to the same AgentScore operator.',\n wallet_auth_requires_wallet_signing:\n 'X-Wallet-Address was sent with a rail that has no wallet signature (Stripe SPT / card). Switch to X-Operator-Token, or use a wallet-signing rail (Tempo MPP, x402).',\n token_expired:\n 'The operator token is expired or revoked. A fresh verification session has been minted — visit verify_url to mint a new token.',\n invalid_credential:\n 'The operator token is not recognized. Switch to a different stored token, or drop the header to bootstrap a fresh session.',\n};\n\n// Field names the gate claims authority over. Merchant-provided `extra` (from the\n// onBeforeSession hook) MUST NOT override these — a buggy or malicious hook could\n// otherwise replace `verify_url` with a phishing URL or drop agent_instructions.\nconst RESERVED_FIELDS = new Set([\n 'error',\n 'decision',\n 'reasons',\n 'verify_url',\n 'session_id',\n 'poll_secret',\n 'poll_url',\n 'agent_instructions',\n 'agent_memory',\n 'claimed_operator',\n 'actual_signer_operator',\n 'expected_signer',\n 'actual_signer',\n 'linked_wallets',\n]);\n\nexport function denialReasonToBody(reason: DenialReason): Record<string, unknown> {\n const message = reason.message ?? DEFAULT_MESSAGES[reason.code];\n const body: Record<string, unknown> = { error: { code: reason.code, message } };\n if (reason.decision) body.decision = reason.decision;\n if (reason.reasons) body.reasons = reason.reasons;\n if (reason.verify_url) body.verify_url = reason.verify_url;\n if (reason.session_id) body.session_id = reason.session_id;\n if (reason.poll_secret) body.poll_secret = reason.poll_secret;\n if (reason.poll_url) body.poll_url = reason.poll_url;\n if (reason.agent_instructions) body.agent_instructions = reason.agent_instructions;\n if (reason.agent_memory) body.agent_memory = reason.agent_memory;\n if (reason.claimed_operator) body.claimed_operator = reason.claimed_operator;\n if (reason.code === 'wallet_signer_mismatch') body.actual_signer_operator = reason.actual_signer_operator ?? null;\n if (reason.expected_signer) body.expected_signer = reason.expected_signer;\n if (reason.actual_signer) body.actual_signer = reason.actual_signer;\n if (reason.linked_wallets && reason.linked_wallets.length > 0) body.linked_wallets = reason.linked_wallets;\n // api_error denials get a default retry hint so agents know it's transient. Vendors can\n // override by spreading their own next_steps into a custom onDenied body.\n if (reason.code === 'api_error' && !(reason.extra && (reason.extra as Record<string, unknown>).next_steps)) {\n body.next_steps = { action: 'retry', retry_after_seconds: 5 };\n }\n if (reason.extra) {\n for (const [key, value] of Object.entries(reason.extra)) {\n if (RESERVED_FIELDS.has(key)) {\n console.warn(`[gate] onBeforeSession returned reserved field \"${key}\" — ignoring to preserve gate authority`);\n continue;\n }\n body[key] = value;\n }\n }\n return body;\n}\n","// Network-aware address normalization. EVM addresses (0x + 40 hex) are\n// case-insensitive in the protocol — we lowercase them so DB lookups against\n// `address_lower`-style columns work. Solana addresses are base58 and are\n// case-sensitive — we MUST preserve the input verbatim, never lowercase.\n//\n// Must produce identical output to the API normalizer (`core/api/src/lib/address.ts`)\n// so the gate, API, and merchants normalize the same way. If the two ever drift,\n// captured wallets won't resolve and signer-match silently breaks.\n\nconst SOLANA_BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;\nconst EVM_RE = /^0x[0-9a-fA-F]{40}$/;\n\nexport const isValidEvmAddress = (address: string): boolean => EVM_RE.test(address);\n\nexport const isSolanaAddress = (address: string): boolean =>\n SOLANA_BASE58_RE.test(address) && !address.startsWith('0x');\n\nexport const isValidAddress = (address: string): boolean =>\n isValidEvmAddress(address) || isSolanaAddress(address);\n\nexport const normalizeAddress = (address: string): string => {\n if (isSolanaAddress(address)) { return address; }\n return address.toLowerCase();\n};\n","export class TTLCache<T> {\n private store = new Map<string, { value: T; expiresAt: number }>();\n private maxSize: number;\n\n constructor(private defaultTtlMs: number, maxSize = 10000) {\n this.maxSize = maxSize;\n }\n\n get(key: string): T | undefined {\n const entry = this.store.get(key);\n if (!entry) return undefined;\n if (Date.now() > entry.expiresAt) {\n this.store.delete(key);\n return undefined;\n }\n return entry.value;\n }\n\n set(key: string, value: T, ttlMs?: number): void {\n if (this.store.size >= this.maxSize) {\n this.sweep();\n }\n if (this.store.size >= this.maxSize) {\n this.evictOldest(this.store.size - this.maxSize + 1);\n }\n this.store.set(key, {\n value,\n expiresAt: Date.now() + (ttlMs ?? this.defaultTtlMs),\n });\n }\n\n /** Remove all expired entries. */\n private sweep(): void {\n const now = Date.now();\n for (const [k, v] of this.store) {\n if (now > v.expiresAt) {\n this.store.delete(k);\n }\n }\n }\n\n /** Evict the oldest `count` entries by insertion order. */\n private evictOldest(count: number): void {\n let removed = 0;\n for (const key of this.store.keys()) {\n if (removed >= count) break;\n this.store.delete(key);\n removed++;\n }\n }\n}\n","import { normalizeAddress } from './address';\nimport { TTLCache } from './cache';\n\n// Character-based trim avoids a CodeQL polynomial-redos false positive on\n// `/\\/+$/` patterns that report library-input strings.\nfunction stripTrailingSlashes(s: string): string {\n let end = s.length;\n while (end > 0 && s.charCodeAt(end - 1) === 47 /* '/' */) end--;\n return end === s.length ? s : s.slice(0, end);\n}\n\ndeclare const __VERSION__: string;\n\n// ---------------------------------------------------------------------------\n// Public types (framework-agnostic)\n// ---------------------------------------------------------------------------\n\nexport interface AgentIdentity {\n address?: string;\n operatorToken?: string;\n}\n\n/**\n * Session metadata returned from `POST /v1/sessions`. Surfaced to the `onBeforeSession`\n * hook so merchants can correlate an AgentScore session with their own resume token\n * (e.g. a pending-order id).\n */\nexport interface SessionMetadata {\n session_id: string;\n verify_url: string;\n poll_secret: string;\n poll_url: string;\n expires_at?: string;\n}\n\n/**\n * Configuration for auto-creating a verification session when no identity is present.\n *\n * The static `context` / `productName` options are sent on every session request. For\n * per-request context (e.g. the specific product the agent was trying to buy), pass\n * a `getSessionOptions` callback that returns dynamic values; its return is merged\n * over the static defaults.\n *\n * `onBeforeSession` is a side-effect hook that runs after the session is minted but\n * before the 403 is built. Use it to pre-create a reservation/draft/pending-order\n * row in your DB so agents can resume via a merchant-specific id. Return value is\n * merged into `DenialReason.extra`, so it surfaces in both the default 403 body and\n * in a custom `onDenied` handler.\n */\nexport interface CreateSessionOnMissing<TCtx = unknown> {\n apiKey: string;\n baseUrl?: string;\n context?: string;\n productName?: string;\n /** Per-request override of `context` / `productName`. Invoked with the framework context. */\n getSessionOptions?: (ctx: TCtx) => Promise<{ context?: string; productName?: string }>\n | { context?: string; productName?: string };\n /** Side-effect hook that runs after the session is minted. Return value is merged\n * into `DenialReason.extra` so custom `onDenied` handlers can include merchant-specific\n * fields (e.g. `order_id`) in the 403 response. Hook errors are logged and swallowed —\n * a failing side effect should not block the 403 from reaching the agent. */\n onBeforeSession?: (ctx: TCtx, session: SessionMetadata) => Promise<Record<string, unknown>>\n | Record<string, unknown>;\n}\n\nexport interface AgentScoreCoreOptions {\n /** AgentScore API key. Required. */\n apiKey: string;\n /** Require KYC verification. */\n requireKyc?: boolean;\n /** Require operator to be clear of sanctions. */\n requireSanctionsClear?: boolean;\n /** Minimum operator age bracket (18 or 21). */\n minAge?: number;\n /** List of blocked jurisdictions (blocklist). */\n blockedJurisdictions?: string[];\n /** List of allowed jurisdictions (allowlist — only these pass). */\n allowedJurisdictions?: string[];\n /** If true, allow the request through when the API is unreachable. Defaults to false. */\n failOpen?: boolean;\n /** How long to cache results, in seconds. Defaults to 300. */\n cacheSeconds?: number;\n /** AgentScore API base URL. Defaults to \"https://api.agentscore.sh\". */\n baseUrl?: string;\n /** Optional chain to filter scoring to. */\n chain?: string;\n /** Prepended to the default User-Agent as `\"{userAgent} (@agent-score/commerce@{version})\"`. Use to attribute API calls to your app. */\n userAgent?: string;\n /** When set and no identity is found, create a verification session instead of denying immediately. */\n createSessionOnMissing?: CreateSessionOnMissing;\n}\n\nexport type DenialCode =\n | 'wallet_not_trusted'\n | 'missing_identity'\n | 'api_error'\n | 'payment_required'\n | 'identity_verification_required'\n // Wallet-signer binding: claimed X-Wallet-Address must resolve to the same operator as\n // the payment signer; wallet-auth is rejected on rails with no wallet signer.\n | 'wallet_signer_mismatch'\n | 'wallet_auth_requires_wallet_signing'\n // Granular credential-state denials passed through from /v1/assess.\n // - `token_expired`: revoked + TTL-expired (the API unifies these). The 401 body carries\n // an auto-minted session, forwarded into DenialReason for one-shot recovery.\n // - `invalid_credential`: the token doesn't exist at all (typo, never minted, fabricated).\n // No auto-session is minted by the API for this case — agents should switch to a\n // different stored token or drop the header to bootstrap a fresh session.\n | 'token_expired'\n | 'invalid_credential';\n\n/**\n * Cross-merchant pattern hint emitted on bootstrap denials and session-create responses.\n * LLM-hosted agents should persist this to long-term memory so future AgentScore encounters skip\n * the cold-start session flow. Contents are the pattern, not secrets.\n */\nexport interface AgentMemoryHint {\n save_for_future_agentscore_gates: true;\n pattern_summary: string;\n quickstart: string;\n identity_check_endpoint: string;\n list_wallets_endpoint?: string;\n identity_paths: { wallet: string; operator_token: string };\n bootstrap: string;\n do_not_persist_in_memory: string[];\n persist_in_credential_store: string[];\n}\n\nexport interface DenialReason {\n code: DenialCode;\n /** Human-readable explanation. When omitted, `denialReasonToBody` substitutes a per-code default. */\n message?: string;\n decision?: string;\n reasons?: string[];\n verify_url?: string;\n session_id?: string;\n poll_secret?: string;\n poll_url?: string;\n agent_instructions?: string;\n /** Cross-merchant memory hint. Emitted on bootstrap denials only by default. */\n agent_memory?: AgentMemoryHint;\n /** Full assess response when the denial came from `/v1/assess`. Lets consumers access fields\n * not promoted to first-class DenialReason properties (e.g., `policy_result`). Undefined for\n * denials that did not originate from an assess call (missing_identity, api_error,\n * payment_required, identity_verification_required). */\n data?: AgentScoreData;\n /** Extra fields returned from the `createSessionOnMissing.onBeforeSession` hook. Merged\n * into the default 403 body; custom `onDenied` handlers can spread these into their own\n * response shape (e.g. to include a merchant-minted `order_id`). */\n extra?: Record<string, unknown>;\n // ---------------------------------------------------------------------------\n // Wallet-signer-match fields — populated for wallet_signer_mismatch only.\n // ---------------------------------------------------------------------------\n /** Operator id resolved from `X-Wallet-Address`. */\n claimed_operator?: string;\n /** Operator id the actual payment signer resolves to. `null` when the signer wallet isn't\n * linked to any operator (treat as a different identity). */\n actual_signer_operator?: string | null;\n /** The wallet the agent claimed via header. Echoed back for self-correction. */\n expected_signer?: string;\n /** The wallet that actually signed the payment. */\n actual_signer?: string;\n /** Wallets the claimed operator could sign with (if enumerable). Present when non-empty. */\n linked_wallets?: string[];\n}\n\nexport interface AgentScoreData {\n decision: string | null;\n decision_reasons: string[];\n identity_method?: string;\n operator_verification?: {\n level: string;\n operator_type: string | null;\n verified_at: string | null;\n };\n /** Account-level KYC facts that apply to every operator under the same account.\n * Populated when the API returns account_verification (post-KYC operator). */\n account_verification?: {\n kyc_level?: string;\n sanctions_clear?: boolean;\n age_bracket?: string;\n jurisdiction?: string;\n verified_at?: string | null;\n };\n resolved_operator?: string | null;\n /** Wallets linked to the same operator as the resolved identity. Capped at 100 entries\n * by the API. Useful for advertising in 402 challenges so wallet-auth agents know which\n * alt-signers will satisfy `wallet_signer_mismatch`. */\n linked_wallets?: string[];\n verify_url?: string;\n policy_result?: {\n all_passed: boolean;\n checks: Array<{\n rule: string;\n passed: boolean;\n required?: unknown;\n actual?: unknown;\n }>;\n } | null;\n}\n\n/**\n * Outcome from `AgentScoreCore.evaluate()`. Adapters map this to framework-specific responses.\n *\n * - `{ kind: 'allow', data }` — the request passed the policy. `data` is present on a normal\n * allow; `undefined` when fail-open short-circuited (identity missing, API unreachable,\n * timeout, or 402 paid-tier required).\n * - `{ kind: 'deny', reason }` — the request was denied. Adapters should render a 403 with the\n * reason, or invoke the caller's custom denial handler.\n */\nexport type EvaluateOutcome =\n | { kind: 'allow'; data?: AgentScoreData }\n | { kind: 'deny'; reason: DenialReason };\n\nexport interface CaptureWalletOptions {\n /** Operator credential (`opc_...`) that the agent authenticated with. */\n operatorToken: string;\n /** Signer wallet recovered from the payment payload. */\n walletAddress: string;\n /** Key-derivation family — `\"evm\"` for any EVM chain, `\"solana\"` for Solana. */\n network: 'evm' | 'solana';\n /** Optional stable key for the logical payment (e.g., payment intent id, tx hash). When the\n * same key is seen again for the same (credential, wallet, network), the server no-ops —\n * prevents agent retries from inflating transaction_count. */\n idempotencyKey?: string;\n}\n\nexport interface VerifyWalletSignerMatchOptions {\n /** The wallet claimed via `X-Wallet-Address`. */\n claimedWallet: string;\n /** The signer wallet recovered from the payment credential. `null` means the rail carries\n * no wallet signer (SPT, card) — the helper returns `wallet_auth_requires_wallet_signing`. */\n signer: string | null;\n /** Network of the signer. EVM covers every EVM chain; `solana` lives in its own namespace. */\n network?: 'evm' | 'solana';\n}\n\nexport type VerifyWalletSignerResult =\n | { kind: 'pass'; claimedOperator: string | null; signerOperator: string | null }\n | {\n kind: 'wallet_signer_mismatch';\n claimedOperator: string | null;\n actualSignerOperator: string | null;\n expectedSigner: string;\n actualSigner: string;\n linkedWallets: string[];\n /** JSON-encoded action copy (action + steps + user_message). Spread into the 403 body\n * verbatim so agents get a concrete recovery path inside the denial response itself. */\n agentInstructions: string;\n }\n | {\n kind: 'wallet_auth_requires_wallet_signing';\n claimedWallet: string;\n agentInstructions: string;\n }\n // Transient — the resolve call to /v1/assess failed or timed out. Caller should\n // retry or surface as 503. Distinct from wallet_signer_mismatch (which is an actual\n // security reject) so legitimate users don't get rejected on network flakes.\n | { kind: 'api_error'; claimedWallet: string };\n\nexport interface AgentScoreCore {\n /**\n * Evaluate the request's identity against the configured policy.\n * @param identity - extracted identity (wallet address and/or operator token)\n * @param ctx - optional framework-specific context (Hono c, Express req, etc.) passed\n * through to `createSessionOnMissing` hooks. Opaque to core.\n */\n evaluate(identity: AgentIdentity | undefined, ctx?: unknown): Promise<EvaluateOutcome>;\n /** Report a wallet seen paying under an operator credential. Fire-and-forget; silently\n * swallows non-fatal errors because capture is informational, not on the critical path. */\n captureWallet(options: CaptureWalletOptions): Promise<void>;\n /**\n * Verify the payment signer resolves to the same operator as the claimed `X-Wallet-Address`.\n *\n * Returns `pass` when the signer is linked to the same operator as the claimed wallet\n * (byte-equal wallets pass trivially; other wallets linked to the same operator also pass —\n * multi-wallet agents work without ergonomic pain). Returns `wallet_signer_mismatch` when\n * the signer resolves to a different (or no) operator. Returns `wallet_auth_requires_wallet_signing`\n * when the signer is `null` (SPT, card — rails that carry no wallet signature).\n *\n * Call this AFTER the gate evaluates (so the claimed wallet's operator is cached) and\n * AFTER the payment credential is parsed (so the signer is known). Merchants should call\n * it before settling payment.\n */\n verifyWalletSignerMatch(options: VerifyWalletSignerMatchOptions): Promise<VerifyWalletSignerResult>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal types\n// ---------------------------------------------------------------------------\n\ninterface AssessResult {\n allow: boolean;\n decision?: string;\n reasons?: string[];\n raw?: unknown;\n}\n\n/**\n * Build the cross-merchant memory hint emitted on bootstrap denials. Base URLs are\n * derived from the gate's AgentScore API base so self-hosted / staging deployments get\n * correct pointers. Contents describe the AgentScore identity substrate in transferable\n * terms; merchant-specific context lives in other `agent_instructions` fields.\n */\n// Canonical production AgentScore API — used as the authoritative source for endpoint pointers\n// emitted to agent memory regardless of how a given merchant configured their gate's baseUrl.\n// Hardcoded so a malicious merchant can't set `baseUrl: \"evil.com\"` and phish agents into\n// sending their credentials to attacker-controlled endpoints.\nconst CANONICAL_AGENTSCORE_API = 'https://api.agentscore.sh';\n\n// JSON-encoded action copy emitted on wallet-signer-match denials. Spread into 403 bodies\n// by merchants so agents get a concrete recovery path inside the denial response itself —\n// no discovery-doc round trip required.\nconst WALLET_SIGNER_MISMATCH_INSTRUCTIONS = JSON.stringify({\n action: 'resign_or_switch_to_operator_token',\n steps: [\n 'Preferred: re-submit the payment signed by expected_signer (or any entry in linked_wallets — same-operator wallets are fungible) and retry with the same X-Wallet-Address.',\n 'Alternative: drop X-Wallet-Address and retry with X-Operator-Token. Use a stored opc_... if you have one; otherwise retry this request with NO identity header — the merchant will mint a verification session in the 403 body (verify_url + poll_secret). Share verify_url with the user, poll, receive a fresh opc_...',\n ],\n user_message:\n 'The payment signer resolves to a different operator than X-Wallet-Address. Re-sign from expected_signer or any linked_wallets entry, or switch to X-Operator-Token.',\n});\n\nconst WALLET_AUTH_REQUIRES_WALLET_SIGNING_INSTRUCTIONS = JSON.stringify({\n action: 'switch_to_operator_token',\n steps: [\n 'This payment rail (Stripe SPT, card) carries no wallet signature — X-Wallet-Address cannot be verified against the payment.',\n 'Drop X-Wallet-Address and retry with X-Operator-Token. If you do not have a stored opc_..., retry with no identity header to receive a verification session.',\n ],\n user_message:\n 'Wallet-address identity is only supported on wallet-signing rails (Tempo MPP, x402). On Stripe or card, use X-Operator-Token instead.',\n});\n\n// `invalid_credential` is permanent — the token doesn't exist (typo, never minted, fabricated).\n// Distinct from `token_expired` (which carries an auto-session for one-shot recovery): the\n// API doesn't auto-mint a session here because the client may simply have a different valid\n// token to try. Agents should switch tokens or drop the header to bootstrap a session.\nconst INVALID_CREDENTIAL_INSTRUCTIONS = JSON.stringify({\n action: 'switch_token_or_restart_session',\n steps: [\n 'The X-Operator-Token you sent does not match any credential. This is a permanent state — retrying with the same token will keep failing.',\n 'If you have other stored opc_... credentials, retry with one of them.',\n 'Otherwise drop X-Operator-Token and retry with no identity header — the merchant will mint a fresh verification session in the 403 body (verify_url + poll_secret) so the user can re-verify and you can poll for a new operator_token.',\n ],\n user_message:\n 'The operator_token is not recognized. Use a different stored token, or restart the verification session flow to mint a new one.',\n});\n\nexport function buildAgentMemoryHint(): AgentMemoryHint {\n // Memory pointers always point at the canonical production API — merchants must not be\n // able to redirect the cross-merchant memory surface, since that would be a phishing\n // vector for the verify URL.\n const api = CANONICAL_AGENTSCORE_API;\n return {\n save_for_future_agentscore_gates: true,\n pattern_summary:\n 'AgentScore is a cross-merchant identity substrate for agent commerce. Any endpoint that ' +\n 'returns 403 missing_identity / identity_verification_required or 402 challenges referencing AgentScore uses ' +\n 'the same identity system. One KYC works across all AgentScore merchants — no re-verification ' +\n 'per site. Save this pattern (and the endpoints below) to persistent memory so future ' +\n 'AgentScore encounters skip the cold-start session flow.',\n quickstart: 'https://docs.agentscore.sh/guides/agent-identity',\n identity_check_endpoint: `${api}/v1/credentials`,\n identity_paths: {\n wallet:\n 'If paying from a crypto wallet you have used before on any AgentScore merchant, send ' +\n '`X-Wallet-Address: 0x...`. Shortest path; no token lifecycle to manage.',\n operator_token:\n 'For any rail (Stripe SPT, card, or a wallet you have not linked yet), send ' +\n '`X-Operator-Token: opc_...`. Reusable across merchants until the token expires.',\n },\n bootstrap:\n 'If you have neither a linked wallet nor a valid operator_token, follow the session/verify ' +\n 'flow in the per-request `agent_instructions` block. This happens at most once per agent ' +\n 'identity — after first verification, the operator_token and any subsequently used wallet ' +\n 'are reusable everywhere.',\n do_not_persist_in_memory: ['operator_token', 'poll_secret'],\n persist_in_credential_store: ['operator_token'],\n };\n}\n\n// ---------------------------------------------------------------------------\n// Core factory\n// ---------------------------------------------------------------------------\n\nexport function createAgentScoreCore(options: AgentScoreCoreOptions): AgentScoreCore {\n if (!options.apiKey) {\n throw new Error('AgentScore API key is required. Get one at https://agentscore.sh/sign-up');\n }\n\n const {\n apiKey,\n requireKyc,\n requireSanctionsClear,\n minAge,\n blockedJurisdictions,\n allowedJurisdictions,\n failOpen = false,\n cacheSeconds = 300,\n baseUrl: rawBaseUrl = 'https://api.agentscore.sh',\n chain: gateChain,\n userAgent,\n createSessionOnMissing,\n } = options;\n\n const baseUrl = stripTrailingSlashes(rawBaseUrl);\n const agentMemoryHint = buildAgentMemoryHint();\n\n const defaultUa = `@agent-score/commerce@${__VERSION__}`;\n const userAgentHeader = userAgent ? `${userAgent} (${defaultUa})` : defaultUa;\n\n const API_TIMEOUT_MS = 10_000;\n\n const cache = new TTLCache<AssessResult>(cacheSeconds * 1000);\n\n async function evaluate(identity: AgentIdentity | undefined, ctx?: unknown): Promise<EvaluateOutcome> {\n // Treat \"returned identity object with no usable fields\" the same as \"no identity at all\" —\n // otherwise a misbehaving custom extractIdentity would send an empty body to /v1/assess.\n if (!identity || (!identity.address && !identity.operatorToken)) {\n if (failOpen) return { kind: 'allow' };\n\n if (createSessionOnMissing) {\n try {\n // Start with static context/productName; let getSessionOptions override per-request.\n const sessionBody: { context?: string; product_name?: string } = {};\n if (createSessionOnMissing.context != null) sessionBody.context = createSessionOnMissing.context;\n if (createSessionOnMissing.productName != null) sessionBody.product_name = createSessionOnMissing.productName;\n\n if (createSessionOnMissing.getSessionOptions && ctx !== undefined) {\n try {\n const dynamic = await createSessionOnMissing.getSessionOptions(ctx);\n if (dynamic?.context != null) sessionBody.context = dynamic.context;\n if (dynamic?.productName != null) sessionBody.product_name = dynamic.productName;\n } catch (err) {\n console.warn('[gate] createSessionOnMissing.getSessionOptions hook failed:', err instanceof Error ? err.message : err);\n }\n }\n\n const sessionBaseUrl = stripTrailingSlashes(createSessionOnMissing.baseUrl ?? 'https://api.agentscore.sh');\n const sessionRes = await fetch(`${sessionBaseUrl}/v1/sessions`, {\n method: 'POST',\n headers: {\n 'X-API-Key': createSessionOnMissing.apiKey,\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': userAgentHeader,\n },\n body: JSON.stringify(sessionBody),\n signal: AbortSignal.timeout(API_TIMEOUT_MS),\n });\n\n if (sessionRes.ok) {\n const data = (await sessionRes.json()) as Record<string, unknown>;\n\n // Validate required fields before trusting the response. A misbehaving\n // (or mocked-wrong) API could 200 without session_id/poll_secret/verify_url,\n // which would propagate `undefined` into the 403 body and leave the agent\n // stuck — treat that as a session-create failure and fall back to the bare\n // missing_identity denial with the probe strategy copy.\n if (\n typeof data.session_id !== 'string' ||\n typeof data.poll_secret !== 'string' ||\n typeof data.verify_url !== 'string'\n ) {\n console.warn('[gate] /v1/sessions returned 200 without required fields — falling back to bare missing_identity');\n // fall through to the bare denial below\n } else {\n\n // Run onBeforeSession side-effect hook. Errors are swallowed — a failing DB\n // write (e.g. can't insert pending order) should not block the 403.\n let extra: Record<string, unknown> | undefined;\n if (createSessionOnMissing.onBeforeSession && ctx !== undefined) {\n try {\n const sessionMeta = {\n session_id: data.session_id as string,\n verify_url: data.verify_url as string,\n poll_secret: data.poll_secret as string,\n poll_url: data.poll_url as string,\n expires_at: data.expires_at as string | undefined,\n };\n const result = await createSessionOnMissing.onBeforeSession(ctx, sessionMeta);\n if (result && typeof result === 'object') extra = result;\n } catch (err) {\n console.warn('[gate] createSessionOnMissing.onBeforeSession hook failed:', err instanceof Error ? err.message : err);\n }\n }\n\n // The API emits `next_steps` (structured object) on /v1/sessions success.\n // Stringify it into the gate's `agent_instructions` contract so merchants\n // get the same JSON-encoded {action, steps, user_message} envelope as every\n // other gate-emitted denial.\n const apiNextSteps = data.next_steps as Record<string, unknown> | undefined;\n return {\n kind: 'deny',\n reason: {\n code: 'identity_verification_required',\n verify_url: data.verify_url as string,\n session_id: data.session_id as string,\n poll_secret: data.poll_secret as string,\n poll_url: data.poll_url as string | undefined,\n agent_instructions: apiNextSteps ? JSON.stringify(apiNextSteps) : undefined,\n agent_memory: agentMemoryHint,\n ...(extra && { extra }),\n },\n };\n }\n }\n } catch (err) {\n // Session-mint failed (network, /v1/sessions returned non-2xx, body parse error,\n // onBeforeSession threw inside the inner try). Falling through to bare\n // missing_identity is correct — agents still get a 403 with a probe-strategy\n // hint. But the silent catch used to mask /v1/sessions schema drift and\n // unreachable-API issues for hours, so log loudly.\n console.warn('[gate] createSessionOnMissing path failed — falling back to bare missing_identity:', err instanceof Error ? err.message : err);\n }\n }\n\n // Bare missing-identity denial (no session was auto-created). Describe the probe\n // strategy so agents without memory can recover: try wallet first on signing rails,\n // fall back to stored opc_..., fall back to session flow (noting that only\n // auto-session merchants return verify_url + poll data on the retry).\n const missingIdentityInstructions = JSON.stringify({\n action: 'probe_identity_then_session',\n steps: [\n 'If you have a wallet AND this merchant accepts a wallet-signing rail (Tempo MPP or x402 — see openapi.json x-payment-info): send X-Wallet-Address and retry. If the wallet is already linked to an AgentScore operator (via prior SIWE claim or prior captureWallet), this passes in one round trip. If the wallet is unlinked or the account has no KYC, the 403 will include a verify_url — share it with the user to claim the wallet + complete KYC, then retry.',\n 'If step 1 is denied or you already have a stored operator_token (valid + not expired): send X-Operator-Token: opc_... and retry.',\n 'If neither applies: retry with NO identity header. Merchants that auto-create verification sessions (most AgentScore merchants do) return verify_url + session_id + poll_secret in the 403 body — share verify_url with the user, then poll poll_url every 5s with the X-Poll-Secret header until status=verified (the poll returns a one-time operator_token). If the retry returns the same bare 403, this merchant does not support self-service session bootstrapping — direct the user to https://agentscore.sh/sign-up to create an AgentScore identity and mint an operator_token from their dashboard (https://agentscore.sh/dashboard/verify). The user hands the opc_... to you, and you retry with X-Operator-Token.',\n ],\n user_message:\n 'Try X-Wallet-Address first if you have a wallet and the merchant accepts Tempo/x402; fall back to a stored X-Operator-Token, then to the session/verify flow described in agent_memory.bootstrap.',\n });\n return {\n kind: 'deny',\n reason: {\n code: 'missing_identity',\n agent_instructions: missingIdentityInstructions,\n agent_memory: agentMemoryHint,\n },\n };\n }\n\n // operator_token is opaque + ASCII-only — lowercasing is safe. Wallet addresses go\n // through normalizeAddress because Solana base58 is case-sensitive and lowercasing\n // would corrupt the cache key (a Solana cache miss every time, plus collision risk\n // with mixed-case variants of the same operator).\n const cacheKey = identity.operatorToken?.toLowerCase() ?? (identity.address ? normalizeAddress(identity.address) : '');\n\n const cached = cache.get(cacheKey);\n if (cached) {\n if (cached.allow) {\n return { kind: 'allow', data: cached.raw as AgentScoreData };\n }\n return {\n kind: 'deny',\n reason: {\n code: 'wallet_not_trusted',\n decision: cached.decision,\n reasons: cached.reasons,\n verify_url: (cached.raw as Record<string, unknown> | undefined)?.verify_url as string | undefined,\n data: cached.raw as AgentScoreData | undefined,\n },\n };\n }\n\n try {\n const body: Record<string, unknown> = {};\n if (identity.address) body.address = identity.address;\n if (identity.operatorToken) body.operator_token = identity.operatorToken;\n if (gateChain) body.chain = gateChain;\n\n const policy: Record<string, unknown> = {};\n if (requireKyc != null) policy.require_kyc = requireKyc;\n if (requireSanctionsClear != null) policy.require_sanctions_clear = requireSanctionsClear;\n if (minAge != null) policy.min_age = minAge;\n if (blockedJurisdictions != null) policy.blocked_jurisdictions = blockedJurisdictions;\n if (allowedJurisdictions != null) policy.allowed_jurisdictions = allowedJurisdictions;\n if (Object.keys(policy).length > 0) body.policy = policy;\n\n const response = await fetch(`${baseUrl}/v1/assess`, {\n method: 'POST',\n headers: {\n 'X-API-Key': apiKey,\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': userAgentHeader,\n },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(API_TIMEOUT_MS),\n });\n\n if (response.status === 402) {\n if (failOpen) return { kind: 'allow' };\n return { kind: 'deny', reason: { code: 'payment_required' } };\n }\n\n // Pass through the API's token_expired 401 (covers both expired and revoked\n // credentials — the API deliberately doesn't distinguish). The 401 body carries\n // an auto-minted session (verify_url + session_id + poll_secret + next_steps +\n // agent_memory) so agents can recover without holding an API key. Forward all of\n // that into the DenialReason so the gate's 403 body includes the session fields.\n if (response.status === 401) {\n try {\n const errData = (await response.clone().json()) as {\n error?: { code?: string };\n session_id?: unknown;\n poll_secret?: unknown;\n verify_url?: unknown;\n poll_url?: unknown;\n next_steps?: unknown;\n agent_memory?: unknown;\n };\n const code = errData?.error?.code;\n if (code === 'token_expired') {\n return {\n kind: 'deny',\n reason: {\n code,\n data: errData as unknown as AgentScoreData,\n ...(typeof errData.verify_url === 'string' ? { verify_url: errData.verify_url } : {}),\n ...(typeof errData.session_id === 'string' ? { session_id: errData.session_id } : {}),\n ...(typeof errData.poll_secret === 'string' ? { poll_secret: errData.poll_secret } : {}),\n ...(typeof errData.poll_url === 'string' ? { poll_url: errData.poll_url } : {}),\n ...(errData.next_steps ? { agent_instructions: JSON.stringify(errData.next_steps) } : {}),\n ...(errData.agent_memory ? { agent_memory: errData.agent_memory as AgentMemoryHint } : {}),\n },\n };\n }\n // The API returns this when the operator_token doesn't exist at all (typo,\n // never minted, fabricated). Distinct from token_expired — no auto-session\n // is issued because the agent may have other valid tokens to try first.\n // Without this branch the gate would fall through to api_error → 503 retry,\n // which loops forever on a permanent state.\n if (code === 'invalid_credential') {\n return {\n kind: 'deny',\n reason: {\n code: 'invalid_credential',\n agent_instructions: INVALID_CREDENTIAL_INSTRUCTIONS,\n agent_memory: agentMemoryHint,\n },\n };\n }\n // Unknown 401 code — log so we notice if the API adds a new credential-state\n // code without us mapping it. Falls through to api_error below.\n if (code) {\n console.warn(`[gate] /v1/assess returned 401 ${code} — no specific handler, surfacing as api_error.`);\n }\n } catch (err) {\n // Body wasn't the expected JSON shape. Don't crash the request, but DO log —\n // a silent swallow here used to mask /v1/sessions schema drift for hours.\n console.warn('[gate] /v1/assess 401 body parse failed:', err instanceof Error ? err.message : err);\n }\n }\n\n // 4xx with a structured error body that ISN'T 401/402: log it so operators see\n // misclassifications instead of opaque 503 retries. Most common cause: a merchant\n // that didn't validate input shape before invoking the gate (invalid_address,\n // invalid_identity). We still fall through to api_error so behavior is unchanged\n // for callers — just visible now.\n if (response.status >= 400 && response.status < 500 && response.status !== 402) {\n try {\n const errData = (await response.clone().json()) as { error?: { code?: string; message?: string } };\n const code = errData?.error?.code;\n if (code && code !== 'token_expired' && code !== 'invalid_credential') {\n console.warn(\n `[gate] /v1/assess returned ${response.status} ${code} — surfacing as api_error. ` +\n 'Validate input shape before invoking the gate to avoid this.',\n );\n }\n } catch {\n // Body wasn't JSON or didn't have the expected shape — silent fall-through.\n }\n }\n\n if (!response.ok) {\n throw new Error(`AgentScore API returned ${response.status}`);\n }\n\n const data = (await response.json()) as Record<string, unknown>;\n const decision = data.decision as string | null | undefined;\n const decisionReasons = (data.decision_reasons as string[]) ?? [];\n const allow = decision === 'allow' || decision == null;\n\n cache.set(cacheKey, { allow, decision: decision ?? undefined, reasons: decisionReasons, raw: data });\n\n if (allow) {\n return { kind: 'allow', data: data as unknown as AgentScoreData };\n }\n\n return {\n kind: 'deny',\n reason: {\n code: 'wallet_not_trusted',\n decision: decision ?? undefined,\n reasons: decisionReasons,\n verify_url: data.verify_url as string | undefined,\n data: data as unknown as AgentScoreData,\n },\n };\n } catch (err) {\n // Network failure, AbortSignal timeout, JSON parse error on a 2xx, or the\n // explicit `throw new Error(...)` for an unhandled non-ok status. Log so ops\n // can distinguish \"API down\" from \"merchant config wrong\" — without this,\n // every transient blip looked identical to a misconfigured base URL.\n console.warn('[gate] /v1/assess call failed — surfacing as api_error:', err instanceof Error ? err.message : err);\n if (failOpen) return { kind: 'allow' };\n return { kind: 'deny', reason: { code: 'api_error' } };\n }\n }\n\n async function captureWallet(options: CaptureWalletOptions): Promise<void> {\n try {\n const body: Record<string, unknown> = {\n operator_token: options.operatorToken,\n wallet_address: options.walletAddress,\n network: options.network,\n };\n if (options.idempotencyKey) body.idempotency_key = options.idempotencyKey;\n await fetch(`${baseUrl}/v1/credentials/wallets`, {\n method: 'POST',\n headers: {\n 'X-API-Key': apiKey,\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': userAgentHeader,\n },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(API_TIMEOUT_MS),\n });\n } catch (err) {\n // Fire-and-forget: don't throw. Log so a persistent capture outage is visible\n // to merchant ops — otherwise wallet↔operator linkage silently stops.\n console.warn('[agentscore-commerce] captureWallet failed:', err instanceof Error ? err.message : err);\n }\n }\n\n /**\n * Resolve a wallet to its operator id via /v1/assess.\n *\n * Returns:\n * - `{ ok: true, operator: <id> }` — wallet is linked to that operator\n * - `{ ok: true, operator: null }` — wallet is valid but not linked to any operator\n * - `{ ok: false }` — the API call failed (network, timeout, non-2xx). Distinguishable so\n * callers can emit `api_error` instead of falsely asserting \"no operator linked\".\n *\n * Checks the main evaluate() cache before making a fresh call — if the gate already\n * resolved this wallet during identity evaluation, we have the resolved_operator already.\n */\n async function resolveWalletToOperator(\n walletAddress: string,\n ): Promise<{ ok: true; operator: string | null; linkedWallets: string[] } | { ok: false }> {\n // Network-aware: lowercases EVM, preserves Solana base58 case. The DB stores both\n // formats verbatim in operator_credential_wallets.wallet_address; lowercasing a\n // Solana address would never match.\n const wallet = normalizeAddress(walletAddress);\n\n // Cache lookup — first the plain cache (populated by evaluate() for identity-headered wallets).\n // Saves a second /v1/assess call when the gate already looked up this wallet.\n const extractFromCached = (raw: Record<string, unknown>): { operator: string | null; linkedWallets: string[] } => {\n const op = raw.resolved_operator;\n const links = raw.linked_wallets;\n return {\n operator: typeof op === 'string' ? op : null,\n linkedWallets: Array.isArray(links) ? (links as unknown[]).filter((w): w is string => typeof w === 'string') : [],\n };\n };\n\n const plainCached = cache.get(wallet);\n if (plainCached?.raw) {\n return { ok: true, ...extractFromCached(plainCached.raw as Record<string, unknown>) };\n }\n const resolveCached = cache.get(`resolve:${wallet}`);\n if (resolveCached?.raw) {\n return { ok: true, ...extractFromCached(resolveCached.raw as Record<string, unknown>) };\n }\n\n try {\n const response = await fetch(`${baseUrl}/v1/assess`, {\n method: 'POST',\n headers: {\n 'X-API-Key': apiKey,\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': userAgentHeader,\n },\n body: JSON.stringify({ address: walletAddress }),\n signal: AbortSignal.timeout(API_TIMEOUT_MS),\n });\n if (!response.ok) return { ok: false };\n const data = (await response.json()) as Record<string, unknown>;\n cache.set(`resolve:${wallet}`, { allow: true, raw: data });\n return { ok: true, ...extractFromCached(data) };\n } catch (err) {\n // Network/timeout/parse on the wallet→operator resolve path. Caller maps\n // `{ok:false}` to `wallet_signer_mismatch.kind === 'api_error'`, which already\n // surfaces as 503 — but log here too so multi-wallet match failures aren't\n // silently indistinguishable from \"operator simply has no linked wallet\".\n console.warn('[gate] resolveWalletToOperator failed — returning { ok:false }:', err instanceof Error ? err.message : err);\n return { ok: false };\n }\n }\n\n function reportSignerEvent(kind: 'pass' | 'wallet_signer_mismatch' | 'wallet_auth_requires_wallet_signing' | 'api_error'): void {\n // Fire-and-forget: surfaces mismatch-catch rate + api_error SLO on the dashboard.\n // Never blocks, awaits, or throws — telemetry failure must not affect the gate's decision.\n try {\n const pending = fetch(`${baseUrl}/v1/telemetry/signer-match`, {\n method: 'POST',\n headers: {\n 'X-API-Key': apiKey,\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': userAgentHeader,\n },\n body: JSON.stringify({ kind }),\n signal: AbortSignal.timeout(API_TIMEOUT_MS),\n });\n if (pending && typeof pending.catch === 'function') {\n pending.catch((err) => {\n console.warn('[agentscore-commerce] signer-match telemetry failed:', err instanceof Error ? err.message : err);\n });\n }\n } catch {\n // Thrown synchronously (e.g., fetch unavailable in test harness) — swallow silently.\n }\n }\n\n async function verifyWalletSignerMatch(\n options: VerifyWalletSignerMatchOptions,\n ): Promise<VerifyWalletSignerResult> {\n const { claimedWallet, signer } = options;\n\n if (!signer) {\n reportSignerEvent('wallet_auth_requires_wallet_signing');\n return {\n kind: 'wallet_auth_requires_wallet_signing',\n claimedWallet,\n agentInstructions: WALLET_AUTH_REQUIRES_WALLET_SIGNING_INSTRUCTIONS,\n };\n }\n\n // Network-aware normalization: lowercase EVM, preserve Solana base58. The byte-equal\n // short-circuit and downstream cache-key derivation MUST match how the DB stores\n // wallets; lowercasing Solana would corrupt both.\n const claimedNorm = normalizeAddress(claimedWallet);\n const signerNorm = normalizeAddress(signer);\n\n // Byte-equal short-circuit — no API lookup; same wallet ≡ same operator by definition.\n if (claimedNorm === signerNorm) {\n reportSignerEvent('pass');\n return { kind: 'pass', claimedOperator: null, signerOperator: null };\n }\n\n const [claimedResolve, signerResolve] = await Promise.all([\n resolveWalletToOperator(claimedNorm),\n resolveWalletToOperator(signerNorm),\n ]);\n\n // Transient API failure on either resolve → emit api_error. Caller should retry or\n // surface 503 rather than falsely reject a legitimate user on a network flake.\n if (!claimedResolve.ok || !signerResolve.ok) {\n reportSignerEvent('api_error');\n return { kind: 'api_error', claimedWallet: claimedNorm };\n }\n\n const claimedOperator = claimedResolve.operator;\n const signerOperator = signerResolve.operator;\n\n if (claimedOperator && signerOperator && claimedOperator === signerOperator) {\n reportSignerEvent('pass');\n return { kind: 'pass', claimedOperator, signerOperator };\n }\n\n reportSignerEvent('wallet_signer_mismatch');\n return {\n kind: 'wallet_signer_mismatch',\n claimedOperator,\n actualSignerOperator: signerOperator,\n expectedSigner: claimedNorm,\n actualSigner: signerNorm,\n // Populated from /v1/assess.linked_wallets on the claimed wallet — the full set of\n // wallets the agent CAN sign with to satisfy the claim (same-operator rule).\n linkedWallets: claimedResolve.linkedWallets,\n agentInstructions: WALLET_SIGNER_MISMATCH_INSTRUCTIONS,\n };\n }\n\n return { evaluate, captureWallet, verifyWalletSignerMatch };\n}\n","/**\n * Payment-signer extraction.\n *\n * Shared between merchants and the gate — both need to recover the on-chain signer from\n * a payment credential without duplicating code. Three rails carry a wallet signer:\n *\n * - **Tempo MPP** — `Authorization: Payment <base64>` header; credential `source` is a DID\n * of the form `did:pkh:eip155:<chain>:<address>`.\n * - **x402 EIP-3009** (EVM, e.g. Base/Sepolia) — `payment-signature` / `x-payment` header;\n * decoded payload carries `payload.authorization.from`.\n * - **x402 SVM** (Solana) — same headers, but `payload.transaction` is a base64-encoded\n * Solana transaction; the SPL Token TransferChecked instruction's source-account owner\n * is the signer. Recovered via `@x402/svm`'s `decodeTransactionFromPayload` +\n * `getTokenPayerFromTransaction`.\n *\n * `mppx` and `@x402/svm` are optional peer dependencies — we import them dynamically so\n * merchants who don't use those rails don't need to install them. The EVM x402 path is pure\n * JSON parsing with no external dep.\n */\n\nexport type SignerNetwork = 'evm' | 'solana';\n\nexport interface PaymentSigner {\n /** Recovered wallet address (EVM lowercased; Solana base58 preserved verbatim). */\n address: string;\n /** Network family — used by `captureWallet` and downstream cross-chain attribution. */\n network: SignerNetwork;\n}\n\n/**\n * Recover the signer wallet from the incoming payment credential, including the network\n * family. Returns `null` when no wallet signature is present (e.g. Stripe SPT, card-only\n * payments, or no credential yet).\n *\n * @param request - the inbound `Request`\n * @param x402PaymentHeader - the value of `payment-signature` or `x-payment` header, if any.\n * Extracted separately because some frameworks (Express) don't expose a web `Request` object.\n */\nexport async function extractPaymentSigner(\n request: Request,\n x402PaymentHeader?: string,\n): Promise<PaymentSigner | null> {\n // MPP — Authorization: Payment <base64>\n const authHeader = request.headers.get('authorization');\n if (authHeader) {\n try {\n const moduleName = 'mppx';\n const mppx = (await import(moduleName).catch(() => null)) as {\n Credential?: {\n extractPaymentScheme: (h: string) => unknown;\n fromRequest: (r: Request) => unknown;\n };\n } | null;\n if (mppx?.Credential?.extractPaymentScheme(authHeader)) {\n const credential = mppx.Credential.fromRequest(request);\n const source = (credential as { source?: string }).source;\n const match = source?.match(/^did:pkh:eip155:\\d+:(0x[0-9a-fA-F]{40})$/);\n if (match) return { address: match[1]!.toLowerCase(), network: 'evm' };\n }\n } catch (err) {\n console.warn('[gate] MPP signer extraction failed:', err instanceof Error ? err.message : err);\n }\n }\n\n // x402 — base64 JSON. Network identifier on `accepted.network` selects the extraction\n // path: `eip155:*` → EIP-3009 `payload.authorization.from`; `solana:*` → SPL Token\n // payer recovered from the encoded transaction.\n if (x402PaymentHeader) {\n try {\n const decoded = atob(x402PaymentHeader);\n const parsed = JSON.parse(decoded) as {\n accepted?: { network?: string };\n payload?: { authorization?: { from?: string }; transaction?: string };\n };\n const network = parsed?.accepted?.network ?? '';\n\n if (network.startsWith('eip155:')) {\n const from = parsed?.payload?.authorization?.from;\n if (typeof from === 'string' && /^0x[0-9a-fA-F]{40}$/.test(from)) {\n return { address: from.toLowerCase(), network: 'evm' };\n }\n } else if (network.startsWith('solana:')) {\n const transaction = parsed?.payload?.transaction;\n if (typeof transaction === 'string') {\n const moduleName = '@x402/svm';\n const svm = (await import(moduleName).catch(() => null)) as {\n decodeTransactionFromPayload?: (p: { transaction: string }) => unknown;\n getTokenPayerFromTransaction?: (tx: unknown) => string | undefined;\n } | null;\n if (svm?.decodeTransactionFromPayload && svm.getTokenPayerFromTransaction) {\n const tx = svm.decodeTransactionFromPayload({ transaction });\n const payer = svm.getTokenPayerFromTransaction(tx);\n if (typeof payer === 'string' && payer.length > 0) return { address: payer, network: 'solana' };\n }\n }\n } else {\n // Back-compat: a payload without an `accepted.network` field still uses EIP-3009\n // shape if `payload.authorization.from` looks EVM. Older x402 clients emitted these.\n const from = parsed?.payload?.authorization?.from;\n if (typeof from === 'string' && /^0x[0-9a-fA-F]{40}$/.test(from)) {\n return { address: from.toLowerCase(), network: 'evm' };\n }\n }\n } catch (err) {\n console.warn('[gate] x402 signer extraction failed:', err instanceof Error ? err.message : err);\n }\n }\n\n return null;\n}\n\n/**\n * Address-only convenience over {@link extractPaymentSigner}. Used by the gate adapters\n * (verifyWalletSignerMatch) where only the address matters for operator comparison.\n */\nexport async function extractPaymentSignerAddress(\n request: Request,\n x402PaymentHeader?: string,\n): Promise<string | null> {\n const result = await extractPaymentSigner(request, x402PaymentHeader);\n return result?.address ?? null;\n}\n\n/**\n * Read the x402 payment header from a `Request`, matching the alternate names merchants might\n * use. Falls back to reading either header directly.\n */\nexport function readX402PaymentHeader(request: Request): string | undefined {\n return (\n request.headers.get('payment-signature') ??\n request.headers.get('x-payment') ??\n undefined\n );\n}\n","import {\n FIXABLE_DENIAL_REASONS,\n buildContactSupportNextSteps,\n buildSignerMismatchBody,\n denialReasonStatus,\n isFixableDenial,\n verificationAgentInstructions,\n} from '../_denial';\nimport { denialReasonToBody } from '../_response';\nimport { createAgentScoreCore } from '../core';\nimport { extractPaymentSignerAddress, readX402PaymentHeader } from '../signer';\nimport type {\n AgentIdentity,\n AgentScoreCoreOptions,\n AgentScoreData,\n CreateSessionOnMissing,\n DenialReason,\n VerifyWalletSignerResult,\n} from '../core';\n\nexport interface AgentScoreGateOptions extends Omit<AgentScoreCoreOptions, 'createSessionOnMissing'> {\n /** Custom function to extract agent identity from a Request. */\n extractIdentity?: (req: Request) => AgentIdentity | undefined;\n /** Custom handler invoked when a request is denied. Must return a Response. */\n onDenied?: (req: Request, reason: DenialReason) => Response | Promise<Response>;\n /** Auto-create a verification session on missing identity. Hooks receive the `Request`. */\n createSessionOnMissing?: CreateSessionOnMissing<Request>;\n}\n\n/**\n * Result of a gate check. `allowed: true` means the request passed; forward it to your\n * handler. `allowed: false` means it was denied; return `response` directly to the client.\n *\n * When the request was authenticated via `operator_token`, `captureWallet` is bound to the\n * identity and can be called after payment to report the signer wallet back to AgentScore.\n * When the request was wallet-authenticated (nothing to associate), `captureWallet` is\n * undefined. Always fire-and-forget.\n */\nexport type GuardResult =\n | {\n allowed: true;\n data?: AgentScoreData;\n captureWallet?: (opts: {\n walletAddress: string;\n network: 'evm' | 'solana';\n idempotencyKey?: string;\n }) => Promise<void>;\n /** Verify the payment signer matches the claimed X-Wallet-Address. Bound only when\n * the request was wallet-authenticated. Pass `opts.signer` explicitly or omit to\n * auto-extract from the original `Request`. */\n verifyWalletSignerMatch?: (opts?: {\n signer?: string | null;\n network?: 'evm' | 'solana';\n }) => Promise<VerifyWalletSignerResult>;\n }\n | { allowed: false; response: Response };\n\nfunction defaultExtractIdentity(req: Request): AgentIdentity | undefined {\n const token = req.headers.get('x-operator-token');\n const addr = req.headers.get('x-wallet-address');\n const identity: AgentIdentity = {};\n if (token && token.length > 0) identity.operatorToken = token;\n if (addr && addr.length > 0) identity.address = addr;\n if (identity.operatorToken || identity.address) return identity;\n return undefined;\n}\n\nfunction defaultOnDenied(_req: Request, reason: DenialReason): Response {\n return new Response(JSON.stringify(denialReasonToBody(reason)), {\n status: denialReasonStatus(reason),\n headers: { 'content-type': 'application/json' },\n });\n}\n\n/**\n * Create a Web Fetch-compatible gate. Works with any runtime that speaks the standard\n * Request/Response API: Cloudflare Workers, Deno Deploy, Bun, Next.js App Router, etc.\n *\n * ```ts\n * const guard = createAgentScoreGate({ apiKey: 'as_live_...', requireKyc: true });\n *\n * export default {\n * async fetch(req: Request) {\n * const result = await guard(req);\n * if (!result.allowed) return result.response;\n * return handle(req, result.data);\n * },\n * };\n * ```\n */\nexport function createAgentScoreGate(options: AgentScoreGateOptions): (req: Request) => Promise<GuardResult> {\n const { extractIdentity = defaultExtractIdentity, onDenied = defaultOnDenied, ...coreOptions } = options;\n const core = createAgentScoreCore(coreOptions as AgentScoreCoreOptions);\n\n return async (req: Request): Promise<GuardResult> => {\n const identity = extractIdentity(req);\n const outcome = await core.evaluate(identity, req);\n\n if (outcome.kind === 'allow') {\n const captureWallet = identity?.operatorToken\n ? (opts: { walletAddress: string; network: 'evm' | 'solana'; idempotencyKey?: string }) =>\n core.captureWallet({ operatorToken: identity.operatorToken!, ...opts })\n : undefined;\n // Section IV: token wins when both headers sent — bind helper only on strict wallet-auth.\n const verifyWalletSignerMatchBound = identity?.address && !identity?.operatorToken\n ? async (opts?: { signer?: string | null; network?: 'evm' | 'solana' }) => {\n const signer =\n opts?.signer !== undefined\n ? opts.signer\n : await extractPaymentSignerAddress(req, readX402PaymentHeader(req));\n return core.verifyWalletSignerMatch({\n claimedWallet: identity.address!,\n signer,\n network: opts?.network,\n });\n }\n : undefined;\n return {\n allowed: true,\n data: outcome.data,\n captureWallet,\n verifyWalletSignerMatch: verifyWalletSignerMatchBound,\n };\n }\n\n const response = await onDenied(req, outcome.reason);\n return { allowed: false, response };\n };\n}\n\n/**\n * Wrap a Web Fetch request handler with the gate. Denied requests are returned directly;\n * allowed requests are passed to `handler` along with the assess data.\n *\n * ```ts\n * export const POST = withAgentScoreGate(\n * { apiKey: 'as_live_...', requireKyc: true },\n * async (req, { data }) => Response.json({ ok: true }),\n * );\n * ```\n */\nexport function withAgentScoreGate<TCtx = unknown>(\n options: AgentScoreGateOptions,\n handler: (\n req: Request,\n gate: {\n data?: AgentScoreData;\n captureWallet?: (opts: {\n walletAddress: string;\n network: 'evm' | 'solana';\n idempotencyKey?: string;\n }) => Promise<void>;\n verifyWalletSignerMatch?: (opts?: {\n signer?: string | null;\n network?: 'evm' | 'solana';\n }) => Promise<VerifyWalletSignerResult>;\n },\n ctx?: TCtx,\n ) => Response | Promise<Response>,\n): (req: Request, ctx?: TCtx) => Promise<Response> {\n const guard = createAgentScoreGate(options);\n return async (req, ctx) => {\n const result = await guard(req);\n if (!result.allowed) return result.response;\n return handler(\n req,\n {\n data: result.data,\n captureWallet: result.captureWallet,\n verifyWalletSignerMatch: result.verifyWalletSignerMatch,\n },\n ctx,\n );\n };\n}\n\nexport { extractPaymentSignerAddress, readX402PaymentHeader };\nexport {\n FIXABLE_DENIAL_REASONS,\n buildContactSupportNextSteps,\n buildSignerMismatchBody,\n denialReasonStatus,\n isFixableDenial,\n verificationAgentInstructions,\n};\nexport { denialReasonToBody };\n"],"mappings":";AA2BO,IAAM,yBAA8C,oBAAI,IAAI;AAAA,EACjE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAUM,SAAS,gBAAgB,SAAiD;AAC/E,MAAI,CAAC,WAAW,QAAQ,WAAW,EAAG,QAAO;AAC7C,SAAO,QAAQ,MAAM,CAAC,MAAM,uBAAuB,IAAI,CAAC,CAAC;AAC3D;AAUO,SAAS,mBAAmB,QAAuC;AACxE,MAAI,OAAO,SAAS,mBAAmB,OAAO,SAAS,qBAAsB,QAAO;AACpF,MAAI,OAAO,SAAS,YAAa,QAAO;AACxC,SAAO;AACT;AAuBO,SAAS,wBAAwB,OAAgE;AACtG,QAAM,EAAE,OAAO,IAAI;AACnB,MAAI,OAAO,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, AgentMemoryHint, AgentScoreCore, AgentScoreCoreOptions, CreateSessionOnMissing, DenialCode, DenialReason, EvaluateOutcome, VerifyWalletSignerMatchOptions, VerifyWalletSignerResult, buildAgentMemoryHint } from './core.mjs';
3
+ export { P as PaymentSigner, S as SignerNetwork, a as extractPaymentSigner, e as extractPaymentSignerAddress, r as readX402PaymentHeader } from './signer-Cvdwn6Cs.mjs';
4
+ export { F as FIXABLE_DENIAL_REASONS, b as buildContactSupportNextSteps, a as buildSignerMismatchBody, d as denialReasonStatus, c as denialReasonToBody, i as isFixableDenial, v as verificationAgentInstructions } from './_response-DmziuJz6.mjs';
5
+ export { EnforcementMode, GateResult, IdentityStatus, PolicyBlock, policyToGateOptions, runGateWithEnforcement, shippingCountryAllowed, shippingStateAllowed } from './identity/policy.mjs';
6
+
7
+ /**
8
+ * Google A2A (Agent-to-Agent) Signed Agent Cards builder.
9
+ *
10
+ * Compose the JSON payload for an A2A v1.0 Signed Agent Card that includes the
11
+ * agent's AgentScore identity claims. Returned object is the unsigned card body —
12
+ * the merchant (or agent) signs it with their wallet / signing key before publishing.
13
+ *
14
+ * Why publish: A2A is a Linux Foundation standard with 150+ orgs (Microsoft, AWS,
15
+ * Salesforce in production). Signed Agent Cards let any A2A-compatible reader discover
16
+ * an agent's verified-identity claims without per-platform integration. AgentScore
17
+ * publishing operator identity in this format means our identity travels with the agent
18
+ * across A2A-aware ecosystems.
19
+ *
20
+ * Spec reference: https://a2a-protocol.org/latest/
21
+ */
22
+
23
+ interface A2AAgentCardCapabilities {
24
+ /** Endpoints the agent exposes — `[{ name: "purchase", path: "/purchase", method: "POST" }, ...]`. */
25
+ endpoints?: {
26
+ name: string;
27
+ path?: string;
28
+ method?: string;
29
+ }[];
30
+ /** Free-form skill tags — `["wine-purchase", "regulated-commerce", ...]`. */
31
+ skills?: string[];
32
+ }
33
+ interface A2AAgentCardIdentity {
34
+ /** Issuer of the identity claims — always `"https://agentscore.sh"` for the AgentScore-issued card. */
35
+ issuer: string;
36
+ /** Operator id under AgentScore. */
37
+ operator_id: string;
38
+ /** KYC tier. */
39
+ kyc_level: string;
40
+ /** Sanctions screening result. */
41
+ sanctions_clear: boolean;
42
+ /** Age bracket. */
43
+ age_bracket: string;
44
+ /** Jurisdiction (ISO-3166-1 alpha-2 or empty). */
45
+ jurisdiction: string;
46
+ /** ISO-8601 timestamp of last verification refresh. */
47
+ verified_at: string | null;
48
+ /** Verify URL where the identity was minted. */
49
+ verify_url: string;
50
+ }
51
+ interface A2AAgentCard {
52
+ /** A2A protocol version. v1.0 was donated to Linux Foundation. */
53
+ protocol_version: string;
54
+ /** Card schema version (this builder emits v1). */
55
+ card_version: number;
56
+ /** Agent's display name. */
57
+ name: string;
58
+ /** One-line description shown to A2A consumers. */
59
+ description?: string;
60
+ /** Agent's canonical URL (homepage, Discord, repo, etc.). */
61
+ url?: string;
62
+ /** Agent capabilities — endpoints + skills. */
63
+ capabilities?: A2AAgentCardCapabilities;
64
+ /** AgentScore identity claims. Empty `null` when no identity is available (pre-KYC). */
65
+ identity: A2AAgentCardIdentity | null;
66
+ /** Vendor-specific extras merged at the top level. */
67
+ extras?: Record<string, unknown>;
68
+ }
69
+ interface BuildA2AAgentCardInput {
70
+ /** Display name for the agent — `"Martin Estate Wine Concierge"`, etc. */
71
+ name: string;
72
+ /** Optional one-line description. */
73
+ description?: string;
74
+ /** Agent's canonical URL. */
75
+ url?: string;
76
+ /** Capabilities — endpoints exposed + skill tags. */
77
+ capabilities?: A2AAgentCardCapabilities;
78
+ /** AgentScore assess data — what `getAgentScoreData(c)` returns or what `assess()` returned directly.
79
+ * Pass `null` to emit a card with no identity claims (publishable but unverified). */
80
+ data?: AgentScoreData | null;
81
+ /** Override the default issuer URL. Default `"https://agentscore.sh"`. */
82
+ issuer?: string;
83
+ /** Override the verify URL. */
84
+ verifyUrl?: string;
85
+ /** Vendor-specific extras merged at the card top level. */
86
+ extras?: Record<string, unknown>;
87
+ }
88
+ /**
89
+ * Compose an A2A Signed Agent Card body with AgentScore identity claims included.
90
+ *
91
+ * Returns the UNSIGNED card. The vendor signs it with their wallet (typically using
92
+ * the same wallet they use for x402 / MPP payments) and publishes the signed envelope
93
+ * to wherever A2A consumers discover cards (a hosted endpoint, on-chain registry,
94
+ * agent-card-server, etc.). Signing is vendor-side because the agent's signing key
95
+ * never leaves their environment.
96
+ *
97
+ * Example:
98
+ * ```ts
99
+ * import { buildA2AAgentCard } from '@agent-score/commerce/identity/hono';
100
+ *
101
+ * app.get('/.well-known/agent-card', async (c) => {
102
+ * const data = getAgentScoreData(c);
103
+ * const card = buildA2AAgentCard({
104
+ * name: 'Martin Estate Wine Concierge',
105
+ * description: 'Buy regulated wines from Martin Estate via agent payments.',
106
+ * url: 'https://agents.martinestate.com',
107
+ * capabilities: {
108
+ * endpoints: [{ name: 'purchase', path: '/purchase', method: 'POST' }],
109
+ * skills: ['wine-purchase', 'regulated-commerce'],
110
+ * },
111
+ * data,
112
+ * });
113
+ * const signed = await yourSign(card);
114
+ * return c.json(signed);
115
+ * });
116
+ * ```
117
+ */
118
+ declare function buildA2AAgentCard(input: BuildA2AAgentCardInput): A2AAgentCard;
119
+
120
+ /**
121
+ * UCP (Universal Commerce Protocol) profile builder.
122
+ *
123
+ * Compose the JSON payload published at `/.well-known/ucp` per the UCP spec, with
124
+ * AgentScore identity claims attached as a capability. Returned object is the unsigned
125
+ * profile body — the merchant signs it (or wraps it in their JWKS-backed envelope)
126
+ * before publishing.
127
+ *
128
+ * Why publish: UCP is the Google-led cross-vendor standard (announced Jan 2026 at NRF
129
+ * with Shopify, Etsy, Wayfair, Target, Walmart, Adyen, Mastercard, Stripe, Visa, Amex,
130
+ * etc.). Every UCP-aware platform discovers a merchant via `/.well-known/ucp`, so
131
+ * shipping this profile means AgentScore-gated merchants are discoverable through the
132
+ * same surface every other UCP merchant uses.
133
+ *
134
+ * Spec reference: https://ucp.dev/
135
+ *
136
+ * UCP profiles do NOT carry KYC / sanctions / age / jurisdiction claims natively —
137
+ * identity in the UCP spec is "who signed this" (JWKS-backed). AgentScore claims layer
138
+ * over UCP via a custom capability so consumers who care about verified-buyer identity
139
+ * can read them; consumers who don't care just see a normal UCP profile.
140
+ */
141
+
142
+ interface UCPSigningKey {
143
+ /** JWK kid (key id). */
144
+ kid: string;
145
+ /** JWK kty (key type) — typically `EC`, `RSA`, or `OKP`. */
146
+ kty: string;
147
+ /** JWK alg (signing algorithm) — typically `ES256`, `RS256`, or `EdDSA`. */
148
+ alg?: string;
149
+ /** JWK use — typically `sig`. */
150
+ use?: string;
151
+ /** JWK crv (curve) for EC / OKP keys. */
152
+ crv?: string;
153
+ /** JWK x / y / n / e / etc. The full key material; passed through verbatim. */
154
+ [k: string]: unknown;
155
+ }
156
+ interface UCPService {
157
+ /** Transport binding — `rest` / `mcp` / `a2a` / `embedded`. */
158
+ type: string;
159
+ /** Service URL (or path for embedded). */
160
+ url?: string;
161
+ /** Optional version pin. */
162
+ version?: string;
163
+ /** Vendor-specific extras for the binding. */
164
+ [k: string]: unknown;
165
+ }
166
+ interface UCPCapability {
167
+ /** Capability name — `checkout`, `catalog`, `agentscore-identity`, etc. */
168
+ name: string;
169
+ /** URL of the JSON Schema describing this capability's payload. */
170
+ schema?: string;
171
+ /** Capability version — semver or date-stamp per UCP convention. */
172
+ version?: string;
173
+ /** Vendor-specific extras for the capability. */
174
+ [k: string]: unknown;
175
+ }
176
+ interface UCPPaymentHandler {
177
+ /** Handler name — `stripe`, `tempo`, `x402-base`, `x402-solana`, etc. */
178
+ name: string;
179
+ /** Handler config — recipient address, profile id, etc. */
180
+ config?: Record<string, unknown>;
181
+ }
182
+ interface UCPProfile {
183
+ /** UCP spec version (date-stamped). */
184
+ version: string;
185
+ /** URL of the UCP spec. */
186
+ spec: string;
187
+ /** URL of this profile's JSON schema. */
188
+ schema?: string;
189
+ /** Display name of the merchant / agent surface. */
190
+ name?: string;
191
+ /** Service bindings — REST, MCP, A2A, embedded transports. */
192
+ services: UCPService[];
193
+ /** Capabilities offered (with schema URLs). */
194
+ capabilities: UCPCapability[];
195
+ /** Payment handlers offered — typically the rails the merchant accepts. */
196
+ payment_handlers: UCPPaymentHandler[];
197
+ /** JWKS — REQUIRED by spec. The merchant signs requests with a private key whose
198
+ * public counterpart is listed here. Verifiers fetch this profile, find the kid, and
199
+ * validate signatures. */
200
+ signing_keys: UCPSigningKey[];
201
+ /** Vendor-specific extras at the top level. */
202
+ [k: string]: unknown;
203
+ }
204
+ interface BuildUCPProfileInput {
205
+ /** UCP spec version. Default `"2026-04-17"` (current at time of writing). */
206
+ version?: string;
207
+ /** Display name for the merchant / agent surface. */
208
+ name?: string;
209
+ /** Service transport bindings. At minimum, the agent's primary REST endpoint. */
210
+ services: UCPService[];
211
+ /** Capabilities offered. AgentScore identity is auto-added as a capability when `data` is provided. */
212
+ capabilities?: UCPCapability[];
213
+ /** Payment handlers — rails the merchant accepts. */
214
+ payment_handlers?: UCPPaymentHandler[];
215
+ /** JWKS — public keys the merchant signs requests with. REQUIRED by spec. */
216
+ signing_keys: UCPSigningKey[];
217
+ /** AgentScore assess data — adds an `agentscore-identity` capability + claims block when present. */
218
+ data?: AgentScoreData | null;
219
+ /** Optional override for the AgentScore capability schema URL. */
220
+ agentscoreSchemaUrl?: string;
221
+ /** Vendor-specific extras at the top level. */
222
+ extras?: Record<string, unknown>;
223
+ }
224
+ /**
225
+ * Compose a UCP profile body for `/.well-known/ucp` publication. Merges AgentScore
226
+ * identity claims into the `capabilities` array as an `agentscore-identity` capability
227
+ * so UCP-aware consumers can discover verified-buyer claims alongside the standard
228
+ * UCP transport metadata.
229
+ *
230
+ * Example:
231
+ * ```ts
232
+ * import { buildUCPProfile } from '@agent-score/commerce/identity/hono';
233
+ *
234
+ * app.get('/.well-known/ucp', async (c) => {
235
+ * const data = getAgentScoreData(c);
236
+ * return c.json(buildUCPProfile({
237
+ * name: 'Martin Estate',
238
+ * services: [{ type: 'rest', url: 'https://agents.martinestate.com' }],
239
+ * payment_handlers: [
240
+ * { name: 'tempo', config: { recipient: TEMPO_ADDR } },
241
+ * { name: 'stripe', config: { profile_id: STRIPE_PROFILE_ID } },
242
+ * ],
243
+ * signing_keys: [{ kid: 'me-2026-04', kty: 'EC', alg: 'ES256', crv: 'P-256', x: '...', y: '...' }],
244
+ * data,
245
+ * }));
246
+ * });
247
+ * ```
248
+ */
249
+ declare function buildUCPProfile(input: BuildUCPProfileInput): UCPProfile;
250
+ declare const AGENTSCORE_UCP_CAPABILITY = "agentscore-identity";
251
+
252
+ export { type A2AAgentCard, type A2AAgentCardCapabilities, type A2AAgentCardIdentity, AGENTSCORE_UCP_CAPABILITY, AgentScoreData, type BuildA2AAgentCardInput, type BuildUCPProfileInput, type UCPCapability, type UCPPaymentHandler, type UCPProfile, type UCPService, type UCPSigningKey, buildA2AAgentCard, buildUCPProfile };