@devlab.group/agent-commerce 2.1.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -5
- package/dist/ap2.js +3 -3
- package/dist/{chunk-SY6GUYSQ.js → chunk-7ZMMXZ4G.js} +3 -3
- package/dist/{chunk-SY6GUYSQ.js.map → chunk-7ZMMXZ4G.js.map} +1 -1
- package/dist/{chunk-UHMYRV3J.js → chunk-HNRDZLSN.js} +7 -5
- package/dist/chunk-HNRDZLSN.js.map +1 -0
- package/dist/{chunk-LZS5BL3W.js → chunk-IEW7NSP2.js} +23 -5
- package/dist/chunk-IEW7NSP2.js.map +1 -0
- package/dist/{chunk-IFGRCXME.js → chunk-Y4RE3XYF.js} +3 -3
- package/dist/{chunk-IFGRCXME.js.map → chunk-Y4RE3XYF.js.map} +1 -1
- package/dist/cli/ap2-MBMQHFX4.js +678 -0
- package/dist/cli/ap2-MBMQHFX4.js.map +1 -0
- package/dist/cli/chunk-2ZZOGI5I.js +1352 -0
- package/dist/cli/chunk-2ZZOGI5I.js.map +1 -0
- package/dist/cli/chunk-3EQBCFZY.js +53 -0
- package/dist/cli/chunk-3EQBCFZY.js.map +1 -0
- package/dist/cli/chunk-3M6U7ILB.js +8 -0
- package/dist/cli/chunk-3M6U7ILB.js.map +1 -0
- package/dist/cli/chunk-3MGAJ5FX.js +70 -0
- package/dist/cli/chunk-3MGAJ5FX.js.map +1 -0
- package/dist/cli/chunk-5K4XEAZV.js +113 -0
- package/dist/cli/chunk-5K4XEAZV.js.map +1 -0
- package/dist/cli/chunk-7JNYFUT3.js +256 -0
- package/dist/cli/chunk-7JNYFUT3.js.map +1 -0
- package/dist/cli/chunk-AA3FIEAR.js +27 -0
- package/dist/cli/chunk-AA3FIEAR.js.map +1 -0
- package/dist/cli/chunk-FHCFR2GS.js +17 -0
- package/dist/cli/chunk-FHCFR2GS.js.map +1 -0
- package/dist/cli/chunk-FRMLWGSS.js +8 -0
- package/dist/cli/chunk-FRMLWGSS.js.map +1 -0
- package/dist/cli/chunk-KLX2YZDG.js +1400 -0
- package/dist/cli/chunk-KLX2YZDG.js.map +1 -0
- package/dist/cli/chunk-NSPPEF5M.js +334 -0
- package/dist/cli/chunk-NSPPEF5M.js.map +1 -0
- package/dist/cli/chunk-OSTCU6ZK.js +44 -0
- package/dist/cli/chunk-OSTCU6ZK.js.map +1 -0
- package/dist/cli/chunk-QQ3WY5L3.js +271 -0
- package/dist/cli/chunk-QQ3WY5L3.js.map +1 -0
- package/dist/cli/chunk-RWVPYAKC.js +1742 -0
- package/dist/cli/chunk-RWVPYAKC.js.map +1 -0
- package/dist/cli/chunk-SPAYKVUP.js +118 -0
- package/dist/cli/chunk-SPAYKVUP.js.map +1 -0
- package/dist/cli/chunk-SS3QFF5N.js +614 -0
- package/dist/cli/chunk-SS3QFF5N.js.map +1 -0
- package/dist/cli/chunk-TPC4EJLT.js +11 -0
- package/dist/cli/chunk-TPC4EJLT.js.map +1 -0
- package/dist/cli/config-4IBGVFSP.js +11 -0
- package/dist/cli/config-4IBGVFSP.js.map +1 -0
- package/dist/cli/index.js +150 -3627
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/mcp-CNWQ2MOE.js +559 -0
- package/dist/cli/mcp-CNWQ2MOE.js.map +1 -0
- package/dist/cli/near-5AY3HWYF.js +58 -0
- package/dist/cli/near-5AY3HWYF.js.map +1 -0
- package/dist/cli/provider-4BQDH56Y.js +396 -0
- package/dist/cli/provider-4BQDH56Y.js.map +1 -0
- package/dist/cli/run-5MB2D45X.js +7286 -0
- package/dist/cli/run-5MB2D45X.js.map +1 -0
- package/dist/cli/svm-3MMYFPC7.js +33 -0
- package/dist/cli/svm-3MMYFPC7.js.map +1 -0
- package/dist/cli/x402-NKR3WQDQ.js +96 -0
- package/dist/cli/x402-NKR3WQDQ.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +48 -5
- package/dist/index.js.map +1 -1
- package/dist/mcp.js +6 -16
- package/dist/mcp.js.map +1 -1
- package/dist/mpp.js +3 -3
- package/dist/x402.d.ts +5 -0
- package/dist/x402.js +4 -4
- package/package.json +2 -2
- package/dist/chunk-LZS5BL3W.js.map +0 -1
- package/dist/chunk-UHMYRV3J.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config/env.ts","../src/config/filename.ts","../src/protocols/acp/constants.ts","../src/config/schema/values.ts","../src/config/schema/acp.ts","../src/config/schema/ap2.ts","../src/config/schema/x402.ts","../src/config/schema/mpp.ts","../src/config/schema/raw.ts","../src/core/execution/backend-request.ts","../src/core/execution/backend-http.ts","../src/core/execution/validation.ts","../src/core/execution/pipeline/authorization.ts","../src/core/execution/pipeline/challenge.ts","../src/core/execution/pipeline/admission.ts","../src/core/execution/pipeline/context.ts","../src/core/execution/pipeline/settlement.ts","../src/core/execution/pipeline/index.ts","../src/core/execution/registry.ts","../src/core/execution/store-event-sink.ts","../src/config/schema/backend.ts","../src/config/schema/resource-schema.ts","../src/config/schema/resources.ts","../src/config/schema/normalize.ts","../src/config/schema/index.ts","../src/config/load.ts","../src/gateway/access-control.ts","../src/gateway/adapters.ts","../src/gateway/ids.ts","../src/gateway/logger.ts","../src/gateway/public-resource.ts","../src/gateway/readiness.ts","../src/gateway/well-known.ts","../src/gateway/routes.ts","../src/gateway/server.ts","../src/protocols/a2a/constants.ts","../src/protocols/a2a/jsonrpc.ts","../src/protocols/a2a/message-mapping.ts","../src/protocols/a2a/x402-extension.ts","../src/protocols/a2a/agent-card.ts","../src/protocols/a2a/descriptor.ts","../src/protocols/a2a/task-mapping.ts","../src/protocols/a2a/payment-resume.ts","../src/protocols/a2a/adapter.ts","../src/protocols/acp/checkout-mapping.ts","../src/protocols/acp/descriptor.ts","../src/protocols/acp/discovery.ts","../src/protocols/acp/errors.ts","../src/protocols/acp/idempotency/fingerprint.ts","../src/protocols/acp/idempotency/store.ts","../src/protocols/acp/router.ts","../src/protocols/acp/spec/2026-04-17/schema.agentic_checkout.json","../src/protocols/acp/validation.ts","../src/protocols/acp/request-guards.ts","../src/protocols/acp/response-mapping.ts","../src/protocols/acp/adapter.ts","../src/storage/receipts/redact.ts","../src/storage/receipts/rows.ts","../src/storage/receipts/schema.ts","../src/storage/receipts/store.ts"],"names":["path","options","url","invalid","durationMs","validators","flowOverrides","fs","parseYaml","value","header","z","task","buildDescriptor","createHash","changes","failure","SCHEMA_VERSION","migrate","randomUUID","fsConstants"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqBA,IAAM,mBAAA,GAAsB,6CAAA;AAG5B,IAAM,WAAA,GAAc,eAAA;AAGpB,IAAM,eAAA,GAAkB,0CAAA;AAGxB,IAAM,kBAAA,GAAqB,gBAAA;AAEpB,SAAS,aAAA,CAAc,KAAA,EAAgB,GAAA,EAAwBA,KAAAA,GAAO,GAAA,EAAc;AACzF,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,gBAAA,CAAiB,KAAA,EAAO,GAAA,EAAKA,KAAI,CAAA;AAAA,EAC1C;AACA,EAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,EAAG;AACxB,IAAA,OAAO,KAAA,CAAM,GAAA,CAAI,CAAC,KAAA,EAAO,KAAA,KAAU,aAAA,CAAc,KAAA,EAAO,GAAA,EAAK,CAAA,EAAGA,KAAI,CAAA,CAAA,EAAI,KAAK,GAAG,CAAC,CAAA;AAAA,EACnF;AACA,EAAA,IAAI,QAAA,CAAS,KAAK,CAAA,EAAG;AACnB,IAAA,MAAM,SAAkC,EAAC;AACzC,IAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,EAAG;AAChD,MAAA,MAAA,CAAO,GAAG,IAAI,aAAA,CAAc,KAAA,EAAO,KAAK,CAAA,EAAGA,KAAI,CAAA,CAAA,EAAI,GAAG,CAAA,CAAE,CAAA;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AAA,IACF;AAAA,GACF;AAEA,EAAA,OAAO,KAAA;AACT","file":"index.js","sourcesContent":["/**\n * `${VAR}` / `${VAR:-default}` substitution over a parsed YAML value.\n *\n * Only string leaves change; the caller coerces numeric and boolean strings\n * afterwards. `${VAR}` requires `VAR` in `env`, where an empty string counts as\n * present. `${VAR:-default}` uses `default` when `VAR` is absent or empty, as a\n * shell does. An unresolved placeholder fails config loading, so startup never\n * proceeds with a missing secret. There is no escape for a literal `${NAME}`.\n *\n * Anything else brace-shaped is refused, including nesting (`${A:-${B}}`) and\n * shell forms (`${VAR-x}`, `${VAR:=x}`, `${VAR:?x}`) that would otherwise load\n * as literal text: `adminToken: ${ADMIN_TOKEN-fallback}` would make that\n * literal the ledger credential. A bare `$VAR` is left alone, so values may\n * contain a dollar sign.\n *\n * The template rules are checked before substitution, and errors name the\n * variable and the config path, never a resolved value.\n */\nimport { CommerceError } from '../core';\nimport { isRecord } from '../core/is-record';\n\nconst PLACEHOLDER_PATTERN = /\\$\\{([A-Za-z_][A-Za-z0-9_]*)(:-([^}]*))?\\}/g;\n\n// An innermost brace token: `${`, then no braces, then `}`\nconst BRACE_TOKEN = /\\$\\{[^{}]*\\}/g;\n\n// PLACEHOLDER_PATTERN's grammar, anchored, for validating one token\nconst SUPPORTED_TOKEN = /^\\$\\{[A-Za-z_][A-Za-z0-9_]*(:-[^}]*)?\\}$/;\n\n// A placeholder whose default segment opens another placeholder\nconst NESTED_PLACEHOLDER = /\\$\\{[^{}]*\\$\\{/;\n\nexport function substituteEnv(value: unknown, env: NodeJS.ProcessEnv, path = '$'): unknown {\n if (typeof value === 'string') {\n return substituteString(value, env, path);\n }\n if (Array.isArray(value)) {\n return value.map((entry, index) => substituteEnv(entry, env, `${path}[${index}]`));\n }\n if (isRecord(value)) {\n const result: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n result[key] = substituteEnv(entry, env, `${path}.${key}`);\n }\n return result;\n }\n return value;\n}\n\nfunction substituteString(value: string, env: NodeJS.ProcessEnv, path: string): string {\n assertTemplateIsSupported(value, path);\n return substituteOnce(value, env, path);\n}\n\n/**\n * Refuses a template this module cannot honor, before any substitution runs.\n *\n * For `${A:-${B}}`, `[^}]*` cannot span the inner `}`, so the match consumes\n * `${A:-${B` and leaves a stray `}`. With `A` set, substitution would succeed\n * and append that `}` to the value unnoticed, so `adminToken` would become a\n * credential the operator does not hold.\n */\nfunction assertTemplateIsSupported(value: string, path: string): void {\n if (NESTED_PLACEHOLDER.test(value)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" nests placeholders (e.g. \"\\${A:-\\${B}}\"), which is not supported: the inner one is not resolved and its closing brace ends up in the value. Use a plain default, or set the variable.`,\n { details: { path } },\n );\n }\n\n for (const [token] of value.matchAll(BRACE_TOKEN)) {\n if (SUPPORTED_TOKEN.test(token)) continue;\n // Quotes the token, not the value; before substitution it holds no secret\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" contains \"${token}\", which is not a supported placeholder. Only \"\\${VAR}\" and \"\\${VAR:-default}\" are recognized; shell forms such as \"\\${VAR-default}\", \"\\${VAR:=default}\" and \"\\${VAR:?message}\" would load as literal text.`,\n { details: { path, token } },\n );\n }\n}\n\nfunction substituteOnce(value: string, env: NodeJS.ProcessEnv, path: string): string {\n return value.replace(\n PLACEHOLDER_PATTERN,\n (_match, name: string, hasDefault: string | undefined, def: string | undefined) => {\n const envValue = env[name];\n\n if (hasDefault !== undefined) {\n if (envValue === undefined || envValue === '') return def ?? '';\n return envValue;\n }\n\n if (envValue === undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Unresolved environment variable \"\\${${name}}\" referenced at config path \"${path}\"`,\n { details: { variable: name, path } },\n );\n }\n return envValue;\n },\n );\n}\n","/**\n * The default configuration filename, shared by the loader, `init`'s default\n * output path and the `--config` help text.\n *\n * Its own module with no imports: `src/cli` loads the rest of `src/config`\n * only through a dynamic import (`src/cli/lib/config-client.ts`), so a broken\n * config module cannot take down commands that never read configuration. A\n * leaf with no module graph can be imported statically without undoing that.\n */\nexport const DEFAULT_CONFIG_FILENAME = 'config.yaml';\n","/**\n * ACP protocol constants shared by the config layer and the adapter.\n *\n * Kept dependency-free: `src/config` reads the operation set at load time, so\n * anything imported here would become a config-load dependency too.\n */\n\n/**\n * The ACP stable snapshot this adapter implements, and the only value accepted\n * in the `API-Version` request header. Both name the same released snapshot;\n * they are separate constants because ACP versions the wire contract and the\n * header independently, and a future snapshot may accept more than one.\n *\n * Changing either means vendoring a new schema directory beside\n * `spec/2026-04-17/` - never editing the vendored one in place.\n */\nexport const ACP_SPEC_VERSION = '2026-04-17';\nexport const ACP_API_VERSION = '2026-04-17';\n\n/** Discovery path fixed by the ACP specification, never a configurable mount */\nexport const ACP_WELL_KNOWN_PATH = '/.well-known/acp.json';\n\n/**\n * The stable checkout operations, by ACP operation id. All five are required\n * when ACP is enabled: a partially configured checkout lifecycle would be\n * advertised as a whole service the seller cannot actually serve.\n */\nexport const ACP_CHECKOUT_OPERATIONS = [\n 'createCheckoutSession',\n 'updateCheckoutSession',\n 'getCheckoutSession',\n 'completeCheckoutSession',\n 'cancelCheckoutSession',\n] as const;\n\nexport type AcpCheckoutOperation = (typeof ACP_CHECKOUT_OPERATIONS)[number];\n\n/**\n * Top-level canonical-input properties each operation always supplies.\n *\n * `path` carries `{ checkout_session_id }`, `body` the ACP request document.\n */\nexport const ACP_OPERATION_INPUT_KEYS: Readonly<\n Record<AcpCheckoutOperation, readonly ('path' | 'body')[]>\n> = {\n createCheckoutSession: ['body'],\n updateCheckoutSession: ['path', 'body'],\n getCheckoutSession: ['path'],\n completeCheckoutSession: ['path', 'body'],\n cancelCheckoutSession: ['path'],\n};\n\n/**\n * Canonical-input properties an operation supplies only when the caller sends\n * them. The pinned schema lets a cancel omit its body, so a bare cancel has no\n * `body`, but one carrying `intent_trace` passes it on.\n */\nexport const ACP_OPERATION_OPTIONAL_INPUT_KEYS: Readonly<\n Partial<Record<AcpCheckoutOperation, readonly 'body'[]>>\n> = {\n cancelCheckoutSession: ['body'],\n};\n\n/** The key inside `path` that carries the checkout session id from the route */\nexport const ACP_SESSION_ID_INPUT_KEY = 'checkout_session_id';\n\n/** Media type for every ACP request and response body */\nexport const ACP_JSON_MEDIA_TYPE = 'application/json';\n\n/**\n * Protocol headers, lowercased as Node delivers them.\n *\n * `API-Version` is mandatory on checkout requests and is never defaulted:\n * answering an unversioned request as if it named the pinned snapshot would be\n * guessing on the caller's behalf about a contract that changes.\n */\nexport const ACP_API_VERSION_HEADER = 'api-version';\nexport const ACP_REQUEST_ID_HEADER = 'request-id';\nexport const ACP_IDEMPOTENCY_KEY_HEADER = 'idempotency-key';\nexport const ACP_IDEMPOTENT_REPLAYED_HEADER = 'idempotent-replayed';\n\n/**\n * Seconds a client is told to wait before retrying a key whose first request is\n * still running. Short: the original is a live HTTP call, not a queue.\n */\nexport const ACP_IN_FLIGHT_RETRY_AFTER_SECONDS = 1;\n\n/**\n * Longest `Request-Id` echoed back. The value is the caller's, so it is\n * bounded and filtered before it is ever written into a response header.\n */\nexport const ACP_MAX_REQUEST_ID_LENGTH = 128;\n\n/** Caller headers forwarded to the merchant; the bearer token stays at the gateway */\nexport const ACP_FORWARDED_HEADERS = [\n 'accept-language',\n 'user-agent',\n ACP_REQUEST_ID_HEADER,\n ACP_API_VERSION_HEADER,\n 'signature',\n 'timestamp',\n] as const;\n\n/** Maximum forwarded header value length; longer values are dropped */\nexport const ACP_MAX_FORWARDED_HEADER_LENGTH = 2048;\n\n/** Fallback and maximum `Retry-After` seconds for merchant 429 or 503 */\nexport const ACP_MERCHANT_RETRY_AFTER_DEFAULT_SECONDS = 5;\nexport const ACP_MERCHANT_RETRY_AFTER_MAX_SECONDS = 300;\n","// Readers for leaves that env substitution may have turned into strings, and addresses\nimport { CommerceError } from '../../core';\nimport { isEvmAddress, isEvmZeroAddress } from '../../payments/x402/addresses';\n\nexport function toNumber(\n value: number | string,\n path: string,\n bounds: { min?: number; max?: number } = {},\n): number {\n // Plain decimal digits only. `Number('')` is 0, which `server.port` accepts\n // (\"let the OS pick\"), so an empty `${PORT:-}` would bind a random port.\n // `Number` also accepts `\"0x50\"` and `\"1e3\"` for fields documented as decimal.\n if (typeof value === 'string' && !/^\\s*\\d+\\s*$/.test(value)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" must be an integer written in decimal digits (got ${value === '' ? 'an empty string' : `\"${value}\"`})`,\n { details: { path } },\n );\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n) || !Number.isInteger(n)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" must be an integer`,\n {\n details: { path },\n },\n );\n }\n if (bounds.min !== undefined && n < bounds.min) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" must be >= ${bounds.min}`,\n {\n details: { path },\n },\n );\n }\n if (bounds.max !== undefined && n > bounds.max) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" must be <= ${bounds.max}`,\n {\n details: { path },\n },\n );\n }\n return n;\n}\n\nexport function toBoolean(value: boolean | string, path: string): boolean {\n if (typeof value === 'boolean') return value;\n const normalized = value.trim().toLowerCase();\n if (normalized === 'true') return true;\n if (normalized === 'false') return false;\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" must be a boolean (\"true\" or \"false\")`,\n { details: { path } },\n );\n}\n\nexport function validateAddress(path: string, value: string): void {\n if (!isEvmAddress(value)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" is not a plausible address (expected \"0x\" followed by 40 hex characters)`,\n { details: { path } },\n );\n }\n if (isEvmZeroAddress(value)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" must not be the zero address`,\n {\n details: { path },\n },\n );\n }\n}\n","// The ACP checkout adapter's settings and its operation-to-resource mapping\nimport { CommerceError, type CommerceResource } from '../../core';\nimport { isRecord } from '../../core/is-record';\nimport {\n ACP_CHECKOUT_OPERATIONS,\n ACP_OPERATION_INPUT_KEYS,\n ACP_OPERATION_OPTIONAL_INPUT_KEYS,\n ACP_SESSION_ID_INPUT_KEY,\n type AcpCheckoutOperation,\n} from '../../protocols/acp/constants';\nimport type { RawConfig } from './raw';\nimport type { AcpProtocolConfig } from './types';\nimport { toBoolean, toNumber } from './values';\n\n// Applied when `protocols.acp` is absent or names no mount\nconst DEFAULT_ACP_MOUNT_PATH = '/acp';\n\n// Idempotency records must outlive ACP's 24-hour retry window, or a replayed\n// key could pass an expired record and run a checkout side effect twice. It is\n// both the default and the floor.\nconst ACP_RETENTION_HOURS = 24;\n\ntype RawAcp = NonNullable<RawConfig['protocols']['acp']>;\n\ntype EnabledAcpConfig = Extract<AcpProtocolConfig, { enabled: true }>;\n\nfunction acpInvalid(\n path: string,\n message: string,\n extra: Record<string, unknown> = {},\n): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, { details: { path, ...extra } });\n}\n\nexport function normalizeAcp(raw: RawAcp | undefined): AcpProtocolConfig {\n const mountPath = raw?.mountPath ?? DEFAULT_ACP_MOUNT_PATH;\n if (raw === undefined || !toBoolean(raw.enabled, 'protocols.acp.enabled')) {\n return { enabled: false, mountPath };\n }\n\n if (raw.auth === undefined) {\n throw acpInvalid(\n 'protocols.acp.auth',\n 'protocols.acp.auth is required when ACP is enabled - every ACP checkout endpoint is authenticated, and \"bearer\" is the only scheme supported in this release',\n );\n }\n if (raw.idempotency === undefined) {\n throw acpInvalid(\n 'protocols.acp.idempotency',\n 'protocols.acp.idempotency is required when ACP is enabled - it names the SQLite file holding checkout idempotency records, and ACP makes the Idempotency-Key mandatory on every checkout POST',\n );\n }\n\n const discovery = raw.discovery;\n\n return {\n enabled: true,\n mountPath,\n auth: raw.auth,\n idempotency: {\n path: raw.idempotency.path,\n retentionHours: toNumber(\n raw.idempotency.retentionHours ?? ACP_RETENTION_HOURS,\n 'protocols.acp.idempotency.retentionHours',\n { min: ACP_RETENTION_HOURS },\n ),\n merchantIdempotent: raw.idempotency.merchantIdempotent ?? false,\n },\n checkout: { operations: normalizeAcpOperations(raw.checkout) },\n // Built key by key so absent metadata stays absent rather than `undefined`\n ...(discovery !== undefined\n ? {\n discovery: {\n ...(discovery.documentationUrl !== undefined\n ? { documentationUrl: discovery.documentationUrl }\n : {}),\n ...(discovery.supportedCurrencies !== undefined\n ? { supportedCurrencies: discovery.supportedCurrencies }\n : {}),\n ...(discovery.supportedLocales !== undefined\n ? { supportedLocales: discovery.supportedLocales }\n : {}),\n ...(discovery.interventionTypes !== undefined\n ? { interventionTypes: discovery.interventionTypes }\n : {}),\n },\n }\n : {}),\n };\n}\n\n// All five operations, each on its own resource. ACP discovery advertises\n// `checkout` as one service, so a partial mapping is refused. Operations differ\n// in method, input and success status, so one resource cannot serve two.\nfunction normalizeAcpOperations(\n checkout: RawAcp['checkout'],\n): Readonly<Record<AcpCheckoutOperation, string>> {\n const configured: Record<string, string> = checkout?.operations ?? {};\n\n for (const key of Object.keys(configured)) {\n if (!(ACP_CHECKOUT_OPERATIONS as readonly string[]).includes(key)) {\n throw acpInvalid(\n `protocols.acp.checkout.operations.${key}`,\n `protocols.acp.checkout.operations names unknown ACP checkout operation \"${key}\". Supported: ${ACP_CHECKOUT_OPERATIONS.join(', ')}.`,\n );\n }\n }\n\n const operations: Record<string, string> = {};\n const claimedBy = new Map<string, AcpCheckoutOperation>();\n for (const operation of ACP_CHECKOUT_OPERATIONS) {\n const path = `protocols.acp.checkout.operations.${operation}`;\n const resourceId = configured[operation];\n if (resourceId === undefined) {\n throw acpInvalid(\n path,\n `${path} is required when ACP is enabled - all five checkout operations must be mapped, since ACP discovery advertises the checkout service as a whole`,\n );\n }\n const claimed = claimedBy.get(resourceId);\n if (claimed !== undefined) {\n throw acpInvalid(\n path,\n `${path} maps resource \"${resourceId}\", which is already mapped to \"${claimed}\" - each ACP checkout operation needs its own resource`,\n { resourceId },\n );\n }\n claimedBy.set(resourceId, operation);\n operations[operation] = resourceId;\n }\n return operations as Record<AcpCheckoutOperation, string>;\n}\n\nexport function validateAcpCheckoutMapping(\n acp: EnabledAcpConfig,\n resources: readonly CommerceResource[],\n): void {\n const byId = new Map(resources.map((resource) => [resource.id, resource]));\n\n for (const operation of ACP_CHECKOUT_OPERATIONS) {\n const resourceId = acp.checkout.operations[operation];\n const path = `protocols.acp.checkout.operations.${operation}`;\n const resource = byId.get(resourceId);\n if (resource === undefined) {\n throw acpInvalid(\n path,\n `${path} maps resource \"${resourceId}\", which is not defined under \"resources\"`,\n { resourceId },\n );\n }\n if (!resource.exposedVia.includes('acp')) {\n throw acpInvalid(\n path,\n `Resource \"${resourceId}\" implements ACP operation \"${operation}\" but does not list \"acp\" in its expose - the mapping says which resource serves the operation, expose says ACP may invoke it, and both are required`,\n { resourceId },\n );\n }\n // ACP checkout carries the merchant's own purchase payment (`payment_data`\n // on completion), and ACP has no wire form for our payment-required\n // outcome, so the invocation itself must be free\n if (resource.pricing.type !== 'free' || resource.paymentMethods.length > 0) {\n throw acpInvalid(\n path,\n `Resource \"${resourceId}\" implements ACP operation \"${operation}\" and must use pricing.type \"free\" with no \"payments\" - ACP checkout carries the merchant's own purchase payment, so the gateway does not also charge for the invocation`,\n { resourceId },\n );\n }\n validateAcpOperationInput(path, operation, resource);\n }\n}\n\n// A schema that forbids a key the adapter sends, or requires one it may not\n// send, fails requests with INPUT_INVALID. Refused at load instead. An optional\n// key counts as sent: a closed cancel schema without `body` would pass a bare\n// cancel and refuse every one that carries `intent_trace`. Normalization has\n// already closed every object node that omits additionalProperties, so the\n// check also looks inside `path` and `body`: a bare `body: { type: object }`\n// arrives here accepting no key at all.\nfunction validateAcpOperationInput(\n path: string,\n operation: AcpCheckoutOperation,\n resource: CommerceResource,\n): void {\n const schema = resource.inputSchema;\n if (schema === undefined) return;\n const keys: readonly string[] = ACP_OPERATION_INPUT_KEYS[operation];\n const optionalKeys: readonly string[] = ACP_OPERATION_OPTIONAL_INPUT_KEYS[operation] ?? [];\n const sent = [...keys, ...optionalKeys];\n\n const topLevel = closedObjectProperties(schema);\n if (topLevel !== undefined) {\n for (const key of sent) {\n if (!Object.hasOwn(topLevel, key)) {\n const when = keys.includes(key) ? 'always sends' : 'sends when the caller supplies it';\n throw acpInvalid(\n path,\n `Resource \"${resource.id}\" implements ACP operation \"${operation}\" but its input schema sets additionalProperties: false without declaring \"${key}\", which the adapter ${when} for this operation`,\n { resourceId: resource.id },\n );\n }\n }\n }\n\n const declared = isRecord(schema['properties']) ? schema['properties'] : {};\n const pathKeys = closedObjectProperties(declared['path']);\n if (\n sent.includes('path') &&\n pathKeys !== undefined &&\n !Object.hasOwn(pathKeys, ACP_SESSION_ID_INPUT_KEY)\n ) {\n throw acpInvalid(\n path,\n `Resource \"${resource.id}\" implements ACP operation \"${operation}\" but its \"path\" schema sets additionalProperties: false without declaring \"${ACP_SESSION_ID_INPUT_KEY}\", which the adapter always sends inside \"path\"`,\n { resourceId: resource.id },\n );\n }\n const bodyKeys = closedObjectProperties(declared['body']);\n if (sent.includes('body') && bodyKeys !== undefined && Object.keys(bodyKeys).length === 0) {\n throw acpInvalid(\n path,\n `Resource \"${resource.id}\" implements ACP operation \"${operation}\" but its \"body\" schema accepts no keys, so it refuses every ACP document. Config load closes an object schema that omits additionalProperties: declare body as { type: object, additionalProperties: true }`,\n { resourceId: resource.id },\n );\n }\n\n const required = schema['required'];\n if (Array.isArray(required)) {\n for (const entry of required) {\n if (typeof entry === 'string' && !keys.includes(entry)) {\n throw acpInvalid(\n path,\n `Resource \"${resource.id}\" implements ACP operation \"${operation}\" but its input schema requires \"${entry}\", which that operation does not always supply (it always sends: ${keys.join(', ')})`,\n { resourceId: resource.id },\n );\n }\n }\n }\n}\n\n// The declared properties of a closed object schema, or undefined when the\n// schema accepts keys it does not declare\nfunction closedObjectProperties(schema: unknown): Record<string, unknown> | undefined {\n if (!isRecord(schema) || schema['additionalProperties'] !== false) return undefined;\n return isRecord(schema['properties']) ? schema['properties'] : {};\n}\n","// AP2 mandate verification settings and each resource's authorization requirement\nimport type { z } from 'zod';\nimport {\n AP2_DEFAULT_CLOCK_SKEW_SECONDS,\n AP2_JWK_COORDINATE_BYTES,\n AP2_JWK_CURVE,\n AP2_JWK_MEMBERS,\n AP2_KEY_TYPE,\n AP2_MAX_CLOCK_SKEW_SECONDS,\n AP2_MODES,\n AP2_SIGNING_ALGORITHM,\n AP2_SPEC_VERSION,\n} from '../../authorization/ap2/constants';\nimport type {\n Ap2AuthorizationConfig,\n Ap2Mode,\n Ap2TrustedIssuer,\n} from '../../authorization/ap2/types';\nimport {\n type AuthorizationMethodName,\n CommerceError,\n type CommerceResource,\n type Pricing,\n} from '../../core';\nimport type { Ap2IssuerSchema, RawConfig, RawResourceEntry } from './raw';\nimport type { AcpProtocolConfig } from './types';\nimport { toBoolean, toNumber } from './values';\n\nconst SUPPORTED_AUTHORIZATION_METHODS: ReadonlySet<string> = new Set(['ap2']);\n\ntype RawAp2 = NonNullable<NonNullable<RawConfig['authorization']>['ap2']>;\n\nfunction ap2Invalid(\n path: string,\n message: string,\n extra: Record<string, unknown> = {},\n): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, { details: { path, ...extra } });\n}\n\nexport function normalizeAp2(raw: RawAp2 | undefined): Ap2AuthorizationConfig | undefined {\n if (raw === undefined) return undefined;\n if (!toBoolean(raw.enabled, 'authorization.ap2.enabled')) return { enabled: false };\n\n const specVersion = raw.specVersion ?? AP2_SPEC_VERSION;\n if (specVersion !== AP2_SPEC_VERSION) {\n throw ap2Invalid(\n 'authorization.ap2.specVersion',\n `authorization.ap2.specVersion \"${specVersion}\" is not supported - this gateway verifies against the tagged AP2 release ${AP2_SPEC_VERSION} only`,\n );\n }\n\n const mode = raw.mode ?? AP2_MODES[0];\n if (!(AP2_MODES as readonly string[]).includes(mode)) {\n throw ap2Invalid(\n 'authorization.ap2.mode',\n `authorization.ap2.mode \"${mode}\" is not supported. Supported: ${AP2_MODES.join(', ')}. Autonomous mode needs open mandates, agent key binding and constraint evaluation, none of which this release implements.`,\n );\n }\n\n if (raw.replay === undefined) {\n throw ap2Invalid(\n 'authorization.ap2.replay',\n 'authorization.ap2.replay is required when AP2 is enabled - it names the SQLite file recording which mandates have been spent, and without it a verified mandate could authorize a second settlement',\n );\n }\n\n const mandateIssuers = normalizeIssuers(\n raw.trust?.mandateIssuers,\n 'authorization.ap2.trust.mandateIssuers',\n );\n const checkoutIssuers = normalizeIssuers(\n raw.trust?.checkoutIssuers,\n 'authorization.ap2.trust.checkoutIssuers',\n );\n\n return {\n enabled: true,\n specVersion: AP2_SPEC_VERSION,\n mode: mode as Ap2Mode,\n trust: { mandateIssuers, checkoutIssuers },\n clockSkewSeconds: toNumber(\n raw.clockSkewSeconds ?? AP2_DEFAULT_CLOCK_SKEW_SECONDS,\n 'authorization.ap2.clockSkewSeconds',\n { min: 0, max: AP2_MAX_CLOCK_SKEW_SECONDS },\n ),\n requireMandateAudience: toBoolean(\n raw.requireMandateAudience ?? false,\n 'authorization.ap2.requireMandateAudience',\n ),\n requireMandateExpiry: toBoolean(\n raw.requireMandateExpiry ?? false,\n 'authorization.ap2.requireMandateExpiry',\n ),\n replay: { path: raw.replay.path },\n };\n}\n\n// Both issuer lists must be non-empty when AP2 is on: verification checks the\n// issuer's signature over the Checkout Mandate and the merchant's over the\n// checkout JWT it binds. An empty list would fail every mandate at request\n// time instead of at load.\nfunction normalizeIssuers(\n raw: readonly z.infer<typeof Ap2IssuerSchema>[] | undefined,\n path: string,\n): readonly Ap2TrustedIssuer[] {\n if (raw === undefined || raw.length === 0) {\n throw ap2Invalid(\n path,\n `${path} is required when AP2 is enabled and must name at least one issuer - trust is operator-configured and static, so an empty list means no mandate can ever verify`,\n );\n }\n\n const seen = new Set<string>();\n return raw.map((entry, index) => {\n const entryPath = `${path}.${index}`;\n if (seen.has(entry.issuer)) {\n throw ap2Invalid(\n `${entryPath}.issuer`,\n `${entryPath}.issuer \"${entry.issuer}\" is listed twice - key lookup resolves by issuer, so a second entry for the same one is silently unreachable. Merge the keys into one entry instead (which is also how a rotation overlaps an old and a new key).`,\n { issuer: entry.issuer },\n );\n }\n seen.add(entry.issuer);\n\n const kids = new Set<string>();\n const keys = entry.keys.map((key, keyIndex) => {\n const keyPath = `${entryPath}.keys.${keyIndex}`;\n if (kids.has(key.kid)) {\n throw ap2Invalid(\n `${keyPath}.kid`,\n `${keyPath}.kid \"${key.kid}\" is listed twice for issuer \"${entry.issuer}\" - a kid selects exactly one key, so which of the two verifies a signature would be undefined`,\n { issuer: entry.issuer, kid: key.kid },\n );\n }\n kids.add(key.kid);\n return { kid: key.kid, jwk: validateJwk(key.jwk, key.kid, keyPath) };\n });\n\n return { issuer: entry.issuer, audience: entry.audience, keys };\n });\n}\n\n// Accepts only a public P-256 key. Every member is checked at load rather than\n// by the JOSE library at the first purchase, so a bad key fails the deploy\n// instead of a buyer's valid mandate.\nfunction validateJwk(\n jwk: Record<string, unknown>,\n kid: string,\n path: string,\n): Readonly<Record<string, string>> {\n const fail = (detail: string): never => {\n throw ap2Invalid(`${path}.jwk`, `${path}.jwk (kid \"${kid}\") ${detail}`, { kid });\n };\n\n for (const member of Object.keys(jwk)) {\n if ((AP2_JWK_MEMBERS as readonly string[]).includes(member)) continue;\n // `d` (an EC private scalar) or `k` (a symmetric key) means signing\n // material was pasted where only verification material belongs, which the\n // operator needs to hear about specifically\n if (member === 'd' || member === 'k') {\n fail(\n `carries private key material (\"${member}\"). The gateway verifies signatures and never produces them; publish only the public half. Treat the pasted key as compromised and rotate it.`,\n );\n }\n fail(\n `has unsupported member \"${member}\". Allowed: ${AP2_JWK_MEMBERS.join(', ')}. Members naming a URL are refused on purpose - keys are configured inline and never fetched.`,\n );\n }\n\n const value = (member: string): string => {\n const raw = jwk[member];\n if (typeof raw !== 'string' || raw.length === 0) {\n fail(`must give \"${member}\" as a non-empty string`);\n }\n return raw as string;\n };\n\n if (value('kty') !== AP2_KEY_TYPE) {\n fail(\n `must have kty \"${AP2_KEY_TYPE}\" (got \"${value('kty')}\") - ${AP2_SIGNING_ALGORITHM} is the only accepted algorithm`,\n );\n }\n if (value('crv') !== AP2_JWK_CURVE) {\n fail(\n `must be on curve \"${AP2_JWK_CURVE}\" (got \"${value('crv')}\") - ${AP2_SIGNING_ALGORITHM} is the only accepted algorithm`,\n );\n }\n for (const coordinate of ['x', 'y'] as const) {\n const encoded = value(coordinate);\n if (!/^[A-Za-z0-9_-]+$/.test(encoded)) {\n fail(`coordinate \"${coordinate}\" is not base64url (no padding, no \"+\" or \"/\")`);\n }\n if (Buffer.from(encoded, 'base64url').length !== AP2_JWK_COORDINATE_BYTES) {\n fail(\n `coordinate \"${coordinate}\" decodes to ${Buffer.from(encoded, 'base64url').length} bytes; a ${AP2_JWK_CURVE} coordinate is ${AP2_JWK_COORDINATE_BYTES}`,\n );\n }\n }\n if (jwk['alg'] !== undefined && value('alg') !== AP2_SIGNING_ALGORITHM) {\n fail(`declares alg \"${value('alg')}\"; only ${AP2_SIGNING_ALGORITHM} is accepted`);\n }\n if (jwk['use'] !== undefined && value('use') !== 'sig') {\n fail(`declares use \"${value('use')}\"; a verification key must be \"sig\"`);\n }\n if (jwk['kid'] !== undefined && value('kid') !== kid) {\n fail(`declares kid \"${value('kid')}\", which disagrees with the configured kid \"${kid}\"`);\n }\n\n const normalized: Record<string, string> = {};\n for (const member of AP2_JWK_MEMBERS) {\n if (jwk[member] !== undefined) normalized[member] = value(member);\n }\n return normalized;\n}\n\n// The AP2 replay store gets its own SQLite file. Reserved mandates, payment\n// attempts and ACP idempotency records have different schemas and retention\n// rules, and a shared file means a migration conflict at startup or a shared\n// write lock on the settlement path.\nexport function validateReplayStoreIsolated(\n replayPath: string,\n receiptsPath: string,\n acp: AcpProtocolConfig,\n): void {\n // Every `:memory:` handle is its own private database, so equal strings do\n // not collide\n if (replayPath === ':memory:') return;\n\n const others: [string, string][] = [['storage.receipts.path', receiptsPath]];\n if (acp.enabled) others.push(['protocols.acp.idempotency.path', acp.idempotency.path]);\n\n for (const [otherPath, other] of others) {\n if (replayPath !== other) continue;\n throw ap2Invalid(\n 'authorization.ap2.replay.path',\n `authorization.ap2.replay.path is the same file as ${otherPath} (\"${replayPath}\") - the AP2 replay store keeps its own schema and must not share a database with another store`,\n );\n }\n}\n\n// Resolves a resource's `authorization.required` list against the configured\n// provider. A requirement that cannot be enforced is refused: the resource\n// would look protected in config and settle unprotected.\nexport function normalizeResourceAuthorization(\n id: string,\n entry: RawResourceEntry,\n pricing: Pricing,\n ap2: Ap2AuthorizationConfig | undefined,\n): CommerceResource['authorization'] | undefined {\n const required = entry.authorization?.required;\n if (required === undefined) return undefined;\n\n const path = `resources.${id}.authorization.required`;\n const methods: AuthorizationMethodName[] = [];\n for (const method of required) {\n if (!SUPPORTED_AUTHORIZATION_METHODS.has(method)) {\n throw ap2Invalid(\n path,\n `Resource \"${id}\" requires unsupported authorization method \"${method}\". Supported: ${[...SUPPORTED_AUTHORIZATION_METHODS].join(', ')}.`,\n { resourceId: id, method },\n );\n }\n if (methods.includes(method as AuthorizationMethodName)) {\n throw ap2Invalid(path, `Resource \"${id}\" lists authorization method \"${method}\" twice`, {\n resourceId: id,\n method,\n });\n }\n if (method === 'ap2' && (ap2 === undefined || !ap2.enabled)) {\n throw ap2Invalid(\n path,\n `Resource \"${id}\" requires authorization method \"ap2\", which is not configured or not enabled under authorization.ap2`,\n { resourceId: id, method },\n );\n }\n methods.push(method as AuthorizationMethodName);\n }\n\n // A mandate binds an exact amount and currency and never unlocks a resource\n // by itself, so it only means something on a fixed-price resource\n if (pricing.type !== 'fixed') {\n throw ap2Invalid(\n path,\n `Resource \"${id}\" requires authorization but its pricing is \"${pricing.type}\" - authorization proves a purchase was approved and never replaces payment, so it applies to fixed-price paid resources only in this release`,\n { resourceId: id },\n );\n }\n\n return { required: methods };\n}\n","// The x402 rail: direct or listed options, declared networks and the facilitator\nimport type { z } from 'zod';\nimport { CommerceError } from '../../core';\nimport { resolveX402Deployment, type X402FacilitatorConfig } from '../../payments/x402/guardrails';\nimport {\n type CustomNetworkDeclaration,\n findX402Network,\n validateCustomNetworks,\n} from '../../payments/x402/networks';\nimport { resolveX402Option, type X402OptionInput } from '../../payments/x402/options';\nimport { X402_DEFAULT_PAYMENT_FLOW } from '../../payments/x402/payment-flow';\nimport type { FacilitatorSchema, RawConfig } from './raw';\nimport type { GatewayConfig, X402OptionConfig } from './types';\nimport { toBoolean, toNumber } from './values';\n\ntype X402Config = NonNullable<GatewayConfig['payments']['x402']>;\n\n// One offer list: the rail's options or a resource's own accepts\nexport interface X402OfferTerms {\n /** Every option, resolved, in order */\n readonly options: readonly X402OptionConfig[];\n /**\n * Default symbols for options omitting `asset`; prices must use USD or\n * the shared symbol\n */\n readonly defaultAssetSymbols: readonly string[];\n}\n\nexport interface NormalizedX402 extends X402OfferTerms {\n readonly config: X402Config;\n /** Resources with their own `x402.accepts`, by id; each replaces the rail's options */\n readonly resources: Readonly<Record<string, X402OfferTerms>>;\n}\n\nfunction x402Invalid(message: string, path: string): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, { details: { path } });\n}\n\n// The fields of one option, as they appear directly under `payments.x402`\nconst DIRECT_OPTION_FIELDS = [\n 'network',\n 'payTo',\n 'asset',\n 'assetName',\n 'assetVersion',\n 'assetDecimals',\n 'assetTransferMethod',\n] as const;\n\ntype RawX402 = NonNullable<RawConfig['payments']['x402']>;\n\n// An entry of `options`, or `payments.x402` itself in the direct form\ninterface RawX402Option {\n readonly scheme?: string | undefined;\n readonly network?: string | undefined;\n readonly payTo?: string | undefined;\n readonly asset?: string | undefined;\n readonly assetName?: string | undefined;\n readonly assetVersion?: string | undefined;\n readonly assetDecimals?: number | string | undefined;\n readonly assetTransferMethod?: string | undefined;\n}\n\nfunction x402OptionInput(raw: RawX402Option, path: string): X402OptionInput {\n return {\n ...(raw.scheme !== undefined ? { scheme: raw.scheme } : {}),\n network: raw.network as string,\n payTo: raw.payTo as string,\n ...(raw.asset !== undefined ? { asset: raw.asset } : {}),\n ...(raw.assetName !== undefined ? { assetName: raw.assetName } : {}),\n ...(raw.assetVersion !== undefined ? { assetVersion: raw.assetVersion } : {}),\n ...(raw.assetTransferMethod !== undefined\n ? { assetTransferMethod: raw.assetTransferMethod }\n : {}),\n ...(raw.assetDecimals !== undefined\n ? {\n assetDecimals: toNumber(raw.assetDecimals, `${path}.assetDecimals`, { min: 0, max: 36 }),\n }\n : {}),\n };\n}\n\n/**\n * Resolves direct `payments.x402` fields like a one-entry `options` array,\n * preserving config form. Resource `x402.accepts` uses the same resolution\n * and rail-level networks, RPC endpoints, facilitator and mainnet settings.\n */\nexport function normalizeX402(raw: RawX402, resources: RawConfig['resources']): NormalizedX402 {\n const at = 'payments.x402';\n const direct = DIRECT_OPTION_FIELDS.filter((field) => raw[field] !== undefined);\n if (raw.options !== undefined && direct.length > 0) {\n throw x402Invalid(\n `${at}: give the option either under ${at}.options or directly (${direct.join(', ')}), not both`,\n `${at}.options`,\n );\n }\n if (raw.options?.length === 0) {\n throw x402Invalid(`${at}.options is empty; list at least one option`, `${at}.options`);\n }\n if (raw.options === undefined) {\n for (const field of ['network', 'payTo'] as const) {\n if (raw[field] === undefined) {\n throw x402Invalid(\n `${at}.${field} is required, unless the options are listed under ${at}.options`,\n `${at}.${field}`,\n );\n }\n }\n }\n\n // `kind` and `displayName` declare a network; `rpcUrl` alone sets the\n // endpoint of a built-in or declared one\n const settings = raw.networks ?? {};\n const declared: Record<string, CustomNetworkDeclaration> = {};\n for (const [id, entry] of Object.entries(settings)) {\n if (entry.kind === undefined && entry.displayName === undefined) continue;\n if (entry.kind === undefined || entry.displayName === undefined) {\n const path = `${at}.networks.${id}`;\n throw x402Invalid(`${path}: declaring a network needs both kind and displayName`, path);\n }\n declared[id] = { kind: entry.kind, displayName: entry.displayName };\n }\n const networks = Object.keys(declared).length > 0 ? declared : undefined;\n if (networks !== undefined) validateCustomNetworks(networks, `${at}.networks`);\n for (const id of Object.keys(settings)) {\n if (!findX402Network(id, networks)) {\n const path = `${at}.networks.${id}`;\n throw x402Invalid(\n `${path}: \"${id}\" is not a known network; declare it with kind and displayName`,\n path,\n );\n }\n }\n\n const facilitator = normalizeFacilitator(raw.facilitator);\n const allowMainnet =\n raw.allowMainnet !== undefined ? toBoolean(raw.allowMainnet, `${at}.allowMainnet`) : undefined;\n const allowUnauthenticatedFacilitator =\n raw.allowUnauthenticatedFacilitator !== undefined\n ? toBoolean(raw.allowUnauthenticatedFacilitator, `${at}.allowUnauthenticatedFacilitator`)\n : undefined;\n\n // Shared by every list, so the rail and its resources use one RPC endpoint\n // per network and one deployment mode\n const rpcOwners = new Map<string, string>();\n let firstMode: string | undefined;\n const resolveList = (entries: readonly (readonly [string, RawX402Option])[]): X402OfferTerms => {\n const resolved = entries.map(([path, entry]) =>\n resolveX402Option(x402OptionInput(entry, path), path, networks),\n );\n const seen = new Set<string>();\n const options = resolved.map((option, i): X402OptionConfig => {\n const path = entries[i]?.[0] as string;\n const network = option.network.id;\n // Require distinct RPC endpoints so each network's health check reads its chain\n const rpcUrl = settings[network]?.rpcUrl ?? raw.rpcUrl;\n if (rpcUrl === undefined) {\n throw x402Invalid(\n `${path}.network: no RPC endpoint for ${network}; set ${at}.rpcUrl or ${at}.networks.${network}.rpcUrl`,\n `${at}.rpcUrl`,\n );\n }\n // Parsed, so `https://rpc.example` and `https://rpc.example/` are one endpoint\n const endpoint = new URL(rpcUrl).href;\n const owner = rpcOwners.get(endpoint);\n if (owner !== undefined && owner !== network) {\n throw x402Invalid(\n `${at}: ${owner} and ${network} would use the same RPC endpoint; give each network its own ${at}.networks.<id>.rpcUrl`,\n `${at}.networks`,\n );\n }\n rpcOwners.set(endpoint, network);\n\n // EVM addresses compare case-insensitively; Solana and NEAR exactly\n const comparable = (value: string) =>\n option.network.family === 'evm' ? value.toLowerCase() : value;\n const key = `${network}|${comparable(option.asset)}|${comparable(option.payTo)}`;\n if (seen.has(key)) {\n throw x402Invalid(\n `${path}: repeats an earlier option, the same asset to the same payTo on ${network}`,\n path,\n );\n }\n seen.add(key);\n\n // The provider makes the same call at construction; running it here lets\n // `agent-commerce validate` report an unsafe deployment before boot\n const { mode } = resolveX402Deployment({\n network,\n payTo: option.payTo,\n asset: option.asset,\n ...(option.assetName !== undefined ? { assetName: option.assetName } : {}),\n ...(option.assetVersion !== undefined ? { assetVersion: option.assetVersion } : {}),\n facilitator,\n ...(allowMainnet !== undefined ? { allowMainnet } : {}),\n ...(allowUnauthenticatedFacilitator !== undefined\n ? { allowUnauthenticatedFacilitator }\n : {}),\n ...(networks !== undefined ? { customNetworks: networks } : {}),\n });\n // Keep all offers in one deployment mode: local, testnet or mainnet\n if (firstMode !== undefined && mode !== firstMode) {\n throw x402Invalid(\n `${path}.network: ${network} is a ${mode} network, but the first option is on a ${firstMode} one; every option must be on the same kind of network`,\n `${path}.network`,\n );\n }\n firstMode = mode;\n\n return {\n network,\n rpcUrl,\n asset: option.asset,\n ...(option.assetName !== undefined ? { assetName: option.assetName } : {}),\n ...(option.assetVersion !== undefined ? { assetVersion: option.assetVersion } : {}),\n assetDecimals: option.assetDecimals,\n payTo: option.payTo,\n ...(option.assetTransferMethod === 'permit2'\n ? { assetTransferMethod: 'permit2' as const }\n : {}),\n };\n });\n return {\n options,\n defaultAssetSymbols: [\n ...new Set(resolved.flatMap((option) => option.defaultAssetSymbol ?? [])),\n ],\n };\n };\n\n const rail = resolveList(\n raw.options !== undefined\n ? raw.options.map((option, i) => [`${at}.options[${i}]`, option] as const)\n : [[at, raw]],\n );\n const resourceTerms: Record<string, X402OfferTerms> = {};\n for (const [id, entry] of Object.entries(resources)) {\n const accepts = entry.x402?.accepts;\n if (accepts === undefined) continue;\n const path = `resources.${id}.x402.accepts`;\n if (accepts.length === 0) {\n throw x402Invalid(`${path} is empty; list at least one option`, path);\n }\n resourceTerms[id] = resolveList(accepts.map((option, i) => [`${path}[${i}]`, option] as const));\n }\n const options = rail.options;\n const first = options[0] as X402OptionConfig;\n const resourceOptions = Object.fromEntries(\n Object.entries(resourceTerms).map(([id, terms]) => [id, terms.options]),\n );\n\n const config: X402Config = {\n enabled: toBoolean(raw.enabled, `${at}.enabled`),\n ...first,\n maxTimeoutSeconds: toNumber(raw.maxTimeoutSeconds, `${at}.maxTimeoutSeconds`, { min: 1 }),\n paymentFlow: raw.paymentFlow ?? X402_DEFAULT_PAYMENT_FLOW,\n facilitator,\n ...(allowMainnet !== undefined ? { allowMainnet } : {}),\n ...(allowUnauthenticatedFacilitator !== undefined ? { allowUnauthenticatedFacilitator } : {}),\n ...(networks !== undefined ? { networks } : {}),\n options,\n ...(Object.keys(resourceOptions).length > 0 ? { resourceOptions } : {}),\n };\n\n return { config, ...rail, resources: resourceTerms };\n}\n\nexport function normalizeFacilitator(\n raw: z.infer<typeof FacilitatorSchema>,\n): X402FacilitatorConfig {\n return raw.mode === 'local'\n ? { mode: 'local', signerPrivateKey: raw.signerPrivateKey }\n : { mode: 'remote', url: raw.url, auth: raw.auth ?? { type: 'none' } };\n}\n","// The MPP rail's settings\nimport { CommerceError } from '../../core';\nimport {\n isMppNetwork,\n MPP_DEFAULT_NETWORK,\n MPP_DEFAULT_PAYMENT_FLOW,\n MPP_MIN_CHALLENGE_SECRET_LENGTH,\n MPP_NETWORKS,\n} from '../../payments/mpp/constants';\nimport { resolveX402Deployment } from '../../payments/x402/guardrails';\nimport type { RawConfig } from './raw';\nimport type { GatewayConfig } from './types';\nimport { toBoolean, toNumber, validateAddress } from './values';\nimport { normalizeFacilitator } from './x402';\n\nexport type NormalizedMpp = NonNullable<GatewayConfig['payments']['mpp']>;\n\nexport function normalizeMpp(raw: RawConfig['payments']['mpp']): NormalizedMpp | undefined {\n if (raw === undefined) return undefined;\n const network = raw.network ?? MPP_DEFAULT_NETWORK;\n if (!isMppNetwork(network)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `payments.mpp.network must be one of ${MPP_NETWORKS.join(', ')}`,\n { details: { path: 'payments.mpp.network' } },\n );\n }\n const mpp: NormalizedMpp = {\n enabled: toBoolean(raw.enabled, 'payments.mpp.enabled'),\n network,\n rpcUrl: raw.rpcUrl,\n asset: raw.asset,\n assetName: raw.assetName,\n assetVersion: raw.assetVersion,\n recipient: raw.recipient,\n realm: raw.realm,\n challengeSecret: raw.challengeSecret,\n ...(raw.challengeTtlSeconds !== undefined\n ? {\n challengeTtlSeconds: toNumber(\n raw.challengeTtlSeconds,\n 'payments.mpp.challengeTtlSeconds',\n { min: 1 },\n ),\n }\n : {}),\n paymentFlow: raw.paymentFlow ?? MPP_DEFAULT_PAYMENT_FLOW,\n facilitator: normalizeFacilitator(raw.facilitator),\n ...(raw.allowMainnet !== undefined\n ? { allowMainnet: toBoolean(raw.allowMainnet, 'payments.mpp.allowMainnet') }\n : {}),\n ...(raw.allowUnauthenticatedFacilitator !== undefined\n ? {\n allowUnauthenticatedFacilitator: toBoolean(\n raw.allowUnauthenticatedFacilitator,\n 'payments.mpp.allowUnauthenticatedFacilitator',\n ),\n }\n : {}),\n };\n validateAddress('payments.mpp.recipient', mpp.recipient);\n validateAddress('payments.mpp.asset', mpp.asset);\n // mppx refuses CR or LF in a quoted challenge parameter\n if (/[\\r\\n]/.test(mpp.realm)) {\n throw new CommerceError('CONFIG_INVALID', 'payments.mpp.realm must be a single line', {\n details: { path: 'payments.mpp.realm' },\n });\n }\n // Length only: the secret itself never appears in an error\n if (mpp.challengeSecret.length < MPP_MIN_CHALLENGE_SECRET_LENGTH) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `payments.mpp.challengeSecret must have length at least ${MPP_MIN_CHALLENGE_SECRET_LENGTH}`,\n { details: { path: 'payments.mpp.challengeSecret' } },\n );\n }\n // The shared x402 address, facilitator and mainnet guards, reported under the\n // MPP config path\n resolveX402Deployment({\n network: mpp.network,\n payTo: mpp.recipient,\n asset: mpp.asset,\n assetName: mpp.assetName,\n assetVersion: mpp.assetVersion,\n facilitator: mpp.facilitator,\n ...(mpp.allowMainnet !== undefined ? { allowMainnet: mpp.allowMainnet } : {}),\n ...(mpp.allowUnauthenticatedFacilitator !== undefined\n ? { allowUnauthenticatedFacilitator: mpp.allowUnauthenticatedFacilitator }\n : {}),\n configPath: 'payments.mpp',\n payToField: 'recipient',\n });\n return mpp;\n}\n","// The Zod schemas for `config.yaml`: shape only, before any business rule\nimport { type ZodTypeAny, z } from 'zod';\nimport { X402_PAYMENT_FLOWS } from '../../payments/x402/payment-flow';\nimport { ACP_WELL_KNOWN_PATH } from '../../protocols/acp/constants';\n\nexport const SUPPORTED_CONFIG_VERSION = 1;\n\n// A number, or a numeric string from env substitution\nconst NumberOrString = z.union([z.number(), z.string()]);\n\n// A boolean, or a \"true\"/\"false\" string from env substitution\nconst BooleanOrString = z.union([z.boolean(), z.string()]);\n\n// An RPC endpoint. The message never echoes the value, which can carry an API key\nconst RpcUrl = z\n .string()\n .min(1)\n .refine(isHttpUrl, { message: 'must be an http:// or https:// URL' });\n\nfunction isHttpUrl(value: string): boolean {\n try {\n const { protocol } = new URL(value);\n return protocol === 'http:' || protocol === 'https:';\n } catch {\n return false;\n }\n}\n\nconst MerchantSchema = z\n .object({\n id: z.string().min(1),\n name: z.string().min(1),\n publicBaseUrl: z.string().min(1),\n })\n .strict();\n\nconst ServerSchema = z\n .object({\n port: NumberOrString,\n host: z.string().min(1),\n // Shared secret gating /api/receipts and /api/events. Without it both\n // routes 404.\n adminToken: z.string().min(1).optional(),\n // Browser origins allowed to call the gateway; none by default. A request\n // with any other `Origin` gets 403 on every route. Entries match the\n // `Origin` header exactly (ignoring case), so `\"*\"` and a trailing slash\n // would match nothing: a silent lockout that an operator might \"fix\" by\n // disabling the check. Both are refused with a pointer.\n allowedOrigins: z\n .array(\n z\n .string()\n .min(1)\n .refine((origin) => origin !== '*', {\n message:\n 'wildcard \"*\" is not supported - allowedOrigins entries are matched literally against the browser\\'s Origin header, so \"*\" would match nothing. List each scheme://host[:port] explicitly.',\n })\n .refine((origin) => !origin.endsWith('/'), {\n message:\n 'must not end with \"/\" - a browser Origin header never has a trailing slash, so this entry would match nothing. Use e.g. \"http://localhost:5173\".',\n }),\n )\n .optional(),\n })\n .strict();\n\nconst StorageSchema = z\n .object({\n receipts: z\n .object({\n driver: z.literal('sqlite'),\n path: z.string().min(1),\n })\n .strict(),\n })\n .strict();\n\n// Every path the gateway registers (`src/gateway/routes.ts`), plus the fixed\n// discovery paths adapters own. A mount equal to one duplicates that route; a\n// mount that is a prefix of one swallows it through its `${mountPath}/*` wildcard.\nconst RESERVED_GATEWAY_PATHS = [\n '/health',\n '/ready',\n '/.well-known/agent-commerce',\n // Fixed by the A2A specification and served by the adapter\n '/.well-known/agent-card.json',\n // Fixed by the ACP specification\n ACP_WELL_KNOWN_PATH,\n '/api/resources',\n '/api/resources/:id/invoke',\n '/api/receipts',\n '/api/events',\n] as const;\n\n// A bad `mountPath` would throw inside Fastify route registration at\n// `server.ready()`, failing the whole gateway with an opaque `FST_ERR_*`.\n// Checked here it is a CONFIG_INVALID naming the value. Pattern syntax (`:`,\n// `*`) is refused because the mount registers its own wildcard.\nconst MountPathSchema = z\n .string()\n .min(1)\n .refine((value) => value.startsWith('/'), {\n message: 'must start with \"/\" - it is an absolute gateway path, e.g. \"/mcp\".',\n })\n .refine((value) => !/[:*?\\s]/.test(value), {\n message:\n 'must not contain \":\", \"*\", \"?\" or whitespace - the mount is a literal path prefix, not a Fastify route pattern, and registers its own wildcard.',\n })\n .refine(\n (value) => {\n const base = value.replace(/\\/+$/, '');\n return !RESERVED_GATEWAY_PATHS.some(\n (reserved) => reserved === base || reserved.startsWith(`${base}/`),\n );\n },\n {\n message: `must not collide with a route the gateway already serves (${RESERVED_GATEWAY_PATHS.join(', ')}); pick a dedicated prefix such as \"/mcp\".`,\n },\n );\n\n// Bearer is the only ACP auth scheme; there is no `none`\nconst AcpAuthSchema = z.object({ type: z.literal('bearer'), token: z.string().min(1) }).strict();\n\nconst AcpIdempotencySchema = z\n .object({\n path: z.string().min(1),\n retentionHours: NumberOrString.optional(),\n merchantIdempotent: z.boolean().optional(),\n })\n .strict();\n\n// Operation names are checked against `ACP_CHECKOUT_OPERATIONS` in the\n// business pass, which names a missing or misspelled operation\nconst AcpCheckoutSchema = z.object({ operations: z.record(z.string().min(1)) }).strict();\n\n// Optional discovery metadata, omitted when not configured\nconst AcpDiscoverySchema = z\n .object({\n documentationUrl: z.string().min(1).optional(),\n supportedCurrencies: z.array(z.string().min(1)).optional(),\n supportedLocales: z.array(z.string().min(1)).optional(),\n interventionTypes: z.array(z.string().min(1)).optional(),\n })\n .strict();\n\nconst ProtocolsSchema = z\n .object({\n http: z.object({ enabled: BooleanOrString }).strict(),\n mcp: z\n .object({\n enabled: BooleanOrString,\n mountPath: MountPathSchema,\n })\n .strict(),\n // Optional; A2A is off unless configured\n a2a: z\n .object({\n enabled: BooleanOrString,\n mountPath: MountPathSchema.optional(),\n })\n .strict()\n .optional(),\n // Optional and off by default. The business pass requires the sub-blocks\n // only when ACP is enabled, so a disabled placeholder stays valid and an\n // enabled block gets a message naming what it lacks.\n acp: z\n .object({\n enabled: BooleanOrString,\n mountPath: MountPathSchema.optional(),\n auth: AcpAuthSchema.optional(),\n idempotency: AcpIdempotencySchema.optional(),\n checkout: AcpCheckoutSchema.optional(),\n discovery: AcpDiscoverySchema.optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\n\nconst BackendMethodSchema = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);\n\n// Strict, so a typo like `bodyy` fails at load instead of silently meaning\n// \"no body binding\"\nconst BackendInputBindingsSchema = z\n .object({\n path: z.string().min(1).optional(),\n query: z.string().min(1).optional(),\n body: z.string().min(1).optional(),\n })\n .strict();\n\nconst BackendHandlerSchema = z\n .object({\n type: z.literal('http'),\n method: BackendMethodSchema,\n url: z.string().min(1),\n headers: z.record(z.string(), z.string()).optional(),\n timeoutMs: NumberOrString.optional(),\n inputBindings: BackendInputBindingsSchema.optional(),\n })\n .strict();\n\nconst PricingSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('free') }).strict(),\n z\n .object({\n type: z.literal('fixed'),\n amount: z.string().min(1),\n currency: z.string().min(1),\n })\n .strict(),\n z\n .object({\n type: z.literal('dynamic'),\n resolver: z.string().min(1),\n })\n .strict(),\n]);\n\nconst JsonSchemaValueSchema: ZodTypeAny = z.record(z.string(), z.unknown());\n\n// Settlement network, payee and token, resolved by x402/options.ts. Network\n// and payee fields follow the SDK's `PaymentOption`; asset fields override defaults\nconst X402OptionSchema = z\n .object({\n scheme: z.string().min(1).optional(),\n network: z.string().min(1),\n payTo: z.string().min(1),\n asset: z.string().min(1).optional(),\n assetName: z.string().min(1).optional(),\n assetVersion: z.string().min(1).optional(),\n assetDecimals: NumberOrString.optional(),\n assetTransferMethod: z.string().min(1).optional(),\n })\n .strict();\n\nconst ResourceEntrySchema = z\n .object({\n name: z.string().min(1),\n description: z.string().optional(),\n input: JsonSchemaValueSchema.optional(),\n output: JsonSchemaValueSchema.optional(),\n backend: BackendHandlerSchema,\n pricing: PricingSchema,\n expose: z.array(z.string().min(1)).min(1),\n payments: z.array(z.string().min(1)).optional(),\n paymentFlow: z.enum(X402_PAYMENT_FLOWS).optional(),\n // This resource's own x402 offers, in place of `payments.x402` options\n x402: z\n .object({ accepts: z.array(X402OptionSchema) })\n .strict()\n .optional(),\n authorization: z\n .object({ required: z.array(z.string().min(1)).min(1) })\n .strict()\n .optional(),\n })\n .strict();\n\nconst ResourcesMapSchema = z.record(z.string().min(1), ResourceEntrySchema);\n\n// Facilitator credentials. `none` and `bearer` fit any facilitator; `cdp` is\n// the one vendor-specific type. Any other type is refused at load.\nconst FacilitatorAuthSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('none') }).strict(),\n z.object({ type: z.literal('bearer'), token: z.string().min(1) }).strict(),\n // Coinbase Developer Platform. Needs the optional peer `@coinbase/x402`,\n // which signs a fresh JWT per request.\n z\n .object({\n type: z.literal('cdp'),\n apiKeyId: z.string().min(1),\n apiKeySecret: z.string().min(1),\n })\n .strict(),\n]);\n\nexport const FacilitatorSchema = z.discriminatedUnion('mode', [\n z\n .object({\n mode: z.literal('local'),\n signerPrivateKey: z.string().min(1),\n })\n .strict(),\n z\n .object({\n mode: z.literal('remote'),\n url: z.string().min(1),\n // Absent auth sends no credential and normalizes to `{ type: 'none' }`,\n // which on mainnet requires `allowUnauthenticatedFacilitator`\n auth: FacilitatorAuthSchema.optional(),\n })\n .strict(),\n]);\n\n// Per-network settings: `kind` and `displayName` declare a network outside\n// the registry; `rpcUrl` is that network's endpoint, built in or declared\nconst X402NetworkSettingsSchema = z\n .object({\n kind: z.enum(['testnet', 'mainnet']).optional(),\n displayName: z.string().min(1).optional(),\n rpcUrl: RpcUrl.optional(),\n })\n .strict();\n\nconst X402Schema = z\n .object({\n enabled: BooleanOrString,\n // Accept direct fields or an `options` array, never both\n network: z.string().min(1).optional(),\n payTo: z.string().min(1).optional(),\n asset: z.string().min(1).optional(),\n assetName: z.string().min(1).optional(),\n assetVersion: z.string().min(1).optional(),\n assetDecimals: NumberOrString.optional(),\n assetTransferMethod: z.string().min(1).optional(),\n options: z.array(X402OptionSchema).optional(),\n networks: z.record(z.string().min(1), X402NetworkSettingsSchema).optional(),\n // The RPC for every network without its own `networks.<id>.rpcUrl`\n rpcUrl: RpcUrl.optional(),\n maxTimeoutSeconds: NumberOrString,\n // `authorization` (the x402 default) settles after the backend call\n paymentFlow: z.enum(X402_PAYMENT_FLOWS).optional(),\n facilitator: FacilitatorSchema,\n // Real funds. Never defaulted; see src/payments/x402/guardrails.ts\n allowMainnet: BooleanOrString.optional(),\n // Accepts credential-free facilitator access on mainnet. Never defaulted\n allowUnauthenticatedFacilitator: BooleanOrString.optional(),\n })\n .strict();\n\nconst MppSchema = z\n .object({\n enabled: BooleanOrString,\n network: z.string().min(1).optional(),\n rpcUrl: RpcUrl,\n asset: z.string().min(1),\n assetName: z.string().min(1),\n assetVersion: z.string().min(1),\n recipient: z.string().min(1),\n realm: z.string().min(1),\n challengeSecret: z.string().min(1),\n challengeTtlSeconds: NumberOrString.optional(),\n // Same values as `payments.x402.paymentFlow`; the default is `upfront`\n paymentFlow: z.enum(X402_PAYMENT_FLOWS).optional(),\n facilitator: FacilitatorSchema,\n // Real funds. Never defaulted; see src/payments/x402/guardrails.ts\n allowMainnet: BooleanOrString.optional(),\n // Accepts credential-free facilitator access on mainnet. Never defaulted\n allowUnauthenticatedFacilitator: BooleanOrString.optional(),\n })\n .strict();\n\nconst PaymentsSchema = z\n .object({\n x402: X402Schema.optional(),\n mpp: MppSchema.optional(),\n })\n .strict();\n\n// A public verification key, inline only: no `jwksUri`, `jku` or discovery\n// URL. AP2 leaves secure key distribution open, and fetching keys would mean\n// fetching from a location a mandate can influence. The business pass checks\n// the JWK's members against `AP2_JWK_MEMBERS`, which also keeps out `x5u`.\nconst Ap2KeySchema = z\n .object({\n kid: z.string().min(1),\n jwk: z.record(z.string(), z.unknown()),\n })\n .strict();\n\nexport const Ap2IssuerSchema = z\n .object({\n issuer: z.string().min(1),\n // Required, not defaulted: without it a mandate minted for another\n // merchant would verify here\n audience: z.string().min(1),\n keys: z.array(Ap2KeySchema).min(1),\n })\n .strict();\n\nconst Ap2Schema = z\n .object({\n enabled: BooleanOrString,\n specVersion: z.string().min(1).optional(),\n mode: z.string().min(1).optional(),\n trust: z\n .object({\n mandateIssuers: z.array(Ap2IssuerSchema).optional(),\n checkoutIssuers: z.array(Ap2IssuerSchema).optional(),\n })\n .strict()\n .optional(),\n clockSkewSeconds: NumberOrString.optional(),\n requireMandateAudience: BooleanOrString.optional(),\n requireMandateExpiry: BooleanOrString.optional(),\n replay: z\n .object({ path: z.string().min(1) })\n .strict()\n .optional(),\n })\n .strict();\n\n// Optional and off by default. The business pass requires the sub-blocks only\n// when AP2 is enabled, and names the missing piece.\nconst AuthorizationSchema = z.object({ ap2: Ap2Schema.optional() }).strict();\n\nexport const RawConfigSchema = z\n .object({\n version: z.literal(SUPPORTED_CONFIG_VERSION),\n merchant: MerchantSchema,\n server: ServerSchema,\n storage: StorageSchema,\n protocols: ProtocolsSchema,\n resources: ResourcesMapSchema,\n payments: PaymentsSchema,\n authorization: AuthorizationSchema.optional(),\n })\n .strict();\n\nexport type RawConfig = z.infer<typeof RawConfigSchema>;\n\nexport type RawResourceEntry = z.infer<typeof ResourceEntrySchema>;\n","/**\n * Shapes a backend request from validated input: the path template, query,\n * body and forwarded headers. The pipeline checks the shape before pricing, so\n * a request the backend cannot receive fails before any payment.\n */\nimport type { BackendHandler, BackendMethod } from '../domain/resource';\nimport { CommerceError } from '../errors';\nimport { isRecord } from '../is-record';\n\n// Never forward credentials, transport headers or fields set by the executor\nconst NEVER_FORWARDED_HEADER =\n /^(authorization|cookie|set-cookie|host|content-length|content-type|connection|keep-alive|te|trailer|transfer-encoding|upgrade|idempotency-key|proxy-.*)$/;\n\n// The one `{param}` grammar, shared by substitution, config, `doctor` and the\n// OpenAPI importer. It admits `-` and `.` because\n// `/report/{report-id}` is ordinary REST. Config refuses any other brace\n// (findUnparsedBraceToken).\nconst PATH_PARAM_PATTERN = /\\{([a-zA-Z0-9_.-]+)\\}/g;\n\n/**\n * `{param}` names in a `backend.url` template, in declaration order. Config,\n * `doctor` and the OpenAPI importer use it so they read the same grammar as\n * substitution.\n */\nexport function extractPathParameterNames(url: string): string[] {\n return [...url.matchAll(PATH_PARAM_PATTERN)].map((match) => match[1] as string);\n}\n\n/**\n * A brace left over after every legal `{param}` is removed, or `undefined`.\n *\n * `{report id}`, `{a/b}`, `{}` and an unbalanced `{` match no parameter and\n * would reach the backend as literals, which on a paid resource means payment\n * without delivery. Config refuses any such residue, and the OpenAPI importer\n * skips the operation.\n */\nexport function findUnparsedBraceToken(url: string): string | undefined {\n const residue = url.replace(PATH_PARAM_PATTERN, '');\n const index = residue.search(/[{}]/);\n if (index === -1) return undefined;\n // Report the offending run, not just the character, so the error is fixable\n const token = /\\{[^{}]*\\}?|\\}/.exec(residue.slice(index));\n return token?.[0] ?? residue[index];\n}\n\n/**\n * Check path values, query collisions and headers before pricing. `call()`\n * repeats these checks. Invalid input or forwarded headers raise\n * `INPUT_INVALID`; invalid configured headers raise `BACKEND_ERROR`.\n * An unparseable URL remains a call-time error. Does no I/O.\n */\nexport function validateBackendRequestShape(\n handler: BackendHandler,\n input: unknown,\n context: ShapeContext,\n backendHeaders?: Readonly<Record<string, string>>,\n): void {\n const inputRecord = isRecord(input) ? input : {};\n\n // Every shape error (missing or invalid path parameter, a bound group that is\n // not an object) throws INPUT_INVALID here\n const parts = buildBackendRequestParts(handler, inputRecord, context);\n // Config refuses a bad header at load; this covers a hand-built resource\n buildHeaders(handler, context, backendHeaders);\n\n let target: URL;\n try {\n target = new URL(parts.url);\n } catch {\n return; // call() raises BACKEND_ERROR for an unparseable URL\n }\n checkQueryCollision(target, parts.query, context);\n}\n\ntype ShapeContext = { readonly requestId: string; readonly resourceId: string };\n\n// The path-templated URL plus the query and body values a request carries\ninterface BackendRequestParts {\n readonly url: string;\n readonly query: Record<string, unknown>;\n // Present when a JSON body should be sent; `value` is what gets encoded\n readonly body?: { readonly value: unknown };\n}\n\nfunction acceptsBody(method: BackendMethod): boolean {\n return method !== 'GET' && method !== 'DELETE';\n}\n\n/**\n * Split validated input into URL, query and body according to\n * `handler.inputBindings`. `call()` and `validateBackendRequestShape()` both\n * use it, so they cannot disagree about the request an input describes. Throws\n * only `CommerceError('INPUT_INVALID')`.\n */\nexport function buildBackendRequestParts(\n handler: BackendHandler,\n input: Record<string, unknown>,\n context: ShapeContext,\n): BackendRequestParts {\n const bindings = handler.inputBindings;\n if (bindings === undefined) {\n const { url, remaining } = applyPathTemplate(handler.url, input, context);\n return acceptsBody(handler.method)\n ? { url, query: {}, body: { value: remaining } }\n : { url, query: remaining };\n }\n\n const pathValues =\n bindings.path === undefined ? {} : resolveBoundGroup(input, bindings.path, 'path', context);\n const { url } = applyPathTemplate(handler.url, pathValues, context);\n const query =\n bindings.query === undefined ? {} : resolveBoundGroup(input, bindings.query, 'query', context);\n\n // An absent body value sends no body rather than `null`. A required body is\n // enforced earlier, by `required` in the resource's input schema.\n const bodyValue = bindings.body === undefined ? undefined : input[bindings.body];\n if (bodyValue === undefined || !acceptsBody(handler.method)) return { url, query };\n return { url, query, body: { value: bodyValue } };\n}\n\nfunction resolveBoundGroup(\n input: Record<string, unknown>,\n key: string,\n kind: 'path' | 'query',\n context: ShapeContext,\n): Record<string, unknown> {\n const value = input[key];\n if (value === undefined) return {};\n if (!isRecord(value)) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Input \"${key}\" must be an object of ${kind} parameters`,\n { ...context, details: { field: key } },\n );\n }\n return value;\n}\n\nexport function checkQueryCollision(\n target: URL,\n remaining: Record<string, unknown>,\n context: { readonly requestId: string; readonly resourceId: string },\n): void {\n const templateKeys = new Set(target.searchParams.keys());\n for (const key of Object.keys(remaining)) {\n if (templateKeys.has(key)) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Input key \"${key}\" collides with a query parameter already set on backend.url`,\n { requestId: context.requestId, resourceId: context.resourceId, details: { field: key } },\n );\n }\n }\n}\n\n// encodeURIComponent leaves \".\" alone, and new URL() then resolves a \".\" or\n// \"..\" segment, stepping outside the template's directory. Slashes are\n// escaped, so only these exact values (and \"\", an empty segment) need refusing.\nconst TRAVERSAL_PATH_VALUES = new Set(['', '.', '..']);\n\nfunction applyPathTemplate(\n template: string,\n input: Record<string, unknown>,\n context: ShapeContext,\n): { url: string; remaining: Record<string, unknown> } {\n const remaining: Record<string, unknown> = { ...input };\n let missing: string | undefined;\n let invalid: string | undefined;\n const url = template.replace(PATH_PARAM_PATTERN, (_match, key: string) => {\n // Object.hasOwn, not `in`: a parameter named \"constructor\" or \"toString\"\n // would otherwise resolve to the inherited Object.prototype member\n if (!Object.hasOwn(remaining, key)) {\n missing = key;\n return '';\n }\n const value = remaining[key];\n delete remaining[key];\n const raw = stringifyPrimitive(value);\n if (TRAVERSAL_PATH_VALUES.has(raw)) {\n invalid = key;\n return '';\n }\n return encodeURIComponent(raw);\n });\n if (missing !== undefined) {\n // Config refuses a template parameter the input schema cannot supply.\n // This covers a hand-built `CommerceResource` that skipped config: through\n // validateBackendRequestShape it fails before payment, instead of calling\n // the backend with an empty path segment.\n throw new CommerceError('INPUT_INVALID', `Path parameter \"${missing}\" was not supplied`, {\n ...context,\n details: { field: missing },\n });\n }\n if (invalid !== undefined) {\n throw new CommerceError('INPUT_INVALID', `Path parameter \"${invalid}\" is not a valid value`, {\n ...context,\n details: { field: invalid },\n });\n }\n return { url, remaining };\n}\n\nexport function stringifyPrimitive(value: unknown): string {\n if (value === undefined || value === null) return '';\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n// `Headers` throws a TypeError on an illegal name or value. The error is\n// rethrown typed and without `cause`: the TypeError quotes the value, which may\n// be a credential.\nexport function buildHeaders(\n handler: BackendHandler,\n context: ShapeContext,\n forwarded: Readonly<Record<string, string>> = {},\n): Headers {\n let headers: Headers;\n try {\n headers = new Headers(handler.headers);\n } catch {\n throw invalidHeaderError(context);\n }\n // Caller headers cannot replace operator-configured backend credentials\n for (const [name, value] of Object.entries(forwarded)) {\n if (NEVER_FORWARDED_HEADER.test(name.toLowerCase())) continue;\n try {\n if (!headers.has(name)) headers.set(name, value);\n } catch {\n throw new CommerceError('INPUT_INVALID', 'A forwarded request header is invalid', {\n ...context,\n details: { reason: 'invalid-forwarded-header' },\n });\n }\n }\n return headers;\n}\n\nexport function setHeader(\n headers: Headers,\n name: string,\n value: string,\n context: ShapeContext,\n): void {\n try {\n headers.set(name, value);\n } catch {\n throw invalidHeaderError(context);\n }\n}\n\nfunction invalidHeaderError(context: ShapeContext): CommerceError {\n return new CommerceError('BACKEND_ERROR', 'Backend request headers are invalid', {\n ...context,\n details: { reason: 'invalid-header' },\n });\n}\n","/**\n * The built-in outbound HTTP path to a merchant backend.\n *\n * - Global `fetch`, always bounded by `AbortSignal.timeout`.\n * - `redirect: 'manual'`: a 3xx response is a `BACKEND_ERROR`, never followed\n * (SSRF hardening).\n * - `{param}` segments in `handler.url` are filled from validated input and\n * URL-encoded; the rest is mapped as `BackendHandler.inputBindings`\n * describes (see `backend-request.ts`).\n */\nimport { type BackendHandler, DEFAULT_BACKEND_TIMEOUT_MS } from '../domain/resource';\nimport { CommerceError, isCommerceError } from '../errors';\nimport type { BackendExecutor, BackendRequest, BackendResponse } from '../interfaces/backend';\nimport { type Logger, NOOP_LOGGER } from '../interfaces/logger';\nimport { isRecord } from '../is-record';\nimport {\n buildBackendRequestParts,\n buildHeaders,\n checkQueryCollision,\n setHeader,\n stringifyPrimitive,\n} from './backend-request';\n\nconst MAX_BODY_SNIPPET_LENGTH = 512;\n\n// How a merchant recognizes a repeat of an operation. The de facto standard\n// name, and the one ACP requires inbound.\nconst IDEMPOTENCY_KEY_HEADER = 'idempotency-key';\n\n// The timeout bounds a response by time, not bytes; this stops a hostile or\n// broken backend from filling memory\nconst MAX_RESPONSE_BODY_BYTES = 1024 * 1024;\n\nexport interface HttpBackendExecutorOptions {\n /** Override for `fetch`, used in tests. Defaults to the global implementation */\n readonly fetchImpl?: typeof fetch;\n /** Receives a non-2xx backend body at debug level; it never reaches the client */\n readonly logger?: Logger;\n}\n\n/**\n * Merchant non-2xx response attached as the `BACKEND_ERROR` cause. Adapters\n * can inspect its body and headers; client errors omit the cause.\n */\nexport class BackendErrorResponse {\n constructor(\n readonly status: number,\n readonly body: unknown,\n /** Lowercase names, as `Headers` yields them */\n readonly headers: Readonly<Record<string, string>> = {},\n ) {}\n}\n\nexport class HttpBackendExecutor implements BackendExecutor {\n private readonly fetchImpl: typeof fetch;\n private readonly logger: Logger;\n\n constructor(options: HttpBackendExecutorOptions = {}) {\n this.fetchImpl = options.fetchImpl ?? fetch;\n this.logger = options.logger ?? NOOP_LOGGER;\n }\n\n async call(handler: BackendHandler, request: BackendRequest): Promise<BackendResponse> {\n const timeoutMs = handler.timeoutMs ?? DEFAULT_BACKEND_TIMEOUT_MS;\n const inputRecord = isRecord(request.input) ? request.input : {};\n\n const context = { requestId: request.requestId, resourceId: request.resourceId };\n // Throws INPUT_INVALID for every shape problem. The pipeline already ran it\n // before payment through validateBackendRequestShape(); this copy covers a\n // caller that bypasses the pipeline.\n const parts = buildBackendRequestParts(handler, inputRecord, context);\n\n let target: URL;\n try {\n target = new URL(parts.url);\n } catch (error) {\n throw new CommerceError('BACKEND_ERROR', 'Backend URL could not be constructed from input', {\n ...context,\n details: { reason: 'invalid-url' },\n cause: error,\n });\n }\n\n // Beyond the per-parameter check: the resolved path must stay under the\n // template's literal prefix (everything before the first `{`)\n const prefixPathname = literalPrefixPathname(handler);\n if (prefixPathname !== undefined && !target.pathname.startsWith(prefixPathname)) {\n throw new CommerceError(\n 'INPUT_INVALID',\n 'Path parameters resolved outside the configured backend path',\n context,\n );\n }\n\n const headers = buildHeaders(handler, context, request.backendHeaders);\n // Replaces a configured header of the same name, unlike content-type below:\n // a static key would make every request look like a retry of the first\n if (request.idempotencyKey !== undefined) {\n setHeader(headers, IDEMPOTENCY_KEY_HEADER, request.idempotencyKey, context);\n }\n let body: string | undefined;\n\n // searchParams.set() replaces an existing param, so a caller key named\n // like an operator's query param (`?apikey=SECRET` in handler.url) would\n // overwrite it. validateBackendRequestShape() runs the same check before\n // payment.\n checkQueryCollision(target, parts.query, context);\n for (const [key, value] of Object.entries(parts.query)) {\n target.searchParams.set(key, stringifyPrimitive(value));\n }\n if (parts.body !== undefined) {\n body = JSON.stringify(parts.body.value);\n // A configured Content-Type, such as `application/vnd.x+json`, wins\n if (!headers.has('content-type')) headers.set('content-type', 'application/json');\n }\n\n const started = performance.now();\n let response: Response;\n try {\n response = await this.fetchImpl(target, {\n method: handler.method,\n headers,\n ...(body !== undefined ? { body } : {}),\n redirect: 'manual',\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n const durationMs = Math.round(performance.now() - started);\n if (isAbortError(error)) {\n throw new CommerceError(\n 'BACKEND_TIMEOUT',\n `Backend request timed out after ${timeoutMs}ms`,\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { timeoutMs, durationMs },\n cause: error,\n },\n );\n }\n throw new CommerceError('BACKEND_ERROR', 'Backend request failed (transport error)', {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { durationMs },\n cause: error,\n });\n }\n const durationMs = Math.round(performance.now() - started);\n\n const isRedirect =\n response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400);\n if (isRedirect) {\n throw new CommerceError(\n 'BACKEND_ERROR',\n 'Backend responded with a redirect, which is not followed',\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { status: response.status, reason: 'redirect-not-followed' },\n },\n );\n }\n\n const responseHeaders = Object.fromEntries(response.headers);\n const contentType = response.headers.get('content-type') ?? '';\n let parsedBody: unknown;\n try {\n parsedBody = await parseBody(response, contentType);\n } catch (error) {\n const tooLarge = isCommerceError(error);\n throw new CommerceError(\n 'BACKEND_ERROR',\n tooLarge\n ? 'Backend response exceeded the maximum allowed size'\n : 'Backend response could not be read',\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: tooLarge\n ? { reason: 'response-too-large', maxBytes: MAX_RESPONSE_BODY_BYTES }\n : { reason: 'read-error' },\n cause: error,\n },\n );\n }\n\n if (response.status < 200 || response.status >= 300) {\n // The status may reach the client, but the body is logged at debug level\n // only: a backend in verbose error mode emits stack traces, hostnames or\n // SQL fragments, and the caller may be anonymous\n this.logger.debug(\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n status: response.status,\n bodySnippet: truncateSnippet(parsedBody),\n },\n 'Backend responded with a non-2xx status',\n );\n throw new CommerceError('BACKEND_ERROR', `Backend responded with status ${response.status}`, {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { status: response.status },\n cause: new BackendErrorResponse(response.status, parsedBody, responseHeaders),\n });\n }\n\n return {\n status: response.status,\n headers: responseHeaders,\n body: parsedBody,\n durationMs,\n };\n }\n}\n\n// `handler.url` never changes, so its literal prefix is parsed once per handler.\n// `null` records a prefix that is not a URL, as when a parameter sits in the\n// host (which config refuses); the containment check is then skipped.\nconst prefixPathnames = new WeakMap<BackendHandler, string | null>();\n\nfunction literalPrefixPathname(handler: BackendHandler): string | undefined {\n let cached = prefixPathnames.get(handler);\n if (cached === undefined) {\n try {\n cached = new URL(handler.url.split('{')[0] ?? handler.url).pathname;\n } catch {\n cached = null;\n }\n prefixPathnames.set(handler, cached);\n }\n return cached ?? undefined;\n}\n\nasync function readBodyCapped(response: Response, maxBytes: number): Promise<string> {\n if (!response.body) return '';\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n // The only CommerceError parseBody can throw, which is how its caller\n // tells an oversized body from a read failure\n throw new CommerceError('BACKEND_ERROR', `response body exceeded ${maxBytes} bytes`);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks).toString('utf8');\n}\n\nasync function parseBody(response: Response, contentType: string): Promise<unknown> {\n const text = await readBodyCapped(response, MAX_RESPONSE_BODY_BYTES);\n if (text.length === 0) return text;\n if (contentType.includes('json')) {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n return text;\n}\n\nfunction truncateSnippet(body: unknown): string {\n const text = typeof body === 'string' ? body : safeStringify(body);\n return text.length > MAX_BODY_SNIPPET_LENGTH\n ? `${text.slice(0, MAX_BODY_SNIPPET_LENGTH)}…`\n : text;\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError');\n}\n","/**\n * A small JSON Schema validator for resource input.\n *\n * Supported subset (draft 2020-12 vocabulary, structural only):\n * - `type`: \"object\" | \"string\" | \"number\" | \"integer\" | \"boolean\" | \"array\" |\n * \"null\", or an array of those (e.g. `[\"object\", \"null\"]`)\n * - `properties` (validated recursively)\n * - `required` (string[])\n * - `additionalProperties` (boolean, or a schema applied to extra properties)\n * - `enum` (allowed values; objects and arrays compared structurally, in any key\n * order)\n * - `items` (one schema applied to every array element, no tuple form)\n *\n * Not enforced: `minLength`, `maxLength`, `pattern`, `format`, `minimum`,\n * `maximum`, `exclusiveMinimum/Maximum`, `multipleOf`, `oneOf`, `anyOf`,\n * `allOf`, `not`, `$ref`, `const`, `patternProperties`, `minItems`,\n * `maxItems`, `uniqueItems`, tuple-form `items`, and a `type` naming anything\n * outside the list above. Config warns at load when a schema uses one of these\n * keywords or a tuple `items`.\n */\nimport { isDeepStrictEqual } from 'node:util';\nimport type { JsonSchema } from '../domain/common';\nimport { isRecord } from '../is-record';\n\nexport interface FieldError {\n readonly path: string;\n readonly message: string;\n}\n\nexport type ValidationResult =\n | { readonly valid: true; readonly value: unknown }\n | { readonly valid: false; readonly errors: readonly FieldError[] };\n\nexport type Validator = (input: unknown) => ValidationResult;\n\nconst SUPPORTED_TYPES = new Set([\n 'object',\n 'string',\n 'number',\n 'integer',\n 'boolean',\n 'array',\n 'null',\n]);\n\n/** Wrap a resource `inputSchema` in a reusable validator function */\nexport function compileJsonSchema(schema: JsonSchema | undefined): Validator {\n return (input: unknown): ValidationResult => {\n if (schema === undefined) return { valid: true, value: input };\n const errors = validateNode(schema, input, '$');\n return errors.length === 0 ? { valid: true, value: input } : { valid: false, errors };\n };\n}\n\nfunction matchesType(type: string, value: unknown): boolean {\n switch (type) {\n case 'object':\n return isRecord(value);\n case 'array':\n return Array.isArray(value);\n case 'string':\n return typeof value === 'string';\n case 'boolean':\n return typeof value === 'boolean';\n case 'number':\n return typeof value === 'number' && Number.isFinite(value);\n case 'integer':\n return typeof value === 'number' && Number.isInteger(value);\n case 'null':\n return value === null;\n default:\n return true;\n }\n}\n\nfunction describeType(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n return typeof value;\n}\n\n// `===` first keeps a top-level -0 equal to 0; isDeepStrictEqual alone would not\nfunction deepEqual(a: unknown, b: unknown): boolean {\n return a === b || isDeepStrictEqual(a, b);\n}\n\nfunction own(obj: Record<string, unknown>, key: string): unknown {\n return Object.hasOwn(obj, key) ? obj[key] : undefined;\n}\n\n// `type` may be a string or an array of strings, e.g. `[\"object\", \"null\"]`. An\n// array with a non-string entry is ignored rather than guessed at.\nfunction typeList(raw: unknown): string[] | undefined {\n if (typeof raw === 'string') return [raw];\n if (Array.isArray(raw) && raw.every((entry): entry is string => typeof entry === 'string')) {\n return raw;\n }\n return undefined;\n}\n\n/**\n * Whether a schema node is an object schema: its `type` includes \"object\"\n * (`[\"object\", \"null\"]` counts), or it has no `type` and declares `properties`\n * or `required`.\n *\n * Config's `defaultClosedObjectSchema` uses it to close schemas and this\n * validator uses it to enforce them. With two definitions, a node could stay\n * open while config believes it closed.\n */\nexport function isObjectSchemaNode(schema: Record<string, unknown>): boolean {\n const types = typeList(schema['type']);\n if (types !== undefined) return types.includes('object');\n return Object.hasOwn(schema, 'properties') || Object.hasOwn(schema, 'required');\n}\n\nfunction validateNode(schema: JsonSchema, value: unknown, path: string): FieldError[] {\n const errors: FieldError[] = [];\n const types = typeList(own(schema, 'type'));\n const recognizedTypes = types?.filter((entry) => SUPPORTED_TYPES.has(entry));\n\n if (\n types !== undefined &&\n recognizedTypes !== undefined &&\n recognizedTypes.length === types.length &&\n types.length > 0\n ) {\n if (!types.some((entry) => matchesType(entry, value))) {\n errors.push({\n path,\n message: `expected type \"${types.join(' | ')}\" but got ${describeType(value)}`,\n });\n return errors;\n }\n }\n\n const enumRaw = own(schema, 'enum');\n if (Array.isArray(enumRaw)) {\n const allowed = enumRaw as unknown[];\n if (!allowed.some((candidate) => deepEqual(candidate, value))) {\n errors.push({ path, message: `must be one of ${JSON.stringify(allowed)}` });\n }\n }\n\n if (isObjectSchemaNode(schema) && isRecord(value)) {\n errors.push(...validateObject(schema, value, path));\n } else if ((types?.includes('array') ?? false) && Array.isArray(value)) {\n errors.push(...validateArray(schema, value, path));\n }\n\n return errors;\n}\n\nfunction validateObject(\n schema: JsonSchema,\n value: Record<string, unknown>,\n path: string,\n): FieldError[] {\n const errors: FieldError[] = [];\n const propsRaw = own(schema, 'properties');\n const properties = isRecord(propsRaw) ? propsRaw : {};\n const requiredRaw = own(schema, 'required');\n const required = Array.isArray(requiredRaw)\n ? requiredRaw.filter((entry): entry is string => typeof entry === 'string')\n : [];\n\n for (const key of required) {\n // Object.hasOwn, not `in`: `in` walks the prototype chain, so a required\n // \"toString\" or \"__proto__\" would always look present\n if (!Object.hasOwn(value, key)) {\n errors.push({ path: `${path}.${key}`, message: 'is required' });\n }\n }\n\n const additional = own(schema, 'additionalProperties');\n\n for (const key of Object.keys(value)) {\n // Own-property lookup: `properties[\"toString\"]` would find the inherited\n // member and skip the additionalProperties check below\n const propSchemaRaw = own(properties, key);\n if (propSchemaRaw !== undefined) {\n if (isRecord(propSchemaRaw)) {\n errors.push(...validateNode(propSchemaRaw, value[key], `${path}.${key}`));\n }\n continue;\n }\n if (additional === false) {\n errors.push({ path: `${path}.${key}`, message: 'additional property not allowed' });\n } else if (isRecord(additional)) {\n errors.push(...validateNode(additional, value[key], `${path}.${key}`));\n }\n }\n\n return errors;\n}\n\nfunction validateArray(schema: JsonSchema, value: unknown[], path: string): FieldError[] {\n const errors: FieldError[] = [];\n const itemsRaw = own(schema, 'items');\n if (isRecord(itemsRaw)) {\n value.forEach((item, index) => {\n errors.push(...validateNode(itemsRaw, item, `${path}[${index}]`));\n });\n }\n return errors;\n}\n","// Verifies and reserves the authorization a resource requires, before its payment is reserved\nimport type { AuthorizationProvider, AuthorizationVerification } from '../../domain/authorization';\nimport type { AuthorizationMethodName } from '../../domain/common';\nimport type { PaymentRequirement } from '../../domain/payment';\nimport type { CanonicalRequest } from '../../domain/request';\nimport type { CommerceResource } from '../../domain/resource';\nimport { CommerceError, describeError, isCommerceError } from '../../errors';\nimport type { AuthorizationHold, PipelineContext } from './context';\n\n// The provider for each method a resource requires, in the resource's order.\n// Config refuses a method that is not enabled at load; it is checked again\n// because missing it here would serve the resource with no authorization.\nexport function resolveAuthorizationProviders(\n providers: readonly AuthorizationProvider[],\n resource: CommerceResource,\n requestId: string,\n): readonly AuthorizationProvider[] {\n const required = resource.authorization?.required ?? [];\n return required.map((method: AuthorizationMethodName) => {\n const found = providers.find((provider) => provider.name === method);\n if (!found) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${resource.id}\" requires authorization method \"${method}\", which is not enabled`,\n { requestId, resourceId: resource.id },\n );\n }\n return found;\n });\n}\n\nexport type AuthorizeAndReserve = (\n request: CanonicalRequest,\n resource: CommerceResource,\n providers: readonly AuthorizationProvider[],\n requirement: PaymentRequirement,\n input: unknown,\n) => Promise<AuthorizationHold | undefined>;\n\nexport function createAuthorizeAndReserve(ctx: PipelineContext): AuthorizeAndReserve {\n const { options, safeEmit, buildEvent } = ctx;\n\n // Verify and reserve what the resource requires, or undefined if it requires\n // none. Runs after payment verification, which has no side effect, so a bad\n // payment proof cannot burn a reservation.\n async function authorizeAndReserve(\n request: CanonicalRequest,\n resource: CommerceResource,\n providers: readonly AuthorizationProvider[],\n requirement: PaymentRequirement,\n input: unknown,\n ): Promise<AuthorizationHold | undefined> {\n if (providers.length === 0) return undefined;\n\n const submission = request.authorization;\n const provider = providers.find((candidate) => candidate.name === submission?.method);\n // A request carries one proof, so a resource requiring two methods is\n // refused here rather than half-checked\n const unmet = providers.filter((candidate) => candidate !== provider).map((c) => c.name);\n\n if (submission === undefined || provider === undefined || unmet.length > 0) {\n await safeEmit(\n buildEvent({\n type: 'authorization.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'error',\n data: { reason: 'AUTHORIZATION_REQUIRED', methods: unmet },\n }),\n );\n throw new CommerceError(\n 'AUTHORIZATION_REQUIRED',\n `Resource \"${resource.id}\" requires authorization: ${unmet.join(', ')}`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n details: { required: providers.map((candidate) => candidate.name), missing: unmet },\n },\n );\n }\n\n let verification: AuthorizationVerification;\n try {\n verification = await provider.verifyAndReserve({\n requestId: request.requestId,\n resourceId: resource.id,\n input,\n submission,\n requirement,\n });\n } catch (error) {\n // An untyped throw says nothing about whose fault it was. Unavailable is\n // honest and retryable; invalid would blame the buyer for our outage.\n const mapped = isCommerceError(error)\n ? error\n : new CommerceError(\n 'AUTHORIZATION_PROVIDER_UNAVAILABLE',\n 'Authorization provider is unavailable',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n },\n );\n await safeEmit(\n buildEvent({\n type: 'authorization.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'error',\n data: { reason: mapped.code, method: provider.name },\n }),\n );\n throw mapped;\n }\n\n await safeEmit(\n buildEvent({\n type: 'authorization.verified',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'ok',\n data: { method: verification.method, reference: verification.reference },\n }),\n );\n\n const context = { requestId: request.requestId, resourceId: resource.id };\n return {\n record: {\n method: verification.method,\n reference: verification.reference,\n ...(verification.metadata !== undefined ? { metadata: verification.metadata } : {}),\n },\n async finalize(action) {\n try {\n await provider[action](verification.reservationId, context);\n } catch (error) {\n // A failure leaves the reservation reserved, which is still\n // unspendable, so the caller's outcome stands\n options.logger.error(\n { err: describeError(error), requestId: request.requestId, action },\n 'Authorization finalization failed; the reservation stays reserved',\n );\n }\n },\n };\n }\n\n return authorizeAndReserve;\n}\n","// What a refused or replayed payment answers with: the unused challenge, when one may be retried\nimport type { PaymentRequirement } from '../../domain/payment';\nimport { CommerceError } from '../../errors';\n\n// A refusal leaves this request's challenge unused. Return it with the\n// provider's reason so the client can retry without fetching another challenge\nexport function retryChallenge(\n requirement: PaymentRequirement,\n reason?: string,\n): { details?: Record<string, unknown> } {\n const envelope = requirement.challenge.envelope;\n if (envelope === undefined && reason === undefined) return {};\n return {\n details: {\n ...(envelope !== undefined ? { challenge: envelope } : {}),\n ...(reason !== undefined ? { reason } : {}),\n },\n };\n}\n\n// Attempt statuses the pipeline treats as finished when handling a replay. The\n// legacy `failed` is not one: it recorded any throw from settle(), so it may\n// hide a transfer, like `settlement-uncertain`.\nconst FINISHED_ATTEMPT_STATUSES: ReadonlySet<string> = new Set(['settled', 'rejected']);\n\n// Include the paid offer's network for the rail's replay code. Finished\n// attempts get 402 with a fresh challenge; unfinished or unreadable attempts\n// keep 409 to avoid prompting a second payment.\nexport function replayError(error: CommerceError, requirement: PaymentRequirement): CommerceError {\n if (error.code !== 'PAYMENT_REPLAYED') return error;\n const status = error.details?.['attemptStatus'];\n const finished = typeof status === 'string' && FINISHED_ATTEMPT_STATUSES.has(status);\n const network = requirement.network;\n if (!finished && network === undefined) return error;\n return new CommerceError('PAYMENT_REPLAYED', error.message, {\n ...(error.requestId !== undefined ? { requestId: error.requestId } : {}),\n ...(error.resourceId !== undefined ? { resourceId: error.resourceId } : {}),\n ...(finished ? { httpStatus: 402 } : {}),\n details: {\n ...error.details,\n ...(network !== undefined ? { network } : {}),\n ...(finished ? retryChallenge(requirement).details : {}),\n },\n });\n}\n","// The payment phase: challenge, offer selection, verification, and the authorization and replay reservations\n\nimport type { PaymentMethodName } from '../../domain/common';\nimport type { PaymentProvider, PaymentRequirement, PaymentResult } from '../../domain/payment';\nimport type { CanonicalRequest, PaymentRequiredOutcome } from '../../domain/request';\nimport type { CommerceResource, Pricing } from '../../domain/resource';\nimport { CommerceError, isCommerceError, toCommerceError } from '../../errors';\nimport { REUSE_REJECTED_AUTHORIZATION_METADATA_KEY } from '../settlement-order';\nimport { type AuthorizeAndReserve, resolveAuthorizationProviders } from './authorization';\nimport { replayError, retryChallenge } from './challenge';\nimport type { PipelineContext, SettleArgs } from './context';\n\n/** A verified payment whose authorization and replay identity are reserved */\nexport interface AdmittedPayment {\n readonly kind: 'admitted';\n readonly settleArgs: SettleArgs;\n}\n\nexport type AdmitPayment = (\n request: CanonicalRequest,\n resource: CommerceResource,\n pricing: Extract<Pricing, { type: 'fixed' }>,\n validInput: unknown,\n) => Promise<PaymentRequiredOutcome | AdmittedPayment>;\n\n/**\n * Builds the payment phase. It returns the challenge when the request carries\n * no proof, and otherwise verifies the proof and reserves the authorization\n * and replay identity, or throws.\n */\nexport function createPaymentAdmission(\n ctx: PipelineContext,\n authorizeAndReserve: AuthorizeAndReserve,\n): AdmitPayment {\n const { options, safeEmit, buildEvent } = ctx;\n\n return async function admitPayment(request, resource, pricing, validInput) {\n const provider = pickProvider(options.paymentProviders, resource.paymentMethods);\n if (!provider) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n `No enabled payment provider for resource \"${resource.id}\"`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n details: { paymentMethods: resource.paymentMethods },\n },\n );\n }\n\n // Resolved before the challenge so the 402 can name what the retry must\n // also carry, and so an uncheckable method fails before payment starts\n const authProviders = resolveAuthorizationProviders(\n options.authorizationProviders ?? [],\n resource,\n request.requestId,\n );\n\n let requirement: PaymentRequirement;\n try {\n requirement = await provider.createRequirement({\n requestId: request.requestId,\n resource,\n amount: pricing.amount,\n currency: pricing.currency,\n requestedAt: options.clock.nowIso(),\n // Transport facts a rail may bind into its challenge, such as a body digest\n ...(request.metadata !== undefined ? { metadata: request.metadata } : {}),\n });\n } catch (error) {\n throw isCommerceError(error)\n ? error\n : new CommerceError('PAYMENT_PROVIDER_UNAVAILABLE', 'Payment provider is unavailable', {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n });\n }\n\n if (!request.payment) {\n await safeEmit(\n buildEvent({\n type: 'payment.required',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n }),\n );\n return {\n kind: 'payment-required',\n requestId: request.requestId,\n resourceId: resource.id,\n requirement,\n ...(authProviders.length > 0\n ? { authorization: authProviders.map((p) => p.requirement) }\n : {}),\n };\n }\n\n const payment = request.payment;\n\n let verification: PaymentResult;\n try {\n // Later steps, including authorization and settlement order, use the\n // selected requirement with its full retry challenge\n if (provider.selectRequirement) {\n requirement = await provider.selectRequirement({\n requestId: request.requestId,\n resource,\n requirement,\n submission: payment,\n });\n }\n verification = await provider.verify({\n requestId: request.requestId,\n resource,\n requirement,\n submission: payment,\n });\n } catch (error) {\n // A typed CommerceError is rethrown as is, keeping its code and its\n // possibly retryable status. Only an untyped throw is mapped, with a\n // fixed client-facing message.\n const mapped = isCommerceError(error)\n ? error\n : new CommerceError('PAYMENT_INVALID', 'Payment verification failed', {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n ...retryChallenge(requirement),\n });\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: mapped.code },\n }),\n );\n throw mapped;\n }\n\n if (verification.status !== 'verified') {\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: verification.rejectionReason ? { reason: verification.rejectionReason } : {},\n }),\n );\n throw new CommerceError(\n 'PAYMENT_INVALID',\n verification.rejectionReason ?? 'Payment was rejected',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n ...retryChallenge(requirement, verification.rejectionReason),\n },\n );\n }\n\n if (!verification.replayKey) {\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: 'missing-replay-key' },\n }),\n );\n throw new CommerceError('PAYMENT_INVALID', 'Payment provider did not return a replay key', {\n requestId: request.requestId,\n resourceId: resource.id,\n });\n }\n const replayKey = verification.replayKey;\n\n const hold = await authorizeAndReserve(\n request,\n resource,\n authProviders,\n requirement,\n validInput,\n );\n\n try {\n await options.store.reservePaymentAttempt({\n requestId: request.requestId,\n resourceId: resource.id,\n provider: provider.name,\n replayKey,\n amount: verification.amount,\n currency: verification.currency,\n ...(verification.payer !== undefined ? { payer: verification.payer } : {}),\n ...(verification.payee !== undefined ? { payee: verification.payee } : {}),\n ...(requirement.metadata?.[REUSE_REJECTED_AUTHORIZATION_METADATA_KEY] === true\n ? { reclaimRejected: true }\n : {}),\n });\n } catch (error) {\n // A duplicate replayKey arrives as PAYMENT_REPLAYED and is kept. Any\n // other failure (a full disk, a dropped connection) is STORAGE_ERROR,\n // never a replay.\n const mapped = toCommerceError(\n error,\n 'STORAGE_ERROR',\n 'Payment attempt could not be recorded',\n );\n await hold?.finalize('release');\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: mapped.code },\n }),\n );\n throw replayError(mapped, requirement);\n }\n\n await safeEmit(\n buildEvent({\n type: 'payment.verified',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'ok',\n }),\n );\n\n return {\n kind: 'admitted',\n settleArgs: {\n request,\n resource,\n provider,\n requirement,\n payment,\n verification,\n replayKey,\n hold,\n },\n };\n };\n}\n\nfunction pickProvider(\n providers: readonly PaymentProvider[],\n methods: readonly PaymentMethodName[],\n): PaymentProvider | undefined {\n for (const method of methods) {\n const found = providers.find((provider) => provider.name === method);\n if (found) return found;\n }\n return undefined;\n}\n","// What the pipeline's stages share: its options, and event and persistence writes that never fail a flow\nimport type { AuthorizationProvider, AuthorizationRecord } from '../../domain/authorization';\nimport type { CommerceEvent, EventSink } from '../../domain/event';\nimport type {\n PaymentProvider,\n PaymentRequirement,\n PaymentResult,\n PaymentSubmission,\n} from '../../domain/payment';\nimport type { CanonicalRequest } from '../../domain/request';\nimport type { CommerceResource, ResourceRegistry } from '../../domain/resource';\nimport { describeError } from '../../errors';\nimport type { BackendExecutor } from '../../interfaces/backend';\nimport type { Logger } from '../../interfaces/logger';\nimport type { Clock, IdGenerator } from '../../interfaces/runtime';\nimport type { ReceiptStore } from '../../interfaces/store';\n\nexport interface CreateExecutionPipelineOptions {\n readonly resources: ResourceRegistry;\n readonly paymentProviders: readonly PaymentProvider[];\n /** Defaults to none */\n readonly authorizationProviders?: readonly AuthorizationProvider[];\n readonly store: ReceiptStore;\n readonly backend: BackendExecutor;\n readonly events: EventSink;\n readonly logger: Logger;\n readonly clock: Clock;\n readonly ids: IdGenerator;\n}\n\n/**\n * A reservation held across settlement, plus the summary the receipt keeps.\n * `finalize` ends it.\n */\nexport interface AuthorizationHold {\n readonly record: AuthorizationRecord;\n finalize(action: 'consume' | 'release' | 'markUncertain'): Promise<void>;\n}\n\n/** A verified, reserved payment and everything its settlement needs */\nexport interface SettleArgs {\n readonly request: CanonicalRequest;\n readonly resource: CommerceResource;\n readonly provider: PaymentProvider;\n readonly requirement: PaymentRequirement;\n readonly payment: PaymentSubmission;\n readonly verification: PaymentResult;\n readonly replayKey: string;\n readonly hold: AuthorizationHold | undefined;\n}\n\nexport interface PipelineContext {\n readonly options: CreateExecutionPipelineOptions;\n /** Emits an event; a failing sink is logged, never thrown */\n readonly safeEmit: (event: CommerceEvent) => Promise<void>;\n /** Runs a store write; a failure is logged, never thrown */\n readonly safePersist: (\n op: () => Promise<void>,\n label: string,\n requestId: string,\n ) => Promise<void>;\n readonly buildEvent: (partial: Omit<CommerceEvent, 'id' | 'at'>) => CommerceEvent;\n}\n\nexport function createPipelineContext(options: CreateExecutionPipelineOptions): PipelineContext {\n async function safeEmit(event: CommerceEvent): Promise<void> {\n try {\n await options.events.emit(event);\n } catch (error) {\n options.logger.error(\n { err: describeError(error), eventType: event.type, requestId: event.requestId },\n 'Event sink failed; commerce flow continues',\n );\n }\n }\n\n async function safePersist(\n op: () => Promise<void>,\n label: string,\n requestId: string,\n ): Promise<void> {\n try {\n await op();\n } catch (error) {\n options.logger.error(\n { err: describeError(error), requestId },\n `Persistence failed: ${label}`,\n );\n }\n }\n\n function buildEvent(partial: Omit<CommerceEvent, 'id' | 'at'>): CommerceEvent {\n return { id: options.ids.next('evt'), at: options.clock.nowIso(), ...partial };\n }\n\n return { options, safeEmit, safePersist, buildEvent };\n}\n","// Settles a verified, reserved payment, or records that the backend failed before it could\nimport type { PaymentRequirement, PaymentResult } from '../../domain/payment';\nimport { CommerceError, isCommerceError } from '../../errors';\nimport { retryChallenge } from './challenge';\nimport type { PipelineContext, SettleArgs } from './context';\n\nexport interface Settlement {\n /** Settles and finalizes the authorization; a refusal or unknown outcome throws */\n readonly settle: (args: SettleArgs) => Promise<PaymentResult>;\n /** Records a backend failure before settlement and releases the authorization */\n readonly abandonSettlement: (args: SettleArgs, backendErrorCode: string) => Promise<void>;\n}\n\nexport function createSettlement(ctx: PipelineContext): Settlement {\n const { options, safeEmit, safePersist, buildEvent } = ctx;\n\n // Settle a verified, reserved payment and finalize its authorization.\n // Rejected or uncertain settlement throws before any response is delivered.\n async function settle(args: SettleArgs): Promise<PaymentResult> {\n const { request, resource, provider, requirement, payment, verification, replayKey, hold } =\n args;\n let settlement: PaymentResult;\n try {\n settlement = await provider.settle({\n requestId: request.requestId,\n resource,\n requirement,\n submission: payment,\n verification,\n });\n } catch (error) {\n // Confirmed non-submission leaves the authorization spendable. Release\n // it for retry and report the provider failure.\n const notSubmitted = notSubmittedReason(error);\n if (notSubmitted !== undefined) {\n await hold?.finalize('release');\n await safePersist(\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'rejected',\n rejectionReason: notSubmitted,\n }),\n 'updatePaymentAttempt(not-submitted)',\n request.requestId,\n );\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: 'settlement-not-submitted', providerReason: notSubmitted },\n }),\n );\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'The payment provider could not settle the payment; nothing was charged',\n { requestId: request.requestId, resourceId: resource.id, cause: error },\n );\n }\n // A throw gives no settlement verdict. The facilitator may have\n // broadcast before losing its response, even without a transaction\n // hash. Keep the authorization uncertain so it cannot be spent again.\n const txHash = settlementTxHash(error);\n await hold?.finalize('markUncertain');\n await safePersist(\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'settlement-uncertain',\n ...(txHash !== undefined ? { externalReference: txHash } : {}),\n ...(error instanceof Error ? { rejectionReason: error.message } : {}),\n }),\n 'updatePaymentAttempt(settlement-uncertain)',\n request.requestId,\n );\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: {\n reason: 'settlement-uncertain',\n ...(txHash !== undefined ? { transactionHash: txHash } : {}),\n },\n }),\n );\n // The replay key remains reserved, so report an uncertain, non-retryable\n // outcome. Expose only the transaction hash from the underlying error.\n throw new CommerceError('PAYMENT_SETTLEMENT_FAILED', 'Settlement could not be confirmed', {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n details: {\n settlementUncertain: true,\n ...(txHash !== undefined ? { transactionHash: txHash } : {}),\n ...settlementParties(requirement, verification),\n },\n });\n }\n\n if (settlement.status !== 'settled') {\n await hold?.finalize('release');\n await safePersist(\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'rejected',\n ...(settlement.rejectionReason !== undefined\n ? { rejectionReason: settlement.rejectionReason }\n : {}),\n ...(settlement.externalReference !== undefined\n ? { externalReference: settlement.externalReference }\n : {}),\n }),\n 'updatePaymentAttempt(rejected)',\n request.requestId,\n );\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: settlement.rejectionReason ? { reason: settlement.rejectionReason } : {},\n }),\n );\n // A returned rejection confirms no settlement. Both rails return 402.\n const rejectionDetails = retryChallenge(requirement, settlement.rejectionReason).details;\n throw new CommerceError(\n 'PAYMENT_SETTLEMENT_FAILED',\n settlement.rejectionReason ?? 'Settlement was rejected',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n httpStatus: 402,\n details: {\n ...rejectionDetails,\n ...settlementParties(requirement, settlement, verification),\n },\n },\n );\n }\n\n await hold?.finalize('consume');\n await safePersist(\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'settled',\n ...(settlement.externalReference !== undefined\n ? { externalReference: settlement.externalReference }\n : {}),\n }),\n 'updatePaymentAttempt(settled)',\n request.requestId,\n );\n await safeEmit(\n buildEvent({\n type: 'payment.settled',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'ok',\n }),\n );\n\n return settlement;\n }\n\n // Record the pre-settlement backend failure and release the authorization\n // hold. Rails with reuse metadata can reserve the unspent replay key again,\n // as after any rejection.\n async function abandonSettlement(args: SettleArgs, backendErrorCode: string): Promise<void> {\n const { request, resource, provider, replayKey, hold } = args;\n await hold?.finalize('release');\n await safePersist(\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'rejected',\n rejectionReason: 'backend_failed',\n }),\n 'updatePaymentAttempt(backend-failed)',\n request.requestId,\n );\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: 'backend-failed', backendErrorCode },\n }),\n );\n }\n\n return { settle, abandonSettlement };\n}\n\n// The reason a provider gave when it threw before submitting anything\nfunction notSubmittedReason(error: unknown): string | undefined {\n if (!isCommerceError(error) || error.details?.['settlementNotSubmitted'] !== true) {\n return undefined;\n }\n const reason = error.details['reason'];\n return typeof reason === 'string' ? reason : 'settlement_not_submitted';\n}\n\n// The broadcast transaction hash a provider attached to a settlement throw,\n// when it knows one\nfunction settlementTxHash(error: unknown): string | undefined {\n const hash = isCommerceError(error) ? error.details?.['transactionHash'] : undefined;\n return typeof hash === 'string' ? hash : undefined;\n}\n\n// Prefer the network and payer reported by settlement or verification, then\n// fall back to the requirement's network\nfunction settlementParties(\n requirement: PaymentRequirement,\n ...results: readonly PaymentResult[]\n): { network?: string; payer?: string } {\n const network = results.find((r) => r.network !== undefined)?.network ?? requirement.network;\n const payer = results.find((r) => r.payer !== undefined)?.payer;\n return {\n ...(network !== undefined ? { network } : {}),\n ...(payer !== undefined ? { payer } : {}),\n };\n}\n","/**\n * The single execution path every protocol adapter converges on. The order is a\n * security boundary; do not reorder:\n *\n * 1. resolve resource (RESOURCE_NOT_FOUND)\n * 2. strip reserved input fields, validate input and the backend request shape\n * (INPUT_INVALID, or BACKEND_ERROR for an illegal configured header)\n * 3. resolve price\n * 4. free: straight to the backend\n * 5. paid: pick provider and createRequirement, then return a challenge, or\n * select the offer the proof pays, verify it, and reserve authorization and\n * replay identities\n * 6. settle before calling the backend, or call the backend first and settle\n * only if it succeeds. Finalize authorization according to the outcome\n * (BACKEND_TIMEOUT / BACKEND_ERROR)\n * 7. persist receipt, emit events, return outcome\n */\n\nimport type { AuthorizationRecord } from '../../domain/authorization';\nimport type { PaymentResult } from '../../domain/payment';\nimport type { CommerceReceipt } from '../../domain/receipt';\nimport type { CanonicalRequest, ExecutionOutcome, ExecutionPipeline } from '../../domain/request';\nimport type { CommerceResource } from '../../domain/resource';\nimport { RESERVED_INPUT_FIELDS } from '../../domain/wire';\nimport { CommerceError, toCommerceError } from '../../errors';\nimport type { BackendResponse } from '../../interfaces/backend';\nimport { isRecord } from '../../is-record';\nimport { validateBackendRequestShape } from '../backend-request';\nimport { SETTLE_AFTER_BACKEND_METADATA_KEY } from '../settlement-order';\nimport { compileJsonSchema, type Validator } from '../validation';\nimport { createPaymentAdmission } from './admission';\nimport { createAuthorizeAndReserve } from './authorization';\nimport {\n type CreateExecutionPipelineOptions,\n createPipelineContext,\n type SettleArgs,\n} from './context';\nimport { createSettlement } from './settlement';\n\nexport type { CreateExecutionPipelineOptions } from './context';\n\nexport function createExecutionPipeline(\n options: CreateExecutionPipelineOptions,\n): ExecutionPipeline {\n const validators = new Map<string, Validator>();\n\n function getValidator(resource: CommerceResource): Validator {\n const cached = validators.get(resource.id);\n if (cached) return cached;\n const compiled = compileJsonSchema(resource.inputSchema);\n validators.set(resource.id, compiled);\n return compiled;\n }\n\n const ctx = createPipelineContext(options);\n const { safeEmit, safePersist, buildEvent } = ctx;\n const { settle, abandonSettlement } = createSettlement(ctx);\n const admitPayment = createPaymentAdmission(ctx, createAuthorizeAndReserve(ctx));\n\n async function execute(request: CanonicalRequest): Promise<ExecutionOutcome> {\n const pipelineStart = options.clock.monotonicMs();\n\n // 1. resolve resource\n const resource = options.resources.get(request.resourceId);\n // Same code and message as an unknown id: a caller on a protocol the\n // resource is not exposed via must not learn that it exists\n if (!resource?.exposedVia.includes(request.protocol)) {\n throw new CommerceError(\n 'RESOURCE_NOT_FOUND',\n `Resource \"${request.resourceId}\" was not found`,\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n },\n );\n }\n\n await safeEmit(\n buildEvent({\n type: 'resource.requested',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n }),\n );\n\n // 2. strip reserved gateway fields, then validate input\n const strippedInput = stripReservedFields(request.input);\n const validation = getValidator(resource)(strippedInput);\n if (!validation.valid) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Input for resource \"${resource.id}\" failed validation`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n details: { errors: validation.errors },\n },\n );\n }\n const validInput = validation.value;\n\n // Before pricing, so a request the backend cannot receive fails before\n // payment (see validateBackendRequestShape)\n validateBackendRequestShape(\n resource.handler,\n validInput,\n { requestId: request.requestId, resourceId: resource.id },\n request.backendHeaders,\n );\n\n // 3. resolve price\n if (resource.pricing.type === 'dynamic') {\n // Config validation rejects this at load; this is defense in depth\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${resource.id}\" uses unsupported dynamic pricing`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n },\n );\n }\n\n // Authorization gates settlement, so on a free resource nothing would read\n // the proof. Config refuses this at load; this is defense in depth.\n if (resource.pricing.type !== 'fixed' && (resource.authorization?.required.length ?? 0) > 0) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${resource.id}\" requires authorization but is not a paid resource`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n },\n );\n }\n\n let paymentResult: PaymentResult | undefined;\n let authorization: AuthorizationRecord | undefined;\n let deferredSettlement: SettleArgs | undefined;\n\n if (resource.pricing.type === 'fixed') {\n const admission = await admitPayment(request, resource, resource.pricing, validInput);\n if (admission.kind === 'payment-required') return admission;\n const { settleArgs } = admission;\n authorization = settleArgs.hold?.record;\n if (settleArgs.requirement.metadata?.[SETTLE_AFTER_BACKEND_METADATA_KEY] === true) {\n deferredSettlement = settleArgs;\n } else {\n paymentResult = await settle(settleArgs);\n }\n }\n\n // 6. call backend\n const backendStart = options.clock.monotonicMs();\n let backendResponse: BackendResponse;\n try {\n backendResponse = await options.backend.call(resource.handler, {\n requestId: request.requestId,\n resourceId: resource.id,\n input: validInput,\n ...(request.idempotencyKey !== undefined ? { idempotencyKey: request.idempotencyKey } : {}),\n ...(request.backendHeaders !== undefined ? { backendHeaders: request.backendHeaders } : {}),\n });\n } catch (error) {\n const commerceError = toCommerceError(error, 'BACKEND_ERROR', 'Backend call failed');\n await safeEmit(\n buildEvent({\n type: 'backend.failed',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'error',\n durationMs: Math.round(options.clock.monotonicMs() - backendStart),\n data: { code: commerceError.code },\n }),\n );\n\n if (deferredSettlement !== undefined) {\n await abandonSettlement(deferredSettlement, commerceError.code);\n throw commerceError;\n }\n\n if (paymentResult !== undefined) {\n // The payment settled and the backend then failed. Record an\n // undelivered receipt for the merchant and tell the buyer what they\n // paid, including the settlement reference.\n const failedReceipt: CommerceReceipt = {\n id: options.ids.next('receipt'),\n requestId: request.requestId,\n resourceId: resource.id,\n deliveredAt: options.clock.nowIso(),\n backendStatus: backendErrorStatus(commerceError),\n protocol: request.protocol,\n payment: paymentResult,\n ...(authorization !== undefined ? { authorization } : {}),\n metadata: { delivered: false, backendErrorCode: commerceError.code },\n };\n await safePersist(\n () => options.store.saveReceipt(failedReceipt),\n 'saveReceipt(backend-failed-after-settlement)',\n request.requestId,\n );\n\n throw new CommerceError(\n 'BACKEND_ERROR',\n 'Payment settled but the backend call failed; the payment was not refunded automatically',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: commerceError,\n details: {\n payment: {\n status: paymentResult.status,\n provider: paymentResult.provider,\n amount: paymentResult.amount,\n currency: paymentResult.currency,\n ...(paymentResult.network !== undefined ? { network: paymentResult.network } : {}),\n ...(paymentResult.externalReference !== undefined\n ? { externalReference: paymentResult.externalReference }\n : {}),\n ...(paymentResult.payer !== undefined ? { payer: paymentResult.payer } : {}),\n ...(typeof paymentResult.metadata?.['amountBaseUnits'] === 'string'\n ? { amountBaseUnits: paymentResult.metadata['amountBaseUnits'] }\n : {}),\n ...(typeof paymentResult.metadata?.['receipt'] === 'string'\n ? { receipt: paymentResult.metadata['receipt'] }\n : {}),\n },\n },\n },\n );\n }\n\n throw commerceError;\n }\n\n await safeEmit(\n buildEvent({\n type: 'backend.called',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'ok',\n durationMs: backendResponse.durationMs,\n data: { status: backendResponse.status },\n }),\n );\n\n // Hold the backend response until settlement succeeds. A refusal or\n // uncertain outcome throws before delivery.\n if (deferredSettlement !== undefined) {\n paymentResult = await settle(deferredSettlement);\n }\n\n // 7. persist receipt, emit final event, return outcome\n const receipt: CommerceReceipt = {\n id: options.ids.next('receipt'),\n requestId: request.requestId,\n resourceId: resource.id,\n deliveredAt: options.clock.nowIso(),\n backendStatus: backendResponse.status,\n durationMs: backendResponse.durationMs,\n protocol: request.protocol,\n ...(paymentResult !== undefined ? { payment: paymentResult } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n };\n\n await safePersist(() => options.store.saveReceipt(receipt), 'saveReceipt', request.requestId);\n\n const totalDurationMs = Math.round(options.clock.monotonicMs() - pipelineStart);\n\n await safeEmit(\n buildEvent({\n type: 'resource.delivered',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'ok',\n durationMs: totalDurationMs,\n }),\n );\n\n return {\n kind: 'delivered',\n requestId: request.requestId,\n resourceId: resource.id,\n backendStatus: backendResponse.status,\n body: backendResponse.body,\n headers: backendResponse.headers,\n ...(paymentResult !== undefined ? { payment: paymentResult } : {}),\n receipt,\n durationMs: totalDurationMs,\n };\n }\n\n return { execute };\n}\n\n// The status the backend returned, which backend-http.ts puts on\n// `details.status` for a non-2xx or redirect response. 0 means no status is\n// known, as after a timeout, a transport failure or an unreadable or oversized\n// body.\nfunction backendErrorStatus(error: CommerceError): number {\n const status = error.details?.['status'];\n return typeof status === 'number' ? status : 0;\n}\n\nconst RESERVED_INPUT_KEYS: readonly string[] = [...RESERVED_INPUT_FIELDS, '__proto__'];\n\nfunction stripReservedFields(input: unknown): unknown {\n if (!isRecord(input)) return input;\n // Object.hasOwn, not `in`, which also matches inherited names\n if (!RESERVED_INPUT_KEYS.some((key) => Object.hasOwn(input, key))) return input;\n const rest: Record<string, unknown> = {};\n for (const key of Object.keys(input)) {\n // \"__proto__\" is dropped too: assigning it would call the inherited setter\n // and replace `rest`'s prototype instead of creating a data property.\n // validation.ts's own-property lookups are the primary control.\n if (!RESERVED_INPUT_KEYS.includes(key)) rest[key] = input[key];\n }\n return rest;\n}\n","// In-memory implementation of the frozen `ResourceRegistry` interface\nimport type { ProtocolName } from '../domain/common';\nimport type { CommerceResource, ResourceRegistry } from '../domain/resource';\nimport { CommerceError } from '../errors';\n\nclass ResourceRegistryImpl implements ResourceRegistry {\n private readonly byId = new Map<string, CommerceResource>();\n private readonly ordered: readonly CommerceResource[];\n\n constructor(resources: readonly CommerceResource[]) {\n for (const resource of resources) {\n if (this.byId.has(resource.id)) {\n throw new CommerceError('CONFIG_INVALID', `Duplicate resource id \"${resource.id}\"`, {\n details: { resourceId: resource.id },\n });\n }\n this.byId.set(resource.id, resource);\n }\n this.ordered = [...resources];\n }\n\n get(id: string): CommerceResource | undefined {\n return this.byId.get(id);\n }\n\n list(): readonly CommerceResource[] {\n return this.ordered;\n }\n\n listExposedVia(protocol: ProtocolName): readonly CommerceResource[] {\n return this.ordered.filter((resource) => resource.exposedVia.includes(protocol));\n }\n\n has(id: string): boolean {\n return this.byId.has(id);\n }\n}\n\n/** Build a `ResourceRegistry` from a validated list of canonical resources */\nexport function createResourceRegistry(resources: readonly CommerceResource[]): ResourceRegistry {\n return new ResourceRegistryImpl(resources);\n}\n","/**\n * `EventSink` that persists every event to the receipt store. A store failure\n * is logged, never thrown to the caller.\n */\nimport type { CommerceEvent, EventSink } from '../domain/event';\nimport { describeError } from '../errors';\nimport type { Logger } from '../interfaces/logger';\nimport type { ReceiptStore } from '../interfaces/store';\n\nexport interface CreateStoreEventSinkOptions {\n readonly store: ReceiptStore;\n readonly logger: Logger;\n}\n\nexport function createStoreEventSink(options: CreateStoreEventSinkOptions): EventSink {\n return {\n async emit(event: CommerceEvent): Promise<void> {\n try {\n await options.store.appendEvent(event);\n } catch (error) {\n options.logger.error(\n { err: describeError(error), eventType: event.type, requestId: event.requestId },\n 'Failed to persist commerce event',\n );\n }\n },\n };\n}\n","// A resource's backend request: input bindings, path parameters, URL and headers\nimport { CommerceError, RESERVED_INPUT_FIELDS } from '../../core';\nimport {\n extractPathParameterNames,\n findUnparsedBraceToken,\n isObjectSchemaNode,\n} from '../../core/execution';\nimport { isRecord } from '../../core/is-record';\nimport type { RawResourceEntry } from './raw';\n\n/**\n * Checks `backend.inputBindings` against the input schema at load. Schemas are\n * closed by default at every depth, so a binding naming an undeclared property\n * could never be supplied, and on a paid resource the backend would get an\n * incomplete request after payment.\n *\n * Returns the schema node `{param}` names must be declared in: the path group\n * with bindings, the whole input without.\n */\nexport function validateInputBindings(\n id: string,\n backend: RawResourceEntry['backend'],\n input: Record<string, unknown> | undefined,\n): { readonly schema: Record<string, unknown> | undefined; readonly where: string } {\n const legacy = { schema: input, where: 'its input schema' } as const;\n const bindings = backend.inputBindings;\n const templated = extractPathParameterNames(backend.url).length > 0;\n if (bindings === undefined) return legacy;\n\n const path = `resources.${id}.backend.inputBindings`;\n const fail = (message: string, details: Record<string, unknown> = {}): never => {\n throw new CommerceError('CONFIG_INVALID', `Resource \"${id}\" ${message}`, {\n details: { path, resourceId: id, ...details },\n });\n };\n\n const entries = Object.entries(bindings).filter(\n (entry): entry is [string, string] => entry[1] !== undefined,\n );\n if (entries.length === 0) {\n fail('has an empty backend.inputBindings - remove the block to use the default mapping');\n }\n if (backend.method === 'GET' || backend.method === 'DELETE') {\n if (bindings.body !== undefined) {\n fail(\n `binds a request body on a ${backend.method}, which sends none - the value would be silently dropped`,\n );\n }\n }\n if (templated && bindings.path === undefined) {\n fail(\n 'has backend.url path parameters but no \"path\" binding - in explicit binding mode nothing else supplies them, so every call would fail to reach the backend',\n );\n }\n\n const seen = new Map<string, string>();\n const properties = isRecord(input?.['properties']) ? input['properties'] : {};\n const required = new Set(\n Array.isArray(input?.['required'])\n ? input['required'].filter((value): value is string => typeof value === 'string')\n : [],\n );\n\n for (const [location, property] of entries) {\n if (RESERVED_INPUT_FIELDS.includes(property)) {\n fail(`binds \"${location}\" to \"${property}\", which is reserved by the gateway`, { location });\n }\n const other = seen.get(property);\n if (other !== undefined) {\n fail(`binds both \"${other}\" and \"${location}\" to the input property \"${property}\"`, {\n location,\n property,\n });\n }\n seen.set(property, location);\n\n if (!Object.hasOwn(properties, property)) {\n fail(\n `binds \"${location}\" to input property \"${property}\", which the input schema does not declare - the schema is closed, so a caller could never supply it`,\n { location, property },\n );\n }\n // `body` may be any JSON value; only the path and query groups are read as\n // name/value pairs\n const declared = properties[property];\n if (location !== 'body' && isRecord(declared) && !isObjectSchemaNode(declared)) {\n fail(\n `binds \"${location}\" to input property \"${property}\", which is not an object schema - ${location} parameters are read as an object of name/value pairs`,\n { location, property },\n );\n }\n }\n\n if (templated && bindings.path !== undefined && !required.has(bindings.path)) {\n fail(\n `binds path parameters to input property \"${bindings.path}\" without listing it in the input schema's \"required\" - a caller that omits it cannot supply any path parameter, so the request could never be built`,\n { property: bindings.path },\n );\n }\n\n if (bindings.path === undefined) return { schema: undefined, where: 'its input schema' };\n const group = properties[bindings.path];\n return {\n schema: isRecord(group) ? group : undefined,\n where: `input.properties.${bindings.path}`,\n };\n}\n\n/**\n * Every `{param}` in `backend.url` must be declared in `properties` and listed\n * in `required`. Otherwise a call can arrive without it, and core's\n * `validateBackendRequestShape` rejects the request, which for a schema that\n * never declares the parameter means every call. Checked at load so\n * `validate` and `doctor` report it; the runtime check covers a hand-built\n * `CommerceResource`.\n */\nexport function validatePathParametersDeclared(\n id: string,\n url: string,\n input: Record<string, unknown> | undefined,\n where: string,\n): void {\n // A brace token the grammar does not recognize is neither extracted nor\n // substituted, so it would reach the backend as a percent-encoded literal\n const stray = findUnparsedBraceToken(url);\n if (stray !== undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has backend.url containing \"${stray}\", which is not a valid path parameter (allowed characters: A-Z a-z 0-9 _ . -). It would reach the backend as literal text, so a paid resource would take payment for a request the backend cannot serve`,\n { details: { path: `resources.${id}.backend.url`, resourceId: id, token: stray } },\n );\n }\n\n const params = extractPathParameterNames(url);\n if (params.length === 0) return;\n\n // Everything before the first `{` must be a complete origin followed by the\n // path's leading `/`. In the host, every other `{param}` defense fails open:\n // `http://{host}/api` parses, the runtime prefix check skips a prefix that\n // is not a URL, and `encodeURIComponent` keeps dots. Caller input would pick\n // the host the gateway calls, such as a metadata service or an internal\n // address, and `http://{region}.api.internal/...` looks ordinary enough to\n // be written by mistake.\n const firstBrace = url.indexOf('{');\n if (firstBrace !== -1) {\n const prefix = url.slice(0, firstBrace);\n let origin: string | undefined;\n try {\n const parsedPrefix = new URL(prefix);\n origin = parsedPrefix.hostname === '' ? undefined : parsedPrefix.origin;\n } catch {\n // Not a URL: the parameter starts before the authority is complete\n }\n if (origin === undefined || !prefix.startsWith(`${origin}/`)) {\n // The URL is not quoted: it may carry a key substituted from the environment\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has a backend.url parameter before the end of the host. A caller-supplied value would choose which host the gateway calls, which is request forgery with the gateway's own network position. Parameters are supported inside the path and query only`,\n { details: { path: `resources.${id}.backend.url`, resourceId: id } },\n );\n }\n }\n\n const propertiesRaw = input?.['properties'];\n const properties = isRecord(propertiesRaw) ? propertiesRaw : {};\n const requiredRaw = input?.['required'];\n const required = new Set(\n Array.isArray(requiredRaw)\n ? requiredRaw.filter((entry): entry is string => typeof entry === 'string')\n : [],\n );\n\n for (const param of params) {\n const path = `resources.${id}.backend.url`;\n if (!Object.hasOwn(properties, param)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has backend.url path parameter \"{${param}}\" which is not declared in ${where} - the caller has no way to supply it, so every call would be refused`,\n { details: { path, resourceId: id, param } },\n );\n }\n if (!required.has(param)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has backend.url path parameter \"{${param}}\" declared in ${where} but not listed in its \"required\" - a call that omits it would be refused`,\n { details: { path, resourceId: id, param } },\n );\n }\n }\n}\n\n// `{param}` templates parse as URLs (the WHATWG parser percent-encodes the\n// braces), so this refuses only malformed URLs and non-http(s) schemes\nexport function validateBackendUrl(id: string, url: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n // The URL is not quoted: it may carry a key substituted from the environment\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has an invalid backend.url: must be an absolute http:// or https:// URL`,\n { details: { path: `resources.${id}.backend.url`, resourceId: id } },\n );\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has a backend.url with scheme \"${parsed.protocol}\": must be http:// or https://`,\n { details: { path: `resources.${id}.backend.url`, resourceId: id } },\n );\n }\n}\n\n// Checked with fetch's own `Headers` rules. Otherwise an illegal name, or a\n// substituted value with a line break inside it, would load cleanly and then\n// refuse every call. The error names the key, never the value, which may be a\n// credential.\nexport function validateBackendHeaders(\n id: string,\n headers: Record<string, string> | undefined,\n): void {\n for (const [name, value] of Object.entries(headers ?? {})) {\n try {\n new Headers([[name, value]]);\n } catch {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has backend header \"${name}\" with an illegal name or value (a name must be an HTTP token; a value must not contain NUL, a character above U+00FF, or a line break except at either end, which fetch trims)`,\n { details: { path: `resources.${id}.backend.headers.${name}`, resourceId: id } },\n );\n }\n }\n}\n","// A resource's input schema: the default closed object and the keywords the validator supports\nimport { CommerceError } from '../../core';\nimport { isObjectSchemaNode } from '../../core/execution';\nimport { isRecord } from '../../core/is-record';\n\n/**\n * Closes every object schema at every depth: a node without\n * `additionalProperties` gets `false`, so unknown keys never reach the\n * merchant's API. An explicit value, including `true`, is kept.\n *\n * JSON Schema itself defaults to open, and core's validator enforces\n * `additionalProperties` only where a node states it, so this recurses into\n * `properties`, `items` and schema-valued `additionalProperties`, the same\n * places the validator descends. Object-ness comes from `isObjectSchemaNode`,\n * the validator's own definition.\n */\nexport function defaultClosedObjectSchema(\n schema: Record<string, unknown>,\n): Record<string, unknown> {\n const isObjectSchema = isObjectSchemaNode(schema);\n const result: Record<string, unknown> = { ...schema };\n\n if (isObjectSchema) {\n const properties = schema['properties'];\n if (isRecord(properties)) {\n result['properties'] = Object.fromEntries(\n Object.entries(properties).map(([key, sub]) => [\n key,\n isRecord(sub) ? defaultClosedObjectSchema(sub) : sub,\n ]),\n );\n }\n if (!Object.hasOwn(schema, 'additionalProperties')) {\n result['additionalProperties'] = false;\n }\n }\n\n const items = schema['items'];\n if (isRecord(items)) {\n result['items'] = defaultClosedObjectSchema(items);\n }\n\n // `additionalProperties: {schema}` (a map of typed objects) is closed too.\n // Not conditional on `isObjectSchema`: the validator applies the subschema\n // wherever it finds one.\n const additional = schema['additionalProperties'];\n if (isRecord(additional)) {\n result['additionalProperties'] = defaultClosedObjectSchema(additional);\n }\n\n return result;\n}\n\n// The input schema of a resource that declares no `input:`. Declaring nothing\n// accepts nothing: without this, `compileJsonSchema(undefined)` would accept\n// any input and forward every key to the backend. A no-argument resource\n// omitting `input:` is a legitimate shape, so it is not refused.\nexport const EMPTY_CLOSED_OBJECT_SCHEMA: Record<string, unknown> = {\n type: 'object',\n properties: {},\n additionalProperties: false,\n};\n\n// Keywords core's validator ignores (see `execution/validation.ts` for the\n// enforced subset). Config warns at load, since an operator who writes\n// `pattern` cannot otherwise tell that it is not enforced.\nconst UNSUPPORTED_SCHEMA_KEYWORDS = [\n 'pattern',\n 'minLength',\n 'maxLength',\n 'format',\n 'minimum',\n 'maximum',\n 'exclusiveMinimum',\n 'exclusiveMaximum',\n 'multipleOf',\n 'oneOf',\n 'anyOf',\n 'allOf',\n 'not',\n '$ref',\n 'const',\n 'patternProperties',\n 'minItems',\n 'maxItems',\n 'uniqueItems',\n];\n\n// `type` set to something that rules out \"object\". No `type` at all does not\n// exclude it: the validator treats `properties`/`required` alone as an object\n// schema.\nfunction excludesObjectType(schema: Record<string, unknown>): boolean {\n const type = schema['type'];\n if (type === undefined || type === 'object') return false;\n if (Array.isArray(type)) return !type.includes('object');\n return true;\n}\n\n/**\n * Walks a resource's input schema once. Warns about unenforced keywords and\n * tuple `items`. Rejects a node whose `type` rules out \"object\" while it\n * declares `properties` or `required`, which then go unchecked (often a\n * copy-pasted sibling whose `type` was never updated), and a closed node\n * requiring a property it never declares, which no input can satisfy.\n */\nexport function validateResourceSchemaKeywords(\n id: string,\n path: string,\n schema: Record<string, unknown>,\n): void {\n for (const keyword of UNSUPPORTED_SCHEMA_KEYWORDS) {\n if (Object.hasOwn(schema, keyword)) {\n console.warn(\n `[agent-commerce] resource \"${id}\" ${path} uses JSON Schema keyword \"${keyword}\", which this gateway does not enforce (see src/core/execution/validation.ts for the supported subset). Remove it or treat it as documentation only.`,\n );\n }\n }\n if (\n (Object.hasOwn(schema, 'properties') || Object.hasOwn(schema, 'required')) &&\n excludesObjectType(schema)\n ) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" ${path} declares \"properties\" and/or \"required\" but its \"type\" (${JSON.stringify(schema['type'])}) does not include \"object\" - the validator will never route a value through either check under that type, so this schema claims to constrain input it does not actually enforce. Remove \"properties\"/\"required\", or include \"object\" in \"type\".`,\n { details: { path: `resources.${id}.${path}`, resourceId: id } },\n );\n }\n // A closed node that requires a property it never declares rejects that\n // property as unknown, so no input can satisfy it and every call would 400.\n // Only when the node is closed: an explicit `additionalProperties`\n // other than `false` leaves the name reachable.\n const requiredRaw = schema['required'];\n const closed = !Object.hasOwn(schema, 'additionalProperties')\n ? true\n : schema['additionalProperties'] === false;\n if (Array.isArray(requiredRaw) && closed && isObjectSchemaNode(schema)) {\n const declared = isRecord(schema['properties']) ? schema['properties'] : {};\n const undeclared = requiredRaw.filter(\n (name): name is string => typeof name === 'string' && !Object.hasOwn(declared, name),\n );\n if (undeclared.length > 0) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" ${path} lists ${undeclared.map((n) => `\"${n}\"`).join(', ')} in \"required\" but does not declare ${undeclared.length === 1 ? 'it' : 'them'} in \"properties\". The schema is closed (additionalProperties: false), so ${undeclared.length === 1 ? 'that name is' : 'those names are'} rejected as an unknown key and no input can ever satisfy this schema. Declare ${undeclared.length === 1 ? 'it' : 'them'} in \"properties\".`,\n { details: { path: `resources.${id}.${path}`, resourceId: id, undeclared } },\n );\n }\n }\n\n const properties = schema['properties'];\n if (isRecord(properties)) {\n for (const [key, sub] of Object.entries(properties)) {\n if (isRecord(sub)) validateResourceSchemaKeywords(id, `${path}.properties.${key}`, sub);\n }\n }\n const additional = schema['additionalProperties'];\n if (isRecord(additional)) {\n validateResourceSchemaKeywords(id, `${path}.additionalProperties`, additional);\n }\n const items = schema['items'];\n if (isRecord(items)) {\n validateResourceSchemaKeywords(id, `${path}.items`, items);\n } else if (Array.isArray(items)) {\n // Tuple-form `items` is valid JSON Schema, but the validator supports only\n // one schema for every element, so a tuple enforces nothing\n console.warn(\n `[agent-commerce] resource \"${id}\" ${path}.items is a tuple (an array of schemas), which this gateway does not enforce - only a single schema applied to every array element is supported (see src/core/execution/validation.ts). Each position's schema is unenforced; treat it as documentation only.`,\n );\n }\n}\n","// Resources: exposure, pricing, payment rails and backend handler\nimport type { Ap2AuthorizationConfig } from '../../authorization/ap2/types';\nimport {\n CommerceError,\n type CommerceResource,\n PAYMENT_METHOD_NAMES,\n PROTOCOL_NAMES,\n type Pricing,\n RESERVED_INPUT_FIELDS,\n} from '../../core';\nimport { MPP_PROFILE } from '../../payments/mpp/constants';\nimport { MCP_TOOL_NAME_PATTERN } from '../../protocols/mcp/constants';\nimport { normalizeResourceAuthorization } from './ap2';\nimport {\n validateBackendHeaders,\n validateBackendUrl,\n validateInputBindings,\n validatePathParametersDeclared,\n} from './backend';\nimport type { NormalizedMpp } from './mpp';\nimport type { RawResourceEntry } from './raw';\nimport {\n defaultClosedObjectSchema,\n EMPTY_CLOSED_OBJECT_SCHEMA,\n validateResourceSchemaKeywords,\n} from './resource-schema';\nimport type { NormalizedProtocols } from './types';\nimport { toNumber } from './values';\nimport type { NormalizedX402 } from './x402';\n\nconst SUPPORTED_PROTOCOLS: ReadonlySet<string> = new Set(PROTOCOL_NAMES);\n\nconst SUPPORTED_PAYMENT_METHODS: ReadonlySet<string> = new Set(PAYMENT_METHOD_NAMES);\n\nexport function normalizeResource(\n id: string,\n entry: RawResourceEntry,\n protocols: NormalizedProtocols,\n x402: NormalizedX402 | undefined,\n mpp: NormalizedMpp | undefined,\n ap2: Ap2AuthorizationConfig | undefined,\n): CommerceResource {\n if (entry.input !== undefined) validateResourceSchemaKeywords(id, 'input', entry.input);\n\n const inputProperties = entry.input?.['properties'];\n if (inputProperties && typeof inputProperties === 'object') {\n for (const reserved of RESERVED_INPUT_FIELDS) {\n if (!(reserved in inputProperties)) continue;\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" declares an input property \"${reserved}\", which is reserved by the gateway`,\n {\n details: {\n path: `resources.${id}.input.properties.${reserved}`,\n resourceId: id,\n },\n },\n );\n }\n }\n\n for (const protocol of entry.expose) {\n if (!SUPPORTED_PROTOCOLS.has(protocol)) {\n const hint = protocol === 'ucp' ? ' (UCP is planned, not supported in this release)' : '';\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" exposes unsupported protocol \"${protocol}\"${hint}. Supported: ${PROTOCOL_NAMES.join(', ')}.`,\n { details: { path: `resources.${id}.expose`, resourceId: id, protocol } },\n );\n }\n }\n if (entry.expose.includes('mcp')) {\n if (!protocols.mcp.enabled) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is exposed via \"mcp\" but protocols.mcp.enabled is false`,\n { details: { path: `resources.${id}.expose`, resourceId: id } },\n );\n }\n if (!MCP_TOOL_NAME_PATTERN.test(id)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is exposed via \"mcp\" but its id is not a legal MCP tool name (allowed: A-Z, a-z, 0-9, \"_\", \"-\", \".\", 1-128 chars)`,\n { details: { path: `resources.${id}`, resourceId: id } },\n );\n }\n }\n if (entry.expose.includes('a2a') && !protocols.a2a.enabled) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is exposed via \"a2a\" but protocols.a2a.enabled is false`,\n { details: { path: `resources.${id}.expose`, resourceId: id } },\n );\n }\n if (entry.expose.includes('acp') && !protocols.acp.enabled) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is exposed via \"acp\" but protocols.acp.enabled is false`,\n { details: { path: `resources.${id}.expose`, resourceId: id } },\n );\n }\n if (entry.expose.includes('http') && !protocols.http.enabled) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is exposed via \"http\" but protocols.http.enabled is false`,\n { details: { path: `resources.${id}.expose`, resourceId: id } },\n );\n }\n\n validateBackendUrl(id, entry.backend.url);\n validateBackendHeaders(id, entry.backend.headers);\n const pathScope = validateInputBindings(id, entry.backend, entry.input);\n validatePathParametersDeclared(id, entry.backend.url, pathScope.schema, pathScope.where);\n\n if (entry.pricing.type === 'dynamic') {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" uses pricing.type \"dynamic\", which is not supported in this release`,\n { details: { path: `resources.${id}.pricing.type`, resourceId: id } },\n );\n }\n\n const paymentMethods = entry.payments ?? [];\n\n if (entry.x402 !== undefined) {\n const at = `resources.${id}.x402`;\n if (x402 === undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" sets x402.accepts, but payments.x402 is not configured`,\n { details: { path: at, resourceId: id } },\n );\n }\n if (entry.pricing.type !== 'fixed' || !paymentMethods.includes('x402')) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" sets x402.accepts, which requires fixed pricing and \"x402\" in payments`,\n { details: { path: at, resourceId: id } },\n );\n }\n }\n // The resource's own offers, or the rail's\n const offers = x402 !== undefined ? (x402.resources[id] ?? x402) : undefined;\n\n if (entry.pricing.type === 'fixed') {\n // An x402 price is charged in every option's token, so the coarsest one\n // bounds it. MPP checks its own token's decimals below.\n const decimals = paymentMethods.includes('x402')\n ? offers?.options.map((option) => option.assetDecimals)\n : undefined;\n validatePricingAmount(id, entry.pricing.amount, decimals && Math.min(...decimals));\n }\n\n if (entry.pricing.type === 'fixed') {\n if (paymentMethods.length === 0) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has fixed pricing but declares no \"payments\" (a paid resource must name at least one payment method)`,\n { details: { path: `resources.${id}.payments`, resourceId: id } },\n );\n }\n for (const method of paymentMethods) {\n if (!SUPPORTED_PAYMENT_METHODS.has(method)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" names unsupported payment method \"${method}\". Supported: ${PAYMENT_METHOD_NAMES.join(', ')}.`,\n { details: { path: `resources.${id}.payments`, resourceId: id, method } },\n );\n }\n }\n // At least one named rail must be enabled, not every one. `main.ts` checks\n // again at composition as defense in depth.\n const enabledRails = [\n ...(x402?.config.enabled ? ['x402'] : []),\n ...(mpp?.enabled ? ['mpp'] : []),\n ];\n if (!paymentMethods.some((method) => enabledRails.includes(method))) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" names payment method(s) \"${paymentMethods.join(', ')}\", none of which is configured and enabled under \"payments\"`,\n { details: { path: `resources.${id}.payments`, resourceId: id, paymentMethods } },\n );\n }\n // An offer in the network's default stablecoin, named or not, charges the\n // price in that token, so the price must name that token or USD\n const symbols = offers?.defaultAssetSymbols ?? [];\n const currency = entry.pricing.currency;\n if (\n x402?.config.enabled &&\n symbols.length > 0 &&\n paymentMethods.includes('x402') &&\n currency !== 'USD' &&\n !(symbols.length === 1 && currency === symbols[0])\n ) {\n const tokens = symbols.join(' and ');\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is priced in ${currency}, but x402 settles in ${tokens}, the default asset of its network. Price it in ${symbols.length === 1 ? `${tokens} or ` : ''}USD.`,\n { details: { path: `resources.${id}.pricing.currency`, resourceId: id } },\n );\n }\n // MPP fixes the currency label and decimal precision for every resource it serves\n if (mpp?.enabled && paymentMethods.includes('mpp')) {\n if (entry.pricing.currency !== MPP_PROFILE.assetSymbol) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is priced in ${entry.pricing.currency}, but MPP charges ${MPP_PROFILE.assetSymbol}`,\n { details: { path: `resources.${id}.pricing.currency`, resourceId: id } },\n );\n }\n validatePricingAmount(id, entry.pricing.amount, MPP_PROFILE.assetDecimals);\n }\n }\n\n if (\n entry.paymentFlow !== undefined &&\n (entry.pricing.type !== 'fixed' ||\n !paymentMethods.some((method) => method === 'x402' || method === 'mpp'))\n ) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" sets paymentFlow, which requires fixed pricing and \"x402\" or \"mpp\" in payments`,\n { details: { path: `resources.${id}.paymentFlow`, resourceId: id } },\n );\n }\n\n const pricing: Pricing =\n entry.pricing.type === 'free'\n ? { type: 'free' }\n : { type: 'fixed', amount: entry.pricing.amount, currency: entry.pricing.currency };\n\n const authorization = normalizeResourceAuthorization(id, entry, pricing, ap2);\n\n return {\n id,\n name: entry.name,\n ...(entry.description !== undefined ? { description: entry.description } : {}),\n inputSchema:\n entry.input !== undefined\n ? defaultClosedObjectSchema(entry.input)\n : EMPTY_CLOSED_OBJECT_SCHEMA,\n ...(entry.output !== undefined ? { outputSchema: entry.output } : {}),\n handler: {\n type: 'http',\n method: entry.backend.method,\n url: entry.backend.url,\n ...(entry.backend.headers !== undefined ? { headers: entry.backend.headers } : {}),\n ...(entry.backend.timeoutMs !== undefined\n ? {\n timeoutMs: toNumber(entry.backend.timeoutMs, `resources.${id}.backend.timeoutMs`, {\n min: 1,\n }),\n }\n : {}),\n ...(entry.backend.inputBindings !== undefined\n ? { inputBindings: pickDefined(entry.backend.inputBindings) }\n : {}),\n },\n pricing,\n exposedVia: entry.expose as CommerceResource['exposedVia'],\n paymentMethods: paymentMethods as CommerceResource['paymentMethods'],\n ...(authorization !== undefined ? { authorization } : {}),\n };\n}\n\n// A plain decimal: no currency symbol, thousands separator, sign or exponent.\n// \"0,01\", \"$0.01\", \"1e-2\" and \"-1\" would otherwise load and then fail every\n// purchase.\nconst PRICING_AMOUNT_PATTERN = /^\\d+(?:\\.\\d+)?$/;\n\nconst ZERO_AMOUNT_PATTERN = /^0(?:\\.0+)?$/;\n\nfunction validatePricingAmount(id: string, amount: string, decimals: number | undefined): void {\n const path = `resources.${id}.pricing.amount`;\n if (!PRICING_AMOUNT_PATTERN.test(amount)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has pricing.amount \"${amount}\", which is not a plain positive decimal (no currency symbol, no thousands separator, no exponent - e.g. \"0.01\")`,\n { details: { path, resourceId: id } },\n );\n }\n if (ZERO_AMOUNT_PATTERN.test(amount)) {\n // A zero-priced paid resource would settle a zero-value transfer\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has pricing.amount \"0\" - a paid resource cannot cost zero; use \"pricing: { type: free }\" instead`,\n { details: { path, resourceId: id } },\n );\n }\n if (decimals !== undefined) {\n const fractionalDigits = amount.includes('.') ? (amount.split('.')[1]?.length ?? 0) : 0;\n if (fractionalDigits > decimals) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has pricing.amount \"${amount}\" with more precision (${fractionalDigits} fractional digits) than the configured asset supports (${decimals} decimals)`,\n { details: { path, resourceId: id } },\n );\n }\n }\n}\n\n// Strips absent optional keys so the result satisfies `exactOptionalPropertyTypes`\nfunction pickDefined<T extends Record<string, string | undefined>>(\n value: T,\n): { [K in keyof T]?: string } {\n return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined)) as {\n [K in keyof T]?: string;\n };\n}\n","// The business-rule pass: coerces leaves and checks cross-references across sections\nimport { CommerceError } from '../../core';\nimport { normalizeAcp, validateAcpCheckoutMapping } from './acp';\nimport { normalizeAp2, validateReplayStoreIsolated } from './ap2';\nimport { normalizeMpp } from './mpp';\nimport { type RawConfig, SUPPORTED_CONFIG_VERSION } from './raw';\nimport { normalizeResource } from './resources';\nimport type { GatewayConfig, NormalizedProtocols } from './types';\nimport { toBoolean, toNumber } from './values';\nimport { normalizeX402 } from './x402';\n\n// Applied when `protocols.a2a` is absent or names no mount\nconst DEFAULT_A2A_MOUNT_PATH = '/a2a';\n\nexport function normalize(raw: RawConfig): GatewayConfig {\n const protocols = {\n http: { enabled: toBoolean(raw.protocols.http.enabled, 'protocols.http.enabled') },\n mcp: {\n enabled: toBoolean(raw.protocols.mcp.enabled, 'protocols.mcp.enabled'),\n mountPath: raw.protocols.mcp.mountPath,\n },\n a2a: {\n enabled: toBoolean(raw.protocols.a2a?.enabled ?? false, 'protocols.a2a.enabled'),\n mountPath: raw.protocols.a2a?.mountPath ?? DEFAULT_A2A_MOUNT_PATH,\n },\n acp: normalizeAcp(raw.protocols.acp),\n };\n validateMountPaths(protocols);\n\n const x402Settings =\n raw.payments.x402 !== undefined ? normalizeX402(raw.payments.x402, raw.resources) : undefined;\n const x402 = x402Settings?.config;\n\n const mpp = normalizeMpp(raw.payments.mpp);\n\n const ap2 = normalizeAp2(raw.authorization?.ap2);\n if (ap2?.enabled) {\n validateReplayStoreIsolated(ap2.replay.path, raw.storage.receipts.path, protocols.acp);\n }\n\n const resources = Object.entries(raw.resources).map(([id, entry]) =>\n normalizeResource(id, entry, protocols, x402Settings, mpp, ap2),\n );\n // CommerceResource has no payment-flow field. Each listed rail carries the\n // overrides; the selected rail applies them.\n const flowOverrides = (rail: 'x402' | 'mpp') => {\n const flows = Object.fromEntries(\n resources.flatMap((resource) => {\n const flow = raw.resources[resource.id]?.paymentFlow;\n return flow !== undefined && resource.paymentMethods.includes(rail)\n ? [[resource.id, flow]]\n : [];\n }),\n );\n return Object.keys(flows).length > 0 ? { resourcePaymentFlows: flows } : {};\n };\n const x402WithFlows = x402 !== undefined ? { ...x402, ...flowOverrides('x402') } : x402;\n const mppWithFlows = mpp !== undefined ? { ...mpp, ...flowOverrides('mpp') } : mpp;\n if (protocols.acp.enabled) validateAcpCheckoutMapping(protocols.acp, resources);\n // Require an exposed resource so the enabled adapter publishes a skill\n if (protocols.a2a.enabled && !resources.some((r) => r.exposedVia.includes('a2a'))) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'protocols.a2a.enabled is true but no resource lists \"a2a\" in its expose',\n { details: { path: 'protocols.a2a.enabled' } },\n );\n }\n\n return {\n version: SUPPORTED_CONFIG_VERSION,\n merchant: {\n id: raw.merchant.id,\n name: raw.merchant.name,\n publicBaseUrl: raw.merchant.publicBaseUrl,\n },\n // Port 0 lets the OS pick a free port, for tests and throwaway instances\n server: {\n port: toNumber(raw.server.port, 'server.port', { min: 0, max: 65535 }),\n host: raw.server.host,\n ...(raw.server.adminToken !== undefined ? { adminToken: raw.server.adminToken } : {}),\n allowedOrigins: raw.server.allowedOrigins ?? [],\n },\n storage: { receipts: { driver: 'sqlite', path: raw.storage.receipts.path } },\n protocols,\n resources,\n payments: {\n ...(x402WithFlows !== undefined ? { x402: x402WithFlows } : {}),\n ...(mppWithFlows !== undefined ? { mpp: mppWithFlows } : {}),\n },\n ...(ap2 !== undefined ? { authorization: { ap2 } } : {}),\n };\n}\n\n// Two enabled mounts may not overlap: each registers a `${mountPath}/*`\n// wildcard, so a shared prefix lets one adapter answer for the other. Disabled\n// protocols mount nothing and are not compared.\nfunction validateMountPaths(protocols: NormalizedProtocols): void {\n const mounts = (\n [\n ['mcp', protocols.mcp],\n ['a2a', protocols.a2a],\n ['acp', protocols.acp],\n ] as const\n ).filter(([, p]) => p.enabled);\n\n for (const [index, [nameA, a]] of mounts.entries()) {\n for (const [nameB, b] of mounts.slice(index + 1)) {\n const baseA = a.mountPath.replace(/\\/+$/, '');\n const baseB = b.mountPath.replace(/\\/+$/, '');\n if (baseA === baseB || baseA.startsWith(`${baseB}/`) || baseB.startsWith(`${baseA}/`)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `protocols.${nameA}.mountPath (\"${a.mountPath}\") collides with protocols.${nameB}.mountPath (\"${b.mountPath}\") - each mount registers a wildcard, so overlapping prefixes cannot both be served`,\n { details: { path: `protocols.${nameA}.mountPath` } },\n );\n }\n }\n }\n}\n","/**\n * `config.yaml` schema, validation and normalization into the canonical\n * `GatewayConfig` (docs/contracts.md).\n *\n * 1. Zod validates shape: types, required fields, unknown keys. Numeric and\n * boolean leaves accept their native type or a string, because env\n * substitution produces strings. Zod transforms interact badly with\n * `.strict()` inference, so coercion happens in plain TypeScript in step 2.\n * 2. A business-rule pass coerces those leaves and checks what needs a\n * specific message: cross-references, disabled protocols and payment\n * methods, dynamic pricing, addresses, duplicate trust entries.\n *\n * Env substitution (`${VAR}` / `${VAR:-default}`) runs over the raw value\n * before both steps, so numeric and boolean fields can be templated. The one\n * exception is `version:`, checked before substitution: it decides whether this\n * parser understands the document at all, so it cannot depend on the\n * environment.\n */\nimport type { ZodError, ZodIssue, z } from 'zod';\nimport { CommerceError } from '../../core';\nimport { isRecord } from '../../core/is-record';\nimport { substituteEnv } from '../env';\nimport { normalize } from './normalize';\nimport { RawConfigSchema, SUPPORTED_CONFIG_VERSION } from './raw';\nimport type { GatewayConfig } from './types';\n\nexport function parseConfig(raw: unknown, env: NodeJS.ProcessEnv): GatewayConfig {\n if (!isRecord(raw)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'Configuration root must be a mapping (object) at \"$\"',\n {\n details: { path: '$' },\n },\n );\n }\n\n checkVersion(raw);\n\n const substituted = substituteEnv(raw, env);\n const parsed = parseWithZod(RawConfigSchema, substituted);\n return normalize(parsed);\n}\n\nfunction checkVersion(raw: Record<string, unknown>): void {\n if (!('version' in raw)) {\n throw new CommerceError('CONFIG_INVALID', 'Configuration is missing required field \"version\"', {\n details: { path: 'version' },\n });\n }\n const version = raw['version'];\n if (version !== SUPPORTED_CONFIG_VERSION) {\n const hint = typeof version === 'string' ? ', written as a number without quotes' : '';\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Unsupported config version \"${String(version)}\": this gateway only supports version ${SUPPORTED_CONFIG_VERSION}${hint}`,\n { details: { path: 'version', supported: SUPPORTED_CONFIG_VERSION } },\n );\n }\n}\n\nfunction parseWithZod<T>(schema: z.ZodType<T>, value: unknown): T {\n const result = schema.safeParse(value);\n if (!result.success) {\n throw zodErrorToConfigError(result.error);\n }\n return result.data;\n}\n\nfunction zodErrorToConfigError(error: ZodError): CommerceError {\n const issues = error.issues.map(describeIssue);\n const first = issues[0];\n const message = first\n ? `Configuration invalid at \"${first.path}\": ${first.message}`\n : 'Configuration invalid';\n return new CommerceError('CONFIG_INVALID', message, { details: { issues } });\n}\n\nfunction describeIssue(issue: ZodIssue): { path: string; message: string; code: string } {\n const path = issue.path.length > 0 ? issue.path.join('.') : '$';\n return { path, message: issue.message, code: issue.code };\n}\n\nexport type {\n AcpDiscoveryConfig,\n AcpProtocolConfig,\n GatewayConfig,\n X402OptionConfig,\n} from './types';\n","/**\n * Locates and parses `config.yaml`, then hands the raw value to `parseConfig`\n * for validation\n */\nimport { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport { parse as parseYaml, YAMLError } from 'yaml';\nimport { CommerceError } from '../core';\nimport { DEFAULT_CONFIG_FILENAME } from './filename';\nimport { type GatewayConfig, parseConfig } from './schema';\n\nconst CONFIG_PATH_ENV_VAR = 'AGENT_COMMERCE_CONFIG';\n\nexport interface LoadConfigOptions {\n readonly path?: string;\n readonly env?: NodeJS.ProcessEnv;\n readonly cwd?: string;\n}\n\nexport async function loadConfig(options: LoadConfigOptions = {}): Promise<GatewayConfig> {\n const env = options.env ?? process.env;\n const cwd = options.cwd ?? process.cwd();\n const configPath = resolveConfigPath(options.path, env, cwd);\n\n let text: string;\n try {\n text = await fs.readFile(configPath, 'utf8');\n } catch (error) {\n throw new CommerceError('CONFIG_INVALID', `Could not read configuration file \"${configPath}\"`, {\n details: { path: configPath },\n cause: error,\n });\n }\n\n let raw: unknown;\n try {\n raw = parseYaml(text);\n } catch (error) {\n const { reason, details } = describeYamlError(error);\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration file \"${configPath}\" is not valid YAML: ${reason}`,\n {\n details: { path: configPath, ...details },\n // Kept for programmatic callers. Never print it: its `.message` quotes\n // the source line (see describeYamlError).\n cause: error,\n },\n );\n }\n\n return parseConfig(raw, env);\n}\n\n// Plain-English phrasing for common YAML error codes. Fixed strings, so they\n// never carry file content; an unlisted code is shown bare.\nconst YAML_ERROR_EXPLANATIONS: Readonly<Record<string, string>> = {\n DUPLICATE_KEY: 'map keys must be unique',\n BAD_INDENT: 'bad indentation',\n TAB_AS_INDENT: 'tabs cannot be used for indentation',\n MISSING_CHAR: 'a required character is missing',\n BLOCK_AS_IMPLICIT_KEY: 'a block value cannot be used as a key (missing quotes, or a stray colon)',\n MULTILINE_IMPLICIT_KEY: 'a key spans multiple lines (missing quotes, or a stray colon)',\n UNEXPECTED_TOKEN: 'unexpected token',\n};\n\n/**\n * Describes a YAML failure from the error's structured `code` and `linePos`\n * only. The `yaml` package's `message` quotes the source line, and a syntax\n * error next to an inline secret (`server.adminToken`, a facilitator\n * `signerPrivateKey`) would print it in `validate` and `doctor` output.\n */\nfunction describeYamlError(error: unknown): {\n reason: string;\n details: Record<string, unknown>;\n} {\n if (!(error instanceof YAMLError)) {\n return { reason: 'unknown YAML parse error', details: {} };\n }\n const start = error.linePos?.[0];\n const where =\n start === undefined ? '' : ` at line ${String(start.line)}, column ${String(start.col)}`;\n const explanation = YAML_ERROR_EXPLANATIONS[error.code];\n const what = explanation === undefined ? error.code : `${error.code} (${explanation})`;\n return {\n reason: `${what}${where}`,\n details: {\n yamlErrorCode: error.code,\n ...(start === undefined ? {} : { line: start.line, column: start.col }),\n },\n };\n}\n\nfunction resolveConfigPath(\n explicitPath: string | undefined,\n env: NodeJS.ProcessEnv,\n cwd: string,\n): string {\n if (explicitPath) return path.resolve(cwd, explicitPath);\n const fromEnv = env[CONFIG_PATH_ENV_VAR];\n if (fromEnv) return path.resolve(cwd, fromEnv);\n return path.resolve(cwd, DEFAULT_CONFIG_FILENAME);\n}\n","/**\n * Two `onRequest` hooks with separate jobs:\n * - `buildAccessControlHook`, registered once on the server: the DNS-rebinding\n * Host check and allowlisted CORS. Neither depends on the path.\n * - `buildOperatorTokenHook`, registered on each operator route (`/api/receipts`,\n * `/api/events`): the `server.adminToken` gate.\n *\n * The token gate is per route because a global hook could only compare\n * `request.url`, which is still percent-encoded, while Fastify's router\n * decodes before matching: `/api/%72eceipts` would pass such a gate and still\n * route to `/api/receipts`. A per-route hook runs only after the router has\n * matched its route, so no path string is compared at all.\n */\nimport type { FastifyReply, FastifyRequest } from 'fastify';\nimport { AUTHORIZATION_HEADER, PAYMENT_HEADER } from '../core';\nimport { createBearerCheck } from '../protocols/http';\n\nconst CORS_METHODS = 'GET,POST,OPTIONS';\n// Allow payment and protocol headers in browser preflights. The gateway does\n// not verify ACP `signature` or `timestamp`. x402 fetch and axios clients also\n// send `access-control-expose-headers` on paid retries.\nconst CORS_HEADERS = [\n 'content-type',\n PAYMENT_HEADER,\n AUTHORIZATION_HEADER,\n 'x-request-id',\n 'authorization',\n 'mcp-protocol-version',\n 'mcp-method',\n 'mcp-name',\n 'a2a-version',\n 'a2a-extensions',\n 'api-version',\n 'idempotency-key',\n 'request-id',\n 'signature',\n 'timestamp',\n 'access-control-expose-headers',\n].join(',');\n// Cross-origin JS sees only CORS-safelisted response headers unless they are\n// named here, so a browser client could read neither the challenge, the\n// settlement result, nor ACP's echoed correlation and replay headers\nconst CORS_EXPOSED_HEADERS = [\n 'payment-required',\n 'payment-response',\n 'www-authenticate',\n 'payment-receipt',\n 'idempotency-key',\n 'request-id',\n 'idempotent-replayed',\n 'retry-after',\n].join(',');\n\nexport interface AccessControlOptions {\n readonly publicBaseUrl: string;\n readonly allowedOrigins: readonly string[];\n}\n\nexport function buildAccessControlHook(\n options: AccessControlOptions,\n): (request: FastifyRequest, reply: FastifyReply) => Promise<void> {\n // Matched case-insensitively, like Host, so a mis-cased allowedOrigins entry\n // does not lock out the dashboard. The response echoes the browser's Origin\n // verbatim, because CORS compares it byte for byte.\n const allowedOrigins = new Set(options.allowedOrigins.map((origin) => origin.toLowerCase()));\n const publicHostname = hostnameOf(options.publicBaseUrl);\n\n return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n // 1. Host check (DNS-rebinding defense), for every request\n const host = request.headers.host;\n if (!isAllowedHost(host, publicHostname)) {\n reply.status(403).send({ status: 'error', code: 'FORBIDDEN', message: 'Host not allowed' });\n return;\n }\n\n // 2. CORS, only for requests carrying an Origin. Agents and MCP clients\n // normally send none and get no CORS headers.\n const origin = request.headers.origin;\n if (origin !== undefined) {\n if (!allowedOrigins.has(origin.toLowerCase())) {\n reply\n .status(403)\n .send({ status: 'error', code: 'FORBIDDEN', message: 'Origin not allowed' });\n return;\n }\n reply.header('access-control-allow-origin', origin);\n reply.header('access-control-allow-methods', CORS_METHODS);\n reply.header('access-control-allow-headers', CORS_HEADERS);\n reply.header('access-control-expose-headers', CORS_EXPOSED_HEADERS);\n reply.header('vary', 'Origin');\n if (request.method === 'OPTIONS') {\n // A preflight carries no credentials, so it is answered here, before\n // any per-route token gate\n reply.status(204).send();\n }\n }\n };\n}\n\n/**\n * Per-route `server.adminToken` gate, registered on each operator route's own\n * definition. With no token configured every request gets a 404, as if the\n * route did not exist; a missing or wrong token gets a 401.\n *\n * Header only: a token in a query string leaks through Referer, history and\n * proxy logs.\n */\nexport function buildOperatorTokenHook(\n adminToken: string | undefined,\n): (request: FastifyRequest, reply: FastifyReply) => Promise<void> {\n const isValidAdminToken = adminToken ? createBearerCheck(adminToken) : undefined;\n // async: Fastify waits for a `done` callback from a hook that returns no\n // Promise, and this one takes none\n return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n if (isValidAdminToken === undefined) {\n reply.status(404).send();\n return;\n }\n if (!isValidAdminToken(request.headers.authorization)) {\n reply\n .status(401)\n .send({ status: 'error', code: 'UNAUTHORIZED', message: 'Admin token required' });\n }\n };\n}\n\n// `new URL()` strips the port and parses IPv6 bracket notation\nfunction hostnameOf(value: string): string {\n try {\n const hostname = new URL(\n value.includes('://') ? value : `http://${value}`,\n ).hostname.toLowerCase();\n // URL#hostname keeps the brackets on an IPv6 literal (\"[::1]\"); strip them\n // so it compares equal to the plain \"::1\" form\n return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;\n } catch {\n return '';\n }\n}\n\n// Loopback names are always accepted, whatever publicBaseUrl says. A\n// DNS-rebinding page sends its own hostname as Host, never one of these, and\n// local setups often bind 127.0.0.1 while publicBaseUrl says localhost.\nconst LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1']);\n\nfunction isAllowedHost(hostHeader: string | undefined, publicHostname: string): boolean {\n if (!hostHeader) return false;\n const hostname = hostnameOf(hostHeader);\n return hostname !== '' && (hostname === publicHostname || LOOPBACK_HOSTNAMES.has(hostname));\n}\n","/**\n * Starts protocol adapters and mounts the HTTP ones. An adapter that fails to\n * start is reported unhealthy; it never stops the server or the other adapters.\n *\n * An `HttpProtocolAdapter` reads `request.raw` itself (MCP's Streamable HTTP\n * transport does), so its mount registers no-op content-type parsers, hands\n * the adapter the raw Node req/res, and calls `reply.hijack()` so Fastify\n * sends no second response.\n *\n * Fastify enforces `bodyLimit` inside the content-type parser, so a no-op\n * parser enforces none, and the MCP SDK's own 4 MB cap is far looser than\n * this one. The mount counts bytes on the socket's 'data' events instead and\n * destroys the connection past MOUNT_BODY_LIMIT_BYTES; `Content-Length` alone\n * would miss a chunked body. Node's HTTP parser already keeps the socket\n * flowing, so the extra listener only observes bytes and never takes one the\n * adapter needs.\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';\nimport {\n type AdapterHealth,\n type Clock,\n CommerceError,\n type HttpProtocolAdapter,\n isHttpProtocolAdapter,\n type Logger,\n type ProtocolAdapter,\n type ProtocolAdapterContext,\n toErrorEnvelope,\n} from '../core';\n\n/**\n * Body cap for adapter mounts, also used by `server.ts` as Fastify's\n * `bodyLimit`, so both surfaces enforce one number. MCP tool payloads could\n * justify more, but a whole JSON-RPC batch is parsed in memory, and this cap\n * bounds that spike.\n */\nexport const MOUNT_BODY_LIMIT_BYTES = 256 * 1024;\n\nexport interface AdapterRuntime {\n readonly adapter: ProtocolAdapter;\n /** Set only when `start()` threw; a failed adapter is never re-queried live */\n readonly startFailure?: AdapterHealth;\n}\n\nexport interface StartAndMountOptions {\n readonly server: FastifyInstance;\n readonly adapters: readonly ProtocolAdapter[];\n readonly context: ProtocolAdapterContext;\n readonly logger: Logger;\n readonly clock: Clock;\n}\n\nexport async function startAndMountAdapters(\n options: StartAndMountOptions,\n): Promise<AdapterRuntime[]> {\n // Checked before any adapter starts: a path claimed twice is a composition\n // bug, and Fastify would only report it at `server.ready()` as an\n // FST_ERR_DUPLICATED_ROUTE naming neither adapter\n assertNoRouteConflicts(options.adapters);\n\n const runtimes: AdapterRuntime[] = [];\n\n for (const adapter of options.adapters) {\n // Every log line the adapter writes carries `adapter: <name>`\n const adapterLogger = options.logger.child({ adapter: adapter.name });\n const adapterContext: ProtocolAdapterContext = { ...options.context, logger: adapterLogger };\n\n try {\n await adapter.start(adapterContext);\n } catch (error) {\n const detail = errorMessage(error);\n adapterLogger.error(\n { err: detail },\n 'Protocol adapter failed to start; gateway continues without it',\n );\n runtimes.push({\n adapter,\n startFailure: { status: 'fail', detail, checkedAt: options.clock.nowIso() },\n });\n continue;\n }\n\n if (isHttpProtocolAdapter(adapter)) {\n mountHttpAdapter(options.server, adapter, adapterLogger);\n }\n runtimes.push({ adapter });\n }\n\n return runtimes;\n}\n\ninterface RouteClaim {\n readonly adapter: string;\n readonly path: string;\n // A mount also owns everything below its path, through its `/*` wildcard\n readonly wildcard: boolean;\n readonly method: 'ALL' | 'GET' | 'POST';\n}\n\nfunction routeClaims(adapters: readonly ProtocolAdapter[]): RouteClaim[] {\n const claims: RouteClaim[] = [];\n for (const adapter of adapters) {\n if (!isHttpProtocolAdapter(adapter)) continue;\n claims.push({\n adapter: adapter.name,\n path: adapter.mountPath.replace(/\\/+$/, ''),\n wildcard: true,\n method: 'ALL',\n });\n for (const route of adapter.additionalHttpRoutes ?? []) {\n claims.push({\n adapter: adapter.name,\n path: route.path.replace(/\\/+$/, ''),\n wildcard: false,\n method: route.method,\n });\n }\n }\n return claims;\n}\n\nfunction claimsCollide(a: RouteClaim, b: RouteClaim): boolean {\n if (a.wildcard && (b.path === a.path || b.path.startsWith(`${a.path}/`))) return true;\n if (b.wildcard && a.path.startsWith(`${b.path}/`)) return true;\n return a.path === b.path && (a.method === b.method || a.method === 'ALL' || b.method === 'ALL');\n}\n\n/**\n * Only claims from different adapters conflict. An adapter may serve a fixed\n * route under its own mount, because Fastify prefers a static route over a\n * wildcard; that is how a protocol that pins a sub-path stays self-contained.\n */\nfunction assertNoRouteConflicts(adapters: readonly ProtocolAdapter[]): void {\n const claims = routeClaims(adapters);\n for (const [index, a] of claims.entries()) {\n for (const b of claims.slice(index + 1)) {\n if (a.adapter === b.adapter || !claimsCollide(a, b)) continue;\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Protocol adapters \"${a.adapter}\" and \"${b.adapter}\" both claim the HTTP path \"${b.path}\"; each adapter path must be served by exactly one adapter`,\n { details: { adapters: [a.adapter, b.adapter], path: b.path } },\n );\n }\n }\n}\n\n/**\n * Requests one adapter may handle at once. The body cap bounds a single\n * request, while the MCP tool-call cap applies after the SDK parses its body.\n * This limit rejects excess requests before those parses can run together.\n * Measured on Node 24: 20 concurrent 256 KiB `tools/call` batches raised RSS\n * from about 135 MB to 470 MB, and the heap returned to its idle size after GC.\n */\nexport const MOUNT_MAX_CONCURRENT_REQUESTS = 20;\n// Ask clients to retry shortly after load shedding\nconst MOUNT_BUSY_RETRY_AFTER_SECONDS = 1;\n\nfunction mountHttpAdapter(\n server: FastifyInstance,\n adapter: HttpProtocolAdapter,\n logger: Logger,\n): void {\n const mountPath = adapter.mountPath;\n const wildcard = mountPath.endsWith('/') ? `${mountPath}*` : `${mountPath}/*`;\n const additionalRoutes = adapter.additionalHttpRoutes ?? [];\n // One counter per adapter, shared by the mount and its fixed routes, so a\n // second route into the same adapter is not a way around the cap\n let inFlight = 0;\n\n void server.register(async (instance) => {\n // Fastify's built-in application/json and text/plain parsers take\n // precedence over '*'. Without exact no-ops here, the JSON parser would\n // drain request.raw and the adapter's transport would read an empty stream.\n instance.addContentTypeParser(\n ['application/json', 'text/plain'],\n (_request, _payload, done) => {\n done(null);\n },\n );\n instance.addContentTypeParser('*', (_request, _payload, done) => {\n done(null);\n });\n\n const makeHandler =\n (handleHttp: (req: IncomingMessage, res: ServerResponse) => Promise<void>) =>\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n if (inFlight >= MOUNT_MAX_CONCURRENT_REQUESTS) {\n // Rejected before a byte of the body is read, so no parse starts\n const error = new CommerceError(\n 'GATEWAY_BUSY',\n 'Too many requests already parsing on this mount; retry shortly.',\n );\n reply\n .status(error.httpStatus)\n .header('retry-after', String(MOUNT_BUSY_RETRY_AFTER_SECONDS))\n .send(toErrorEnvelope(error));\n return;\n }\n inFlight += 1;\n try {\n const stopEnforcing = enforceMountBodyLimit(\n request.raw,\n reply.raw,\n MOUNT_BODY_LIMIT_BYTES,\n logger,\n );\n try {\n await handleHttp(request.raw, reply.raw);\n } catch (error) {\n logger.error({ err: errorMessage(error) }, 'Protocol adapter request handler threw');\n if (!reply.raw.headersSent) {\n reply.raw.statusCode = 500;\n reply.raw.end();\n }\n }\n stopEnforcing();\n reply.hijack();\n } finally {\n // Always released: a stranded count shrinks the cap for good and\n // eventually refuses every request on this mount\n inFlight -= 1;\n }\n };\n\n const mountHandler = makeHandler((req, res) => adapter.handleHttp(req, res));\n instance.all(mountPath, mountHandler);\n instance.all(wildcard, mountHandler);\n\n for (const route of additionalRoutes) {\n instance.route({\n method: route.method,\n url: route.path,\n handler: makeHandler((req, res) => route.handleHttp(req, res)),\n });\n }\n });\n}\n\nfunction enforceMountBodyLimit(\n req: IncomingMessage,\n res: ServerResponse,\n maxBytes: number,\n logger: Logger,\n): () => void {\n const socket = req.socket;\n let total = 0;\n let stopped = false;\n const onData = (chunk: Buffer): void => {\n total += chunk.length;\n if (total > maxBytes) {\n stop();\n logger.warn({ maxBytes }, 'Request body exceeded the mount body limit; connection closed');\n // A bare destroy gives a legitimate client an ECONNRESET that never\n // names the cap, so try a 413 with a JSON-RPC error first. If the\n // adapter already started its own response, just destroy. The rest of\n // the oversized body is never read.\n if (!res.headersSent) {\n const body = JSON.stringify({\n jsonrpc: '2.0',\n id: null,\n error: { code: -32600, message: `Request body exceeds the ${maxBytes}-byte mount limit` },\n });\n try {\n res.writeHead(413, {\n 'content-type': 'application/json',\n 'content-length': Buffer.byteLength(body),\n });\n // The callback fires once the write reaches the OS, not the peer,\n // so the destroy can still truncate the 413 into an ECONNRESET.\n // Accepted: leaving the read side open would let the oversized\n // body keep flowing to whatever reads `req`.\n res.end(body, () => socket.destroy());\n return;\n } catch {\n // The socket may already be gone; fall through to a bare destroy\n }\n }\n socket.destroy();\n }\n };\n const stop = (): void => {\n if (stopped) return;\n stopped = true;\n // A keep-alive socket serves many requests and each adds both listeners.\n // Leaving the 'close' ones behind piles them up until MaxListenersExceeded.\n socket.removeListener('data', onData);\n socket.removeListener('close', stop);\n };\n socket.on('data', onData);\n socket.once('close', stop);\n return stop;\n}\n\nexport async function getAdapterHealth(\n runtime: AdapterRuntime,\n clock: Clock,\n): Promise<AdapterHealth> {\n if (runtime.startFailure) return runtime.startFailure;\n try {\n return await runtime.adapter.health();\n } catch (error) {\n return { status: 'fail', detail: errorMessage(error), checkedAt: clock.nowIso() };\n }\n}\n\nexport async function stopAdapters(\n runtimes: readonly AdapterRuntime[],\n logger: Logger,\n): Promise<void> {\n for (const runtime of runtimes) {\n try {\n await runtime.adapter.stop();\n } catch (error) {\n logger\n .child({ adapter: runtime.adapter.name })\n .error({ err: errorMessage(error) }, 'Protocol adapter failed to stop cleanly');\n }\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","// Default `IdGenerator`, used when the caller injects none\nimport { randomUUID } from 'node:crypto';\nimport type { IdGenerator } from '../core';\n\nexport function createDefaultIdGenerator(): IdGenerator {\n return {\n next(prefix?: string): string {\n const id = randomUUID();\n return prefix ? `${prefix}_${id}` : id;\n },\n };\n}\n","/**\n * Pino logger factory that redacts the credential and proof headers in\n * `SECRET_HEADERS` and the fields named in `SECRET_FIELD_NAMES`.\n *\n * Two separate pino instances, because Fastify's `loggerInstance` option forces\n * its generic `Logger` type into `FastifyInstance`, which conflicts with our\n * `Logger` shape under `exactOptionalPropertyTypes`:\n * - `fastifyLoggerOptions()`: options for Fastify's `logger` option, so\n * Fastify builds its own instance for HTTP access logs.\n * - `createGatewayLogger()`: a standalone instance wrapped to the `src/core`\n * `Logger` shape, injected into the pipeline and protocol adapters.\n * Both share the redaction paths and the level and pretty-print policy.\n */\n\nimport { createRequire } from 'node:module';\nimport type { FastifyReply, FastifyRequest } from 'fastify';\nimport pino, { type LoggerOptions, type Logger as PinoLogger } from 'pino';\nimport { AUTHORIZATION_HEADER, type Logger, PAYMENT_HEADER } from '../core';\n\n/**\n * Absolute path to pino-pretty, or `undefined` when it is not installed.\n *\n * pino-pretty is a devDependency, so a consumer of the published package\n * usually lacks it, yet an unset `NODE_ENV` still selects the pretty default.\n * An unresolvable transport makes `pino()` throw and takes `createGateway()`\n * down with it. Passing the absolute path also stops pino resolving the\n * target from a different directory than this module.\n */\nconst PINO_PRETTY_PATH: string | undefined = (() => {\n try {\n return createRequire(import.meta.url).resolve('pino-pretty');\n } catch {\n return undefined;\n }\n})();\n\n// Each name is redacted at the top level and one level down ('*.privateKey'\n// matches `wallet.privateKey`). Pino's redact wildcards are single-level, so\n// `a.b.privateKey` is not covered: never put a secret in error details or log\n// a raw object that may nest one deeper without extending these paths.\nconst SECRET_FIELD_NAMES = [\n 'privateKey',\n 'signerPrivateKey',\n 'signature',\n 'seed',\n 'mnemonic',\n 'secret',\n 'challengeSecret',\n 'apiKey',\n 'adminToken',\n 'token',\n] as const;\n\n// Credential and proof headers. The proof headers come from the wire constants,\n// so a renamed one stays redacted; `agent-authorization` carries an AP2 mandate.\nconst SECRET_HEADERS = ['authorization', PAYMENT_HEADER, AUTHORIZATION_HEADER] as const;\n\nexport const REDACT_PATHS: readonly string[] = [\n ...SECRET_HEADERS.map((name) => `req.headers[${JSON.stringify(name)}]`),\n ...SECRET_FIELD_NAMES,\n ...SECRET_FIELD_NAMES.map((name) => `*.${name}`),\n];\n\nexport interface CreateGatewayLoggerOptions {\n readonly level?: string;\n readonly name?: string;\n readonly nodeEnv?: string;\n readonly prettyPrint?: boolean;\n}\n\nexport interface CreatedGatewayLogger {\n /** Raw pino instance, not shared with Fastify (see file header) */\n readonly pino: PinoLogger;\n /** `src/core` `Logger`-shaped wrapper */\n readonly core: Logger;\n}\n\nfunction baseLoggerOptions(options: CreateGatewayLoggerOptions): LoggerOptions {\n const nodeEnv = options.nodeEnv ?? process.env['NODE_ENV'] ?? 'development';\n // No pino-pretty worker thread in tests, which create many short-lived loggers\n const wantPretty = options.prettyPrint ?? (nodeEnv !== 'production' && nodeEnv !== 'test');\n // Even an explicit `prettyPrint: true` falls back to JSON when pino-pretty\n // is missing, rather than throwing\n const usePretty = wantPretty && PINO_PRETTY_PATH !== undefined;\n\n return {\n level: options.level ?? process.env['LOG_LEVEL'] ?? (nodeEnv === 'test' ? 'silent' : 'info'),\n ...(options.name !== undefined ? { name: options.name } : {}),\n redact: { paths: [...REDACT_PATHS], censor: '[REDACTED]' },\n ...(usePretty ? { transport: { target: PINO_PRETTY_PATH as string } } : {}),\n };\n}\n\n/**\n * Replaces a URL's query string with `?[REDACTED]` before it reaches a log line\n * or a response body: the admin token is header only, but any query parameter\n * on any route may carry something sensitive. Every place that shows a request\n * URL to a log or a client calls this instead of redacting its own way.\n */\nfunction sanitizeUrl(url: string | undefined): string | undefined {\n if (url === undefined) return undefined;\n const queryIndex = url.indexOf('?');\n return queryIndex === -1 ? url : `${url.slice(0, queryIndex)}?[REDACTED]`;\n}\n\n// Replaces Fastify's default `req` serializer, so the logged URL is sanitized\nfunction redactedReqSerializer(req: {\n method?: string;\n url?: string;\n host?: string;\n ip?: string;\n socket?: { remotePort?: number };\n}): Record<string, unknown> {\n return {\n method: req.method,\n url: sanitizeUrl(req.url),\n host: req.host,\n remoteAddress: req.ip,\n remotePort: req.socket?.remotePort,\n };\n}\n\n/** Options for Fastify's own `logger` option (see file header) */\nexport function fastifyLoggerOptions(options: CreateGatewayLoggerOptions = {}): LoggerOptions {\n return {\n ...baseLoggerOptions(options),\n serializers: { req: redactedReqSerializer },\n };\n}\n\n/**\n * Replaces Fastify's default 404 handler, whose log line interpolates\n * `request.raw.url` into a plain string and so bypasses the `req` serializer.\n * Exported so the tests exercise the handler that ships.\n */\nexport function buildNotFoundHandler(): (request: FastifyRequest, reply: FastifyReply) => void {\n return (request, reply) => {\n const safeUrl = sanitizeUrl(request.raw.url) ?? '';\n const message = `Route ${request.method}:${safeUrl} not found`;\n request.log.info(message);\n reply.code(404).send({ message, error: 'Not Found', statusCode: 404 });\n };\n}\n\nexport function createGatewayLogger(\n options: CreateGatewayLoggerOptions = {},\n): CreatedGatewayLogger {\n const instance = pino(baseLoggerOptions(options));\n return { pino: instance, core: wrapPino(instance) };\n}\n\nfunction wrapPino(instance: PinoLogger): Logger {\n const logger: Logger = {\n debug: (obj, msg) => instance.debug(obj, msg),\n info: (obj, msg) => instance.info(obj, msg),\n warn: (obj, msg) => instance.warn(obj, msg),\n error: (obj, msg) => instance.error(obj, msg),\n child: (bindings) => wrapPino(instance.child(bindings)),\n };\n return logger;\n}\n","/**\n * Secret-free projection of a `CommerceResource`, served by the public\n * `GET /api/resources`. `handler.headers` may carry resolved backend secrets,\n * such as an `Authorization` value built from `${API_KEY}`, so no handler\n * field except the method is copied.\n */\nimport type { CommerceResource } from '../core';\n\nexport interface PublicResource {\n readonly id: string;\n readonly name: string;\n readonly description?: string;\n readonly inputSchema?: Record<string, unknown>;\n readonly outputSchema?: Record<string, unknown>;\n readonly method: string;\n readonly pricing: CommerceResource['pricing'];\n readonly exposedVia: readonly string[];\n readonly paymentMethods: readonly string[];\n}\n\nexport function toPublicResource(resource: CommerceResource): PublicResource {\n return {\n id: resource.id,\n name: resource.name,\n ...(resource.description !== undefined ? { description: resource.description } : {}),\n ...(resource.inputSchema !== undefined ? { inputSchema: resource.inputSchema } : {}),\n ...(resource.outputSchema !== undefined ? { outputSchema: resource.outputSchema } : {}),\n method: resource.handler.method,\n pricing: resource.pricing,\n exposedVia: resource.exposedVia,\n paymentMethods: resource.paymentMethods,\n };\n}\n","/**\n * `GET /ready`: 503 when the store, a protocol adapter, or a payment or\n * authorization provider reports `fail`; `warn` still counts as serving.\n * Providers count because a payment provider that cannot reach its RPC would\n * otherwise leave the gateway ready while it serves 402 challenges it cannot\n * honor.\n *\n * The route is unauthenticated, so a health `detail` or a thrown message never\n * reaches the client, only a fixed vocabulary.\n *\n * An evaluation calls every dependency's `health()`, some of which make\n * upstream RPC calls. `createReadinessProbe` memoizes it for\n * READINESS_TTL_MS and collapses concurrent callers onto one evaluation, which\n * `/ready` and `/.well-known/agent-commerce` share.\n */\nimport type {\n AdapterDescriptor,\n AdapterHealth,\n AuthorizationProvider,\n Clock,\n Logger,\n PaymentProvider,\n ReceiptStore,\n} from '../core';\nimport { type AdapterRuntime, getAdapterHealth } from './adapters';\n\nexport interface ReadinessCheck {\n readonly name: string;\n readonly status: AdapterHealth['status'];\n readonly detail?: string;\n}\n\nexport interface ReadinessResult {\n readonly ready: boolean;\n readonly store: ReadinessCheck;\n readonly adapters: readonly ReadinessCheck[];\n readonly paymentProviders: readonly ReadinessCheck[];\n readonly authorizationProviders: readonly ReadinessCheck[];\n}\n\nexport interface CheckReadinessOptions {\n readonly store: ReceiptStore;\n readonly adapterRuntimes: readonly AdapterRuntime[];\n readonly paymentProviders: readonly PaymentProvider[];\n readonly authorizationProviders: readonly AuthorizationProvider[];\n readonly clock: Clock;\n readonly logger: Logger;\n}\n\nexport interface ProbedAdapter {\n readonly descriptor: AdapterDescriptor;\n readonly health: AdapterHealth;\n}\n\n// The client-facing detail per status; `threw` covers a health() that threw\n// and defaults to the `fail` detail\ntype HealthDetails = Readonly<Record<AdapterHealth['status'], string | undefined>> & {\n readonly threw?: string;\n};\n\nconst STORE_DETAIL: HealthDetails = {\n pass: undefined,\n warn: 'store-degraded',\n fail: 'store-unwritable',\n threw: 'store-unreachable',\n};\n\nconst ADAPTER_DETAIL: HealthDetails = {\n pass: undefined,\n warn: 'adapter-degraded',\n fail: 'adapter-unreachable',\n};\n\nconst PAYMENT_PROVIDER_DETAIL: HealthDetails = {\n pass: undefined,\n warn: 'payment-provider-degraded',\n fail: 'payment-provider-unreachable',\n};\n\nconst AUTHORIZATION_PROVIDER_DETAIL: HealthDetails = {\n pass: undefined,\n warn: 'authorization-provider-degraded',\n fail: 'authorization-provider-unreachable',\n};\n\n// A readiness check plus the health it came from, detail included. Only the\n// check reaches /ready; the well-known document publishes adapter health\n// without its detail.\ninterface Probed {\n readonly check: ReadinessCheck;\n readonly health: AdapterHealth;\n}\n\n/**\n * One probe for the store, the adapters and both provider kinds. A `health()`\n * that throws counts as failing and is logged at error; a returned detail is\n * logged at debug.\n */\nasync function probe(\n target: { readonly name: string; health(): Promise<AdapterHealth> },\n kind: string,\n details: HealthDetails,\n options: Pick<CheckReadinessOptions, 'clock' | 'logger'>,\n): Promise<Probed> {\n let health: AdapterHealth;\n let threw = false;\n try {\n health = await target.health();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n options.logger.error({ err: message, name: target.name }, `${kind} health() threw`);\n health = { status: 'fail', checkedAt: options.clock.nowIso() };\n threw = true;\n }\n if (health.detail !== undefined) {\n options.logger.debug(\n { name: target.name, detail: health.detail },\n `${kind} health detail (not sent to the client)`,\n );\n }\n const detail = threw ? (details.threw ?? details.fail) : details[health.status];\n return {\n check: {\n name: target.name,\n status: health.status,\n ...(detail !== undefined ? { detail } : {}),\n },\n health,\n };\n}\n\ninterface Evaluation {\n readonly result: ReadinessResult;\n readonly adapters: readonly ProbedAdapter[];\n readonly paymentProviders: readonly ProbedProvider[];\n}\n\n/** A payment provider's health, detail and components included */\nexport interface ProbedProvider {\n readonly name: string;\n readonly health: AdapterHealth;\n}\n\nasync function evaluate(options: CheckReadinessOptions): Promise<Evaluation> {\n const [store, adapters, paymentProviders, authorizationProviders] = await Promise.all([\n probe({ name: 'store', health: () => options.store.health() }, 'store', STORE_DETAIL, options),\n Promise.all(\n options.adapterRuntimes.map(async (runtime) => ({\n runtime,\n probed: await probe(\n // getAdapterHealth turns a throw into a failed result, so an adapter\n // failure is logged at debug as a detail rather than at error\n { name: runtime.adapter.name, health: () => getAdapterHealth(runtime, options.clock) },\n 'adapter',\n ADAPTER_DETAIL,\n options,\n ),\n })),\n ),\n Promise.all(\n options.paymentProviders.map((provider) =>\n probe(provider, 'payment provider', PAYMENT_PROVIDER_DETAIL, options),\n ),\n ),\n // An unusable authorization provider blocks readiness on the same threshold\n // as a payment one: a resource that requires a mandate cannot be served\n // without it, and serving the challenge anyway promises what we cannot honor\n Promise.all(\n options.authorizationProviders.map((provider) =>\n probe(provider, 'authorization provider', AUTHORIZATION_PROVIDER_DETAIL, options),\n ),\n ),\n ]);\n\n const checks = [\n store,\n ...adapters.map((a) => a.probed),\n ...paymentProviders,\n ...authorizationProviders,\n ];\n return {\n result: {\n ready: checks.every((probed) => probed.check.status !== 'fail'),\n store: store.check,\n adapters: adapters.map((a) => a.probed.check),\n paymentProviders: paymentProviders.map((p) => p.check),\n authorizationProviders: authorizationProviders.map((p) => p.check),\n },\n adapters: adapters.map(({ runtime, probed }) => ({\n descriptor: runtime.adapter.descriptor,\n health: probed.health,\n })),\n paymentProviders: paymentProviders.map((probed, index) => ({\n name: (options.paymentProviders[index] as PaymentProvider).name,\n health: probed.health,\n })),\n };\n}\n\n// Short enough that an outage or a recovery shows within one window\nconst READINESS_TTL_MS = 2_000;\n\nexport interface ReadinessProbe {\n check(): Promise<ReadinessResult>;\n /** All adapter health results, including detail, from the cached evaluation */\n adapterHealth(): Promise<readonly ProbedAdapter[]>;\n /** All payment provider health results from that evaluation */\n paymentHealth(): Promise<readonly ProbedProvider[]>;\n}\n\nexport function createReadinessProbe(\n options: CheckReadinessOptions,\n ttlMs: number = READINESS_TTL_MS,\n): ReadinessProbe {\n let cached: { readonly evaluation: Evaluation; readonly at: number } | undefined;\n let inFlight: Promise<Evaluation> | undefined;\n\n const current = async (): Promise<Evaluation> => {\n const now = options.clock.monotonicMs();\n if (cached && now - cached.at < ttlMs) return cached.evaluation;\n if (inFlight) return inFlight;\n\n inFlight = evaluate(options)\n .then((evaluation) => {\n cached = { evaluation, at: options.clock.monotonicMs() };\n return evaluation;\n })\n .finally(() => {\n inFlight = undefined;\n });\n return inFlight;\n };\n\n return {\n check: async () => (await current()).result,\n adapterHealth: async () => (await current()).adapters,\n paymentHealth: async () => (await current()).paymentProviders,\n };\n}\n","/**\n * `GET /.well-known/agent-commerce`: the merchant, the `AdapterDescriptor` of\n * every adapter, provider and store, and the protocol and spec versions. The\n * route is unauthenticated, so nothing here may be a credential.\n *\n * The settlement destination, `network` and `asset` are public: a payer needs\n * them to build a payment, and the destination is visible on-chain after any\n * transfer. `rpcUrl` and the facilitator URL are withheld, because commercial\n * providers embed an API key in the URL (Alchemy's `/v2/<KEY>`, Infura's\n * `/v3/<KEY>`, QuickNode's per-endpoint token). The facilitator private key\n * never appears.\n */\n\nimport type { GatewayConfig } from '../config';\nimport type { X402OptionConfig } from '../config/schema';\nimport type {\n AdapterDescriptor,\n AdapterHealth,\n AuthorizationProvider,\n PaymentProvider,\n ReceiptStore,\n} from '../core';\nimport { MPP_DEFAULT_PAYMENT_FLOW, MPP_PROFILE } from '../payments/mpp/constants';\nimport {\n type DeploymentMode,\n requireX402Network,\n resolveDeploymentMode,\n} from '../payments/x402/networks';\nimport { x402OfferName } from '../payments/x402/options';\nimport { X402_DEFAULT_PAYMENT_FLOW, type X402PaymentFlow } from '../payments/x402/payment-flow';\nimport { PACKAGE_VERSION } from '../version';\nimport type { ProbedAdapter, ProbedProvider } from './readiness';\n\n// Not derived from `PACKAGE_VERSION`: it names the wire contract a client\n// negotiates against, which changes only when that contract does\nconst GATEWAY_SUPPORTED_SPEC = 'agent-commerce/v1.0.0';\n\n/**\n * The protocol block as published, not as configured.\n *\n * Built field by field rather than spread from `config.protocols`, because that\n * object carries `protocols.acp.auth.token` - a live credential - plus the\n * idempotency database path and the operation-to-resource mapping. This route\n * is unauthenticated, so a future config field must be added here deliberately\n * to become public, never by inheriting a shape.\n */\nexport interface WellKnownProtocols {\n readonly http: { readonly enabled: boolean };\n readonly mcp: { readonly enabled: boolean; readonly mountPath: string };\n readonly a2a: { readonly enabled: boolean; readonly mountPath: string };\n readonly acp: { readonly enabled: boolean; readonly mountPath: string };\n}\n\nexport interface WellKnownDocument {\n readonly gateway: { readonly implementationVersion: string; readonly supportedSpec: string };\n readonly merchant: GatewayConfig['merchant'];\n readonly protocols: WellKnownProtocols;\n readonly adapters: ReadonlyArray<AdapterDescriptor & { readonly health: AdapterHealth }>;\n readonly paymentProviders: readonly AdapterDescriptor[];\n /**\n * Empty unless the gateway has an authorization provider (`authorization.ap2.enabled`).\n * Listed apart from `paymentProviders` because an authorization method is not\n * a payment rail and must never be selectable as one.\n */\n readonly authorizationProviders: readonly AdapterDescriptor[];\n readonly store: AdapterDescriptor;\n readonly payments: {\n readonly x402?: {\n readonly enabled: boolean;\n readonly network: string;\n readonly asset: string;\n /** Absent for a Permit2 token that has no EIP-712 domain */\n readonly assetName?: string;\n readonly assetVersion?: string;\n readonly assetDecimals: number;\n readonly payTo: string;\n /** Absent for EIP-3009, the default */\n readonly assetTransferMethod?: 'permit2';\n readonly maxTimeoutSeconds: number;\n readonly facilitator: { readonly mode: 'local' | 'remote' };\n /** `local`, `testnet` or `mainnet`, from the network */\n readonly mode: DeploymentMode;\n /** `authorization` settles after the backend; `upfront` before it */\n readonly paymentFlow: X402PaymentFlow;\n /** Resources that set their own flow, by id; absent when none does */\n readonly resourcePaymentFlows?: Readonly<Record<string, X402PaymentFlow>>;\n /** All rail offers when multiple exist; top-level fields mirror the first */\n readonly options?: readonly WellKnownX402Offer[];\n /** Resource offer overrides by id, replacing the rail's offers */\n readonly resourceOptions?: Readonly<Record<string, readonly WellKnownX402Offer[]>>;\n };\n /** Public settlement fields; excludes the challenge secret and facilitator credentials */\n readonly mpp?: {\n readonly enabled: boolean;\n readonly network: string;\n readonly asset: string;\n readonly assetName: string;\n readonly assetVersion: string;\n readonly assetDecimals: number;\n readonly recipient: string;\n readonly facilitator: { readonly mode: 'local' | 'remote' };\n readonly mode: DeploymentMode;\n /** `upfront` settles before the backend; `authorization` after it */\n readonly paymentFlow: X402PaymentFlow;\n /** Resources that set their own flow, by id; absent when none does */\n readonly resourcePaymentFlows?: Readonly<Record<string, X402PaymentFlow>>;\n };\n };\n}\n\n/** One x402 offer's public terms */\nexport interface WellKnownX402Offer {\n readonly network: string;\n readonly asset: string;\n readonly assetName?: string;\n readonly assetVersion?: string;\n readonly assetDecimals: number;\n readonly payTo: string;\n readonly assetTransferMethod?: 'permit2';\n /** Last reported health status, excluding diagnostic detail */\n readonly status?: AdapterHealth['status'];\n}\n\nexport interface BuildWellKnownOptions {\n readonly config: GatewayConfig;\n readonly paymentProviders: readonly PaymentProvider[];\n readonly authorizationProviders: readonly AuthorizationProvider[];\n readonly store: ReceiptStore;\n /** From the readiness cache, sharing `/ready`'s `health()` calls */\n readonly adapters: readonly ProbedAdapter[];\n /** From the same probe; the x402 provider's components give each offer's status */\n readonly paymentHealth?: readonly ProbedProvider[];\n}\n\n/**\n * Drops `detail` from a health result; `/ready` replaces it with a fixed\n * vocabulary. For a thrown `health()` or a start failure `detail` holds the\n * raw error message, often a module path or an internal hostname, and\n * `createGateway` accepts arbitrary adapters whose details this code cannot\n * vouch for.\n */\nfunction publicHealth(health: AdapterHealth): AdapterHealth {\n const { detail: _detail, ...rest } = health;\n return rest;\n}\n\nfunction publicProtocols(protocols: GatewayConfig['protocols']): WellKnownProtocols {\n return {\n http: { enabled: protocols.http.enabled },\n mcp: { enabled: protocols.mcp.enabled, mountPath: protocols.mcp.mountPath },\n a2a: { enabled: protocols.a2a.enabled, mountPath: protocols.a2a.mountPath },\n acp: { enabled: protocols.acp.enabled, mountPath: protocols.acp.mountPath },\n };\n}\n\n// Allowlist public offer fields: RPC URLs can contain API keys\nfunction publicOffer(\n option: X402OptionConfig,\n statuses: ReadonlyMap<string, AdapterHealth['status']>,\n): WellKnownX402Offer {\n const { network, asset, assetName, assetVersion, assetDecimals, payTo, assetTransferMethod } =\n option;\n const status = statuses.get(x402OfferName(option));\n return {\n network,\n asset,\n ...(assetName !== undefined ? { assetName } : {}),\n ...(assetVersion !== undefined ? { assetVersion } : {}),\n assetDecimals,\n payTo,\n ...(assetTransferMethod !== undefined ? { assetTransferMethod } : {}),\n ...(status !== undefined ? { status } : {}),\n };\n}\n\n// A rail's per-resource flows, or nothing when no resource overrides the rail\nfunction flowOverrides(flows: Readonly<Record<string, X402PaymentFlow>> | undefined): {\n readonly resourcePaymentFlows?: Readonly<Record<string, X402PaymentFlow>>;\n} {\n return flows !== undefined && Object.keys(flows).length > 0\n ? { resourcePaymentFlows: flows }\n : {};\n}\n\nexport function buildWellKnownDocument(options: BuildWellKnownOptions): WellKnownDocument {\n const adapters = options.adapters.map(({ descriptor, health }) => ({\n ...descriptor,\n health: publicHealth(health),\n }));\n\n const { x402, mpp } = options.config.payments;\n const x402Health = options.paymentHealth?.find((probed) => probed.name === 'x402')?.health;\n const offerStatuses = new Map(\n (x402Health?.components ?? []).map((component) => [component.name, component.status]),\n );\n\n return {\n gateway: {\n implementationVersion: PACKAGE_VERSION,\n supportedSpec: GATEWAY_SUPPORTED_SPEC,\n },\n merchant: options.config.merchant,\n protocols: publicProtocols(options.config.protocols),\n adapters,\n paymentProviders: options.paymentProviders.map((provider) => provider.descriptor),\n authorizationProviders: options.authorizationProviders.map((provider) => provider.descriptor),\n store: options.store.descriptor,\n payments: {\n ...(x402 !== undefined\n ? {\n x402: {\n enabled: x402.enabled,\n network: x402.network,\n asset: x402.asset,\n ...(x402.assetName !== undefined ? { assetName: x402.assetName } : {}),\n ...(x402.assetVersion !== undefined ? { assetVersion: x402.assetVersion } : {}),\n assetDecimals: x402.assetDecimals,\n payTo: x402.payTo,\n ...(x402.assetTransferMethod !== undefined\n ? { assetTransferMethod: x402.assetTransferMethod }\n : {}),\n maxTimeoutSeconds: x402.maxTimeoutSeconds,\n // Only local or remote is public: the facilitator URL can carry\n // a tenant path or an API key, and the signer key is secret\n facilitator: { mode: x402.facilitator.mode },\n mode: resolveDeploymentMode(\n requireX402Network(x402.network, 'payments.x402.network', x402.networks),\n ),\n paymentFlow: x402.paymentFlow ?? X402_DEFAULT_PAYMENT_FLOW,\n ...flowOverrides(x402.resourcePaymentFlows),\n ...(x402.options !== undefined && x402.options.length > 1\n ? { options: x402.options.map((option) => publicOffer(option, offerStatuses)) }\n : {}),\n ...(x402.resourceOptions !== undefined\n ? {\n resourceOptions: Object.fromEntries(\n Object.entries(x402.resourceOptions).map(([id, list]) => [\n id,\n list.map((option) => publicOffer(option, offerStatuses)),\n ]),\n ),\n }\n : {}),\n },\n }\n : {}),\n ...(mpp !== undefined\n ? {\n mpp: {\n enabled: mpp.enabled,\n network: mpp.network,\n asset: mpp.asset,\n assetName: mpp.assetName,\n assetVersion: mpp.assetVersion,\n assetDecimals: MPP_PROFILE.assetDecimals,\n recipient: mpp.recipient,\n facilitator: { mode: mpp.facilitator.mode },\n mode: resolveDeploymentMode(requireX402Network(mpp.network, 'payments.mpp.network')),\n paymentFlow: mpp.paymentFlow ?? MPP_DEFAULT_PAYMENT_FLOW,\n ...flowOverrides(mpp.resourcePaymentFlows),\n },\n }\n : {}),\n },\n };\n}\n","/**\n * The gateway's own HTTP surface (docs/contracts.md \"Gateway HTTP surface\").\n * Adapter mounting (e.g. `/mcp`) is handled separately in adapters.ts.\n */\n\nimport { Transform } from 'node:stream';\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';\nimport type { GatewayConfig } from '../config';\nimport {\n AUTHORIZATION_HEADER,\n type AuthorizationProvider,\n type CanonicalRequest,\n type Clock,\n CommerceError,\n type ExecutionPipeline,\n type Logger,\n PAYMENT_HEADER,\n PAYMENT_REQUIRED_HEADER,\n PAYMENT_RESPONSE_HEADER,\n type PaymentMethodName,\n type PaymentProvider,\n parseAuthorizationHeader,\n type ReceiptStore,\n type ResourceRegistry,\n toCommerceError,\n toErrorEnvelope,\n toPaymentRequiredEnvelope,\n} from '../core';\nimport { isRecord } from '../core/is-record';\nimport { mppProblem, mppProblemDetail } from '../payments/mpp/problems';\nimport { CONTENT_DIGEST_METADATA_KEY, contentDigest } from '../payments/mpp/transport';\nimport {\n settlementFailure,\n settlementResponse,\n settlementResponseFromDetails,\n x402ErrorCode,\n x402RefusalStatus,\n} from '../payments/x402/transport';\nimport { buildOperatorTokenHook } from './access-control';\nimport type { AdapterRuntime } from './adapters';\nimport { toPublicResource } from './public-resource';\nimport { createReadinessProbe } from './readiness';\nimport { buildWellKnownDocument } from './well-known';\n\n// Legacy x402 proof header; this gateway accepts v2 only\nconst X402_V1_PAYMENT_HEADER = 'x-payment';\n\nexport interface RegisterRoutesOptions {\n readonly server: FastifyInstance;\n readonly config: GatewayConfig;\n readonly pipeline: ExecutionPipeline;\n readonly resources: ResourceRegistry;\n readonly store: ReceiptStore;\n readonly paymentProviders: readonly PaymentProvider[];\n readonly authorizationProviders: readonly AuthorizationProvider[];\n readonly clock: Clock;\n readonly adapterRuntimes: readonly AdapterRuntime[];\n readonly logger: Logger;\n}\n\nexport function registerRoutes(options: RegisterRoutesOptions): void {\n const { server } = options;\n\n // `adapterRuntimes` is filled in place once adapters start, so the probe\n // reads the live list\n const readinessProbe = createReadinessProbe({\n store: options.store,\n adapterRuntimes: options.adapterRuntimes,\n paymentProviders: options.paymentProviders,\n authorizationProviders: options.authorizationProviders,\n clock: options.clock,\n logger: options.logger,\n });\n\n server.get('/health', async () => ({ status: 'ok' }));\n\n server.get('/ready', async (_request, reply) => {\n const readiness = await readinessProbe.check();\n reply.status(readiness.ready ? 200 : 503);\n return readiness;\n });\n\n server.get('/.well-known/agent-commerce', async () =>\n buildWellKnownDocument({\n config: options.config,\n paymentProviders: options.paymentProviders,\n authorizationProviders: options.authorizationProviders,\n store: options.store,\n adapters: await readinessProbe.adapterHealth(),\n paymentHealth: await readinessProbe.paymentHealth(),\n }),\n );\n\n // List provider-backed rails in challenge order\n const backed = (method: string) =>\n options.paymentProviders.some((provider) => provider.name === method);\n server.get('/api/resources', async () => ({\n resources: options.resources.list().map((resource) => {\n const listed = toPublicResource(resource);\n return { ...listed, paymentMethods: listed.paymentMethods.filter(backed) };\n }),\n }));\n\n server.post(\n '/api/resources/:id/invoke',\n { preParsing: async (request, _reply, payload) => payload.pipe(digestingStream(request)) },\n async (request, reply) => {\n await handleInvoke(request, reply, options);\n },\n );\n\n // The admin token gate is per route, not global; access-control.ts says why\n const tokenHook = buildOperatorTokenHook(options.config.server.adminToken);\n\n server.get(\n '/api/receipts',\n { onRequest: tokenHook },\n ledgerHandler('receipts', (list) => options.store.listReceipts(list)),\n );\n server.get(\n '/api/events',\n { onRequest: tokenHook },\n ledgerHandler('events', (list) => options.store.listEvents(list)),\n );\n}\n\n// Keep a digest of each invoke body's original bytes through parsing.\nconst bodyDigests = new WeakMap<FastifyRequest, string>();\n\n// Forward each body chunk unchanged and record the digest at the end.\nfunction digestingStream(request: FastifyRequest): Transform {\n const chunks: Buffer[] = [];\n return new Transform({\n transform(chunk: Buffer, _encoding, callback) {\n chunks.push(chunk);\n callback(null, chunk);\n },\n flush(callback) {\n if (chunks.length > 0) bodyDigests.set(request, contentDigest(Buffer.concat(chunks)));\n callback();\n },\n });\n}\n\n// `GET /api/receipts` and `GET /api/events`: one page of a ledger\nfunction ledgerHandler<K extends string>(\n key: K,\n list: (options: { limit?: number }) => Promise<unknown>,\n): (request: FastifyRequest, reply: FastifyReply) => Promise<Record<K, unknown> | undefined> {\n return async (request, reply) => {\n try {\n const limit = parseLimit((request.query as Record<string, unknown>)['limit']);\n return { [key]: await list(limit !== undefined ? { limit } : {}) } as Record<K, unknown>;\n } catch (error) {\n const commerceError = toCommerceError(error);\n reply.status(commerceError.httpStatus).send(toErrorEnvelope(commerceError));\n return undefined;\n }\n };\n}\n\nasync function handleInvoke(\n request: FastifyRequest,\n reply: FastifyReply,\n options: RegisterRoutesOptions,\n): Promise<void> {\n const resourceId = (request.params as { id: string }).id;\n // Track the selected rail so errors use its payment headers\n let paymentMethod: PaymentMethodName | undefined;\n\n try {\n const resource = options.resources.get(resourceId);\n if (!resource?.exposedVia.includes('http')) {\n throw new CommerceError('RESOURCE_NOT_FOUND', `Resource \"${resourceId}\" was not found`, {\n requestId: request.id,\n resourceId,\n });\n }\n\n // createGateway puts provider-backed methods first, so this label matches\n // the rail selected by the pipeline. Without a method, drop the proof\n // instead of inventing a rail; the pipeline receives an unpaid request.\n paymentMethod = resource.paymentMethods[0];\n const paymentValue = paymentProof(request, paymentMethod);\n const payment =\n paymentValue !== undefined && paymentMethod !== undefined\n ? { method: paymentMethod, payload: paymentValue }\n : undefined;\n\n // Its own header rather than a reserved body field: HTTP already carries\n // the payment proof out of band, and an authorization inside the body\n // would have to survive every backend input-binding mode intact\n const authorization = parseAuthorizationHeader(\n request.headers[AUTHORIZATION_HEADER],\n request.id,\n );\n\n const digest = bodyDigests.get(request);\n const canonicalRequest: CanonicalRequest = {\n requestId: request.id,\n resourceId,\n input: request.body ?? {},\n protocol: 'http',\n receivedAt: options.clock.nowIso(),\n ...(payment !== undefined ? { payment } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n ...(digest !== undefined ? { metadata: { [CONTENT_DIGEST_METADATA_KEY]: digest } } : {}),\n };\n\n const outcome = await options.pipeline.execute(canonicalRequest);\n\n if (outcome.kind === 'payment-required') {\n const envelope = toPaymentRequiredEnvelope(outcome);\n if (envelope.payment.provider === 'mpp') {\n const challenge = envelope.payment.envelope?.['wwwAuthenticate'];\n if (typeof challenge === 'string') reply.header('www-authenticate', challenge);\n } else if (envelope.payment.envelope !== undefined) {\n // v2 clients read this header. A v1-only proof gets a challenge\n // naming the unsupported version; the body keeps the full envelope.\n const v1Only =\n request.headers[X402_V1_PAYMENT_HEADER] !== undefined &&\n request.headers[PAYMENT_HEADER] === undefined;\n reply.header(\n PAYMENT_REQUIRED_HEADER,\n encodeHeaderDocument(\n v1Only\n ? { ...envelope.payment.envelope, error: 'invalid_x402_version' }\n : envelope.payment.envelope,\n ),\n );\n }\n // A challenge is per-request (fresh nonce window, fresh expiry). Caching\n // one would hand a later buyer an expired offer.\n reply.header('cache-control', 'no-store');\n if (envelope.payment.provider === 'mpp') {\n // Use Problem Details for unpaid MPP requests and refusals\n const { status: _envelopeStatus, ...members } = envelope;\n reply\n .header('content-type', 'application/problem+json')\n .status(402)\n .send({\n ...mppProblem(envelope.code, 402),\n status: 402,\n detail: envelope.message,\n ...members,\n });\n return;\n }\n reply.status(402).send(envelope);\n return;\n }\n\n if (outcome.payment) {\n reply.header(\n PAYMENT_RESPONSE_HEADER,\n encodeHeaderDocument(settlementResponse(outcome.payment)),\n );\n const receipt = outcome.payment.metadata?.['receipt'];\n if (outcome.payment.provider === 'mpp' && typeof receipt === 'string') {\n reply.header('payment-receipt', receipt);\n }\n // Payment headers identify this buyer's payment; MPP also requires\n // private caching for responses carrying `Payment-Receipt`\n reply.header('cache-control', 'private');\n }\n reply.status(outcome.backendStatus).send(outcome.body);\n } catch (error) {\n sendInvokeError(reply, toCommerceError(error), paymentMethod);\n }\n}\n\n// A provider outage is no verdict on the payment, so the client may retry the\n// same proof after a short pause\nconst PROVIDER_UNAVAILABLE_CODES: ReadonlySet<string> = new Set([\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'AUTHORIZATION_PROVIDER_UNAVAILABLE',\n]);\nconst PROVIDER_RETRY_AFTER_SECONDS = 5;\n\n// Codes whose MPP response body is a Problem Details document\nconst MPP_PROBLEM_CODES: ReadonlySet<string> = new Set([\n 'PAYMENT_INVALID',\n 'PAYMENT_REPLAYED',\n 'PAYMENT_SETTLEMENT_FAILED',\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n]);\n\nfunction sendInvokeError(\n reply: FastifyReply,\n error: CommerceError,\n paymentMethod: PaymentMethodName | undefined,\n): void {\n const details = error.details;\n if (PROVIDER_UNAVAILABLE_CODES.has(error.code)) {\n reply.header('retry-after', String(PROVIDER_RETRY_AFTER_SECONDS));\n }\n // Report a settled payment even if backend delivery fails. MPP forbids a\n // `Payment-Receipt` header on error responses, so send only this summary\n const settled = settlementResponseFromDetails(details);\n if (settled !== undefined) {\n reply.header(PAYMENT_RESPONSE_HEADER, encodeHeaderDocument(settled));\n }\n if (error.code === 'PAYMENT_SETTLEMENT_FAILED') {\n reply.header(PAYMENT_RESPONSE_HEADER, encodeHeaderDocument(settlementFailure(details)));\n }\n // Attach a fresh challenge to a 402 when the rail provides one\n const challenge = details?.['challenge'];\n if (error.httpStatus === 402 && isRecord(challenge)) {\n if (paymentMethod === 'mpp' && typeof challenge['wwwAuthenticate'] === 'string') {\n reply.header('www-authenticate', challenge['wwwAuthenticate']);\n } else if (paymentMethod === 'x402' && error.code !== 'PAYMENT_SETTLEMENT_FAILED') {\n // x402 includes the reason in the challenge; settlement refusals use\n // `PAYMENT-RESPONSE` alone\n reply.header(\n PAYMENT_REQUIRED_HEADER,\n encodeHeaderDocument({\n ...challenge,\n error: x402ErrorCode(error.code, details?.['reason'], details?.['network']),\n }),\n );\n }\n reply.header('cache-control', 'no-store');\n }\n\n const envelope = toErrorEnvelope(error);\n if (paymentMethod === 'mpp' && MPP_PROBLEM_CODES.has(error.code)) {\n // RFC 9457 `status` is the HTTP status, so it replaces the envelope's\n // `status: 'error'`; the other envelope fields stay as extension members\n const { status: _envelopeStatus, ...members } = envelope;\n const reason = typeof details?.['reason'] === 'string' ? details['reason'] : undefined;\n reply\n .header('content-type', 'application/problem+json')\n .status(error.httpStatus)\n .send({\n ...mppProblem(error.code, error.httpStatus, reason),\n status: error.httpStatus,\n // The reason token stays in `message` and `details.reason`\n detail: mppProblemDetail(reason, error.message),\n ...members,\n });\n return;\n }\n // Preserve the challenge when a missing Permit2 allowance changes 402 to 412\n const status =\n paymentMethod === 'x402'\n ? x402RefusalStatus(error.code, error.httpStatus, details?.['reason'])\n : error.httpStatus;\n reply.status(status).send(envelope);\n}\n\n// Each rail has its own proof header. MPP uses HTTP authentication, and an\n// `Authorization` value in another scheme is not a payment proof.\nfunction paymentProof(\n request: FastifyRequest,\n method: PaymentMethodName | undefined,\n): string | undefined {\n if (method === 'mpp') {\n const value = request.headers.authorization;\n return value !== undefined && /^Payment\\s+\\S/i.test(value) ? value : undefined;\n }\n const value = request.headers[PAYMENT_HEADER];\n return Array.isArray(value) ? value[0] : value;\n}\n\n/**\n * Base64 of a JSON document, the encoding every x402 v2 payment header uses.\n * Not imported from the x402 SDK: this module is reachable from the main\n * entry point, which must import no optional peer.\n */\nfunction encodeHeaderDocument(document: unknown): string {\n return Buffer.from(JSON.stringify(document), 'utf8').toString('base64');\n}\n\n// Undefined when absent or unparseable, so the store applies its default. A\n// parseable value below 1 is INPUT_INVALID, because SQLite reads a negative\n// LIMIT as unbounded.\nfunction parseLimit(value: unknown): number | undefined {\n if (Array.isArray(value)) return parseLimit(value[0]);\n let n: number | undefined;\n if (typeof value === 'number' && Number.isFinite(value)) n = Math.trunc(value);\n else if (typeof value === 'string' && value.length > 0) {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) n = Math.trunc(parsed);\n }\n if (n === undefined) return undefined;\n if (n <= 0) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Query parameter \"limit\" must be a positive integer (got ${n})`,\n {\n details: { field: 'limit' },\n },\n );\n }\n return n;\n}\n","// `createGateway()`: the Fastify server, usable with injected fakes and without `main.ts`\n\nimport type { IncomingMessage } from 'node:http';\nimport Fastify, { type FastifyInstance } from 'fastify';\nimport type { GatewayConfig } from '../config';\nimport {\n type AuthorizationProvider,\n type BackendExecutor,\n type Clock,\n type CommerceResource,\n type ExecutionPipeline,\n type IdGenerator,\n type Logger,\n type PaymentProvider,\n type ProtocolAdapter,\n type ProtocolAdapterContext,\n type ReceiptStore,\n type ResourceRegistry,\n systemClock,\n} from '../core';\nimport {\n createExecutionPipeline,\n createResourceRegistry,\n createStoreEventSink,\n HttpBackendExecutor,\n} from '../core/execution';\nimport { buildAccessControlHook } from './access-control';\nimport {\n type AdapterRuntime,\n MOUNT_BODY_LIMIT_BYTES,\n startAndMountAdapters,\n stopAdapters,\n} from './adapters';\nimport { createDefaultIdGenerator } from './ids';\nimport { buildNotFoundHandler, createGatewayLogger, fastifyLoggerOptions } from './logger';\nimport { registerRoutes } from './routes';\n\nconst REQUEST_ID_HEADER = 'x-request-id';\n// The audit request id is always minted: a caller-chosen one could repeat\n// another flow's id and interleave its audit rows with that flow's. A\n// caller's X-Request-Id in this bounded form survives only as the\n// `clientRequestId` binding on the request's log lines.\nconst CLIENT_REQUEST_ID_PATTERN = /^[A-Za-z0-9._:-]{1,64}$/;\n\nfunction clientRequestIdOf(raw: IncomingMessage): string | undefined {\n const header = raw.headers[REQUEST_ID_HEADER];\n const value = Array.isArray(header) ? header[0] : header;\n return value !== undefined && CLIENT_REQUEST_ID_PATTERN.test(value) ? value : undefined;\n}\n\nexport interface GatewayOptions {\n readonly config: GatewayConfig;\n readonly store: ReceiptStore;\n readonly paymentProviders: readonly PaymentProvider[];\n /** Defaults to none; each resource declares the methods it requires */\n readonly authorizationProviders?: readonly AuthorizationProvider[];\n readonly protocolAdapters: readonly ProtocolAdapter[];\n readonly logger?: Logger;\n readonly clock?: Clock;\n readonly ids?: IdGenerator;\n /** Override for tests */\n readonly backend?: BackendExecutor;\n}\n\nexport interface GatewayInstance {\n readonly pipeline: ExecutionPipeline;\n readonly resources: ResourceRegistry;\n listen(): Promise<{ url: string }>;\n close(): Promise<void>;\n /** Fastify instance, for `.inject()` in tests */\n readonly server: FastifyInstance;\n}\n\n// Ingress labels a proof with `paymentMethods[0]`, while the pipeline selects\n// the first method backed by a provider. Move backed methods first, preserving\n// declared order within each group, so both paths select the same rail.\nfunction withProviderBackedMethodsFirst(\n resource: CommerceResource,\n providers: readonly PaymentProvider[],\n): CommerceResource {\n const backed = (method: string) => providers.some((provider) => provider.name === method);\n const ordered = [\n ...resource.paymentMethods.filter(backed),\n ...resource.paymentMethods.filter((method) => !backed(method)),\n ];\n return ordered.some((method, i) => method !== resource.paymentMethods[i])\n ? { ...resource, paymentMethods: ordered }\n : resource;\n}\n\nexport async function createGateway(options: GatewayOptions): Promise<GatewayInstance> {\n const clock = options.clock ?? systemClock;\n const ids = options.ids ?? createDefaultIdGenerator();\n const logger = options.logger ?? createGatewayLogger({ name: options.config.merchant.id }).core;\n const backend = options.backend ?? new HttpBackendExecutor({ logger });\n\n const authorizationProviders = options.authorizationProviders ?? [];\n\n const resources = createResourceRegistry(\n options.config.resources.map((resource) =>\n withProviderBackedMethodsFirst(resource, options.paymentProviders),\n ),\n );\n const events = createStoreEventSink({ store: options.store, logger });\n const pipeline = createExecutionPipeline({\n resources,\n paymentProviders: options.paymentProviders,\n authorizationProviders,\n store: options.store,\n backend,\n events,\n logger,\n clock,\n ids,\n });\n\n const server = Fastify({\n // Same cap as adapter mounts, which enforce it on the socket instead\n bodyLimit: MOUNT_BODY_LIMIT_BYTES,\n genReqId: () => ids.next('req'),\n childLoggerFactory: (parent, bindings, childOptions, rawReq) => {\n const clientRequestId = clientRequestIdOf(rawReq);\n return parent.child(\n clientRequestId !== undefined ? { ...bindings, clientRequestId } : bindings,\n childOptions,\n );\n },\n logger: fastifyLoggerOptions({ name: `${options.config.merchant.id}-http` }),\n });\n\n // Fastify's default 404 handler logs the raw URL, query string included\n server.setNotFoundHandler(buildNotFoundHandler());\n\n // Host check and CORS for every request. Closed by default: with no\n // allowedOrigins, every request carrying an Origin is refused. The admin\n // token gate is per route, in routes.ts.\n server.addHook(\n 'onRequest',\n buildAccessControlHook({\n publicBaseUrl: options.config.merchant.publicBaseUrl,\n allowedOrigins: options.config.server.allowedOrigins,\n }),\n );\n\n const adapterRuntimes: AdapterRuntime[] = [];\n\n registerRoutes({\n server,\n config: options.config,\n pipeline,\n resources,\n store: options.store,\n paymentProviders: options.paymentProviders,\n authorizationProviders,\n clock,\n adapterRuntimes,\n logger,\n });\n\n const context: ProtocolAdapterContext = {\n pipeline,\n resources,\n events,\n logger,\n clock,\n ids,\n publicBaseUrl: options.config.merchant.publicBaseUrl,\n };\n\n const started = await startAndMountAdapters({\n server,\n adapters: options.protocolAdapters,\n context,\n logger,\n clock,\n });\n adapterRuntimes.push(...started);\n\n await server.ready();\n\n return {\n pipeline,\n resources,\n async listen(): Promise<{ url: string }> {\n const url = await server.listen({\n port: options.config.server.port,\n host: options.config.server.host,\n });\n return { url };\n },\n async close(): Promise<void> {\n await stopAdapters(adapterRuntimes, logger);\n await server.close();\n },\n server,\n };\n}\n","/**\n * A2A pins, kept in one place so nothing infers one version from another.\n *\n * The specification revision and the negotiation version look alike but\n * differ: `1.0.1` names the document this adapter was written against, `1.0`\n * is what a client negotiates on the wire. Neither is this package's version\n * (`PACKAGE_VERSION`).\n */\n\n/** A2A specification revision this adapter targets */\nexport const A2A_SPEC_VERSION = '1.0.1';\n\n/** Protocol negotiation version carried on the wire */\nexport const A2A_PROTOCOL_VERSION = '1.0';\n\n/** The only transport binding this adapter serves */\nexport const A2A_PROTOCOL_BINDING = 'JSONRPC';\n\n/**\n * Fixed by the A2A specification: a client fetches the card from this exact\n * path, so it is not configurable. `src/config` reserves it against adapter\n * mounts for the same reason.\n */\nexport const A2A_AGENT_CARD_PATH = '/.well-known/agent-card.json';\n\n/** Mount serving the JSON-RPC endpoint, unless configuration says otherwise */\nexport const A2A_DEFAULT_MOUNT_PATH = '/a2a';\n\n/** Content type on both sides of every supported A2A exchange */\nexport const A2A_JSON_MEDIA_TYPE = 'application/json';\n\n/** Card identity when the operator names none. Matches the MCP adapter's default server name */\nexport const A2A_DEFAULT_AGENT_NAME = 'agent-commerce';\n\n/**\n * Version negotiation header. An absent or empty value means `0.3`, which\n * this adapter does not serve.\n */\nexport const A2A_VERSION_HEADER = 'a2a-version';\n\n/** The one JSON-RPC method this adapter serves, not the legacy `message/send` */\nexport const A2A_METHOD_SEND_MESSAGE = 'SendMessage';\n\n/**\n * Push notification configuration methods. The card declares no push\n * support, so these return `PushNotificationNotSupportedError`.\n */\nexport const A2A_PUSH_CONFIG_METHODS: readonly string[] = [\n 'CreateTaskPushNotificationConfig',\n 'GetTaskPushNotificationConfig',\n 'ListTaskPushNotificationConfigs',\n 'DeleteTaskPushNotificationConfig',\n];\n\n/**\n * A2A methods that exist and are not served here, kept apart from unknown\n * methods so a caller learns whether it hit a refused method or a typo. The\n * descriptor and the transport both read this one list.\n * `A2A_TASK_LOOKUP_METHODS` get a different error code on the wire.\n */\nexport const A2A_UNSUPPORTED_METHODS: readonly string[] = [\n 'SendStreamingMessage',\n 'GetTask',\n 'ListTasks',\n 'CancelTask',\n 'SubscribeToTask',\n ...A2A_PUSH_CONFIG_METHODS,\n 'GetExtendedAgentCard',\n];\n\n/**\n * Methods A2A gives an agent no capability flag to decline. No task can be\n * read back or canceled, so they answer `TaskNotFoundError`.\n */\nexport const A2A_TASK_LOOKUP_METHODS: readonly string[] = ['GetTask', 'CancelTask'];\n\n/**\n * Terminal states for completed and failed calls. An unpaid x402 extension\n * task instead waits in `TASK_STATE_INPUT_REQUIRED`. `GetTask` finds no task\n * in any state.\n */\nexport const A2A_TASK_STATE_COMPLETED = 'TASK_STATE_COMPLETED';\nexport const A2A_TASK_STATE_FAILED = 'TASK_STATE_FAILED';\n\n/** An unpaid x402 extension task waiting for a payment message */\nexport const A2A_TASK_STATE_INPUT_REQUIRED = 'TASK_STATE_INPUT_REQUIRED';\n\n/** Extension activation header, a comma-separated list of extension URIs */\nexport const A2A_EXTENSIONS_HEADER = 'a2a-extensions';\n","/**\n * JSON-RPC 2.0 framing for the A2A binding.\n *\n * Transport errors only: this file decides whether a request *is* a valid A2A\n * JSON-RPC call, never what the call means. Commerce outcomes are mapped\n * elsewhere, so a malformed frame and a refused purchase can never be\n * confused for one another.\n *\n * Every JSON-RPC-level failure is returned as a 200 with an `error` member,\n * per the JSON-RPC over HTTP convention A2A clients expect; HTTP status codes\n * are reserved for things that are not JSON-RPC at all (wrong verb, adapter\n * down).\n */\nimport { isRecord } from '../../core/is-record';\n\n/** JSON-RPC 2.0 reserved codes */\nexport const JSONRPC_PARSE_ERROR = -32700;\nexport const JSONRPC_INVALID_REQUEST = -32600;\nexport const JSONRPC_METHOD_NOT_FOUND = -32601;\nexport const JSONRPC_INVALID_PARAMS = -32602;\nexport const JSONRPC_INTERNAL_ERROR = -32603;\n\n/** A2A `TaskNotFoundError` for a task id this stateless adapter cannot find */\nexport const A2A_ERROR_TASK_NOT_FOUND = -32001;\n\n/** A2A `PushNotificationNotSupportedError` for push configuration methods */\nexport const A2A_ERROR_PUSH_NOTIFICATION_NOT_SUPPORTED = -32003;\n\n/**\n * A2A `UnsupportedOperationError` for a known operation or message feature\n * this adapter does not serve. Unknown methods use `METHOD_NOT_FOUND`.\n */\nexport const A2A_ERROR_UNSUPPORTED_OPERATION = -32004;\n\n/** A2A `ContentTypeNotSupportedError` for a non-JSON structured data part */\nexport const A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED = -32005;\n\n/** A2A `VersionNotSupportedError` when the requested major.minor is unsupported */\nexport const A2A_ERROR_VERSION_NOT_SUPPORTED = -32009;\n\n// Use the A2A error name without its `Error` suffix as the ErrorInfo reason.\n// Standard JSON-RPC codes carry no A2A error detail.\nconst A2A_ERROR_REASONS: ReadonlyMap<number, string> = new Map([\n [A2A_ERROR_TASK_NOT_FOUND, 'TASK_NOT_FOUND'],\n [A2A_ERROR_PUSH_NOTIFICATION_NOT_SUPPORTED, 'PUSH_NOTIFICATION_NOT_SUPPORTED'],\n [A2A_ERROR_UNSUPPORTED_OPERATION, 'UNSUPPORTED_OPERATION'],\n [A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED, 'CONTENT_TYPE_NOT_SUPPORTED'],\n [A2A_ERROR_VERSION_NOT_SUPPORTED, 'VERSION_NOT_SUPPORTED'],\n]);\n\n/** An id may legally be a string, a number or null; anything else is not one */\nexport type JsonRpcId = string | number | null;\n\nexport interface JsonRpcErrorBody {\n readonly code: number;\n readonly message: string;\n readonly data?: readonly Record<string, unknown>[];\n}\n\nexport interface JsonRpcRequest {\n readonly id: JsonRpcId;\n readonly method: string;\n readonly params: unknown;\n}\n\nexport type JsonRpcParseResult =\n | { readonly ok: true; readonly request: JsonRpcRequest }\n | { readonly ok: false; readonly id: JsonRpcId; readonly error: JsonRpcErrorBody };\n\n// Echoed back only when the request carried a usable one\nfunction readId(value: unknown): JsonRpcId {\n if (typeof value === 'string' || typeof value === 'number') return value;\n return null;\n}\n\nexport function jsonRpcResult(id: JsonRpcId, result: unknown): Record<string, unknown> {\n return { jsonrpc: '2.0', id, result };\n}\n\n/**\n * Add `google.rpc.ErrorInfo` to the detail array for A2A-specific errors.\n */\nexport function jsonRpcError(\n id: JsonRpcId,\n code: number,\n message: string,\n): Record<string, unknown> {\n const reason = A2A_ERROR_REASONS.get(code);\n const error: JsonRpcErrorBody = {\n code,\n message,\n ...(reason !== undefined\n ? {\n data: [\n {\n '@type': 'type.googleapis.com/google.rpc.ErrorInfo',\n reason,\n domain: 'a2a-protocol.org',\n },\n ],\n }\n : {}),\n };\n return { jsonrpc: '2.0', id, error };\n}\n\nexport function parseJsonRpcRequest(rawBody: string): JsonRpcParseResult {\n let payload: unknown;\n try {\n payload = JSON.parse(rawBody);\n } catch {\n // The parser's own message names offsets and input fragments; neither is\n // the caller's business, and echoing input is how bodies get reflected\n return { ok: false, id: null, error: { code: JSONRPC_PARSE_ERROR, message: 'Invalid JSON.' } };\n }\n\n if (Array.isArray(payload)) {\n return {\n ok: false,\n id: null,\n error: {\n code: JSONRPC_INVALID_REQUEST,\n message: 'Batch requests are not supported: send a single JSON-RPC request object.',\n },\n };\n }\n if (!isRecord(payload)) {\n return {\n ok: false,\n id: null,\n error: { code: JSONRPC_INVALID_REQUEST, message: 'Request must be a JSON-RPC 2.0 object.' },\n };\n }\n\n const id = readId(payload['id']);\n // Notifications have no reply. Reject them before they can run or charge.\n if (payload['id'] === undefined) {\n return {\n ok: false,\n id,\n error: {\n code: JSONRPC_INVALID_REQUEST,\n message: 'Request must include an \"id\"; notifications are unsupported.',\n },\n };\n }\n if (payload['jsonrpc'] !== '2.0') {\n return {\n ok: false,\n id,\n error: { code: JSONRPC_INVALID_REQUEST, message: 'Request must set \"jsonrpc\" to \"2.0\".' },\n };\n }\n const method = payload['method'];\n if (typeof method !== 'string' || method.length === 0) {\n return {\n ok: false,\n id,\n error: { code: JSONRPC_INVALID_REQUEST, message: 'Request must carry a \"method\" string.' },\n };\n }\n const params = payload['params'];\n if (params !== undefined && !isRecord(params)) {\n return {\n ok: false,\n id,\n error: {\n code: JSONRPC_INVALID_PARAMS,\n message: 'Request \"params\" must be an object.',\n },\n };\n }\n\n return { ok: true, request: { id, method, params: params ?? {} } };\n}\n","/**\n * The Agent Commerce invocation envelope for A2A.\n *\n * A2A has no `skillId` on a request: `SendMessage` carries a message, not a\n * tool call, so which canonical resource a caller wants has to be stated\n * somewhere the protocol leaves open. That place is a structured data part:\n *\n * ```json\n * { \"message\": { \"role\": \"ROLE_USER\", \"messageId\": \"msg-1\",\n * \"parts\": [{ \"data\": { \"resource\": \"market_report\",\n * \"input\": { \"symbol\": \"ETH\" } },\n * \"mediaType\": \"application/json\" }] } }\n * ```\n *\n * Payment and authorization proofs ride in the reserved `_payment` and\n * `_authorization` input fields, as over MCP; there is no A2A-specific\n * representation.\n *\n * The accepted shape is narrow on purpose. Everything richer that A2A allows\n * (text parts, files, multi-part messages, task continuation) is rejected:\n * `INPUT_INVALID` for a malformed envelope, `PROTOCOL_UNSUPPORTED` for a legal\n * A2A message this adapter does not serve. `details.a2aErrorCode` carries a\n * more specific JSON-RPC code when one applies. Taking the first of several\n * data parts, for example, could execute a paid call the buyer did not mean\n * to make.\n */\nimport { z } from 'zod';\nimport { CommerceError } from '../../core';\nimport { isRecord } from '../../core/is-record';\nimport { A2A_JSON_MEDIA_TYPE } from './constants';\nimport { A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED, A2A_ERROR_TASK_NOT_FOUND } from './jsonrpc';\n\n// The only role a request message may carry. A2A v1 spells roles this way\nconst A2A_USER_ROLE = 'ROLE_USER';\n\n/** The one message shape that calls a skill, as refusals and the Agent Card name it */\nexport const A2A_CALL_SHAPE = 'one data part {\"resource\": \"<skill id>\", \"input\": {...}}';\n\n/**\n * The refusal for a role other than `ROLE_USER`, or undefined. An A2A 0.x\n * client sends `user`, so this is what turns its messages away.\n */\nexport function userRoleProblem(role: unknown): string | undefined {\n return role === A2A_USER_ROLE\n ? undefined\n : `Unsupported message role \"${String(role)}\": only ${A2A_USER_ROLE} is accepted.`;\n}\n\n/** What a supported envelope reduces to. Nothing protocol-shaped survives */\nexport interface A2aInvocation {\n readonly resourceId: string;\n readonly input: Record<string, unknown>;\n /** Client-assigned message id */\n readonly messageId: string;\n}\n\n/**\n * Shape only; every semantic rule is checked below, where the failure can name\n * itself. Parts stay untyped records: zod would collapse a file part and a\n * malformed one into the same union failure.\n */\nconst UnknownRecord = z.record(z.string(), z.unknown());\n\nconst MessageSchema = z.object({\n role: z.string(),\n messageId: z.string().optional(),\n parts: z.array(UnknownRecord),\n taskId: z.string().optional(),\n contextId: z.string().optional(),\n referenceTaskIds: z.array(z.string()).optional(),\n});\n\nconst ParamsSchema = z.object({\n message: MessageSchema,\n taskId: z.string().optional(),\n contextId: z.string().optional(),\n});\n\nfunction invalid(message: string): CommerceError {\n return new CommerceError('INPUT_INVALID', message);\n}\n\nfunction unsupported(message: string, a2aErrorCode?: number): CommerceError {\n return new CommerceError(\n 'PROTOCOL_UNSUPPORTED',\n message,\n a2aErrorCode !== undefined ? { details: { a2aErrorCode } } : {},\n );\n}\n\n/**\n * Continuation is refused rather than ignored: a caller resuming a task would\n * otherwise get a fresh, independently billed execution back and no signal\n * that their task id meant nothing here. Since this adapter stores no tasks,\n * it returns `TaskNotFoundError` for every supplied task id.\n */\nfunction assertNoContinuation(params: z.infer<typeof ParamsSchema>): void {\n const message = params.message;\n if (params.taskId !== undefined || message.taskId !== undefined) {\n throw unsupported(\n 'Task not found: tasks are not persisted, so send a request with no taskId.',\n A2A_ERROR_TASK_NOT_FOUND,\n );\n }\n if (params.contextId !== undefined || message.contextId !== undefined) {\n throw unsupported(\n 'Multi-turn conversational continuation is not supported: send a request with no contextId.',\n );\n }\n if (message.referenceTaskIds !== undefined && message.referenceTaskIds.length > 0) {\n throw unsupported('Referencing previous tasks is not supported.');\n }\n}\n\n/**\n * Names the part kind so a caller learns which of theirs is the problem.\n *\n * A2A v1 gives `Part` a content oneof (`text`, `data`, `raw` for inline bytes,\n * or `url`) with `filename` and `mediaType` beside it, where v0.3 used a\n * nested `file` object. Both spellings are refused as unsupported, so a\n * v0.3-shaped client is not told its envelope is malformed.\n */\nfunction assertSupportedPart(part: Record<string, unknown>): void {\n if ('file' in part || 'raw' in part || 'url' in part) {\n throw unsupported(\n `File and URL parts are not supported: send ${A2A_CALL_SHAPE}.`,\n A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED,\n );\n }\n if ('text' in part) {\n throw unsupported(\n `Text parts are not supported: send ${A2A_CALL_SHAPE}.`,\n A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED,\n );\n }\n if (!('data' in part)) {\n throw invalid('Message part carries no \"data\": send a structured data part.');\n }\n const mediaType = part['mediaType'];\n if (mediaType !== undefined && mediaType !== A2A_JSON_MEDIA_TYPE) {\n throw unsupported(\n `Media type \"${String(mediaType)}\" is not supported: parts must be ${A2A_JSON_MEDIA_TYPE}.`,\n A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED,\n );\n }\n}\n\n/**\n * Turns `SendMessage` params into a resource id and an input object, or throws\n * a `CommerceError`. Pure: it resolves no resource and touches no payment.\n */\nexport function parseInvocation(rawParams: unknown): A2aInvocation {\n const parsed = ParamsSchema.safeParse(rawParams);\n if (!parsed.success) {\n throw invalid(\n 'Request must carry a \"message\" with a \"role\" and a \"parts\" array of structured data parts.',\n );\n }\n const params = parsed.data;\n const message = params.message;\n // A2A requires a message id. This adapter also rejects an empty one.\n if (message.messageId === undefined || message.messageId.length === 0) {\n throw invalid('Message must carry a non-empty \"messageId\".');\n }\n const messageId = message.messageId;\n\n assertNoContinuation(params);\n\n const roleProblem = userRoleProblem(message.role);\n if (roleProblem !== undefined) throw invalid(roleProblem);\n if (message.parts.length === 0) {\n throw invalid('Message carries no parts: send exactly one structured data part.');\n }\n if (message.parts.length > 1) {\n throw unsupported(\n `Multi-part messages are not supported: send exactly one structured data part (received ${message.parts.length}).`,\n );\n }\n\n const part = message.parts[0];\n if (part === undefined) throw invalid('Message carries no parts.');\n assertSupportedPart(part);\n\n const data = part['data'];\n if (!isRecord(data)) {\n throw invalid('Message part \"data\" must be a JSON object.');\n }\n\n const resourceId = data['resource'];\n if (typeof resourceId !== 'string') {\n throw invalid('Message part data must carry a \"resource\" string naming a canonical resource.');\n }\n if (resourceId.length === 0) {\n throw invalid('Message part data \"resource\" must not be empty.');\n }\n\n const rawInput = data['input'];\n // Absent means \"no arguments\", which is a real case for a zero-input\n // resource. Present-but-not-an-object is a mistake, never an empty call.\n if (rawInput !== undefined && !isRecord(rawInput)) {\n throw invalid('Message part data \"input\" must be a JSON object.');\n }\n\n return { resourceId, input: rawInput ?? {}, messageId };\n}\n","/**\n * x402 payment over A2A. The x402 v2 transport puts payment documents in\n * message metadata and resumes an input-required task with a payment message.\n * This adapter uses A2A 1.0 states, roles, parts and extension headers.\n * Clients that do not activate the extension use `_payment` on a new task.\n */\nimport {\n AUTHORIZATION_INPUT_FIELD,\n type AuthorizationSubmission,\n type Clock,\n type CommerceError,\n type PaymentResult,\n parseAuthorizationSubmission,\n} from '../../core';\nimport { isRecord } from '../../core/is-record';\nimport {\n settlementFailure,\n settlementResponse,\n settlementResponseFromDetails,\n x402ErrorCode,\n} from '../../payments/x402/transport';\n\n/** The URI the x402 A2A transport declares for the extension */\nexport const A2A_X402_EXTENSION_URI = 'https://github.com/google-a2a/a2a-x402/v0.1';\n\n/** The x402 protocol version of every document the extension carries */\nexport const A2A_X402_PROTOCOL_VERSION = 2;\n\nexport const X402_PAYMENT_STATUS_KEY = 'x402.payment.status';\nexport const X402_PAYMENT_REQUIRED_KEY = 'x402.payment.required';\nexport const X402_PAYMENT_PAYLOAD_KEY = 'x402.payment.payload';\nexport const X402_PAYMENT_RECEIPTS_KEY = 'x402.payment.receipts';\nexport const X402_PAYMENT_ERROR_KEY = 'x402.payment.error';\n\n// How long an unpaid task waits when the requirement names no expiry, and the\n// longest it waits regardless\nconst DEFAULT_PENDING_TTL_MS = 10 * 60 * 1000;\nconst MAX_PENDING_TTL_MS = 60 * 60 * 1000;\n\n// Bound memory used by unpaid tasks from unauthenticated callers. Each task\n// holds one request's input. A full store refuses new purchases rather than\n// evicting a live one, whose buyer may already have signed.\nconst MAX_PENDING_PAYMENTS = 256;\n\n/** `A2A-Extensions` is a comma-separated URI list, possibly repeated */\nexport function requestsX402Extension(header: string | readonly string[] | undefined): boolean {\n const values = typeof header === 'string' ? [header] : (header ?? []);\n return values.some((value) =>\n value.split(',').some((uri) => uri.trim() === A2A_X402_EXTENSION_URI),\n );\n}\n\n/** A purchase waiting for its payment, held between the two messages */\nexport interface PendingPayment {\n readonly contextId: string;\n readonly resourceId: string;\n /** Validated by the pipeline again when the payment arrives */\n readonly input: Record<string, unknown>;\n readonly authorization?: AuthorizationSubmission;\n /** Network of the requirement, for a failure receipt whose error names none */\n readonly network?: string;\n readonly expiresAtMs: number;\n}\n\n/**\n * Unpaid tasks, in memory and per process. A restart, or a payment routed to\n * another instance, loses the task: the client gets `TaskNotFoundError` before\n * anything is verified or settled, and starts over.\n */\nexport function createPendingPayments(clock: Clock, maxEntries = MAX_PENDING_PAYMENTS) {\n const tasks = new Map<string, PendingPayment>();\n const now = (): number => clock.now().getTime();\n\n function purgeExpired(): void {\n const at = now();\n for (const [taskId, pending] of tasks) {\n if (pending.expiresAtMs <= at) tasks.delete(taskId);\n }\n }\n\n return {\n /** Holds a purchase until `expiresAt`; returns false, holding nothing, when full */\n put(taskId: string, pending: Omit<PendingPayment, 'expiresAtMs'>, expiresAt?: string): boolean {\n purgeExpired();\n if (tasks.size >= maxEntries) return false;\n const requested = expiresAt !== undefined ? Date.parse(expiresAt) : Number.NaN;\n const ttl = Number.isFinite(requested) ? requested - now() : DEFAULT_PENDING_TTL_MS;\n const expiresAtMs = now() + Math.min(Math.max(ttl, 0), MAX_PENDING_TTL_MS);\n tasks.set(taskId, { ...pending, expiresAtMs });\n return true;\n },\n\n get(taskId: string): PendingPayment | undefined {\n const pending = tasks.get(taskId);\n if (pending === undefined) return undefined;\n if (pending.expiresAtMs <= now()) {\n tasks.delete(taskId);\n return undefined;\n }\n return pending;\n },\n\n delete(taskId: string): void {\n tasks.delete(taskId);\n },\n\n size(): number {\n return tasks.size;\n },\n\n clear(): void {\n tasks.clear();\n },\n };\n}\n\nexport type PendingPayments = ReturnType<typeof createPendingPayments>;\n\n/** What a follow-up message on a pending task asks for */\nexport type PaymentSubmissionMessage =\n | { readonly kind: 'submitted'; readonly payload: Record<string, unknown> }\n | { readonly kind: 'rejected' };\n\n/** Reads the payment status and payload from a message's metadata */\nexport function readPaymentSubmission(message: unknown): PaymentSubmissionMessage | undefined {\n const metadata = isRecord(message) ? message['metadata'] : undefined;\n if (!isRecord(metadata)) return undefined;\n const status = metadata[X402_PAYMENT_STATUS_KEY];\n if (status === 'payment-rejected') return { kind: 'rejected' };\n const payload = metadata[X402_PAYMENT_PAYLOAD_KEY];\n if (status === 'payment-submitted' && isRecord(payload)) return { kind: 'submitted', payload };\n return undefined;\n}\n\n/**\n * Read `input._authorization` from a payment message. Ignore other input;\n * the task already holds the purchase. Malformed mandates raise\n * `AUTHORIZATION_INVALID`.\n */\nexport function readFollowUpAuthorization(message: unknown): AuthorizationSubmission | undefined {\n const parts = isRecord(message) ? message['parts'] : undefined;\n if (!Array.isArray(parts)) return undefined;\n for (const part of parts) {\n const data: unknown = isRecord(part) ? part['data'] : undefined;\n const input = isRecord(data) ? data['input'] : undefined;\n if (isRecord(input) && input[AUTHORIZATION_INPUT_FIELD] !== undefined) {\n return parseAuthorizationSubmission(input[AUTHORIZATION_INPUT_FIELD]);\n }\n }\n return undefined;\n}\n\nexport function paymentRequiredMetadata(\n envelope: Record<string, unknown>,\n): Record<string, unknown> {\n return {\n [X402_PAYMENT_STATUS_KEY]: 'payment-required',\n [X402_PAYMENT_REQUIRED_KEY]: envelope,\n };\n}\n\nexport function paymentCompletedMetadata(payment: PaymentResult): Record<string, unknown> {\n return {\n [X402_PAYMENT_STATUS_KEY]: 'payment-completed',\n [X402_PAYMENT_RECEIPTS_KEY]: [settlementResponse(payment)],\n };\n}\n\n/**\n * A failure after a payment submission. A backend failure after settlement\n * still reports the payment as completed, with its receipt: the money moved.\n * `network` is the requirement's.\n */\nexport function paymentFailureMetadata(\n error: CommerceError,\n network?: string,\n): Record<string, unknown> {\n const settled = settlementResponseFromDetails(error.details);\n if (settled !== undefined && settled['success'] === true) {\n return {\n [X402_PAYMENT_STATUS_KEY]: 'payment-completed',\n [X402_PAYMENT_RECEIPTS_KEY]: [settled],\n };\n }\n // A backend failure before settlement keeps its own commerce error code.\n const code = error.code.startsWith('PAYMENT_')\n ? x402ErrorCode(error.code, error.details?.['reason'], error.details?.['network'])\n : error.code.toLowerCase();\n const failure = settlementFailure(error.details);\n const receipt =\n failure['network'] === '' && network !== undefined ? { ...failure, network } : failure;\n return {\n [X402_PAYMENT_STATUS_KEY]: 'payment-failed',\n [X402_PAYMENT_ERROR_KEY]: code,\n // Keep the failure reason, including `settlement_pending` when a hash is known\n [X402_PAYMENT_RECEIPTS_KEY]: [\n error.details?.['settlementUncertain'] === true ? receipt : { ...receipt, errorReason: code },\n ],\n };\n}\n\nexport function paymentRejectedMetadata(): Record<string, unknown> {\n return { [X402_PAYMENT_STATUS_KEY]: 'payment-rejected' };\n}\n","/**\n * Builds the A2A v1 Agent Card from canonical resources.\n *\n * One skill per resource exposed via `expose: [a2a]`, skill id = resource id.\n * A2A has no field for a skill's input schema, so the card shows the call\n * shape through fields it does define: a sentence in the agent description,\n * which also says where the schemas are published, and one example per skill.\n */\nimport { AUTHORIZATION_INPUT_FIELD, type CommerceResource, PAYMENT_INPUT_FIELD } from '../../core';\nimport { isRecord } from '../../core/is-record';\nimport { joinUrl } from '../http';\nimport { A2A_JSON_MEDIA_TYPE, A2A_PROTOCOL_BINDING, A2A_PROTOCOL_VERSION } from './constants';\nimport { A2A_CALL_SHAPE } from './message-mapping';\nimport type { A2aAgentCard, A2aAgentSkill } from './types';\nimport { A2A_X402_EXTENSION_URI, A2A_X402_PROTOCOL_VERSION } from './x402-extension';\n\n// The gateway route that lists every resource with its input schema\nconst RESOURCES_PATH = '/api/resources';\n\nexport interface AgentCardOptions {\n readonly name: string;\n readonly description: string;\n /** Version of this gateway build, not of the protocol */\n readonly version: string;\n /** Externally reachable gateway base URL, from configuration */\n readonly publicBaseUrl: string;\n /** Gateway path the JSON-RPC endpoint is mounted at */\n readonly mountPath: string;\n readonly resources: readonly CommerceResource[];\n}\n\n/**\n * Free/paid is on the card because a caller choosing between skills should not\n * have to attempt a call to discover one costs money. The price itself is in\n * the description, where a human-readable amount belongs.\n */\nfunction skillTags(resource: CommerceResource): string[] {\n return ['agent-commerce', resource.pricing.type === 'free' ? 'free' : 'paid'];\n}\n\nfunction skillDescription(resource: CommerceResource): string {\n const base = resource.description ?? resource.name;\n if (resource.pricing.type === 'fixed') {\n return `${base} Costs ${resource.pricing.amount} ${resource.pricing.currency} per call.`;\n }\n if (resource.pricing.type === 'dynamic') {\n return `${base} Requires payment (amount determined at request time).`;\n }\n return base;\n}\n\n/**\n * Build a sample from schema examples, defaults, enum values or the declared\n * type. Objects include required properties only. Other constraints may need\n * different input.\n */\nfunction exampleValue(schema: unknown, name: string): unknown {\n if (!isRecord(schema)) return `<${name}>`;\n const examples = schema['examples'];\n if (Array.isArray(examples) && examples.length > 0) return examples[0];\n if (schema['default'] !== undefined) return schema['default'];\n const allowed = schema['enum'];\n if (Array.isArray(allowed) && allowed.length > 0) return allowed[0];\n const declared = schema['type'];\n const type: unknown = Array.isArray(declared) ? declared[0] : declared;\n switch (type) {\n case 'object':\n return exampleObject(schema);\n case 'array':\n return schema['items'] !== undefined ? [exampleValue(schema['items'], name)] : [];\n case 'number':\n case 'integer':\n return 0;\n case 'boolean':\n return false;\n case 'null':\n return null;\n default:\n return `<${name}>`;\n }\n}\n\nfunction exampleObject(schema: Record<string, unknown>): Record<string, unknown> {\n const properties = isRecord(schema['properties']) ? schema['properties'] : {};\n const required = Array.isArray(schema['required']) ? schema['required'] : [];\n const example: Record<string, unknown> = {};\n for (const key of required) {\n // The reserved fields carry proofs, which no example can hold\n if (typeof key !== 'string' || key === PAYMENT_INPUT_FIELD || key === AUTHORIZATION_INPUT_FIELD)\n continue;\n example[key] = exampleValue(properties[key], key);\n }\n return example;\n}\n\n/** The `data` value of a data part that calls the skill, as JSON */\nfunction skillExample(resource: CommerceResource): string {\n return JSON.stringify({\n resource: resource.id,\n input: exampleObject(resource.inputSchema ?? {}),\n });\n}\n\nfunction buildAgentSkill(resource: CommerceResource): A2aAgentSkill {\n return {\n id: resource.id,\n name: resource.name,\n description: skillDescription(resource),\n tags: skillTags(resource),\n examples: [skillExample(resource)],\n inputModes: [A2A_JSON_MEDIA_TYPE],\n outputModes: [A2A_JSON_MEDIA_TYPE],\n };\n}\n\nfunction agentDescription(options: AgentCardOptions): string {\n const call = `Call a skill by sending ${A2A_CALL_SHAPE} with media type ${A2A_JSON_MEDIA_TYPE}. Each skill has an example; input schemas are at ${joinUrl(options.publicBaseUrl, RESOURCES_PATH)}.`;\n const pay = options.resources.some((resource) => resource.pricing.type !== 'free')\n ? ` For paid skills, retry with a payment proof in \"input.${PAYMENT_INPUT_FIELD}\".`\n : '';\n return `${options.description} ${call}${pay}`;\n}\n\nexport function buildAgentCard(options: AgentCardOptions): A2aAgentCard {\n return {\n name: options.name,\n description: agentDescription(options),\n version: options.version,\n supportedInterfaces: [\n {\n url: joinUrl(options.publicBaseUrl, options.mountPath),\n protocolBinding: A2A_PROTOCOL_BINDING,\n protocolVersion: A2A_PROTOCOL_VERSION,\n },\n ],\n capabilities: {\n streaming: false,\n pushNotifications: false,\n extendedAgentCard: false,\n // Only a skill whose rail is x402 can be paid through the extension.\n // Not required: `_payment` keeps working for clients without it.\n ...(options.resources.some((resource) => resource.paymentMethods[0] === 'x402')\n ? {\n extensions: [\n {\n uri: A2A_X402_EXTENSION_URI,\n description: 'x402 payments: input-required tasks carrying x402 v2 documents.',\n required: false,\n // Lets a client holding an x402 v1 library tell before it pays\n params: { x402Version: A2A_X402_PROTOCOL_VERSION },\n },\n ],\n }\n : {}),\n },\n defaultInputModes: [A2A_JSON_MEDIA_TYPE],\n defaultOutputModes: [A2A_JSON_MEDIA_TYPE],\n skills: options.resources.map(buildAgentSkill),\n };\n}\n","/**\n * Adapter self-description.\n *\n * `supportedSpec` is the A2A specification revision (`1.0.1`), never the\n * negotiation version (`1.0`) and never this package's version. Status is\n * `experimental` while the adapter lacks the features in the unsupported list\n * below; an entry leaves that list only when its feature is implemented.\n */\nimport type { AdapterDescriptor } from '../../core';\nimport { A2A_SPEC_VERSION, A2A_UNSUPPORTED_METHODS } from './constants';\n\n// What this adapter implements\nconst A2A_CAPABILITIES: readonly string[] = [\n 'agent-card',\n 'jsonrpc',\n 'SendMessage',\n // The x402 A2A transport, opt-in per request\n 'x402-extension',\n];\n\n/**\n * Major A2A features this adapter does not implement, served on\n * `/.well-known/agent-commerce` and printed by `doctor`, so no client assumes\n * full protocol support\n */\nexport const A2A_UNSUPPORTED: readonly string[] = [\n // Methods, as the protocol names them; the transport refuses the same list\n ...A2A_UNSUPPORTED_METHODS,\n // Transports other than the one binding served\n 'HTTP+JSON/REST binding',\n 'gRPC binding',\n // Behaviors\n 'SSE',\n 'long-running task persistence',\n 'task resumption other than an x402 extension payment',\n 'push notifications',\n 'multi-turn conversational continuation',\n 'authenticated extended agent cards',\n 'A2A authentication schemes',\n 'artifact types beyond Agent Commerce outcome data',\n // Pending x402 payments live in process memory\n 'x402 extension payments across gateway restarts or instances',\n];\n\nexport function buildDescriptor(implementationVersion: string): AdapterDescriptor {\n return {\n name: 'a2a',\n kind: 'protocol',\n implementationVersion,\n supportedSpec: A2A_SPEC_VERSION,\n capabilities: A2A_CAPABILITIES,\n status: 'experimental',\n unsupported: A2A_UNSUPPORTED,\n };\n}\n","/**\n * Execution outcomes as terminal A2A Tasks.\n *\n * A2A models an execution's output as a Task carrying Artifacts, so a\n * completed purchase comes back as one, not as a plain Message, which models\n * conversation.\n *\n * A commerce outcome is never a JSON-RPC error. Payment required, an unknown\n * resource, input the resource schema rejects and a broken backend are all\n * answers, returned as a terminal Task in the JSON-RPC `result`. Only a\n * malformed or unsupported A2A request gets a JSON-RPC error, so a client can\n * tell a refused purchase from a broken gateway.\n *\n * Every artifact payload is an existing canonical envelope, verbatim: there is\n * no A2A-specific delivery, payment-required or error schema.\n */\nimport {\n type CommerceError,\n DELIVERY_SUMMARY_META_KEY,\n type DeliveredOutcome,\n type PaymentRequiredOutcome,\n toDeliverySummary,\n toErrorEnvelope,\n toPaymentRequiredEnvelope,\n} from '../../core';\nimport { isRecord } from '../../core/is-record';\nimport {\n A2A_JSON_MEDIA_TYPE,\n A2A_TASK_STATE_COMPLETED,\n A2A_TASK_STATE_FAILED,\n A2A_TASK_STATE_INPUT_REQUIRED,\n} from './constants';\nimport type { A2aArtifact, A2aTask } from './types';\nimport { A2A_X402_EXTENSION_URI } from './x402-extension';\n\nexport interface TaskIdentity {\n /** Gateway request id, reused so a task correlates with receipts and events */\n readonly taskId: string;\n /** Fresh for each purchase; a pending x402 payment keeps this context */\n readonly contextId: string;\n readonly artifactId: string;\n /** Id of the agent message on the task status */\n readonly statusMessageId: string;\n readonly timestamp: string;\n}\n\n/**\n * A data part's payload must be a JSON object, but a merchant backend may\n * return a string, a number or an array. Those are wrapped under `value`, one\n * predictable rule a caller can code against.\n */\nfunction dataPayload(body: unknown): Record<string, unknown> {\n return isRecord(body) ? body : { value: body ?? null };\n}\n\nfunction task(\n identity: TaskIdentity,\n state: string,\n artifact: Omit<A2aArtifact, 'artifactId'>,\n): A2aTask {\n return {\n id: identity.taskId,\n contextId: identity.contextId,\n status: { state, timestamp: identity.timestamp },\n artifacts: [{ artifactId: identity.artifactId, ...artifact }],\n };\n}\n\nexport function completedTask(outcome: DeliveredOutcome, identity: TaskIdentity): A2aTask {\n return task(identity, A2A_TASK_STATE_COMPLETED, {\n name: outcome.resourceId,\n parts: [{ data: dataPayload(outcome.body), mediaType: A2A_JSON_MEDIA_TYPE }],\n // Same meta key MCP attaches its summary under, so a buyer reads the\n // record of their own purchase the same way on either protocol\n metadata: { [DELIVERY_SUMMARY_META_KEY]: { ...toDeliverySummary(outcome) } },\n });\n}\n\n/**\n * Without the x402 extension, payment required ends the task. The client\n * starts a new one with `_payment`. With the extension, `inputRequired` keeps\n * this task open for a payment message.\n */\nexport function paymentRequiredTask(\n outcome: PaymentRequiredOutcome,\n identity: TaskIdentity,\n): A2aTask {\n const envelope = toPaymentRequiredEnvelope(outcome);\n return withStatusMessage(\n task(identity, A2A_TASK_STATE_FAILED, {\n name: outcome.resourceId,\n parts: [{ data: { ...envelope }, mediaType: A2A_JSON_MEDIA_TYPE }],\n }),\n envelope.message,\n identity.statusMessageId,\n );\n}\n\n/** The same task waiting for payment, with the extension's metadata on its status message */\nexport function inputRequired(\n base: A2aTask,\n metadata: Record<string, unknown>,\n messageId: string,\n): A2aTask {\n return withStatusMessage(\n { ...base, status: { ...base.status, state: A2A_TASK_STATE_INPUT_REQUIRED } },\n 'Payment is required. Send the x402 payment payload on this task.',\n messageId,\n metadata,\n );\n}\n\n/** Set the agent status message; metadata marks x402 extension use */\nexport function withStatusMessage(\n base: A2aTask,\n text: string,\n messageId: string,\n metadata?: Record<string, unknown>,\n): A2aTask {\n return {\n ...base,\n status: {\n ...base.status,\n message: {\n role: 'ROLE_AGENT',\n messageId,\n contextId: base.contextId,\n taskId: base.id,\n parts: [{ text }],\n ...(metadata !== undefined ? { metadata, extensions: [A2A_X402_EXTENSION_URI] } : {}),\n },\n },\n };\n}\n\n/** Put the error envelope in the artifact and its message in task status */\nexport function failedTask(error: CommerceError, identity: TaskIdentity): A2aTask {\n const envelope = toErrorEnvelope(error);\n return withStatusMessage(\n task(identity, A2A_TASK_STATE_FAILED, {\n parts: [{ data: { ...envelope }, mediaType: A2A_JSON_MEDIA_TYPE }],\n }),\n envelope.message,\n identity.statusMessageId,\n );\n}\n","// Completing a purchase that waits for an x402 extension payment, from the follow-up message that pays or declines it\nimport type { CanonicalRequest, ProtocolAdapterContext } from '../../core';\nimport { CommerceError, toCommerceError } from '../../core';\nimport { toLogInfo } from '../../core/errors';\nimport { isRecord } from '../../core/is-record';\nimport { A2A_TASK_STATE_FAILED } from './constants';\nimport { JSONRPC_INVALID_PARAMS, type JsonRpcId, jsonRpcError, jsonRpcResult } from './jsonrpc';\nimport { userRoleProblem } from './message-mapping';\nimport { completedTask, failedTask, type TaskIdentity, withStatusMessage } from './task-mapping';\nimport type { A2aTask } from './types';\nimport {\n type PendingPayment,\n type PendingPayments,\n paymentCompletedMetadata,\n paymentFailureMetadata,\n paymentRejectedMetadata,\n readFollowUpAuthorization,\n readPaymentSubmission,\n X402_PAYMENT_PAYLOAD_KEY,\n X402_PAYMENT_STATUS_KEY,\n} from './x402-extension';\n\n/** A2A's JSON-RPC result wraps the terminal task */\nexport function taskResult(id: JsonRpcId, task: A2aTask): Record<string, unknown> {\n return jsonRpcResult(id, { task });\n}\n\n/**\n * A message on a task waiting for an x402 extension payment, recognized by\n * its `taskId` whether or not the header activated the extension again. Any\n * other task id falls through to `parseInvocation`, which answers TaskNotFoundError.\n */\nexport async function resumePayment(\n context: ProtocolAdapterContext | undefined,\n pendingPayments: PendingPayments | undefined,\n id: JsonRpcId,\n params: unknown,\n): Promise<Record<string, unknown> | undefined> {\n const message = isRecord(params) ? params['message'] : undefined;\n const taskId = isRecord(message) ? message['taskId'] : undefined;\n if (context === undefined || typeof taskId !== 'string') return undefined;\n const pending = pendingPayments?.get(taskId);\n if (pending === undefined) return undefined;\n\n const messageId = isRecord(message) ? message['messageId'] : undefined;\n if (typeof messageId !== 'string' || messageId.length === 0) {\n return jsonRpcError(id, JSONRPC_INVALID_PARAMS, 'Message must carry a non-empty \"messageId\".');\n }\n // Apply the same role check as a new purchase\n const roleProblem = userRoleProblem(isRecord(message) ? message['role'] : undefined);\n if (roleProblem !== undefined) return jsonRpcError(id, JSONRPC_INVALID_PARAMS, roleProblem);\n // Reject a mismatched context without consuming the pending task.\n const contextId = isRecord(message) ? message['contextId'] : undefined;\n if (contextId !== undefined && contextId !== pending.contextId) {\n return jsonRpcError(id, JSONRPC_INVALID_PARAMS, 'Message \"contextId\" does not match the task.');\n }\n const submission = readPaymentSubmission(message);\n if (submission === undefined) {\n // The task stays pending, so a corrected message can still pay it\n return jsonRpcError(\n id,\n JSONRPC_INVALID_PARAMS,\n `For a pending task, set \"${X402_PAYMENT_STATUS_KEY}\" to \"payment-submitted\" and provide a \"${X402_PAYMENT_PAYLOAD_KEY}\" object, or set it to \"payment-rejected\".`,\n );\n }\n // A mandate stored with the purchase wins. One sent here is verified\n // against the stored resource and input, like the payment.\n let authorization = pending.authorization;\n if (authorization === undefined && submission.kind === 'submitted') {\n try {\n authorization = readFollowUpAuthorization(message);\n } catch (err) {\n return jsonRpcError(id, JSONRPC_INVALID_PARAMS, toCommerceError(err).message);\n }\n }\n // Taken before execution, so a second payment message for the task finds\n // nothing and cannot run the purchase twice\n pendingPayments?.delete(taskId);\n const statusMessageId = context.ids.next('a2a-msg');\n const identity: TaskIdentity = {\n taskId,\n contextId: pending.contextId,\n artifactId: context.ids.next('a2a-artifact'),\n statusMessageId,\n timestamp: context.clock.nowIso(),\n };\n\n if (submission.kind === 'rejected') {\n const declined: A2aTask = {\n id: taskId,\n contextId: pending.contextId,\n status: { state: A2A_TASK_STATE_FAILED, timestamp: identity.timestamp },\n artifacts: [],\n };\n return taskResult(\n id,\n withStatusMessage(\n declined,\n 'Payment was declined.',\n statusMessageId,\n paymentRejectedMetadata(),\n ),\n );\n }\n return taskResult(\n id,\n await payPending(\n context,\n { ...pending, ...(authorization !== undefined ? { authorization } : {}) },\n submission.payload,\n identity,\n ),\n );\n}\n\n// The pending purchase, now with the x402 `PaymentPayload` as its proof\nasync function payPending(\n context: ProtocolAdapterContext,\n pending: PendingPayment,\n payload: Record<string, unknown>,\n identity: TaskIdentity,\n): Promise<A2aTask> {\n const requestId = context.ids.next('a2a');\n const request: CanonicalRequest = {\n requestId,\n resourceId: pending.resourceId,\n input: pending.input,\n protocol: 'a2a',\n receivedAt: context.clock.nowIso(),\n // The same encoding as the HTTP header's base64 PaymentPayload JSON\n payment: {\n method: 'x402',\n payload: Buffer.from(JSON.stringify(payload), 'utf8').toString('base64'),\n },\n ...(pending.authorization !== undefined ? { authorization: pending.authorization } : {}),\n };\n let error: CommerceError;\n try {\n const outcome = await context.pipeline.execute(request);\n if (outcome.kind === 'delivered' && outcome.payment !== undefined) {\n return withStatusMessage(\n completedTask(outcome, identity),\n 'Payment settled.',\n identity.statusMessageId,\n paymentCompletedMetadata(outcome.payment),\n );\n }\n // A proof was sent, so neither a free delivery nor a new challenge is a\n // payment this task can report\n error = new CommerceError('PAYMENT_INVALID', 'The payment was not accepted.', { requestId });\n } catch (err) {\n error = toCommerceError(err);\n context.logger.warn(\n { resourceId: pending.resourceId, requestId, err: toLogInfo(error) },\n 'a2a adapter: x402 extension payment failed',\n );\n }\n const metadata = paymentFailureMetadata(error, pending.network);\n let text = 'Payment failed.';\n if (metadata[X402_PAYMENT_STATUS_KEY] === 'payment-completed') {\n text = 'Payment settled, but the resource could not be delivered.';\n } else if (!error.code.startsWith('PAYMENT_')) {\n text = 'The resource could not be delivered.';\n }\n return withStatusMessage(failedTask(error, identity), text, identity.statusMessageId, metadata);\n}\n","/**\n * A2A (Agent2Agent) protocol adapter, experimental.\n *\n * Serves two paths: the configured mount (`/a2a`), where the JSON-RPC endpoint\n * lives, and the specification-fixed `/.well-known/agent-card.json`, declared\n * through `additionalHttpRoutes` so the gateway needs no A2A-specific routing.\n *\n * Only the synchronous `SendMessage` path is served; every other A2A method\n * is listed in `descriptor.unsupported`. This adapter maps reserved payment\n * fields but leaves verification, settlement and merchant calls to the pipeline.\n */\nimport { createHash } from 'node:crypto';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport {\n type AdapterDescriptor,\n type AdapterHealth,\n type AdapterHttpRoute,\n type CanonicalRequest,\n CommerceError,\n type CommerceResource,\n type ExecutionOutcome,\n extractReservedInputFields,\n type HttpProtocolAdapter,\n type ProtocolAdapterContext,\n toCommerceError,\n} from '../../core';\nimport { toLogInfo } from '../../core/errors';\nimport { isRecord } from '../../core/is-record';\nimport { PACKAGE_VERSION } from '../../version';\nimport { readCappedBody } from '../http';\nimport { buildAgentCard } from './agent-card';\nimport {\n A2A_AGENT_CARD_PATH,\n A2A_DEFAULT_AGENT_NAME,\n A2A_DEFAULT_MOUNT_PATH,\n A2A_EXTENSIONS_HEADER,\n A2A_JSON_MEDIA_TYPE,\n A2A_METHOD_SEND_MESSAGE,\n A2A_PROTOCOL_VERSION,\n A2A_PUSH_CONFIG_METHODS,\n A2A_TASK_LOOKUP_METHODS,\n A2A_UNSUPPORTED_METHODS,\n A2A_VERSION_HEADER,\n} from './constants';\nimport { buildDescriptor } from './descriptor';\nimport {\n A2A_ERROR_PUSH_NOTIFICATION_NOT_SUPPORTED,\n A2A_ERROR_TASK_NOT_FOUND,\n A2A_ERROR_UNSUPPORTED_OPERATION,\n A2A_ERROR_VERSION_NOT_SUPPORTED,\n JSONRPC_INTERNAL_ERROR,\n JSONRPC_INVALID_PARAMS,\n JSONRPC_INVALID_REQUEST,\n JSONRPC_METHOD_NOT_FOUND,\n JSONRPC_PARSE_ERROR,\n type JsonRpcId,\n jsonRpcError,\n parseJsonRpcRequest,\n} from './jsonrpc';\nimport { type A2aInvocation, parseInvocation } from './message-mapping';\nimport { resumePayment, taskResult } from './payment-resume';\nimport {\n completedTask,\n failedTask,\n inputRequired,\n paymentRequiredTask,\n type TaskIdentity,\n} from './task-mapping';\nimport type { A2aAgentCard, A2aTask } from './types';\nimport {\n A2A_X402_EXTENSION_URI,\n createPendingPayments,\n type PendingPayments,\n paymentRequiredMetadata,\n requestsX402Extension,\n} from './x402-extension';\n\n// A second line behind the gateway mount's cap, bounding what this adapter\n// buffers if it is mounted without that guard\nconst MAX_REQUEST_BODY_BYTES = 256 * 1024;\n\n// Accept patch suffixes; only major.minor determines the protocol version\nconst VERSION_PATTERN = /^(\\d+\\.\\d+)(?:\\.\\d+)?$/;\n\n// A2A version parameter; the header is matched case-insensitively\nconst A2A_VERSION_PARAMETER = 'A2A-Version';\n\n// Cache the card until the adapter starts again with new configuration\nconst AGENT_CARD_CACHE_CONTROL = 'public, max-age=300';\n\nexport interface A2aAdapterOptions {\n readonly mountPath?: string;\n /** Agent name published on the card */\n readonly agentName?: string;\n readonly agentDescription?: string;\n /** Version published on the card. Defaults to this package's version */\n readonly agentVersion?: string;\n}\n\nconst DEFAULT_AGENT_DESCRIPTION =\n 'Agent Commerce Gateway: canonical commerce resources exposed as A2A skills.';\n\nexport class A2aProtocolAdapter implements HttpProtocolAdapter {\n readonly name = 'a2a' as const;\n readonly mountPath: string;\n readonly descriptor: AdapterDescriptor;\n readonly additionalHttpRoutes: readonly AdapterHttpRoute[];\n\n private readonly agentName: string;\n private readonly agentDescription: string;\n private readonly agentVersion: string;\n\n private context: ProtocolAdapterContext | undefined;\n private started = false;\n // The card lists only a2a-exposed resources, but a caller can name any id,\n // so the adapter refuses another protocol's resource itself\n private skillsById: ReadonlyMap<string, CommerceResource> = new Map();\n // Built once at start: resources are fixed at config load, and a per-request\n // build would be work an unauthenticated GET could trigger at will\n private card: A2aAgentCard | undefined;\n private cardBody = '';\n private cardEtag = '';\n // Purchases waiting for an x402 extension payment\n private pendingPayments: PendingPayments | undefined;\n\n constructor(options: A2aAdapterOptions = {}) {\n this.mountPath = options.mountPath ?? A2A_DEFAULT_MOUNT_PATH;\n this.agentName = options.agentName ?? A2A_DEFAULT_AGENT_NAME;\n this.agentDescription = options.agentDescription ?? DEFAULT_AGENT_DESCRIPTION;\n this.agentVersion = options.agentVersion ?? PACKAGE_VERSION;\n this.descriptor = buildDescriptor(PACKAGE_VERSION);\n this.additionalHttpRoutes = [\n {\n method: 'GET',\n path: A2A_AGENT_CARD_PATH,\n handleHttp: (req, res) => this.handleAgentCard(req, res),\n },\n ];\n }\n\n async start(context: ProtocolAdapterContext): Promise<void> {\n this.context = context;\n this.started = false;\n\n let resources: readonly CommerceResource[] = [];\n try {\n resources = context.resources.listExposedVia('a2a');\n } catch (err) {\n context.logger.error(\n { err: toLogInfo(err) },\n 'a2a adapter: failed to list a2a-exposed resources',\n );\n resources = [];\n }\n\n this.skillsById = new Map(resources.map((resource) => [resource.id, resource]));\n this.card = buildAgentCard({\n name: this.agentName,\n description: this.agentDescription,\n version: this.agentVersion,\n publicBaseUrl: context.publicBaseUrl,\n mountPath: this.mountPath,\n resources,\n });\n this.pendingPayments = createPendingPayments(context.clock);\n this.cardBody = JSON.stringify(this.card);\n this.cardEtag = `\"${createHash('sha256').update(this.cardBody).digest('base64url')}\"`;\n this.started = true;\n\n context.logger.info(\n { mountPath: this.mountPath, cardPath: A2A_AGENT_CARD_PATH, skillCount: resources.length },\n 'a2a adapter started',\n );\n }\n\n /** `GET /.well-known/agent-card.json` */\n async handleAgentCard(req: IncomingMessage, res: ServerResponse): Promise<void> {\n try {\n if (!this.started || this.card === undefined) {\n this.writeJson(res, 503, { error: 'A2A adapter is not running.' });\n return;\n }\n if (req.method !== 'GET') {\n this.writeJson(res, 405, { error: 'Method not allowed. The Agent Card is read-only.' });\n return;\n }\n const cacheHeaders = { 'cache-control': AGENT_CARD_CACHE_CONTROL, etag: this.cardEtag };\n if (matchesEtag(req.headers['if-none-match'], this.cardEtag)) {\n res.writeHead(304, cacheHeaders);\n res.end();\n return;\n }\n res.writeHead(200, { 'content-type': A2A_JSON_MEDIA_TYPE, ...cacheHeaders });\n res.end(this.cardBody);\n } catch (err) {\n this.context?.logger.error({ err: toLogInfo(err) }, 'a2a adapter: agent card request failed');\n this.writeJson(res, 500, { error: 'Internal server error.' });\n }\n }\n\n /** `POST <mountPath>`: the A2A JSON-RPC endpoint */\n async handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void> {\n try {\n if (!this.started) {\n this.writeJson(\n res,\n 503,\n jsonRpcError(null, JSONRPC_INTERNAL_ERROR, 'A2A adapter is not running.'),\n );\n return;\n }\n if (req.method !== 'POST') {\n this.writeJson(\n res,\n 405,\n jsonRpcError(\n null,\n JSONRPC_INVALID_REQUEST,\n 'Method not allowed. This endpoint only accepts POST.',\n ),\n );\n return;\n }\n\n const read = await readCappedBody(req, MAX_REQUEST_BODY_BYTES);\n if (read.kind === 'too-large') {\n this.writeJson(\n res,\n 413,\n jsonRpcError(\n null,\n JSONRPC_INVALID_REQUEST,\n `Request body exceeds the ${MAX_REQUEST_BODY_BYTES}-byte limit.`,\n ),\n );\n return;\n }\n if (read.kind !== 'ok') {\n this.writeJson(\n res,\n 200,\n jsonRpcError(null, JSONRPC_PARSE_ERROR, 'Could not read the request body.'),\n );\n return;\n }\n\n const parsed = parseJsonRpcRequest(read.text);\n if (!parsed.ok) {\n this.writeJson(res, 200, jsonRpcError(parsed.id, parsed.error.code, parsed.error.message));\n return;\n }\n\n // Parse first to echo the request id on version errors. The query\n // parameter substitutes for an absent version header.\n const version = req.headers[A2A_VERSION_HEADER];\n const declared =\n (Array.isArray(version) ? version[0] : version) ??\n new URL(req.url ?? '/', 'http://localhost').searchParams.get(A2A_VERSION_PARAMETER);\n if (declared?.match(VERSION_PATTERN)?.[1] !== A2A_PROTOCOL_VERSION) {\n this.writeJson(\n res,\n 200,\n jsonRpcError(\n parsed.request.id,\n A2A_ERROR_VERSION_NOT_SUPPORTED,\n `Unsupported A2A protocol version. Send the ${A2A_VERSION_PARAMETER} header with \"${A2A_PROTOCOL_VERSION}\".`,\n ),\n );\n return;\n }\n\n const response = await this.dispatch(\n parsed.request.id,\n parsed.request.method,\n parsed.request.params,\n requestsX402Extension(req.headers[A2A_EXTENSIONS_HEADER]),\n );\n // Echo the extension when it shaped the task, even without the\n // request header on a payment follow-up\n this.writeJson(\n res,\n 200,\n response,\n usesX402Extension(response) ? { [A2A_EXTENSIONS_HEADER]: A2A_X402_EXTENSION_URI } : {},\n );\n } catch (err) {\n // Nothing from `err` reaches the client\n this.context?.logger.error({ err: toLogInfo(err) }, 'a2a adapter: request handling failed');\n this.writeJson(\n res,\n 200,\n jsonRpcError(null, JSONRPC_INTERNAL_ERROR, 'Internal server error.'),\n );\n }\n }\n\n private async dispatch(\n id: JsonRpcId,\n method: string,\n params: unknown,\n x402Extension: boolean,\n ): Promise<Record<string, unknown>> {\n if (A2A_PUSH_CONFIG_METHODS.includes(method)) {\n return jsonRpcError(\n id,\n A2A_ERROR_PUSH_NOTIFICATION_NOT_SUPPORTED,\n `A2A method \"${method}\" is not supported: this agent does not support push notifications.`,\n );\n }\n if (A2A_TASK_LOOKUP_METHODS.includes(method)) {\n return jsonRpcError(\n id,\n A2A_ERROR_TASK_NOT_FOUND,\n 'Task not found. Finished tasks are not retained; continue a pending payment with SendMessage.',\n );\n }\n if (A2A_UNSUPPORTED_METHODS.includes(method)) {\n return jsonRpcError(\n id,\n A2A_ERROR_UNSUPPORTED_OPERATION,\n `A2A method \"${method}\" is not supported by this deployment.`,\n );\n }\n if (method !== A2A_METHOD_SEND_MESSAGE) {\n return jsonRpcError(id, JSONRPC_METHOD_NOT_FOUND, `Unknown method \"${method}\".`);\n }\n\n const resumed = await resumePayment(this.context, this.pendingPayments, id, params);\n if (resumed !== undefined) return resumed;\n\n let invocation: ReturnType<typeof parseInvocation>;\n try {\n invocation = parseInvocation(params);\n } catch (err) {\n const error = toCommerceError(err);\n const a2aErrorCode = error.details?.['a2aErrorCode'];\n const code =\n typeof a2aErrorCode === 'number'\n ? a2aErrorCode\n : error.code === 'PROTOCOL_UNSUPPORTED'\n ? A2A_ERROR_UNSUPPORTED_OPERATION\n : JSONRPC_INVALID_PARAMS;\n // CommerceError messages are written for a client; nothing else is\n // relayed\n return jsonRpcError(id, code, error.message);\n }\n\n return this.execute(id, invocation, x402Extension);\n }\n\n // One accepted invocation, one `pipeline.execute()`\n private async execute(\n id: JsonRpcId,\n invocation: A2aInvocation,\n x402Extension: boolean,\n ): Promise<Record<string, unknown>> {\n const context = this.context;\n if (context === undefined) {\n return jsonRpcError(id, JSONRPC_INTERNAL_ERROR, 'A2A adapter is not running.');\n }\n\n const resource = this.skillsById.get(invocation.resourceId);\n if (resource === undefined) {\n // A commerce outcome, so a failed task rather than a JSON-RPC error. It\n // reads the same whether the resource is missing or scoped to another\n // protocol, so a caller cannot probe what A2A does not expose.\n return taskResult(\n id,\n failedTask(\n new CommerceError(\n 'RESOURCE_NOT_FOUND',\n `Unknown canonical resource \"${invocation.resourceId}\".`,\n ),\n this.taskIdentity(context, context.ids.next('a2a')),\n ),\n );\n }\n\n const requestId = context.ids.next('a2a');\n const identity = this.taskIdentity(context, requestId);\n\n // Reserved-field extraction sits inside the try: a malformed\n // `_authorization` envelope becomes a failed task like any other outcome\n try {\n const { input, payment, authorization } = extractReservedInputFields(\n invocation.input,\n resource,\n requestId,\n );\n const request: CanonicalRequest = {\n requestId,\n resourceId: invocation.resourceId,\n input,\n protocol: 'a2a',\n receivedAt: context.clock.nowIso(),\n ...(payment !== undefined ? { payment } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n };\n const outcome: ExecutionOutcome = await context.pipeline.execute(request);\n if (outcome.kind !== 'payment-required') {\n return taskResult(id, completedTask(outcome, identity));\n }\n const task = paymentRequiredTask(outcome, identity);\n const envelope = outcome.requirement.challenge.envelope;\n // The extension carries x402 only; any other rail keeps the terminal task\n if (!x402Extension || outcome.requirement.provider !== 'x402' || !isRecord(envelope)) {\n return taskResult(id, task);\n }\n const network = outcome.requirement.network;\n const held = this.pendingPayments?.put(\n identity.taskId,\n {\n contextId: identity.contextId,\n resourceId: invocation.resourceId,\n input,\n ...(authorization !== undefined ? { authorization } : {}),\n ...(network !== undefined ? { network } : {}),\n },\n outcome.requirement.expiresAt,\n );\n if (held === false) {\n return taskResult(\n id,\n failedTask(\n new CommerceError(\n 'GATEWAY_BUSY',\n 'Too many unpaid purchases are waiting for payment; retry shortly.',\n ),\n identity,\n ),\n );\n }\n return taskResult(\n id,\n inputRequired(task, paymentRequiredMetadata(envelope), identity.statusMessageId),\n );\n } catch (err) {\n // A downstream failure is the caller's answer, not a broken frame.\n // `toCommerceError` replaces a non-commerce error's message, so nothing\n // internal reaches the artifact.\n const error = toCommerceError(err);\n context.logger.warn(\n { resourceId: invocation.resourceId, requestId, err: toLogInfo(error) },\n 'a2a adapter: execution failed',\n );\n return taskResult(id, failedTask(error, identity));\n }\n }\n\n private taskIdentity(context: ProtocolAdapterContext, requestId: string): TaskIdentity {\n return {\n taskId: requestId,\n contextId: context.ids.next('a2a-ctx'),\n artifactId: context.ids.next('a2a-artifact'),\n statusMessageId: context.ids.next('a2a-msg'),\n timestamp: context.clock.nowIso(),\n };\n }\n\n async health(): Promise<AdapterHealth> {\n const checkedAt = this.context?.clock.nowIso() ?? new Date().toISOString();\n if (!this.started || this.card === undefined) {\n return { status: 'fail', detail: 'A2A adapter has not been started.', checkedAt };\n }\n return { status: 'pass', detail: `${this.skillsById.size} skill(s) published.`, checkedAt };\n }\n\n async stop(): Promise<void> {\n this.started = false;\n this.card = undefined;\n this.cardBody = '';\n this.cardEtag = '';\n this.pendingPayments?.clear();\n this.pendingPayments = undefined;\n this.skillsById = new Map();\n this.context = undefined;\n }\n\n private writeJson(\n res: ServerResponse,\n status: number,\n body: unknown,\n headers: Readonly<Record<string, string>> = {},\n ): void {\n if (res.headersSent) return;\n res.writeHead(status, { 'content-type': A2A_JSON_MEDIA_TYPE, ...headers });\n res.end(JSON.stringify(body));\n }\n}\n\n// True when the response is a task whose status message lists the extension\nfunction usesX402Extension(response: Record<string, unknown>): boolean {\n const result = response['result'] as { readonly task?: A2aTask } | undefined;\n return result?.task?.status.message?.extensions?.includes(A2A_X402_EXTENSION_URI) === true;\n}\n\n// Compare entity tags weakly; `*` matches any current card\nfunction matchesEtag(header: string | undefined, etag: string): boolean {\n if (header === undefined) return false;\n return header\n .split(',')\n .map((tag) => tag.trim().replace(/^W\\//, ''))\n .some((tag) => tag === '*' || tag === etag);\n}\n\nexport function createA2aAdapter(options: A2aAdapterOptions = {}): A2aProtocolAdapter {\n return new A2aProtocolAdapter(options);\n}\n","/**\n * ACP checkout operation -> canonical request.\n *\n * Each operation maps to one configured resource and one deterministic input\n * envelope: the keys `ACP_OPERATION_INPUT_KEYS` lists, plus any key in\n * `ACP_OPERATION_OPTIONAL_INPUT_KEYS` the caller supplied.\n *\n * No payment field is synthesized. ACP `payment_data` on completion is the\n * merchant's own purchase payment and stays inside `body` as business input;\n * a `PaymentSubmission` built from it would charge a gateway payment on top.\n */\nimport type { CanonicalRequest } from '../../core';\nimport {\n ACP_OPERATION_INPUT_KEYS,\n ACP_OPERATION_OPTIONAL_INPUT_KEYS,\n ACP_SESSION_ID_INPUT_KEY,\n} from './constants';\nimport type { AcpGuardedRequest } from './request-guards';\n\nexport interface AcpCanonicalRequestOptions {\n readonly request: AcpGuardedRequest;\n readonly resourceId: string;\n readonly requestId: string;\n readonly receivedAt: string;\n /**\n * Names this checkout operation to the merchant. The adapter derives it from\n * the idempotency scope, so it is the same value on every retry - unlike\n * `requestId`, which is new each time.\n */\n readonly idempotencyKey?: string;\n}\n\nexport function toCanonicalRequest(options: AcpCanonicalRequestOptions): CanonicalRequest {\n const { request, resourceId, requestId, receivedAt, idempotencyKey } = options;\n return {\n requestId,\n resourceId,\n input: canonicalInput(request),\n protocol: 'acp',\n receivedAt,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(request.forwardedHeaders !== undefined && Object.keys(request.forwardedHeaders).length > 0\n ? { backendHeaders: request.forwardedHeaders }\n : {}),\n };\n}\n\nfunction canonicalInput(request: AcpGuardedRequest): Record<string, unknown> {\n const keys = ACP_OPERATION_INPUT_KEYS[request.route.operation];\n const optionalKeys = ACP_OPERATION_OPTIONAL_INPUT_KEYS[request.route.operation] ?? [];\n const input: Record<string, unknown> = {};\n\n if (keys.includes('path') && request.route.sessionId !== undefined) {\n input['path'] = { [ACP_SESSION_ID_INPUT_KEY]: request.route.sessionId };\n }\n if (keys.includes('body')) {\n input['body'] = request.body;\n } else if (optionalKeys.includes('body') && Object.keys(request.body).length > 0) {\n input['body'] = request.body;\n }\n return input;\n}\n","/**\n * Adapter self-description.\n *\n * `supportedSpec` is the pinned ACP snapshot, never this package's version.\n * Status is `experimental` while the adapter lacks the features in the\n * unsupported list below; an entry leaves that list only when its feature is\n * implemented.\n */\nimport type { AdapterDescriptor } from '../../core';\nimport { ACP_CHECKOUT_OPERATIONS, ACP_SPEC_VERSION } from './constants';\n\n// What this adapter implements\nconst ACP_CAPABILITIES: readonly string[] = [\n 'rest transport',\n 'well-known discovery',\n 'bearer authentication',\n 'API-Version enforcement',\n // Forwarded as received: the gateway verifies neither signature header\n 'request header forwarding to the merchant',\n 'checkout service',\n ...ACP_CHECKOUT_OPERATIONS,\n];\n\n/**\n * Major ACP features this adapter does not implement, served on\n * `/.well-known/agent-commerce` and printed by `doctor`, so no client assumes\n * full protocol support\n */\nexport const ACP_UNSUPPORTED: readonly string[] = [\n // Services this seller does not implement, named as ACP names them. The\n // discovery document advertises `checkout` alone, and these are the reason.\n 'carts service',\n 'feed service',\n 'standalone orders service',\n 'delegate_payment',\n 'delegate_authentication',\n // Bindings and delivery directions\n 'ACP MCP transport binding',\n 'webhooks',\n 'outbound merchant-to-agent delivery',\n 'ACP client role',\n // Request authentication beyond the bearer token\n 'Signature header verification',\n 'Timestamp replay-window verification',\n // Extensions, versioning and payment handlers\n 'discount extension',\n 'general ACP extension framework',\n 'multiple ACP API versions',\n 'seller-backed payment handler integration',\n];\n\nexport function buildDescriptor(implementationVersion: string): AdapterDescriptor {\n return {\n name: 'acp',\n kind: 'protocol',\n implementationVersion,\n supportedSpec: ACP_SPEC_VERSION,\n capabilities: ACP_CAPABILITIES,\n status: 'experimental',\n unsupported: ACP_UNSUPPORTED,\n };\n}\n","/**\n * The `/.well-known/acp.json` seller discovery document.\n *\n * It advertises what this adapter implements: one transport, one service, one\n * API version. Optional metadata appears only when an operator configured it;\n * currencies are never inferred from the x402 configuration, a different\n * payment domain.\n *\n * The document is public, so the bearer token, backend URLs, resource mapping\n * and idempotency database location are not even inputs to this function.\n */\nimport { joinUrl } from '../http';\nimport { ACP_SPEC_VERSION } from './constants';\n\n/** Discovery metadata an operator may configure. Absent fields are omitted, never guessed */\nexport interface AcpDiscoveryMetadata {\n readonly documentationUrl?: string;\n readonly supportedCurrencies?: readonly string[];\n readonly supportedLocales?: readonly string[];\n readonly interventionTypes?: readonly string[];\n}\n\nexport interface AcpDiscoveryOptions {\n /** Externally reachable base URL of the gateway */\n readonly publicBaseUrl: string;\n readonly mountPath: string;\n readonly metadata?: AcpDiscoveryMetadata;\n}\n\nexport function buildAcpDiscoveryDocument(options: AcpDiscoveryOptions): Record<string, unknown> {\n const metadata = options.metadata ?? {};\n return {\n protocol: {\n name: 'acp',\n version: ACP_SPEC_VERSION,\n supported_versions: [ACP_SPEC_VERSION],\n ...(metadata.documentationUrl !== undefined\n ? { documentation_url: metadata.documentationUrl }\n : {}),\n },\n api_base_url: joinUrl(options.publicBaseUrl, options.mountPath),\n // REST only: ACP's MCP transport is a fixed checkout binding, not the\n // generic MCP adapter this gateway also serves\n transports: ['rest'],\n capabilities: {\n services: ['checkout'],\n ...(metadata.interventionTypes !== undefined\n ? { intervention_types: metadata.interventionTypes }\n : {}),\n ...(metadata.supportedCurrencies !== undefined\n ? { supported_currencies: metadata.supportedCurrencies }\n : {}),\n ...(metadata.supportedLocales !== undefined\n ? { supported_locales: metadata.supportedLocales }\n : {}),\n },\n };\n}\n","/**\n * The ACP `Error` object and the one writer every ACP response goes through,\n * so no handler invents its own error shape. Every error message is written by\n * the gateway: no stack, backend body, Ajv message, token or internal path\n * reaches a client.\n */\nimport type { ServerResponse } from 'node:http';\nimport { ACP_JSON_MEDIA_TYPE } from './constants';\n\n/** The three categories the pinned snapshot allows */\nexport type AcpErrorType = 'invalid_request' | 'processing_error' | 'service_unavailable';\n\nexport interface AcpError {\n readonly type: AcpErrorType;\n readonly code: string;\n readonly message: string;\n /** RFC 9535 JSONPath into the caller's document, never into ours */\n readonly param?: string;\n /** Only on version errors, per the snapshot */\n readonly supported_versions?: readonly string[];\n}\n\n/** An ACP error plus the status it is served with */\nexport interface AcpFailure {\n readonly status: number;\n readonly error: AcpError;\n /** Seconds for `Retry-After`, where the failure invites a retry */\n readonly retryAfterSeconds?: number;\n}\n\nexport function acpFailure(\n status: number,\n type: AcpErrorType,\n code: string,\n message: string,\n extra: { readonly param?: string; readonly supportedVersions?: readonly string[] } = {},\n): AcpFailure {\n return {\n status,\n error: {\n type,\n code,\n message,\n ...(extra.param !== undefined ? { param: extra.param } : {}),\n ...(extra.supportedVersions !== undefined\n ? { supported_versions: extra.supportedVersions }\n : {}),\n },\n };\n}\n\n/**\n * Response headers the adapter may set. Merchant backend headers are never\n * proxied: a backend's `Set-Cookie` or tracing header belongs to the\n * merchant's domain, not to the ACP client. `Retry-After` is rebuilt from a\n * parsed and capped number, not copied.\n */\nexport type AcpResponseHeaders = Readonly<Record<string, string>>;\n\nexport function writeAcpJson(\n res: ServerResponse,\n status: number,\n body: unknown,\n headers: AcpResponseHeaders = {},\n): void {\n if (res.headersSent) return;\n res.writeHead(status, { 'content-type': ACP_JSON_MEDIA_TYPE, ...headers });\n res.end(JSON.stringify(body));\n}\n\nexport function writeAcpFailure(\n res: ServerResponse,\n failure: AcpFailure,\n headers: AcpResponseHeaders = {},\n): void {\n writeAcpJson(res, failure.status, failure.error, headers);\n}\n","/**\n * Operation keys and request fingerprints for ACP idempotency.\n *\n * The fingerprint covers the parsed JSON value, not the raw bytes, so a retry\n * through another serializer (other key order, `1.0` for `1`, whitespace) is\n * a retry, not a 422 conflict. Array order, `null` versus an absent property,\n * and type still count: `1` and `\"1\"` are different requests.\n */\nimport { createHash } from 'node:crypto';\n\n/**\n * The name the merchant sees for one checkout operation, hashed from the same\n * scope that claims the key locally (deployment, endpoint, caller's key), so\n * it stays the same across client and network retries, a gateway restart and\n * a credential rotation.\n *\n * The caller's key alone does not name an operation: ACP scopes it per\n * endpoint, so one client may send `Idempotency-Key: 1` to both create and\n * complete. Two clients that pick the same key share a derived key, as they\n * share a claim row; ACP makes key uniqueness the client's responsibility.\n */\nexport function operationKey(scope: {\n readonly deployment: string;\n readonly endpoint: string;\n readonly key: string;\n}): string {\n return sha256(`acp-operation:${scope.deployment}:${scope.endpoint}:${scope.key}`);\n}\n\n/** SHA-256 over the canonical form of a parsed JSON document */\nexport function requestFingerprint(body: unknown): string {\n return sha256(canonicalize(body));\n}\n\n/**\n * Deterministic JSON canonicalization in the spirit of RFC 8785, limited to\n * what `JSON.parse` produces. Not the `canonicalize` package: that is an\n * optional peer (AP2), and this module is in the peer-free main entry.\n *\n * Object keys are sorted by UTF-16 code unit. Numbers go through\n * `JSON.stringify`, which writes each in its shortest round-trip form, so\n * `1.0` becomes `1` and `1e2` becomes `100`.\n */\nfunction canonicalize(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return `[${value.map(canonicalize).join(',')}]`;\n if (typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n // JSON.parse never yields `undefined`, but an object literal could;\n // dropping such keys keeps them equal to absent ones\n .filter(([, entry]) => entry !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalize(entry)}`).join(',')}}`;\n }\n // Strings, numbers and booleans, whose encodings keep the types distinct\n return JSON.stringify(value) ?? 'null';\n}\n\nfunction sha256(value: string): string {\n return createHash('sha256').update(value, 'utf8').digest('hex');\n}\n","/**\n * Durable ACP checkout idempotency, in its own database file: it is protocol\n * replay semantics for a checkout, unrelated to the payment replay defense in\n * the receipt store, with its own lifetime and retention.\n *\n * A key is claimed atomically before the side effect starts, so a second\n * request with the same key finds the claim instead of starting a second\n * checkout.\n *\n * A merchant call over HTTP and a SQLite commit are not one transaction. By\n * default, an attempt with an uncertain merchant outcome is marked\n * `unresolved` so a retry cannot repeat the operation. A row still\n * `in_flight` when the store opens is also marked unresolved: the earlier\n * process may have crashed before recording the outcome. With\n * `releaseOrphans`, the store frees these rows for a merchant configured to\n * deduplicate by the derived key. This assumes one gateway process per file.\n *\n * Only `completed` rows expire. Deleting an unresolved one would hand the next\n * retry a clean key; clearing it is an operator's decision, taken against the\n * merchant's own records. The merchant should still be idempotent on\n * destructive operations: this store does not make its API exactly-once.\n */\nimport type { Database } from 'better-sqlite3';\nimport { type Logger, NOOP_LOGGER } from '../../../core';\nimport { openSqliteDatabase } from '../../../storage/sqlite';\n\n// v2 keys rows by the deployment's public base URL; v1 keyed them by a\n// bearer-token digest (see `migrate`)\nconst SCHEMA_VERSION = 2;\n\n/** Longest `Idempotency-Key` ACP allows */\nexport const ACP_MAX_IDEMPOTENCY_KEY_LENGTH = 255;\n\n/** Scope of one claim: which deployment, which endpoint, which key */\nexport interface AcpIdempotencyScope {\n /**\n * The gateway's public base URL, not a credential: a rotated token must not\n * give a retry a fresh key and re-run an operation whose outcome may be\n * unknown. The URL survives rotation and still separates two gateways in\n * front of one merchant. It is not secret and is stored as-is, so an\n * operator can see which deployment wrote an unresolved row.\n */\n readonly deployment: string;\n /** The concrete endpoint path, so one key may be reused across operations */\n readonly endpoint: string;\n readonly key: string;\n}\n\n/** A response worth replaying: status plus the ACP document that was sent */\nexport interface AcpStoredResponse {\n readonly status: number;\n readonly body: unknown;\n}\n\nexport type AcpIdempotencyClaim =\n /** The caller owns the key and must now do the work */\n | { readonly kind: 'reserved' }\n /** Same scope, same body, still running elsewhere */\n | { readonly kind: 'in-flight' }\n /** Same scope, same body, and an earlier attempt's outcome was never learned */\n | { readonly kind: 'unresolved' }\n /** Same scope, different body: the key was reused for another request */\n | { readonly kind: 'conflict' }\n /** Same scope, same body, already answered */\n | ({ readonly kind: 'replay' } & AcpStoredResponse);\n\nexport interface AcpIdempotencyStore {\n /** Atomically claim `scope`, or report what already holds it */\n claim(scope: AcpIdempotencyScope, fingerprint: string): AcpIdempotencyClaim;\n /** Store the answer, making later retries a replay */\n complete(scope: AcpIdempotencyScope, response: AcpStoredResponse): void;\n /**\n * Keep the claim with no answer: the merchant may have acted. Later retries\n * are refused, neither replayed nor re-run.\n */\n markUnresolved(scope: AcpIdempotencyScope): void;\n /**\n * Drop the claim so a retry can run. The caller must establish that no\n * merchant call ran or that the merchant deduplicates by the derived key.\n */\n release(scope: AcpIdempotencyScope): void;\n close(): void;\n}\n\nexport interface AcpIdempotencyStoreOptions {\n /** File path, or ':memory:' for tests */\n readonly path: string;\n /** Never below 24 hours; config enforces the floor */\n readonly retentionHours: number;\n /**\n * Free claims left in flight by an earlier process. Enable only when the\n * merchant deduplicates by the derived key.\n */\n readonly releaseOrphans?: boolean;\n readonly logger?: Logger;\n /** Injectable for tests that need to move time */\n readonly now?: () => number;\n}\n\ninterface ClaimRow {\n state: string;\n fingerprint: string;\n status: number | null;\n body_json: string | null;\n}\n\nexport function createAcpIdempotencyStore(\n options: AcpIdempotencyStoreOptions,\n): AcpIdempotencyStore {\n const logger = options.logger ?? NOOP_LOGGER;\n const now = options.now ?? (() => Date.now());\n const retentionMs = options.retentionHours * 60 * 60 * 1000;\n\n const db: Database = openSqliteDatabase({\n path: options.path,\n label: 'ACP idempotency database',\n logger,\n });\n migrate(db, logger);\n resolveOrphanedClaims(db, logger, options.releaseOrphans === true);\n\n const selectStmt = db.prepare<[string, string, string], ClaimRow>(\n `SELECT state, fingerprint, status, body_json FROM acp_idempotency\n WHERE deployment = ? AND endpoint = ? AND idempotency_key = ?`,\n );\n const insertStmt = db.prepare(\n `INSERT INTO acp_idempotency\n (deployment, endpoint, idempotency_key, fingerprint, state, created_at, expires_at)\n VALUES (@deployment, @endpoint, @idempotency_key, @fingerprint, 'in_flight', @created_at, @expires_at)`,\n );\n const completeStmt = db.prepare(\n `UPDATE acp_idempotency SET state = 'completed', status = @status, body_json = @body_json\n WHERE deployment = @deployment AND endpoint = @endpoint AND idempotency_key = @idempotency_key`,\n );\n const deleteStmt = db.prepare(\n `DELETE FROM acp_idempotency\n WHERE deployment = ? AND endpoint = ? AND idempotency_key = ?`,\n );\n const unresolvedStmt = db.prepare(\n `UPDATE acp_idempotency SET state = 'unresolved'\n WHERE deployment = @deployment AND endpoint = @endpoint AND idempotency_key = @idempotency_key`,\n );\n // Completed rows only: to the next retry, a deleted unresolved row would look\n // like an operation that never happened\n const expireStmt = db.prepare(\n \"DELETE FROM acp_idempotency WHERE expires_at <= ? AND state = 'completed'\",\n );\n\n // Expired rows are swept lazily inside the claim transaction, with no\n // background worker\n const claimTx = db.transaction(\n (scope: AcpIdempotencyScope, fingerprint: string): AcpIdempotencyClaim => {\n const at = now();\n expireStmt.run(new Date(at).toISOString());\n\n const existing = selectStmt.get(scope.deployment, scope.endpoint, scope.key);\n if (existing === undefined) {\n insertStmt.run({\n deployment: scope.deployment,\n endpoint: scope.endpoint,\n idempotency_key: scope.key,\n fingerprint,\n created_at: new Date(at).toISOString(),\n expires_at: new Date(at + retentionMs).toISOString(),\n });\n return { kind: 'reserved' };\n }\n\n // Fingerprint first: a key reused for a different body conflicts whether\n // or not the first request has finished, and \"in flight\" would invite a\n // retry that can only conflict\n if (existing.fingerprint !== fingerprint) return { kind: 'conflict' };\n if (existing.state === 'unresolved') return { kind: 'unresolved' };\n if (existing.state !== 'completed') return { kind: 'in-flight' };\n return {\n kind: 'replay',\n status: existing.status ?? 500,\n body: existing.body_json === null ? null : JSON.parse(existing.body_json),\n };\n },\n );\n\n let closed = false;\n return {\n claim(scope, fingerprint) {\n return claimTx(scope, fingerprint);\n },\n complete(scope, response) {\n completeStmt.run({\n deployment: scope.deployment,\n endpoint: scope.endpoint,\n idempotency_key: scope.key,\n status: response.status,\n body_json: JSON.stringify(response.body ?? null),\n });\n },\n markUnresolved(scope) {\n unresolvedStmt.run({\n deployment: scope.deployment,\n endpoint: scope.endpoint,\n idempotency_key: scope.key,\n });\n },\n release(scope) {\n deleteStmt.run(scope.deployment, scope.endpoint, scope.key);\n },\n close() {\n if (closed) return;\n closed = true;\n db.close();\n },\n };\n}\n\n// Runs when the store opens, before this process claims anything, so an\n// `in_flight` row outlived the process that claimed it and would otherwise\n// answer \"retry later\" forever\nfunction resolveOrphanedClaims(db: Database, logger: Logger, release: boolean): void {\n if (release) {\n const { changes } = db.prepare(\"DELETE FROM acp_idempotency WHERE state = 'in_flight'\").run();\n if (changes > 0) {\n logger.warn(\n { released: changes },\n 'acp idempotency: freed claims left in flight by an earlier process; merchant deduplication is enabled',\n );\n }\n return;\n }\n const { changes } = db\n .prepare(\"UPDATE acp_idempotency SET state = 'unresolved' WHERE state = 'in_flight'\")\n .run();\n if (changes > 0) {\n logger.warn(\n { unresolved: changes },\n 'acp idempotency: marked claims left in flight by an earlier process as unresolved; ' +\n 'reconcile these operations against the merchant before trusting a retry',\n );\n }\n}\n\n// `PRAGMA user_version` marks the schema, so reopening a current file is a no-op\nfunction migrate(db: Database, logger: Logger): void {\n const current = db.pragma('user_version', { simple: true }) as number;\n if (current >= SCHEMA_VERSION) return;\n\n const apply = db.transaction(() => {\n if (current === 1) {\n // v1 keyed rows by a one-way digest of the bearer token, which cannot be\n // mapped to a deployment. The table is rebuilt empty, since nothing would\n // ever match those rows again, and the number of open claims dropped is\n // logged.\n const carried = db\n .prepare(\"SELECT COUNT(*) AS count FROM acp_idempotency WHERE state != 'completed'\")\n .get() as { count: number };\n if (carried.count > 0) {\n logger.warn(\n { unresolved: carried.count },\n 'acp idempotency: schema v1 -> v2 discards claims keyed by the old bearer-token digest; ' +\n 'reconcile these operations against the merchant before trusting a retry',\n );\n }\n db.exec('DROP TABLE acp_idempotency');\n }\n\n db.exec(`\n CREATE TABLE IF NOT EXISTS acp_idempotency (\n deployment TEXT NOT NULL,\n endpoint TEXT NOT NULL,\n idempotency_key TEXT NOT NULL,\n fingerprint TEXT NOT NULL,\n state TEXT NOT NULL,\n status INTEGER,\n body_json TEXT,\n created_at TEXT NOT NULL,\n expires_at TEXT NOT NULL,\n PRIMARY KEY (deployment, endpoint, idempotency_key)\n );\n CREATE INDEX IF NOT EXISTS idx_acp_idempotency_expires_at\n ON acp_idempotency(expires_at);\n `);\n db.pragma(`user_version = ${SCHEMA_VERSION}`);\n });\n apply();\n}\n","/**\n * The five stable checkout routes, matched against the adapter's mount.\n *\n * The route table is closed: anything else under the mount is a 404, so a\n * client cannot discover an unimplemented ACP service by probing paths.\n */\nimport type { AcpCheckoutOperation } from './constants';\n\n// Longest raw path segment accepted before decoding, which also bounds\n// `checkout_session_id`\nconst MAX_SEGMENT_LENGTH = 512;\n\nconst COLLECTION = 'checkout_sessions';\n\nexport interface AcpRouteMatch {\n readonly operation: AcpCheckoutOperation;\n /**\n * The concrete endpoint path, rebuilt from the matched segments rather than\n * taken from the raw URL: it scopes idempotency keys, so it must be one\n * canonical string per endpoint and never carry a query string or an\n * alternative encoding of the same path\n */\n readonly path: string;\n /** Absent only for `createCheckoutSession` */\n readonly sessionId?: string;\n /** POST routes carry an ACP request document; the GET route carries none */\n readonly acceptsBody: boolean;\n}\n\nexport type AcpRouteResult =\n | { readonly kind: 'match'; readonly route: AcpRouteMatch }\n | { readonly kind: 'not-found' }\n | { readonly kind: 'method-not-allowed'; readonly allow: readonly string[] };\n\n/**\n * Matches `method` + `url` against the checkout routes below `mountPath`.\n *\n * The URL arrives raw from Node, so it still carries any query string and may\n * be percent-encoded; both are handled here rather than by every caller.\n */\nexport function matchAcpRoute(\n method: string | undefined,\n url: string | undefined,\n mountPath: string,\n): AcpRouteResult {\n const segments = routeSegments(url, mountPath);\n if (segments === undefined || segments[0] !== COLLECTION) return { kind: 'not-found' };\n\n const verb = (method ?? '').toUpperCase();\n\n // POST /checkout_sessions\n if (segments.length === 1) {\n if (verb !== 'POST') return { kind: 'method-not-allowed', allow: ['POST'] };\n return {\n kind: 'match',\n route: {\n operation: 'createCheckoutSession',\n path: endpointPath(mountPath, segments),\n acceptsBody: true,\n },\n };\n }\n\n const sessionId = segments[1];\n if (sessionId === undefined || !isSessionId(sessionId)) return { kind: 'not-found' };\n\n // GET|POST /checkout_sessions/{id}\n if (segments.length === 2) {\n if (verb === 'GET') {\n return {\n kind: 'match',\n route: {\n operation: 'getCheckoutSession',\n path: endpointPath(mountPath, segments),\n sessionId,\n acceptsBody: false,\n },\n };\n }\n if (verb === 'POST') {\n return {\n kind: 'match',\n route: {\n operation: 'updateCheckoutSession',\n path: endpointPath(mountPath, segments),\n sessionId,\n acceptsBody: true,\n },\n };\n }\n return { kind: 'method-not-allowed', allow: ['GET', 'POST'] };\n }\n\n // POST /checkout_sessions/{id}/{complete|cancel}\n if (segments.length === 3) {\n const operation =\n segments[2] === 'complete'\n ? 'completeCheckoutSession'\n : segments[2] === 'cancel'\n ? 'cancelCheckoutSession'\n : undefined;\n if (operation === undefined) return { kind: 'not-found' };\n if (verb !== 'POST') return { kind: 'method-not-allowed', allow: ['POST'] };\n return {\n kind: 'match',\n route: { operation, path: endpointPath(mountPath, segments), sessionId, acceptsBody: true },\n };\n }\n\n return { kind: 'not-found' };\n}\n\n// Accept decoded merchant ids such as `gid://shop/Checkout/1`. Reject empty\n// ids and ASCII control characters.\nfunction isSessionId(value: string): boolean {\n if (value.length === 0) return false;\n for (const char of value) {\n const code = char.charCodeAt(0);\n if (code < 0x20 || code === 0x7f) return false;\n }\n return true;\n}\n\n// Re-encode each segment so `/` inside a session id cannot become a route\n// separator or a distinct idempotency scope\nfunction endpointPath(mountPath: string, segments: readonly string[]): string {\n return `${mountPath.replace(/\\/+$/, '')}/${segments.map(encodeURIComponent).join('/')}`;\n}\n\n/**\n * Path segments below the mount, or `undefined` when the URL is not under it.\n *\n * A percent-encoded separator (`%2F`) is decoded per segment *after* the split,\n * so an id can never smuggle in an extra path segment.\n */\nfunction routeSegments(url: string | undefined, mountPath: string): readonly string[] | undefined {\n if (url === undefined) return undefined;\n const path = url.split('?')[0]?.split('#')[0] ?? '';\n const base = mountPath.replace(/\\/+$/, '');\n if (path !== base && !path.startsWith(`${base}/`)) return undefined;\n\n const rest = path.slice(base.length);\n const segments: string[] = [];\n for (const raw of rest.split('/')) {\n if (raw.length === 0) continue;\n if (raw.length > MAX_SEGMENT_LENGTH) return undefined;\n try {\n segments.push(decodeURIComponent(raw));\n } catch {\n // A malformed escape is not a route this adapter serves\n return undefined;\n }\n }\n return segments;\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://example.com/schemas/agentic-checkout/bundle.schema.json\",\n \"title\": \"Agentic Checkout — Schema Bundle\",\n \"$defs\": {\n \"VariantOption\": {\n \"description\": \"Represents a single variant option for a product (e.g., size, color, material)\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Variant attribute name (e.g., 'Size', 'Color')\"\n },\n \"value\": {\n \"type\": \"string\",\n \"description\": \"Variant attribute value (e.g., 'Large', 'Blue')\"\n }\n },\n \"required\": [\n \"name\",\n \"value\"\n ],\n \"example\": {\n \"name\": \"Color\",\n \"value\": \"Midnight Blue\"\n }\n },\n \"WeightInfo\": {\n \"description\": \"Product weight with unit of measurement\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"value\": {\n \"type\": \"number\",\n \"description\": \"Numeric weight value\"\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\n \"g\",\n \"kg\",\n \"oz\",\n \"lb\"\n ],\n \"description\": \"Unit of measurement for weight\"\n }\n },\n \"required\": [\n \"value\",\n \"unit\"\n ],\n \"example\": {\n \"value\": 250,\n \"unit\": \"g\"\n }\n },\n \"DimensionsInfo\": {\n \"description\": \"Physical dimensions of a product with unit of measurement\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"length\": {\n \"type\": \"number\",\n \"description\": \"Length dimension\"\n },\n \"width\": {\n \"type\": \"number\",\n \"description\": \"Width dimension\"\n },\n \"height\": {\n \"type\": \"number\",\n \"description\": \"Height dimension\"\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\n \"cm\",\n \"in\"\n ],\n \"description\": \"Unit of measurement for dimensions\"\n }\n },\n \"required\": [\n \"length\",\n \"width\",\n \"height\",\n \"unit\"\n ],\n \"example\": {\n \"length\": 15.5,\n \"width\": 10.2,\n \"height\": 5.8,\n \"unit\": \"cm\"\n }\n },\n \"DiscountDetail\": {\n \"description\": \"Information about a discount applied to the checkout or a specific item\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"code\": {\n \"type\": \"string\",\n \"description\": \"Discount code if applicable\"\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"percentage\",\n \"fixed\",\n \"bogo\",\n \"volume\"\n ],\n \"description\": \"Type of discount\"\n },\n \"amount\": {\n \"type\": \"integer\",\n \"description\": \"Discount amount in minor currency units (e.g. 100 cents for $1.00 or 100 for ¥100)\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Human-readable discount description\"\n },\n \"source\": {\n \"type\": \"string\",\n \"enum\": [\n \"coupon\",\n \"automatic\",\n \"loyalty\"\n ],\n \"description\": \"Source of the discount\"\n }\n },\n \"required\": [\n \"type\",\n \"amount\"\n ],\n \"example\": {\n \"code\": \"SAVE20\",\n \"type\": \"percentage\",\n \"amount\": 1600,\n \"description\": \"20% off your order\",\n \"source\": \"coupon\"\n }\n },\n \"Address\": {\n \"description\": \"Physical address for shipping, billing, or pickup locations\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Recipient name for this address\"\n },\n \"line_one\": {\n \"type\": \"string\",\n \"description\": \"Primary street address line\"\n },\n \"line_two\": {\n \"type\": \"string\",\n \"description\": \"Secondary address line (apartment, suite, etc.)\"\n },\n \"city\": {\n \"type\": \"string\",\n \"description\": \"City name\"\n },\n \"state\": {\n \"type\": \"string\",\n \"description\": \"State or province code\"\n },\n \"country\": {\n \"type\": \"string\",\n \"description\": \"ISO 3166-1 alpha-2 country code\"\n },\n \"postal_code\": {\n \"type\": \"string\",\n \"description\": \"Postal or ZIP code\"\n },\n \"company\": {\n \"type\": \"string\",\n \"description\": \"Postal or ZIP code\"\n }\n },\n \"required\": [\n \"name\",\n \"line_one\",\n \"city\",\n \"state\",\n \"country\",\n \"postal_code\"\n ],\n \"example\": {\n \"name\": \"Jane Doe\",\n \"line_one\": \"123 Main Street\",\n \"line_two\": \"Apt 4B\",\n \"city\": \"New York\",\n \"state\": \"NY\",\n \"country\": \"US\",\n \"postal_code\": \"10001\"\n }\n },\n \"AffiliateAttributionSource\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Context about where the attribution originated.\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"url\",\n \"platform\",\n \"unknown\"\n ],\n \"description\": \"The type of attribution source.\"\n },\n \"url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"Canonical content URL when type is 'url'.\"\n }\n },\n \"required\": [\n \"type\"\n ],\n \"example\": {\n \"type\": \"url\",\n \"url\": \"https://example.com/product-review\"\n }\n },\n \"AffiliateAttributionMetadata\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"oneOf\": [\n {\n \"type\": \"string\",\n \"description\": \"String metadata value\"\n },\n {\n \"type\": \"number\",\n \"description\": \"Numeric metadata value\"\n },\n {\n \"type\": \"boolean\",\n \"description\": \"Boolean metadata value\"\n }\n ]\n },\n \"description\": \"Flat key/value map for additional non-sensitive context. Keys must be strings; values must be strings, numbers, or booleans. Arrays and nested objects are NOT permitted.\",\n \"example\": {\n \"campaign_type\": \"influencer\",\n \"commission_rate\": 0.15,\n \"is_verified\": true\n }\n },\n \"AffiliateAttribution\": {\n \"type\": \"object\",\n \"description\": \"Optional affiliate attribution data for crediting third-party publishers. Write-only: not returned in responses. Forward compatibility: Servers SHOULD ignore unknown fields to support future extensions (per RFC §8.2).\",\n \"properties\": {\n \"provider\": {\n \"type\": \"string\",\n \"description\": \"Identifier for the attribution provider / affiliate network namespace (e.g., 'impact.com').\"\n },\n \"token\": {\n \"type\": \"string\",\n \"description\": \"Opaque provider-issued token for fraud-resistant validation. Treat as secret.\"\n },\n \"publisher_id\": {\n \"type\": \"string\",\n \"description\": \"Provider-scoped affiliate/publisher identifier. Required if token is omitted.\"\n },\n \"campaign_id\": {\n \"type\": \"string\",\n \"description\": \"Provider-scoped campaign identifier.\"\n },\n \"creative_id\": {\n \"type\": \"string\",\n \"description\": \"Provider-scoped creative identifier.\"\n },\n \"sub_id\": {\n \"type\": \"string\",\n \"description\": \"Provider-scoped sub-tracking identifier.\"\n },\n \"source\": {\n \"$ref\": \"#/$defs/AffiliateAttributionSource\"\n },\n \"issued_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC3339 timestamp when the attribution token was issued.\"\n },\n \"expires_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC3339 timestamp when the attribution token expires.\"\n },\n \"metadata\": {\n \"$ref\": \"#/$defs/AffiliateAttributionMetadata\"\n },\n \"touchpoint\": {\n \"type\": \"string\",\n \"enum\": [\n \"first\",\n \"last\"\n ],\n \"description\": \"Attribution touchpoint type. Use 'first' when capturing at session creation, 'last' when capturing at completion. Enables multi-touch attribution models.\"\n }\n },\n \"required\": [\n \"provider\"\n ],\n \"anyOf\": [\n {\n \"required\": [\n \"token\"\n ]\n },\n {\n \"required\": [\n \"publisher_id\"\n ]\n }\n ],\n \"example\": {\n \"provider\": \"impact.com\",\n \"token\": \"atp_01J8Z3WXYZ9ABC\",\n \"publisher_id\": \"pub_123\",\n \"campaign_id\": \"camp_summer2026\",\n \"touchpoint\": \"first\",\n \"source\": {\n \"type\": \"url\",\n \"url\": \"https://example.com/product-review\"\n },\n \"issued_at\": \"2026-02-11T10:00:00Z\",\n \"expires_at\": \"2026-02-11T11:00:00Z\"\n }\n },\n \"FulfillmentDetails\": {\n \"description\": \"Details about how items will be fulfilled (shipping, pickup, or delivery information)\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Full name for fulfillment contact\"\n },\n \"phone_number\": {\n \"type\": \"string\",\n \"description\": \"Contact phone number. E.164 format recommended (e.g., +15551234567) for global interoperability and SMS/delivery carrier systems.\"\n },\n \"email\": {\n \"type\": \"string\",\n \"format\": \"email\",\n \"description\": \"Contact email address\"\n },\n \"address\": {\n \"$ref\": \"#/$defs/Address\",\n \"description\": \"Fulfillment address\"\n }\n },\n \"example\": {\n \"name\": \"John Smith\",\n \"phone_number\": \"15551234567\",\n \"email\": \"john.smith@example.com\",\n \"address\": {\n \"name\": \"John Smith\",\n \"line_one\": \"555 Golden Gate Avenue\",\n \"line_two\": \"Apt 401\",\n \"city\": \"San Francisco\",\n \"state\": \"CA\",\n \"country\": \"US\",\n \"postal_code\": \"94102\"\n }\n }\n },\n \"CompanyInfo\": {\n \"description\": \"Information about a company or organization associated with the buyer\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Company or organization name\"\n },\n \"tax_id\": {\n \"type\": \"string\",\n \"description\": \"Business tax identification number\"\n },\n \"department\": {\n \"type\": \"string\",\n \"description\": \"Department within the organization\"\n },\n \"cost_center\": {\n \"type\": \"string\",\n \"description\": \"Cost center code for internal accounting\"\n }\n },\n \"required\": [\n \"name\"\n ],\n \"example\": {\n \"name\": \"Acme Corporation\",\n \"tax_id\": \"12-3456789\",\n \"department\": \"Marketing\",\n \"cost_center\": \"CC-2001\"\n }\n },\n \"LoyaltyInfo\": {\n \"description\": \"Loyalty program information including membership details and rewards balance\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"tier\": {\n \"type\": \"string\",\n \"description\": \"Loyalty program tier level\"\n },\n \"points_balance\": {\n \"type\": \"integer\",\n \"description\": \"Current loyalty points balance\"\n },\n \"member_since\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the customer joined the loyalty program\"\n }\n },\n \"example\": {\n \"tier\": \"Gold\",\n \"points_balance\": 5000,\n \"member_since\": \"2024-01-15T09:00:00Z\"\n }\n },\n \"TaxExemption\": {\n \"description\": \"Tax exemption information including exemption type and applicable regions\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"certificate_id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for the tax exemption certificate\"\n },\n \"certificate_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"resale\",\n \"exempt_organization\",\n \"government\"\n ],\n \"description\": \"Type of tax exemption certificate\"\n },\n \"exempt_regions\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Region code where tax exemption applies (e.g., state abbreviation)\"\n },\n \"description\": \"List of regions where the exemption applies (e.g., state codes)\"\n },\n \"expires_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the exemption certificate expires\"\n }\n },\n \"required\": [\n \"certificate_id\",\n \"certificate_type\"\n ],\n \"example\": {\n \"certificate_id\": \"cert_12345\",\n \"certificate_type\": \"resale\",\n \"exempt_regions\": [\n \"CA\",\n \"NY\",\n \"TX\"\n ],\n \"expires_at\": \"2027-12-31T23:59:59Z\"\n }\n },\n \"Buyer\": {\n \"description\": \"Information about the buyer including contact details, company info, and loyalty status\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"first_name\": {\n \"type\": \"string\",\n \"description\": \"Buyer's first name\"\n },\n \"last_name\": {\n \"type\": \"string\",\n \"description\": \"Buyer's last name\"\n },\n \"full_name\": {\n \"type\": \"string\",\n \"description\": \"Buyer's full name\"\n },\n \"email\": {\n \"type\": \"string\",\n \"format\": \"email\",\n \"description\": \"Buyer's email address\"\n },\n \"phone_number\": {\n \"type\": \"string\",\n \"description\": \"Buyer's phone number\"\n },\n \"customer_id\": {\n \"type\": \"string\",\n \"description\": \"Merchant's internal customer identifier\"\n },\n \"account_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"guest\",\n \"registered\",\n \"business\"\n ],\n \"description\": \"Type of buyer account\"\n },\n \"authentication_status\": {\n \"type\": \"string\",\n \"enum\": [\n \"authenticated\",\n \"guest\",\n \"requires_signin\"\n ],\n \"description\": \"Buyer's authentication status\"\n },\n \"company\": {\n \"$ref\": \"#/$defs/CompanyInfo\",\n \"description\": \"Company information for business buyers\"\n },\n \"loyalty\": {\n \"$ref\": \"#/$defs/LoyaltyInfo\",\n \"description\": \"Loyalty program information\"\n },\n \"tax_exemption\": {\n \"$ref\": \"#/$defs/TaxExemption\",\n \"description\": \"Tax exemption details\"\n }\n },\n \"required\": [\n \"email\"\n ],\n \"example\": {\n \"first_name\": \"Sarah\",\n \"last_name\": \"Johnson\",\n \"full_name\": \"Sarah Johnson\",\n \"email\": \"sarah.johnson@example.com\",\n \"phone_number\": \"+1-415-555-0123\",\n \"customer_id\": \"cust_abc123\",\n \"account_type\": \"registered\",\n \"authentication_status\": \"authenticated\"\n }\n },\n \"InterventionCapabilities\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Intervention capabilities. Context-specific fields: display_context, redirect_context, max_redirects, max_interaction_depth (requests only). required, enforcement (responses only). supported field contains intersection in responses.\",\n \"properties\": {\n \"supported\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\n \"3ds\",\n \"biometric\",\n \"address_verification\"\n ]\n },\n \"description\": \"Intervention types supported. Agent request: Interventions the agent can handle. Seller response: Intersection of supported interventions.\"\n },\n \"required\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\n \"3ds\",\n \"biometric\"\n ]\n },\n \"description\": \"Intervention methods required for this session (seller only).\"\n },\n \"enforcement\": {\n \"type\": \"string\",\n \"enum\": [\n \"always\",\n \"conditional\",\n \"optional\"\n ],\n \"description\": \"When required interventions are enforced (seller only).\"\n },\n \"display_context\": {\n \"type\": \"string\",\n \"enum\": [\n \"native\",\n \"webview\",\n \"modal\",\n \"redirect\"\n ],\n \"description\": \"How the Agent presents interventions (agent only).\"\n },\n \"redirect_context\": {\n \"type\": \"string\",\n \"enum\": [\n \"in_app\",\n \"external_browser\",\n \"none\"\n ],\n \"description\": \"How the Agent handles redirects (agent only).\"\n },\n \"max_redirects\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Maximum number of redirects the Agent can handle (agent only).\"\n },\n \"max_interaction_depth\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Maximum depth of nested interactions the Agent can handle (agent only).\"\n }\n },\n \"example\": {\n \"supported\": [\n \"3ds\",\n \"address_verification\"\n ],\n \"display_context\": \"native\",\n \"redirect_context\": \"in_app\",\n \"max_redirects\": 3,\n \"max_interaction_depth\": 2\n }\n },\n \"Capabilities\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Capabilities object used in requests and responses. Context determines the party: requests are from Agents, responses are from Sellers. Seller responses contain the intersection of supported interventions.\",\n \"properties\": {\n \"payment\": {\n \"$ref\": \"#/$defs/Payment\"\n },\n \"interventions\": {\n \"$ref\": \"#/$defs/InterventionCapabilities\"\n },\n \"extensions\": {\n \"oneOf\": [\n {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Extension identifier string\"\n },\n \"uniqueItems\": true,\n \"description\": \"Extensions the agent understands (request). Simple identifiers like 'discount'.\"\n },\n {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/ExtensionDeclaration\"\n },\n \"uniqueItems\": true,\n \"description\": \"Active extensions for this session (response). Objects with name, extends, schema, spec.\"\n }\n ],\n \"description\": \"Extensions supported by the party. Requests: array of extension identifiers. Responses: array of extension declaration objects.\"\n }\n },\n \"example\": {\n \"interventions\": {\n \"supported\": [\n \"3ds\"\n ],\n \"display_context\": \"native\"\n },\n \"extensions\": [\n \"discount\",\n \"affiliate_attribution\"\n ]\n }\n },\n \"ExtensionDeclaration\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Extension declaration in capabilities.extensions (response). Describes an active extension and which schema fields it adds.\",\n \"required\": [\n \"name\"\n ],\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z][a-z0-9_-]*(@\\\\d{4}-\\\\d{2}-\\\\d{2})?$|^[a-z][a-z0-9]*(?:\\\\.[a-z][a-z0-9_-]*)+(@\\\\d{4}-\\\\d{2}-\\\\d{2})?$\",\n \"description\": \"Unique identifier for the extension.\"\n },\n \"extends\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\$\\\\.[A-Za-z][A-Za-z0-9]*(\\\\.[A-Za-z][A-Za-z0-9_]*)*$\",\n \"description\": \"JSONPath expression identifying a schema field added by this extension\"\n },\n \"uniqueItems\": true,\n \"description\": \"JSONPath expressions identifying the schema fields added by this extension. Format: $.<SchemaName>.<fieldName> (e.g., $.CheckoutSession.discounts).\"\n },\n \"schema\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the extension's JSON Schema definition.\"\n },\n \"spec\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the extension's specification document.\"\n }\n },\n \"example\": {\n \"name\": \"discount\",\n \"extends\": [\n \"$.CheckoutSession.discounts\",\n \"$.CheckoutSessionCreateRequest.coupons\"\n ],\n \"schema\": \"https://example.com/schemas/extensions/discount.schema.json\",\n \"spec\": \"https://example.com/specs/extensions/discount\"\n }\n },\n \"PaymentMethodObject\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Payment method with additional constraints (e.g., card brands, PSP routing)\",\n \"properties\": {\n \"method\": {\n \"type\": \"string\",\n \"description\": \"The payment method identifier\"\n },\n \"brands\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\n \"visa\",\n \"mastercard\",\n \"amex\",\n \"discover\",\n \"diners\",\n \"jcb\",\n \"unionpay\",\n \"eftpos\",\n \"interac\"\n ]\n },\n \"description\": \"Specific card brands/networks accepted\"\n },\n \"funding_types\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\n \"credit\",\n \"debit\",\n \"prepaid\"\n ]\n },\n \"description\": \"For card methods, funding types accepted\"\n },\n \"providers\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Payment service provider identifier\"\n },\n \"description\": \"Optional PSP routing information\"\n }\n },\n \"required\": [\n \"method\"\n ],\n \"example\": {\n \"method\": \"card\",\n \"brands\": [\n \"visa\",\n \"mastercard\"\n ],\n \"providers\": [\n \"stripe\",\n \"adyen\"\n ]\n }\n },\n \"Item\": {\n \"description\": \"A purchasable item with variant options (e.g., size, color) and quantity\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for the item\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Display name of the item\"\n },\n \"unit_amount\": {\n \"type\": \"integer\",\n \"description\": \"Price per unit in minor currency units (e.g. 100 cents for $1.00 or 100 for ¥100)\"\n }\n },\n \"required\": [\n \"id\"\n ],\n \"example\": {\n \"id\": \"item_123\",\n \"name\": \"Wireless Headphones\",\n \"unit_amount\": 7999\n }\n },\n \"Disclosure\": {\n \"description\": \"Legal disclosure or terms that must be acknowledged by the buyer\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"disclaimer\"\n ],\n \"description\": \"Type of disclosure\"\n },\n \"content_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"plain\",\n \"markdown\"\n ],\n \"description\": \"Format of the disclosure content. When set to 'markdown', content MUST conform to CommonMark (https://spec.commonmark.org/0.31.2/). Raw HTML elements MUST NOT be included. When set to 'plain', content is plain text with no formatting.\"\n },\n \"content\": {\n \"type\": \"string\",\n \"description\": \"The disclosure text content. When content_type is 'markdown', this MUST be valid CommonMark with no raw HTML. Agents MUST render using a CommonMark-compliant parser with raw HTML output disabled or sanitized.\"\n }\n },\n \"required\": [\n \"type\",\n \"content_type\",\n \"content\"\n ],\n \"example\": {\n \"type\": \"disclaimer\",\n \"content_type\": \"plain\",\n \"content\": \"This product contains small parts and is not suitable for children under 3 years.\"\n }\n },\n \"CustomAttribute\": {\n \"description\": \"Custom key-value attribute for merchant-specific metadata on line items\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"display_name\": {\n \"type\": \"string\",\n \"description\": \"Human-readable label for the attribute\"\n },\n \"value\": {\n \"type\": \"string\",\n \"description\": \"Attribute value\"\n }\n },\n \"required\": [\n \"display_name\",\n \"value\"\n ],\n \"example\": {\n \"display_name\": \"Engraving\",\n \"value\": \"Happy Birthday!\"\n }\n },\n \"MarketplaceSellerDetails\": {\n \"description\": \"Information about a third-party seller in a marketplace model\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Name of the marketplace seller or vendor\"\n }\n },\n \"required\": [\n \"name\"\n ],\n \"example\": {\n \"name\": \"TechGear Store\"\n }\n },\n \"PaymentHandler\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Payment handler configuration and capabilities\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Seller-defined handler identifier\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Handler name in reverse-DNS format (e.g., dev.acp.tokenized.card)\"\n },\n \"display_name\": {\n \"type\": \"string\",\n \"description\": \"Human-readable name for UI (e.g., Credit Card). Use when showing payment options to the buyer.\"\n },\n \"version\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{4}-\\\\d{2}-\\\\d{2}$\",\n \"description\": \"Handler version in YYYY-MM-DD format\"\n },\n \"spec\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to handler specification\"\n },\n \"requires_delegate_payment\": {\n \"type\": \"boolean\",\n \"description\": \"Whether this handler requires using delegate_payment API\"\n },\n \"requires_pci_compliance\": {\n \"type\": \"boolean\",\n \"description\": \"Whether this handler routes PCI DSS sensitive data\"\n },\n \"psp\": {\n \"type\": \"string\",\n \"description\": \"Payment Service Provider identifier\"\n },\n \"config_schema\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to JSON Schema for handler configuration\"\n },\n \"instrument_schemas\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to a JSON Schema defining accepted payment instrument format\"\n },\n \"description\": \"URLs to JSON Schemas for payment instruments\"\n },\n \"config\": {\n \"type\": \"object\",\n \"description\": \"Handler-specific configuration\"\n },\n \"display_order\": {\n \"type\": \"integer\",\n \"description\": \"Optional merchant-suggested display order (lower = higher preference). Suggestive only; platform/agent MAY reorder.\"\n }\n },\n \"required\": [\n \"id\",\n \"name\",\n \"version\",\n \"spec\",\n \"requires_delegate_payment\",\n \"requires_pci_compliance\",\n \"psp\",\n \"config_schema\",\n \"instrument_schemas\",\n \"config\"\n ],\n \"example\": {\n \"id\": \"handler_stripe_01\",\n \"name\": \"Stripe\",\n \"type\": \"direct\",\n \"instrument_schemas\": [\n \"https://example.com/schemas/payment/card.json\"\n ]\n }\n },\n \"Payment\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Payment configuration with handlers\",\n \"properties\": {\n \"handlers\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/PaymentHandler\"\n },\n \"description\": \"Available payment handlers\"\n }\n },\n \"required\": [\n \"handlers\"\n ],\n \"example\": {\n \"handlers\": []\n }\n },\n \"LineItem\": {\n \"description\": \"A line item in the checkout representing a product with pricing, discounts, and fulfillment details\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for the line item\"\n },\n \"item\": {\n \"$ref\": \"#/$defs/Item\",\n \"description\": \"Reference to the item being purchased\"\n },\n \"quantity\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Number of units for this line item\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Display name of the line item\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Detailed description of the line item\"\n },\n \"images\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"Image URL for the product\"\n },\n \"description\": \"Array of image URLs for this line item\"\n },\n \"unit_amount\": {\n \"type\": \"integer\",\n \"description\": \"The unit price of the line item in the smallest currency unit (e.g., cents for USD)\"\n },\n \"disclosures\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Disclosure\"\n },\n \"description\": \"Legal disclosures or disclaimers for this item\"\n },\n \"custom_attributes\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/CustomAttribute\"\n },\n \"description\": \"Custom attributes specific to this line item\"\n },\n \"marketplace_seller_details\": {\n \"$ref\": \"#/$defs/MarketplaceSellerDetails\",\n \"description\": \"Seller details for marketplace items\"\n },\n \"product_id\": {\n \"type\": \"string\",\n \"description\": \"Merchant's product identifier\"\n },\n \"sku\": {\n \"type\": \"string\",\n \"description\": \"Stock keeping unit identifier\"\n },\n \"variant_id\": {\n \"type\": \"string\",\n \"description\": \"Product variant identifier\"\n },\n \"category\": {\n \"type\": \"string\",\n \"description\": \"Product category\"\n },\n \"tags\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Product tag or category\"\n },\n \"description\": \"Product tags or labels\"\n },\n \"weight\": {\n \"$ref\": \"#/$defs/WeightInfo\",\n \"description\": \"Weight information for the item\"\n },\n \"dimensions\": {\n \"$ref\": \"#/$defs/DimensionsInfo\",\n \"description\": \"Dimensions for the item\"\n },\n \"availability_status\": {\n \"type\": \"string\",\n \"enum\": [\n \"in_stock\",\n \"low_stock\",\n \"out_of_stock\",\n \"backorder\",\n \"pre_order\"\n ],\n \"description\": \"Current availability status of the item\"\n },\n \"available_quantity\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Quantity currently available for purchase\"\n },\n \"max_quantity_per_order\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Maximum quantity allowed per order\"\n },\n \"fulfillable_on\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when item becomes available for fulfillment\"\n },\n \"variant_options\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/VariantOption\"\n },\n \"description\": \"Selected product variant options (e.g., size, color)\"\n },\n \"discount_details\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/DiscountDetail\"\n },\n \"description\": \"Line-item level discount details\"\n },\n \"tax_exempt\": {\n \"type\": \"boolean\",\n \"description\": \"Whether this line item is tax exempt\"\n },\n \"tax_exemption_reason\": {\n \"type\": \"string\",\n \"description\": \"Reason for tax exemption if applicable\"\n },\n \"parent_id\": {\n \"type\": \"string\",\n \"description\": \"Reference to parent line item for bundled products\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Line-item level totals breakdown including base_amount, discount, subtotal, tax, and total\"\n }\n },\n \"required\": [\n \"id\",\n \"item\",\n \"quantity\",\n \"totals\"\n ],\n \"example\": {\n \"id\": \"item_001\",\n \"product_id\": \"prod_tshirt_blue_m\",\n \"name\": \"Organic Cotton T-Shirt\",\n \"quantity\": 2,\n \"base_amount\": 2900,\n \"discount\": 0,\n \"subtotal\": 5800,\n \"tax\": 464,\n \"total\": 6264,\n \"currency\": \"usd\",\n \"image_url\": \"https://example.com/images/tshirt-blue.jpg\"\n }\n },\n \"TaxBreakdownItem\": {\n \"description\": \"Breakdown of tax amounts by type, jurisdiction, or rate\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"jurisdiction\": {\n \"type\": \"string\",\n \"description\": \"Tax jurisdiction name (e.g., 'California State Tax', 'City of San Francisco')\"\n },\n \"rate\": {\n \"type\": \"number\",\n \"description\": \"Tax rate as a decimal (e.g., 0.0875 for 8.75%)\"\n },\n \"amount\": {\n \"type\": \"integer\",\n \"description\": \"Tax amount in minor currency units (e.g. 100 cents for $1.00 or 100 for ¥100)\"\n }\n },\n \"required\": [\n \"jurisdiction\",\n \"rate\",\n \"amount\"\n ],\n \"example\": {\n \"name\": \"State Sales Tax\",\n \"amount\": 464,\n \"rate\": 0.08\n }\n },\n \"Total\": {\n \"description\": \"Total amounts for the checkout including subtotal, discounts, tax, shipping, and final total\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"items_base_amount\",\n \"items_discount\",\n \"subtotal\",\n \"discount\",\n \"fulfillment\",\n \"tax\",\n \"fee\",\n \"gift_wrap\",\n \"tip\",\n \"store_credit\",\n \"total\",\n \"amount_refunded\"\n ],\n \"description\": \"Type of total line item\"\n },\n \"display_text\": {\n \"type\": \"string\",\n \"description\": \"Localized display text for this total\"\n },\n \"amount\": {\n \"type\": \"integer\",\n \"description\": \"Amount in minor currency units (e.g. 100 cents for $1.00 or 100 for ¥100)\"\n },\n \"presentment_amount\": {\n \"type\": \"integer\",\n \"description\": \"Amount in presentment currency minor units if different from settlement currency\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Additional descriptive text for this total\"\n },\n \"breakdown\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/TaxBreakdownItem\"\n },\n \"description\": \"Detailed breakdown for tax totals\"\n }\n },\n \"required\": [\n \"type\",\n \"display_text\",\n \"amount\"\n ],\n \"example\": {\n \"currency\": \"usd\",\n \"subtotal\": 5800,\n \"discount\": 0,\n \"tax\": 464,\n \"shipping\": 500,\n \"total\": 6764\n }\n },\n \"FulfillmentOptionPickup\": {\n \"description\": \"In-store or curbside pickup fulfillment option with pickup location details\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"pickup\",\n \"description\": \"Fulfillment type discriminator\"\n },\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for this fulfillment option\"\n },\n \"title\": {\n \"type\": \"string\",\n \"description\": \"Display title for this pickup option\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Additional details about this pickup option\"\n },\n \"location\": {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Location name\"\n },\n \"address\": {\n \"$ref\": \"#/$defs/Address\",\n \"description\": \"Pickup address\"\n },\n \"phone\": {\n \"type\": \"string\",\n \"description\": \"Location phone number\"\n },\n \"instructions\": {\n \"type\": \"string\",\n \"description\": \"Special pickup instructions\"\n }\n },\n \"required\": [\n \"name\",\n \"address\"\n ],\n \"description\": \"Pickup location details\"\n },\n \"pickup_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"in_store\",\n \"curbside\",\n \"locker\"\n ],\n \"description\": \"Type of pickup method\"\n },\n \"ready_by\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when order will be ready for pickup\"\n },\n \"pickup_by\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp by which order must be picked up\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Cost breakdown for this fulfillment option\"\n }\n },\n \"required\": [\n \"type\",\n \"id\",\n \"title\",\n \"location\",\n \"totals\"\n ],\n \"example\": {\n \"id\": \"pickup_01\",\n \"type\": \"pickup\",\n \"name\": \"Store Pickup\",\n \"cost\": 0,\n \"currency\": \"usd\",\n \"address\": {\n \"name\": \"Downtown Store\",\n \"line_one\": \"123 Main St\",\n \"city\": \"San Francisco\",\n \"state\": \"CA\",\n \"country\": \"US\",\n \"postal_code\": \"94102\"\n }\n }\n },\n \"FulfillmentOptionLocalDelivery\": {\n \"description\": \"Local delivery fulfillment option with delivery address and scheduling details\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"local_delivery\",\n \"description\": \"Fulfillment type discriminator\"\n },\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for this fulfillment option\"\n },\n \"title\": {\n \"type\": \"string\",\n \"description\": \"Display title for this local delivery option\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Additional details about this delivery option\"\n },\n \"delivery_window\": {\n \"type\": \"object\",\n \"properties\": {\n \"start\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp for delivery window start\"\n },\n \"end\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp for delivery window end\"\n }\n },\n \"required\": [\n \"start\",\n \"end\"\n ],\n \"description\": \"Expected delivery time window\"\n },\n \"service_area\": {\n \"type\": \"object\",\n \"properties\": {\n \"radius_miles\": {\n \"type\": \"number\",\n \"description\": \"Delivery radius in miles\"\n },\n \"center_postal_code\": {\n \"type\": \"string\",\n \"description\": \"Center point postal code for delivery radius\"\n }\n },\n \"description\": \"Geographic service area for local delivery\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Cost breakdown for this fulfillment option\"\n }\n },\n \"required\": [\n \"type\",\n \"id\",\n \"title\",\n \"totals\"\n ],\n \"example\": {\n \"id\": \"delivery_01\",\n \"type\": \"local_delivery\",\n \"name\": \"Same Day Delivery\",\n \"cost\": 999,\n \"currency\": \"usd\",\n \"address\": {\n \"name\": \"Jane Doe\",\n \"line_one\": \"456 Oak Ave\",\n \"city\": \"San Francisco\",\n \"state\": \"CA\",\n \"country\": \"US\",\n \"postal_code\": \"94103\"\n }\n }\n },\n \"FulfillmentOptionShipping\": {\n \"description\": \"Shipping fulfillment option with carrier, service level, and delivery estimates\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"shipping\",\n \"description\": \"Fulfillment type discriminator\"\n },\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for this fulfillment option\"\n },\n \"title\": {\n \"type\": \"string\",\n \"description\": \"Display title for this shipping option (e.g., 'Standard Shipping', 'Express')\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Additional details about this shipping option\"\n },\n \"carrier\": {\n \"type\": \"string\",\n \"description\": \"Shipping carrier name (e.g., 'USPS', 'FedEx')\"\n },\n \"earliest_delivery_time\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp for earliest expected delivery\"\n },\n \"latest_delivery_time\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp for latest expected delivery\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Cost breakdown for this fulfillment option\"\n }\n },\n \"required\": [\n \"type\",\n \"id\",\n \"title\",\n \"totals\"\n ],\n \"example\": {\n \"id\": \"ship_01\",\n \"type\": \"shipping\",\n \"name\": \"Standard Shipping\",\n \"cost\": 500,\n \"currency\": \"usd\",\n \"carrier\": \"USPS\",\n \"service_level\": \"ground\"\n }\n },\n \"FulfillmentOptionDigital\": {\n \"description\": \"Digital delivery fulfillment option for downloadable or streaming content\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"digital\",\n \"description\": \"Fulfillment type discriminator\"\n },\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for this fulfillment option\"\n },\n \"title\": {\n \"type\": \"string\",\n \"description\": \"Display title for this digital delivery option\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Additional details about digital delivery method\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Cost breakdown for this fulfillment option\"\n }\n },\n \"required\": [\n \"type\",\n \"id\",\n \"title\",\n \"totals\"\n ],\n \"example\": {\n \"id\": \"digital_01\",\n \"type\": \"digital\",\n \"name\": \"Instant Download\",\n \"cost\": 0,\n \"currency\": \"usd\"\n }\n },\n \"SelectedFulfillmentOption\": {\n \"description\": \"Fulfillment option selected by the buyer for specific line items\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"shipping\",\n \"digital\",\n \"pickup\",\n \"local_delivery\"\n ],\n \"description\": \"Type of fulfillment option selected\"\n },\n \"option_id\": {\n \"type\": \"string\",\n \"description\": \"ID of the selected fulfillment option\"\n },\n \"item_ids\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Line item identifier\"\n },\n \"description\": \"List of line item IDs associated with this fulfillment option\"\n }\n },\n \"required\": [\n \"type\",\n \"option_id\",\n \"item_ids\"\n ],\n \"example\": {\n \"id\": \"ship_01\",\n \"type\": \"shipping\",\n \"item_ids\": [\n \"item_001\",\n \"item_002\"\n ]\n }\n },\n \"GiftWrap\": {\n \"description\": \"Gift wrapping option with associated cost and customization details\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"enabled\": {\n \"type\": \"boolean\",\n \"description\": \"Whether gift wrapping is enabled for this order\"\n },\n \"style\": {\n \"type\": \"string\",\n \"enum\": [\n \"birthday\",\n \"holiday\",\n \"elegant\"\n ],\n \"description\": \"Gift wrap style selected\"\n },\n \"charge\": {\n \"type\": \"integer\",\n \"description\": \"Additional charge for gift wrapping in minor currency units (e.g. 100 cents for $1.00 or 100 for ¥100)\"\n }\n },\n \"required\": [\n \"enabled\"\n ],\n \"example\": {\n \"available\": true,\n \"cost\": 500,\n \"currency\": \"usd\",\n \"message\": \"Happy Birthday!\"\n }\n },\n \"SplitPayment\": {\n \"description\": \"Split payment configuration allowing payment across multiple methods or parties\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\",\n \"description\": \"Payment amount in minor currency units (e.g. 100 cents for $1.00 or 100 for ¥100) for this split\"\n }\n },\n \"required\": [\n \"amount\"\n ],\n \"example\": {\n \"enabled\": true,\n \"methods\": [\n \"card\",\n \"paypal\"\n ]\n }\n },\n \"FulfillmentGroup\": {\n \"description\": \"Group of line items that share the same fulfillment method and destination\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for this fulfillment group\"\n },\n \"item_ids\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Line item identifier in this fulfillment group\"\n },\n \"description\": \"List of line item IDs in this fulfillment group\"\n },\n \"destination_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"shipping\",\n \"pickup\",\n \"local_delivery\",\n \"digital\"\n ],\n \"description\": \"Type of fulfillment for this group\"\n },\n \"fulfillment_details\": {\n \"$ref\": \"#/$defs/FulfillmentDetails\",\n \"description\": \"Fulfillment contact and address details\"\n },\n \"location_id\": {\n \"type\": \"string\",\n \"description\": \"Location identifier for pickup or local delivery\"\n },\n \"instructions\": {\n \"type\": \"string\",\n \"description\": \"Special fulfillment instructions\"\n }\n },\n \"required\": [\n \"id\",\n \"item_ids\",\n \"destination_type\"\n ],\n \"example\": {\n \"id\": \"fg_01\",\n \"fulfillment_option_id\": \"ship_01\",\n \"item_ids\": [\n \"item_001\",\n \"item_002\"\n ]\n }\n },\n \"EstimatedDelivery\": {\n \"description\": \"Estimated delivery date range for a fulfillment option\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"earliest\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp for earliest expected delivery\"\n },\n \"latest\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp for latest expected delivery\"\n }\n },\n \"required\": [\n \"earliest\",\n \"latest\"\n ],\n \"example\": {\n \"earliest\": \"2026-02-15\",\n \"latest\": \"2026-02-20\"\n }\n },\n \"OrderConfirmation\": {\n \"description\": \"Order confirmation details including order number and tracking information\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"confirmation_number\": {\n \"type\": \"string\",\n \"description\": \"Order confirmation number\"\n },\n \"confirmation_email_sent\": {\n \"type\": \"boolean\",\n \"description\": \"Whether a confirmation email has been sent\"\n },\n \"receipt_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the order receipt\"\n },\n \"invoice_number\": {\n \"type\": \"string\",\n \"description\": \"Invoice number if generated\"\n },\n \"order_notes\": {\n \"type\": \"string\",\n \"description\": \"Echo of order_notes attached to the order.\"\n }\n },\n \"example\": {\n \"order_id\": \"ord_abc123\",\n \"order_number\": \"12345\",\n \"confirmation_url\": \"https://example.com/orders/ord_abc123\"\n }\n },\n \"SupportInfo\": {\n \"description\": \"Customer support contact information including email, phone, and URL\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"email\": {\n \"type\": \"string\",\n \"format\": \"email\",\n \"description\": \"Support contact email\"\n },\n \"phone\": {\n \"type\": \"string\",\n \"description\": \"Support contact phone number\"\n },\n \"hours\": {\n \"type\": \"string\",\n \"description\": \"Support hours of operation\"\n },\n \"help_center_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to merchant's help center\"\n }\n },\n \"example\": {\n \"email\": \"support@example.com\",\n \"phone\": \"+1-800-555-0123\",\n \"url\": \"https://example.com/support\"\n }\n },\n \"MessageInfo\": {\n \"description\": \"Informational message to display to the buyer during checkout\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"info\",\n \"description\": \"Message type discriminator\"\n },\n \"severity\": {\n \"type\": \"string\",\n \"enum\": [\n \"info\",\n \"low\",\n \"medium\",\n \"high\",\n \"critical\"\n ],\n \"description\": \"Severity level of this informational message\"\n },\n \"resolution\": {\n \"type\": \"string\",\n \"enum\": [\n \"recoverable\",\n \"requires_buyer_input\",\n \"requires_buyer_review\"\n ],\n \"description\": \"Who resolves this message. 'recoverable': agent can fix via API. 'requires_buyer_input': buyer must provide info. 'requires_buyer_review': buyer must authorize.\"\n },\n \"param\": {\n \"type\": \"string\",\n \"description\": \"RFC 9535 JSONPath\"\n },\n \"content_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"plain\",\n \"markdown\"\n ],\n \"description\": \"Format of the message content. When set to 'markdown', content MUST conform to CommonMark (https://spec.commonmark.org/0.31.2/). Raw HTML elements MUST NOT be included. When set to 'plain', content is plain text with no formatting.\"\n },\n \"content\": {\n \"type\": \"string\",\n \"description\": \"Informational message text. When content_type is 'markdown', this MUST be valid CommonMark with no raw HTML. Agents MUST render using a CommonMark-compliant parser with raw HTML output disabled or sanitized.\"\n }\n },\n \"required\": [\n \"type\",\n \"content_type\",\n \"content\"\n ],\n \"example\": {\n \"id\": \"msg_info_01\",\n \"message\": \"Free shipping on orders over $50\",\n \"display_context\": \"banner\"\n }\n },\n \"MessageWarning\": {\n \"description\": \"Warning message to display to the buyer during checkout (non-blocking)\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"warning\",\n \"description\": \"Message type discriminator\"\n },\n \"code\": {\n \"type\": \"string\",\n \"enum\": [\n \"low_stock\",\n \"high_demand\",\n \"shipping_delay\",\n \"price_change\",\n \"expiring_promotion\",\n \"limited_availability\",\n \"discount_code_expired\",\n \"discount_code_invalid\",\n \"discount_code_already_applied\",\n \"discount_code_combination_disallowed\",\n \"discount_code_minimum_not_met\",\n \"discount_code_user_not_logged_in\",\n \"discount_code_user_ineligible\",\n \"discount_code_usage_limit_reached\"\n ],\n \"description\": \"Warning code indicating the type of warning\"\n },\n \"severity\": {\n \"type\": \"string\",\n \"enum\": [\n \"info\",\n \"low\",\n \"medium\",\n \"high\",\n \"critical\"\n ],\n \"description\": \"Severity level of this warning\"\n },\n \"resolution\": {\n \"type\": \"string\",\n \"enum\": [\n \"recoverable\",\n \"requires_buyer_input\",\n \"requires_buyer_review\"\n ],\n \"description\": \"Who resolves this message. 'recoverable': agent can fix via API. 'requires_buyer_input': buyer must provide info. 'requires_buyer_review': buyer must authorize.\"\n },\n \"param\": {\n \"type\": \"string\",\n \"description\": \"RFC 9535 JSONPath\"\n },\n \"content_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"plain\",\n \"markdown\"\n ],\n \"description\": \"Format of the warning message content. When set to 'markdown', content MUST conform to CommonMark (https://spec.commonmark.org/0.31.2/). Raw HTML elements MUST NOT be included. When set to 'plain', content is plain text with no formatting.\"\n },\n \"content\": {\n \"type\": \"string\",\n \"description\": \"Warning message text. When content_type is 'markdown', this MUST be valid CommonMark with no raw HTML. Agents MUST render using a CommonMark-compliant parser with raw HTML output disabled or sanitized.\"\n }\n },\n \"required\": [\n \"type\",\n \"code\",\n \"content_type\",\n \"content\"\n ],\n \"example\": {\n \"id\": \"msg_warn_01\",\n \"message\": \"Only 2 items left in stock\",\n \"code\": \"low_stock\",\n \"param\": \"$.items[0]\"\n }\n },\n \"MessageError\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Business-logic error within a valid CheckoutSession response. Used in messages[] on 2xx responses when the session is valid but has actionable issues (e.g. status \\\"not_ready_for_payment\\\"). The agent can respond by asking the buyer for corrections or trying alternatives. Use MessageError—not Error—when you can return a valid CheckoutSession and the problem is conversational (e.g. invalid email → code \\\"invalid\\\" and param \\\"$.buyer.email\\\"; out of stock → code \\\"out_of_stock\\\" and param \\\"$.items[0]\\\").\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"error\",\n \"description\": \"Message type discriminator\"\n },\n \"code\": {\n \"type\": \"string\",\n \"enum\": [\n \"missing\",\n \"invalid\",\n \"out_of_stock\",\n \"payment_declined\",\n \"requires_sign_in\",\n \"requires_3ds\",\n \"low_stock\",\n \"quantity_exceeded\",\n \"coupon_invalid\",\n \"coupon_expired\",\n \"minimum_not_met\",\n \"maximum_exceeded\",\n \"region_restricted\",\n \"age_verification_required\",\n \"approval_required\",\n \"unsupported\",\n \"not_found\",\n \"conflict\",\n \"rate_limited\",\n \"expired\",\n \"intervention_required\"\n ],\n \"description\": \"Error code indicating the type of error\"\n },\n \"severity\": {\n \"type\": \"string\",\n \"enum\": [\n \"info\",\n \"low\",\n \"medium\",\n \"high\",\n \"critical\"\n ],\n \"description\": \"Severity level of this error\"\n },\n \"resolution\": {\n \"type\": \"string\",\n \"enum\": [\n \"recoverable\",\n \"requires_buyer_input\",\n \"requires_buyer_review\"\n ],\n \"description\": \"Who resolves this message. 'recoverable': agent can fix via API. 'requires_buyer_input': buyer must provide info. 'requires_buyer_review': buyer must authorize.\"\n },\n \"param\": {\n \"type\": \"string\",\n \"description\": \"RFC 9535 JSONPath\"\n },\n \"content_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"plain\",\n \"markdown\"\n ],\n \"description\": \"Format of the error message content. When set to 'markdown', content MUST conform to CommonMark (https://spec.commonmark.org/0.31.2/). Raw HTML elements MUST NOT be included. When set to 'plain', content is plain text with no formatting.\"\n },\n \"content\": {\n \"type\": \"string\",\n \"description\": \"Error message text. When content_type is 'markdown', this MUST be valid CommonMark with no raw HTML. Agents MUST render using a CommonMark-compliant parser with raw HTML output disabled or sanitized.\"\n }\n },\n \"required\": [\n \"type\",\n \"code\",\n \"content_type\",\n \"content\"\n ],\n \"example\": {\n \"id\": \"msg_err_01\",\n \"message\": \"Invalid email address format\",\n \"code\": \"invalid\",\n \"param\": \"$.buyer.email\"\n }\n },\n \"Link\": {\n \"description\": \"Hyperlink with URL, display text, and optional action semantics\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"terms_of_use\",\n \"privacy_policy\",\n \"return_policy\",\n \"shipping_policy\",\n \"contact_us\",\n \"about_us\",\n \"faq\",\n \"support\"\n ],\n \"description\": \"Type of link\"\n },\n \"title\": {\n \"type\": \"string\",\n \"description\": \"Display text for the link\"\n },\n \"url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL destination\"\n }\n },\n \"required\": [\n \"type\",\n \"url\"\n ],\n \"example\": {\n \"url\": \"https://example.com/terms\",\n \"text\": \"Terms of Service\",\n \"action\": \"view\"\n }\n },\n \"PaymentData\": {\n \"description\": \"Payment instrument data collected from the buyer (e.g., card details, wallet tokens)\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"handler_id\": {\n \"type\": \"string\",\n \"description\": \"ID of the payment handler to use\"\n },\n \"instrument\": {\n \"type\": \"object\",\n \"description\": \"Payment instrument details\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"description\": \"Instrument type (e.g., card, wallet_token)\"\n },\n \"credential\": {\n \"type\": \"object\",\n \"description\": \"Payment credential\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"description\": \"Credential type (e.g., spt, wallet_token)\"\n },\n \"token\": {\n \"type\": \"string\",\n \"description\": \"Credential token value\"\n }\n },\n \"required\": [\n \"type\",\n \"token\"\n ]\n }\n },\n \"required\": [\n \"type\",\n \"credential\"\n ]\n },\n \"billing_address\": {\n \"$ref\": \"#/$defs/Address\",\n \"description\": \"Billing address for the payment\"\n },\n \"purchase_order_number\": {\n \"type\": \"string\",\n \"description\": \"Purchase order number\"\n },\n \"payment_terms\": {\n \"type\": \"string\",\n \"enum\": [\n \"immediate\",\n \"net_15\",\n \"net_30\",\n \"net_60\",\n \"net_90\"\n ],\n \"description\": \"Payment terms for B2B transactions\"\n },\n \"due_date\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when payment is due\"\n },\n \"approval_required\": {\n \"type\": \"boolean\",\n \"description\": \"Whether this payment requires approval\"\n }\n },\n \"anyOf\": [\n {\n \"required\": [\n \"handler_id\",\n \"instrument\"\n ]\n },\n {\n \"required\": [\n \"purchase_order_number\"\n ]\n }\n ],\n \"example\": {\n \"type\": \"vault_token\",\n \"token\": \"vt_01J8Z3WXYZ9ABC123\"\n }\n },\n \"ProtocolVersion\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Protocol metadata included in checkout responses. Indicates the ACP version.\",\n \"properties\": {\n \"version\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{4}-\\\\d{2}-\\\\d{2}$\",\n \"example\": \"2026-01-27\",\n \"description\": \"ACP protocol version in YYYY-MM-DD format.\"\n }\n },\n \"required\": [\n \"version\"\n ],\n \"example\": {\n \"version\": \"2026-04-17\"\n }\n },\n \"DiscountAllocation\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Breakdown of how a discount amount was allocated to a specific target.\",\n \"required\": [\n \"path\",\n \"amount\"\n ],\n \"properties\": {\n \"path\": {\n \"type\": \"string\",\n \"description\": \"JSONPath to the allocation target (e.g., '$.line_items[0]', '$.totals.shipping').\"\n },\n \"amount\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Amount allocated to this target in minor (cents) currency units.\"\n }\n },\n \"example\": {\n \"target\": \"line_item\",\n \"target_id\": \"item_001\",\n \"amount\": 500\n }\n },\n \"Coupon\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Coupon details describing the discount terms.\",\n \"required\": [\n \"id\",\n \"name\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for the coupon.\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Human-readable coupon name (e.g., 'Summer Sale 20% Off').\"\n },\n \"percent_off\": {\n \"type\": \"number\",\n \"minimum\": 0,\n \"maximum\": 100,\n \"description\": \"Percentage discount (0-100). Mutually exclusive with amount_off.\"\n },\n \"amount_off\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Fixed discount amount in minor currency units. Mutually exclusive with percent_off.\"\n },\n \"currency\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z]{3}$\",\n \"description\": \"ISO 4217 currency code for amount_off. Required if amount_off is set.\"\n },\n \"duration\": {\n \"type\": \"string\",\n \"enum\": [\n \"once\",\n \"repeating\",\n \"forever\"\n ],\n \"description\": \"How long the discount applies. 'once' = single use, 'repeating' = multiple billing periods, 'forever' = indefinitely.\"\n },\n \"duration_in_months\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Number of months the coupon applies if duration is 'repeating'.\"\n },\n \"max_redemptions\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Maximum number of times this coupon can be redeemed across all customers.\"\n },\n \"times_redeemed\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Number of times this coupon has been redeemed.\"\n },\n \"metadata\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"type\": \"string\",\n \"description\": \"Metadata value\"\n },\n \"description\": \"Arbitrary key-value metadata attached to the coupon.\"\n }\n },\n \"example\": {\n \"code\": \"SAVE20\",\n \"metadata\": {}\n }\n },\n \"AppliedDiscount\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"A discount that was successfully applied to the checkout session.\",\n \"required\": [\n \"id\",\n \"coupon\",\n \"amount\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for this applied discount instance.\"\n },\n \"code\": {\n \"type\": \"string\",\n \"description\": \"The discount code entered by the user. Omitted for automatic discounts.\"\n },\n \"coupon\": {\n \"$ref\": \"#/$defs/Coupon\",\n \"description\": \"Details about the underlying coupon/promotion.\"\n },\n \"amount\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Total discount amount in minor (cents) currency units.\"\n },\n \"automatic\": {\n \"type\": \"boolean\",\n \"default\": false,\n \"description\": \"True if applied automatically by merchant rules (no code required).\"\n },\n \"start\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the discount became active.\"\n },\n \"end\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the discount expires.\"\n },\n \"method\": {\n \"type\": \"string\",\n \"enum\": [\n \"each\",\n \"across\"\n ],\n \"description\": \"Allocation method. 'each' = applied independently per item. 'across' = split proportionally by value.\"\n },\n \"priority\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Stacking order for discount calculation. Lower numbers applied first (1 = first).\"\n },\n \"allocations\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/DiscountAllocation\"\n },\n \"description\": \"Breakdown of where this discount was allocated. Sum of allocation amounts equals total amount.\"\n }\n },\n \"example\": {\n \"code\": \"SAVE20\",\n \"amount\": 1000,\n \"allocations\": []\n }\n },\n \"DiscountsRequest\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Discount codes input for checkout create/update requests.\",\n \"properties\": {\n \"codes\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Discount code to apply\"\n },\n \"description\": \"Discount codes to apply. Case-insensitive. Replaces previously submitted codes. Send empty array to clear.\"\n }\n },\n \"example\": {\n \"codes\": [\n \"SAVE20\",\n \"FREESHIP\"\n ]\n }\n },\n \"DiscountsResponse\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Discount codes input and applied discounts output in checkout responses.\",\n \"properties\": {\n \"codes\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Discount code submitted\"\n },\n \"description\": \"Echo of submitted discount codes.\"\n },\n \"applied\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/AppliedDiscount\"\n },\n \"description\": \"Discounts successfully applied (code-based and automatic).\"\n },\n \"rejected\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/RejectedDiscount\"\n },\n \"description\": \"Discount codes that could not be applied, with reasons.\"\n }\n },\n \"example\": {\n \"codes\": [\n \"SAVE20\"\n ],\n \"applied\": [],\n \"rejected\": []\n }\n },\n \"RejectedDiscount\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"A discount code that could not be applied, with the reason.\",\n \"required\": [\n \"code\",\n \"reason\"\n ],\n \"properties\": {\n \"code\": {\n \"type\": \"string\",\n \"description\": \"The discount code that was rejected.\"\n },\n \"reason\": {\n \"$ref\": \"#/$defs/DiscountErrorCode\",\n \"description\": \"Error code indicating why the discount was rejected.\"\n },\n \"message\": {\n \"type\": \"string\",\n \"description\": \"Human-readable explanation of why the code was rejected.\"\n }\n },\n \"example\": {\n \"code\": \"EXPIRED10\",\n \"reason\": \"discount_code_expired\"\n }\n },\n \"DiscountErrorCode\": {\n \"type\": \"string\",\n \"enum\": [\n \"discount_code_expired\",\n \"discount_code_invalid\",\n \"discount_code_already_applied\",\n \"discount_code_combination_disallowed\",\n \"discount_code_minimum_not_met\",\n \"discount_code_user_not_logged_in\",\n \"discount_code_user_ineligible\",\n \"discount_code_usage_limit_reached\"\n ],\n \"description\": \"Error codes for rejected discount codes, used in messages[].code.\",\n \"example\": \"discount_code_expired\"\n },\n \"PaymentResponse\": {\n \"description\": \"Payment configuration returned by the seller including accepted methods and handlers\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"provider\": {\n \"type\": \"string\",\n \"description\": \"Payment provider identifier\"\n },\n \"instruments\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"description\": \"Payment instrument schema reference\"\n },\n \"description\": \"Available payment instruments\"\n },\n \"handlers\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"description\": \"Payment handler configuration\"\n },\n \"description\": \"Available payment handlers\"\n }\n },\n \"example\": {\n \"instruments\": [],\n \"handlers\": []\n }\n },\n \"RiskSignals\": {\n \"description\": \"Risk and fraud detection signals for the checkout session\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"ip_address\": {\n \"type\": \"string\",\n \"description\": \"IP address of the buyer\"\n },\n \"user_agent\": {\n \"type\": \"string\",\n \"description\": \"User agent string of the buyer's browser\"\n },\n \"accept_language\": {\n \"type\": \"string\",\n \"description\": \"Accept-Language header from the buyer's browser\"\n },\n \"session_id\": {\n \"type\": \"string\",\n \"description\": \"Session identifier for the buyer\"\n },\n \"device_fingerprint\": {\n \"type\": \"string\",\n \"description\": \"Device fingerprint for fraud detection\"\n }\n },\n \"example\": {\n \"ip_country\": \"US\",\n \"device_fingerprint\": \"fp_abc123\"\n }\n },\n \"Order\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Order returned after checkout completion. Contains order details and optional rich post-purchase tracking.\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"order\",\n \"description\": \"Discriminator field for webhook payloads. Always 'order' when present.\"\n },\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for the order\"\n },\n \"checkout_session_id\": {\n \"type\": \"string\",\n \"description\": \"ID of the checkout session that created this order\"\n },\n \"order_number\": {\n \"type\": \"string\",\n \"description\": \"Human-readable order number for customer reference\"\n },\n \"client_reference_id\": {\n \"type\": \"string\",\n \"description\": \"Reference from the client (agent/platform) stored on the order for reconciliation (e.g. platform transaction id, PO number, ERP id).\"\n },\n \"permalink_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"Permanent URL where the customer can view order details\"\n },\n \"status\": {\n \"type\": \"string\",\n \"description\": \"Order-level status. Implementations MUST accept unrecognized values gracefully. Defined values: 'created', 'confirmed', 'manual_review', 'processing', 'shipped', 'completed', 'canceled'. 'completed' means all items have been delivered/received regardless of fulfillment method. Distinct from LineItem.status 'fulfilled', which indicates the seller has dispatched the item.\"\n },\n \"estimated_delivery\": {\n \"$ref\": \"#/$defs/EstimatedDelivery\",\n \"description\": \"Estimated delivery time range\"\n },\n \"confirmation\": {\n \"$ref\": \"#/$defs/OrderConfirmation\",\n \"description\": \"Order confirmation details\"\n },\n \"support\": {\n \"$ref\": \"#/$defs/SupportInfo\",\n \"description\": \"Customer support contact information\"\n },\n \"line_items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/OrderLineItem\"\n },\n \"description\": \"What was ordered, with per-item fulfillment tracking\"\n },\n \"fulfillments\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Fulfillment\"\n },\n \"description\": \"How items are being delivered (shipping, pickup, digital)\"\n },\n \"adjustments\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Adjustment\"\n },\n \"description\": \"Post-order changes: refunds, credits, returns, disputes\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Order-level totals using the same Total schema as checkout. The 'total' entry is always the original charged amount. 'amount_refunded' tracks cumulative refunds.\"\n }\n },\n \"required\": [\n \"id\",\n \"checkout_session_id\",\n \"permalink_url\"\n ],\n \"example\": {\n \"id\": \"ord_abc123\",\n \"order_number\": \"12345\",\n \"status\": \"confirmed\",\n \"currency\": \"usd\",\n \"total\": 6764,\n \"line_items\": [],\n \"created_at\": \"2026-02-13T10:30:00Z\"\n }\n },\n \"OrderLineItem\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Per-line-item tracking of what was ordered and fulfillment progress.\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Line item identifier, used for references in fulfillments and adjustments\"\n },\n \"title\": {\n \"type\": \"string\",\n \"description\": \"Product name\"\n },\n \"product_id\": {\n \"type\": \"string\",\n \"description\": \"Catalog product ID\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Product description\"\n },\n \"image_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"Product image URL\"\n },\n \"url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"Product page URL\"\n },\n \"quantity\": {\n \"$ref\": \"#/$defs/OrderLineItemQuantity\"\n },\n \"unit_price\": {\n \"type\": \"integer\",\n \"description\": \"Price per unit in minor currency units (cents)\"\n },\n \"subtotal\": {\n \"type\": \"integer\",\n \"description\": \"Line total in minor currency units\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Optional line-item level totals breakdown using the same Total schema as checkout. Merchants who can provide richer breakdowns MAY use this alongside or instead of unit_price/subtotal.\"\n },\n \"status\": {\n \"type\": \"string\",\n \"description\": \"Derived from quantity fields. Implementations MUST accept unrecognized values gracefully. Defined values: 'processing', 'partial', 'fulfilled', 'removed'. Rules: 'removed' if current==0, 'fulfilled' if fulfilled==current, 'partial' if 0<fulfilled<current, 'processing' otherwise.\"\n }\n },\n \"required\": [\n \"id\",\n \"title\",\n \"quantity\"\n ],\n \"example\": {\n \"id\": \"oli_001\",\n \"title\": \"Running Shoes\",\n \"status\": \"fulfilled\",\n \"quantity\": {\n \"ordered\": 2,\n \"current\": 2,\n \"fulfilled\": 2\n }\n }\n },\n \"OrderLineItemQuantity\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Quantity tracking for an order line item. Uses a 3-field model: ordered (original), current (active after cancellations/returns), fulfilled (completed).\",\n \"properties\": {\n \"ordered\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Quantity originally ordered by the customer\"\n },\n \"current\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Current active quantity on the order. May be less than ordered due to cancellations or returns. A value of 0 means the line item has been fully removed.\"\n },\n \"fulfilled\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"default\": 0,\n \"description\": \"Quantity that has been fulfilled (shipped, picked up, or digitally delivered). Applies to all fulfillment types, not just shipping.\"\n }\n },\n \"required\": [\n \"ordered\",\n \"current\"\n ],\n \"example\": {\n \"ordered\": 3,\n \"current\": 3,\n \"fulfilled\": 2\n }\n },\n \"LineItemReference\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Reference to a line item with quantity, used in fulfillments and adjustments\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Line item ID reference\"\n },\n \"quantity\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Quantity in this fulfillment or adjustment\"\n }\n },\n \"required\": [\n \"id\",\n \"quantity\"\n ],\n \"example\": {\n \"line_item_id\": \"item_001\",\n \"quantity\": 1\n }\n },\n \"Fulfillment\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"A fulfillment represents how items are delivered to the buyer (shipping, pickup, digital).\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Fulfillment identifier\"\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"shipping\",\n \"pickup\",\n \"digital\"\n ],\n \"description\": \"Fulfillment method type\"\n },\n \"status\": {\n \"type\": \"string\",\n \"description\": \"Current fulfillment status. Implementations MUST accept unrecognized values gracefully. Defined values: 'pending', 'processing', 'shipped', 'in_transit', 'out_for_delivery', 'ready_for_pickup', 'delivered', 'failed', 'canceled'. Not all statuses apply to all types.\"\n },\n \"line_items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/LineItemReference\"\n },\n \"description\": \"Which line items and quantities are in this fulfillment\"\n },\n \"carrier\": {\n \"type\": \"string\",\n \"description\": \"Carrier name (e.g., 'FedEx', 'UPS', 'USPS'). Applies to type: shipping.\"\n },\n \"tracking_number\": {\n \"type\": \"string\",\n \"description\": \"Carrier tracking number. Applies to type: shipping.\"\n },\n \"tracking_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to track this shipment. Applies to type: shipping.\"\n },\n \"destination\": {\n \"$ref\": \"#/$defs/Address\"\n },\n \"estimated_delivery\": {\n \"$ref\": \"#/$defs/EstimatedDelivery\"\n },\n \"digital_delivery\": {\n \"type\": \"object\",\n \"description\": \"Digital delivery details. Applies to type: digital.\",\n \"properties\": {\n \"access_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to access digital content (download link, streaming page, etc.)\"\n },\n \"license_key\": {\n \"type\": \"string\",\n \"description\": \"License or activation key\"\n },\n \"expires_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"When access expires (RFC 3339 timestamp)\"\n }\n }\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Human-readable description (e.g., 'Backordered - ships Feb 15')\"\n },\n \"events\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/FulfillmentEvent\"\n },\n \"description\": \"Append-only event log tracking fulfillment progress\"\n }\n },\n \"required\": [\n \"id\",\n \"type\"\n ],\n \"example\": {\n \"id\": \"ful_001\",\n \"type\": \"shipping\",\n \"status\": \"shipped\",\n \"line_items\": [],\n \"tracking_number\": \"1Z999AA10123456784\",\n \"carrier\": \"UPS\"\n }\n },\n \"FulfillmentEvent\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"A point-in-time event in the fulfillment lifecycle.\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Event identifier\"\n },\n \"type\": {\n \"type\": \"string\",\n \"description\": \"Event type. Implementations MUST accept unrecognized values gracefully. Defined values: 'processing', 'shipped', 'in_transit', 'out_for_delivery', 'ready_for_pickup', 'delivered', 'failed_attempt', 'returned_to_sender', 'canceled', 'undeliverable'. 'out_for_delivery' and 'ready_for_pickup' are ACP extensions for richer agent experiences.\"\n },\n \"occurred_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when this event occurred\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Human-readable description (e.g., 'Left at front door')\"\n },\n \"location\": {\n \"type\": \"string\",\n \"description\": \"Location where this event occurred (e.g., 'Memphis, TN')\"\n }\n },\n \"required\": [\n \"id\",\n \"type\",\n \"occurred_at\"\n ],\n \"example\": {\n \"status\": \"shipped\",\n \"timestamp\": \"2026-02-13T14:00:00Z\",\n \"location\": \"San Francisco, CA\"\n }\n },\n \"Adjustment\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"A post-order change such as refund, credit, return, or dispute.\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Adjustment identifier\"\n },\n \"type\": {\n \"type\": \"string\",\n \"description\": \"Type of adjustment. Implementations MUST accept unrecognized values gracefully. Defined values: 'refund', 'credit', 'return', 'exchange', 'price_adjustment', 'cancellation', 'dispute'. Use 'refund' for both full and partial refunds (distinguish by amount). 'credit' replaces 'store_credit'. 'dispute' covers chargebacks.\"\n },\n \"occurred_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when this adjustment occurred\"\n },\n \"status\": {\n \"type\": \"string\",\n \"description\": \"Adjustment status. Implementations MUST accept unrecognized values gracefully. Defined values: 'pending', 'completed', 'failed'.\"\n },\n \"line_items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/LineItemReference\"\n },\n \"description\": \"Which line items and quantities are affected\"\n },\n \"amount\": {\n \"type\": \"integer\",\n \"description\": \"Total amount credited to the buyer in minor currency units, inclusive of any applicable tax\"\n },\n \"currency\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z]{3}$\",\n \"description\": \"ISO 4217 currency code\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Human-readable reason (e.g., 'Defective item')\"\n },\n \"reason\": {\n \"type\": \"string\",\n \"description\": \"Structured reason code\"\n }\n },\n \"required\": [\n \"id\",\n \"type\",\n \"occurred_at\",\n \"status\"\n ],\n \"example\": {\n \"id\": \"adj_001\",\n \"type\": \"refund\",\n \"amount\": 1000,\n \"currency\": \"usd\",\n \"reason\": \"Customer request\",\n \"created_at\": \"2026-02-14T10:00:00Z\"\n }\n },\n \"AuthenticationMetadata\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"description\": \"Seller-provided authentication metadata for 3DS flows.\",\n \"required\": [\n \"acquirer_details\",\n \"directory_server\"\n ],\n \"properties\": {\n \"acquirer_details\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Details about the acquirer used for this 3DS Authentication. This object MUST be present.\",\n \"properties\": {\n \"acquirer_bin\": {\n \"type\": \"string\",\n \"maxLength\": 11,\n \"description\": \"The Acquirer BIN (directory-server specific).\"\n },\n \"acquirer_country\": {\n \"type\": \"string\",\n \"minLength\": 2,\n \"maxLength\": 2,\n \"description\": \"Two-letter ISO 3166-1 alpha-2 country code.\"\n },\n \"acquirer_merchant_id\": {\n \"type\": \"string\",\n \"maxLength\": 35,\n \"description\": \"The Merchant ID assigned by the acquirer.\"\n },\n \"merchant_name\": {\n \"type\": \"string\",\n \"maxLength\": 40,\n \"description\": \"Merchant name assigned by the acquirer.\"\n },\n \"requestor_id\": {\n \"type\": \"string\",\n \"maxLength\": 35,\n \"description\": \"Requestor ID (if required by the directory server).\"\n }\n },\n \"required\": [\n \"acquirer_bin\",\n \"acquirer_country\",\n \"acquirer_merchant_id\",\n \"merchant_name\"\n ]\n },\n \"directory_server\": {\n \"type\": \"string\",\n \"enum\": [\n \"american_express\",\n \"mastercard\",\n \"visa\"\n ],\n \"description\": \"The 3DS directory server used for this Authentication.\"\n },\n \"flow_preference\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Contains additional details on the seller's preference for the 3DS authentication flow. Sellers MAY request a preference, but issuers ultimately decide the actual flow.\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"challenge\",\n \"frictionless\"\n ],\n \"description\": \"Type of flow requested for this 3DS Authentication. 'challenge' requests a challenge flow; 'frictionless' requests a frictionless flow.\"\n },\n \"challenge\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Details about the requested challenge flow.\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"mandated\",\n \"preferred\"\n ],\n \"description\": \"Subtype of challenge preference.\"\n }\n }\n },\n \"frictionless\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Details about the requested frictionless flow.\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"low_risk\"\n ],\n \"description\": \"Subtype of frictionless preference.\"\n }\n }\n }\n },\n \"required\": [\n \"type\"\n ]\n }\n },\n \"example\": {\n \"three_ds_version\": \"2.1.0\",\n \"merchant_name\": \"Example Store\"\n }\n },\n \"AuthenticationResult\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Agent-provided authentication results returned to the seller for card-based 3D Secure.\",\n \"properties\": {\n \"outcome\": {\n \"type\": \"string\",\n \"description\": \"The outcome of this 3DS Authentication.\",\n \"enum\": [\n \"abandoned\",\n \"attempt_acknowledged\",\n \"authenticated\",\n \"canceled\",\n \"denied\",\n \"informational\",\n \"internal_error\",\n \"not_supported\",\n \"processing_error\",\n \"rejected\"\n ],\n \"example\": \"authenticated\"\n },\n \"outcome_details\": {\n \"type\": \"object\",\n \"description\": \"Detailed authentication data. This field is required when the outcome is 'authenticated', 'informational', or 'attempt_acknowledged'.\",\n \"additionalProperties\": false,\n \"properties\": {\n \"three_ds_cryptogram\": {\n \"type\": \"string\",\n \"description\": \"The 3DS cryptogram (authentication value / AAV/CAVV/AEVV). This value is 20 bytes, base64-encoded into a 28-character string.\",\n \"example\": \"AbCdEfGhIjKlMnOpQrStUvWxY0=\"\n },\n \"electronic_commerce_indicator\": {\n \"type\": \"string\",\n \"description\": \"Electronic Commerce Indicator (ECI) returned by the 3D Secure provider. Indicates the degree/type of authentication performed.\",\n \"enum\": [\n \"01\",\n \"02\",\n \"05\",\n \"06\",\n \"07\"\n ],\n \"example\": \"05\"\n },\n \"transaction_id\": {\n \"type\": \"string\",\n \"description\": \"Transaction identifier returned by the 3DS system:\\n- For 3DS1: the XID\\n- For 3DS2: the Directory Server Transaction ID (dsTransID)\",\n \"example\": \"dsTransId_abc123\"\n },\n \"version\": {\n \"type\": \"string\",\n \"description\": \"The 3D Secure version used for this authentication (for example '1.0.2' or '2.2.0').\",\n \"example\": \"2.2.0\"\n }\n },\n \"required\": [\n \"three_ds_cryptogram\",\n \"electronic_commerce_indicator\",\n \"transaction_id\",\n \"version\"\n ]\n }\n },\n \"required\": [\n \"outcome\"\n ],\n \"allOf\": [\n {\n \"if\": {\n \"properties\": {\n \"outcome\": {\n \"enum\": [\n \"authenticated\",\n \"informational\",\n \"attempt_acknowledged\"\n ]\n }\n }\n },\n \"then\": {\n \"required\": [\n \"outcome_details\"\n ]\n }\n }\n ],\n \"example\": {\n \"status\": \"authenticated\",\n \"transaction_id\": \"3ds_abc123\",\n \"eci\": \"05\"\n }\n },\n \"MarketingConsentOption\": {\n \"description\": \"Seller-declared marketing consent option that specifies an available channel for which the seller must obtain the buyer's consent before sending marketing content\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"channel\": {\n \"type\": \"string\",\n \"description\": \"Channel for marketing consent.\",\n \"examples\": [\"email\", \"sms\", \"whatsapp\"]\n },\n \"display_text\": {\n \"type\": \"string\",\n \"description\": \"What the buyer is consenting to receive, e.g., 'promotional emails, product launches, and exclusive offers'. Agents MAY use this to compose their own consent prompt.\"\n },\n \"privacy_policy_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the seller's privacy policy governing use of the buyer's contact information for marketing.\"\n },\n \"is_subscribed\": {\n \"type\": \"boolean\",\n \"description\": \"Whether the buyer is currently subscribed to marketing via this channel. When true, agents SHOULD render the consent checkbox as pre-checked. Defaults to false if omitted.\"\n }\n },\n \"required\": [\n \"channel\",\n \"display_text\",\n \"privacy_policy_url\"\n ],\n \"example\": {\n \"channel\": \"email\",\n \"display_text\": \"Promotional emails, product launches, and exclusive offers\",\n \"privacy_policy_url\": \"https://www.example.com/privacy\",\n \"is_subscribed\": false\n }\n },\n \"MarketingConsent\": {\n \"description\": \"Buyer's marketing consent decision for a specific channel submitted at checkout completion\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"channel\": {\n \"type\": \"string\",\n \"description\": \"Channel matching the consent option channel.\",\n \"examples\": [\"email\", \"sms\", \"whatsapp\"]\n },\n \"opted_in\": {\n \"type\": \"boolean\",\n \"description\": \"Whether the buyer consented to receive marketing via this channel.\"\n }\n },\n \"required\": [\n \"channel\",\n \"opted_in\"\n ],\n \"example\": {\n \"channel\": \"email\",\n \"opted_in\": true\n }\n },\n \"CheckoutSessionBase\": {\n \"description\": \"Base checkout session model containing common fields for all checkout session states\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for the checkout session\"\n },\n \"protocol\": {\n \"$ref\": \"#/$defs/ProtocolVersion\",\n \"description\": \"Protocol version metadata\"\n },\n \"capabilities\": {\n \"$ref\": \"#/$defs/Capabilities\",\n \"description\": \"Negotiated capabilities between agent and seller\"\n },\n \"buyer\": {\n \"$ref\": \"#/$defs/Buyer\",\n \"description\": \"Buyer information\"\n },\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\n \"incomplete\",\n \"not_ready_for_payment\",\n \"requires_escalation\",\n \"authentication_required\",\n \"ready_for_payment\",\n \"pending_approval\",\n \"complete_in_progress\",\n \"completed\",\n \"canceled\",\n \"in_progress\",\n \"expired\"\n ],\n \"description\": \"Current status of the checkout session\"\n },\n \"currency\": {\n \"type\": \"string\",\n \"description\": \"ISO 4217 settlement currency code\"\n },\n \"presentment_currency\": {\n \"type\": \"string\",\n \"description\": \"ISO 4217 presentment currency code if different from settlement currency\"\n },\n \"exchange_rate\": {\n \"type\": \"number\",\n \"description\": \"Exchange rate from presentment to settlement currency\"\n },\n \"exchange_rate_timestamp\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when exchange rate was determined\"\n },\n \"locale\": {\n \"type\": \"string\",\n \"description\": \"Locale code (e.g., 'en-US') for localizing content\"\n },\n \"timezone\": {\n \"type\": \"string\",\n \"description\": \"IANA timezone identifier (e.g., 'America/New_York')\"\n },\n \"line_items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/LineItem\"\n },\n \"description\": \"Line items in the checkout session\"\n },\n \"fulfillment_details\": {\n \"$ref\": \"#/$defs/FulfillmentDetails\",\n \"description\": \"Fulfillment contact and address details\"\n },\n \"fulfillment_options\": {\n \"type\": \"array\",\n \"items\": {\n \"oneOf\": [\n {\n \"$ref\": \"#/$defs/FulfillmentOptionShipping\"\n },\n {\n \"$ref\": \"#/$defs/FulfillmentOptionDigital\"\n },\n {\n \"$ref\": \"#/$defs/FulfillmentOptionPickup\"\n },\n {\n \"$ref\": \"#/$defs/FulfillmentOptionLocalDelivery\"\n }\n ]\n },\n \"description\": \"Available fulfillment options\"\n },\n \"selected_fulfillment_options\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/SelectedFulfillmentOption\"\n },\n \"description\": \"Currently selected fulfillment options\"\n },\n \"fulfillment_groups\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/FulfillmentGroup\"\n },\n \"description\": \"Optional grouping of line items by fulfillment method\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Cart-level totals breakdown\"\n },\n \"messages\": {\n \"type\": \"array\",\n \"items\": {\n \"oneOf\": [\n {\n \"$ref\": \"#/$defs/MessageInfo\"\n },\n {\n \"$ref\": \"#/$defs/MessageWarning\"\n },\n {\n \"$ref\": \"#/$defs/MessageError\"\n }\n ]\n },\n \"description\": \"Messages to communicate with the buyer (info, warnings, errors)\"\n },\n \"links\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Link\"\n },\n \"description\": \"Relevant links (terms, policies, support)\"\n },\n \"authentication_metadata\": {\n \"$ref\": \"#/$defs/AuthenticationMetadata\",\n \"description\": \"Authentication metadata for payment interventions (e.g., 3DS)\"\n },\n \"created_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the session was created\"\n },\n \"updated_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp of last update\"\n },\n \"expires_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the session expires\"\n },\n \"continue_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to continue or resume the checkout session\"\n },\n \"metadata\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"description\": \"Arbitrary metadata for merchant use\"\n },\n \"quote_id\": {\n \"type\": \"string\",\n \"description\": \"Quote identifier if this session is based on a quote\"\n },\n \"quote_expires_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the quote expires\"\n },\n \"discounts\": {\n \"$ref\": \"#/$defs/DiscountsResponse\",\n \"description\": \"Discount extension: submitted codes and applied discounts. Present when the 'discount' extension is active.\"\n },\n \"marketing_consent_options\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/MarketingConsentOption\"\n },\n \"description\": \"Marketing consent options the seller offers. When present, the agent SHOULD display these to the buyer before checkout completion. Agents MAY selectively surface a subset of options; options not surfaced MUST be omitted from marketing_consents in the complete request. When absent, the agent MUST NOT surface any marketing consent UI. An empty array is equivalent to absent.\"\n },\n \"order\": {\n \"$ref\": \"#/$defs/Order\"\n }\n },\n \"required\": [\n \"id\",\n \"status\",\n \"currency\",\n \"line_items\",\n \"totals\",\n \"fulfillment_options\",\n \"messages\",\n \"links\",\n \"capabilities\"\n ],\n \"example\": {\n \"id\": \"cs_abc123\",\n \"status\": \"ready_for_payment\",\n \"currency\": \"usd\",\n \"line_items\": [],\n \"totals\": {\n \"currency\": \"usd\",\n \"subtotal\": 5800,\n \"total\": 6764\n },\n \"fulfillment_options\": [],\n \"messages\": [],\n \"links\": [],\n \"capabilities\": {}\n }\n },\n \"CheckoutSession\": {\n \"description\": \"Checkout session response model\",\n \"allOf\": [\n {\n \"$ref\": \"#/$defs/CheckoutSessionBase\"\n }\n ],\n \"example\": {\n \"id\": \"cs_abc123\",\n \"status\": \"ready_for_payment\",\n \"currency\": \"usd\",\n \"line_items\": [],\n \"totals\": {\n \"currency\": \"usd\",\n \"subtotal\": 5800,\n \"total\": 6764\n },\n \"fulfillment_options\": [],\n \"messages\": [],\n \"links\": [],\n \"capabilities\": {}\n }\n },\n \"CheckoutSessionWithOrder\": {\n \"description\": \"Checkout session response after completion, includes the created order\",\n \"allOf\": [\n {\n \"$ref\": \"#/$defs/CheckoutSessionBase\"\n },\n {\n \"description\": \"Order extension for completed checkout sessions\",\n \"type\": \"object\",\n \"properties\": {\n \"order\": {\n \"$ref\": \"#/$defs/Order\",\n \"description\": \"Order created when checkout is completed\"\n }\n },\n \"required\": [\n \"order\"\n ]\n }\n ],\n \"example\": {\n \"id\": \"cs_abc123\",\n \"status\": \"completed\",\n \"currency\": \"usd\",\n \"line_items\": [],\n \"totals\": {\n \"currency\": \"usd\",\n \"subtotal\": 5800,\n \"total\": 6764\n },\n \"fulfillment_options\": [],\n \"messages\": [],\n \"links\": [],\n \"capabilities\": {},\n \"order\": {\n \"id\": \"ord_abc123\",\n \"order_number\": \"12345\",\n \"status\": \"confirmed\",\n \"currency\": \"usd\",\n \"total\": 6764,\n \"line_items\": [],\n \"created_at\": \"2026-02-13T10:30:00Z\"\n }\n }\n },\n \"CheckoutSessionCreateRequest\": {\n \"description\": \"Request to create a new checkout session\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"buyer\": {\n \"$ref\": \"#/$defs/Buyer\",\n \"description\": \"Buyer information\"\n },\n \"line_items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Item\"\n },\n \"minItems\": 1,\n \"description\": \"Items to add to the checkout session\"\n },\n \"currency\": {\n \"type\": \"string\",\n \"description\": \"ISO 4217 currency code\"\n },\n \"fulfillment_details\": {\n \"$ref\": \"#/$defs/FulfillmentDetails\",\n \"description\": \"Fulfillment contact and address details\"\n },\n \"capabilities\": {\n \"$ref\": \"#/$defs/Capabilities\",\n \"description\": \"Agent capabilities and supported features\"\n },\n \"fulfillment_groups\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/FulfillmentGroup\"\n },\n \"description\": \"Grouping of items by fulfillment method\"\n },\n \"affiliate_attribution\": {\n \"$ref\": \"#/$defs/AffiliateAttribution\",\n \"description\": \"Affiliate attribution data for first-touch tracking\"\n },\n \"coupons\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Coupon code to apply\"\n },\n \"description\": \"DEPRECATED: Use discounts.codes instead. Discount codes to apply.\"\n },\n \"discounts\": {\n \"$ref\": \"#/$defs/DiscountsRequest\",\n \"description\": \"Discount codes to apply to the checkout session.\"\n },\n \"locale\": {\n \"type\": \"string\",\n \"description\": \"Locale code for localizing content (e.g., 'en-US')\"\n },\n \"timezone\": {\n \"type\": \"string\",\n \"description\": \"IANA timezone identifier (e.g., 'America/New_York')\"\n },\n \"quote_id\": {\n \"type\": \"string\",\n \"description\": \"Quote identifier if this session is based on a quote\"\n },\n \"metadata\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"description\": \"Arbitrary metadata for merchant use\"\n },\n \"order_notes\": {\n \"type\": \"string\",\n \"maxLength\": 5000,\n \"description\": \"Optional customer/order notes (e.g., delivery instructions, gift message).\"\n }\n },\n \"required\": [\n \"line_items\",\n \"currency\",\n \"capabilities\"\n ],\n \"example\": {\n \"items\": [\n {\n \"product_id\": \"prod_tshirt_blue_m\",\n \"quantity\": 2\n }\n ],\n \"currency\": \"usd\",\n \"capabilities\": {}\n }\n },\n \"CheckoutSessionUpdateRequest\": {\n \"description\": \"Request to update an existing checkout session\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"buyer\": {\n \"$ref\": \"#/$defs/Buyer\",\n \"description\": \"Updated buyer information\"\n },\n \"line_items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Item\"\n },\n \"description\": \"Items to update in the checkout session\"\n },\n \"fulfillment_details\": {\n \"$ref\": \"#/$defs/FulfillmentDetails\",\n \"description\": \"Updated fulfillment contact and address\"\n },\n \"fulfillment_groups\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/FulfillmentGroup\"\n },\n \"description\": \"Updated fulfillment groupings\"\n },\n \"selected_fulfillment_options\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/SelectedFulfillmentOption\"\n },\n \"description\": \"Fulfillment option selected by the buyer\"\n },\n \"coupons\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Coupon code to apply\"\n },\n \"description\": \"DEPRECATED: Use discounts.codes instead. Discount codes to apply.\"\n },\n \"discounts\": {\n \"$ref\": \"#/$defs/DiscountsRequest\",\n \"description\": \"Discount codes to apply. Replaces previously submitted codes.\"\n },\n \"order_notes\": {\n \"type\": \"string\",\n \"maxLength\": 5000,\n \"description\": \"Optional customer/order notes.\"\n }\n },\n \"example\": {\n \"buyer\": {\n \"email\": \"customer@example.com\"\n }\n }\n },\n \"CheckoutSessionCompleteRequest\": {\n \"description\": \"Request to complete a checkout session and create an order\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"buyer\": {\n \"$ref\": \"#/$defs/Buyer\",\n \"description\": \"Final buyer information\"\n },\n \"payment_data\": {\n \"$ref\": \"#/$defs/PaymentData\",\n \"description\": \"Payment method and details\"\n },\n \"authentication_result\": {\n \"$ref\": \"#/$defs/AuthenticationResult\",\n \"description\": \"Authentication result for 3DS flows\"\n },\n \"affiliate_attribution\": {\n \"$ref\": \"#/$defs/AffiliateAttribution\",\n \"description\": \"Affiliate attribution data for last-touch tracking\"\n },\n \"risk_signals\": {\n \"$ref\": \"#/$defs/RiskSignals\",\n \"description\": \"Risk and fraud signals\"\n },\n \"marketing_consents\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/MarketingConsent\"\n },\n \"description\": \"Buyer's marketing consent decisions. Agents SHOULD include an entry for each consent option surfaced to the buyer. Options not surfaced MUST be omitted — omission preserves existing subscription state. Sellers SHOULD ignore entries in marketing_consents that do not correspond to a channel in marketing_consent_options.\"\n },\n \"order_notes\": {\n \"type\": \"string\",\n \"maxLength\": 5000,\n \"description\": \"Optional customer/order notes (delivery instructions, gift message).\"\n }\n },\n \"required\": [\n \"payment_data\"\n ],\n \"example\": {\n \"payment_data\": {\n \"type\": \"vault_token\",\n \"token\": \"vt_01J8Z3WXYZ9ABC123\"\n }\n }\n },\n \"IntentTrace\": {\n \"description\": \"Structured reason for why a buyer action was taken, used for analytics and debugging\",\n \"type\": \"object\",\n \"properties\": {\n \"reason_code\": {\n \"type\": \"string\",\n \"description\": \"Reason for abandonment. This enum is extensible: servers SHOULD accept unrecognized values and treat them as 'other' (see RFC Section 7.2). Validators SHOULD be configured for lenient enum handling.\",\n \"enum\": [\n \"price_sensitivity\",\n \"shipping_cost\",\n \"shipping_speed\",\n \"product_fit\",\n \"trust_security\",\n \"returns_policy\",\n \"payment_options\",\n \"comparison\",\n \"timing_deferred\",\n \"other\"\n ]\n },\n \"trace_summary\": {\n \"type\": \"string\",\n \"maxLength\": 500,\n \"description\": \"A generated summary of the specific objection or negotiation gap.\"\n },\n \"metadata\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"type\": [\n \"string\",\n \"number\",\n \"boolean\"\n ],\n \"description\": \"Metadata value\"\n },\n \"description\": \"Additional structured metadata about the intent\"\n }\n },\n \"required\": [\n \"reason_code\"\n ],\n \"example\": {\n \"reason_code\": \"buyer_initiated\",\n \"description\": \"Customer requested to complete checkout\",\n \"metadata\": {}\n }\n },\n \"CancelSessionRequest\": {\n \"description\": \"Request to cancel a checkout session\",\n \"type\": \"object\",\n \"properties\": {\n \"intent_trace\": {\n \"$ref\": \"#/$defs/IntentTrace\"\n }\n },\n \"example\": {\n \"intent_trace\": {\n \"reason_code\": \"buyer_cancelled\",\n \"description\": \"Customer decided not to purchase\"\n }\n }\n },\n \"DiscoveryResponse\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Well-known discovery document served at /.well-known/acp.json. Describes the seller's capabilities. This is stable, deterministic information that does not vary per session. Session-specific capabilities (payment methods, payment handlers) are negotiated inline via the capabilities object on POST /checkout_sessions.\",\n \"properties\": {\n \"protocol\": {\n \"$ref\": \"#/$defs/DiscoveryProtocol\"\n },\n \"api_base_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"Base URL for the ACP REST API. Agents append resource paths to this URL (e.g., {api_base_url}/checkout_sessions).\"\n },\n \"transports\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\"rest\", \"mcp\"]\n },\n \"uniqueItems\": true,\n \"description\": \"Transport bindings supported by this seller. \\\"rest\\\" indicates the REST API at api_base_url. \\\"mcp\\\" indicates a Model Context Protocol server is available (see SEP #135). New values are introduced in new API versions; agents MAY treat this enum as exhaustive for a given version.\"\n },\n \"capabilities\": {\n \"$ref\": \"#/$defs/DiscoveryCapabilities\"\n }\n },\n \"required\": [\"protocol\", \"api_base_url\", \"transports\", \"capabilities\"],\n \"example\": {\n \"protocol\": {\n \"name\": \"acp\",\n \"version\": \"2026-04-17\",\n \"supported_versions\": [\"2025-09-29\", \"2026-01-30\", \"2026-04-17\"]\n },\n \"api_base_url\": \"https://acp.stripe.com/api\",\n \"transports\": [\"rest\"],\n \"capabilities\": {\n \"services\": [\"checkout\"]\n }\n }\n },\n \"DiscoveryCapabilities\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Seller capabilities advertised in the well-known discovery document. Contains feature declarations that are stable across sessions.\",\n \"properties\": {\n \"services\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\"checkout\", \"orders\", \"delegate_payment\", \"carts\"]\n },\n \"uniqueItems\": true,\n \"description\": \"Services available from this seller. Indicates which ACP operations are implemented. This enum is closed per API version; new values are introduced in new API versions. Agents MAY treat the set as exhaustive for a given version.\"\n },\n \"extensions\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/DiscoveryExtension\"\n },\n \"description\": \"Extensions the seller supports. Whether a specific extension is active for a given session is determined during checkout session creation.\"\n },\n \"intervention_types\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\"3ds\", \"biometric\", \"address_verification\"]\n },\n \"uniqueItems\": true,\n \"description\": \"Intervention types the seller supports. Actual availability for a specific session is negotiated via the capabilities object on POST /checkout_sessions. This enum is closed per API version; new values are introduced in new API versions. Agents MAY treat the set as exhaustive for a given version.\"\n },\n \"supported_currencies\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z]{3}$\",\n \"description\": \"ISO 4217 currency code in lowercase (e.g., \\\"usd\\\", \\\"eur\\\")\"\n },\n \"uniqueItems\": true,\n \"description\": \"ISO 4217 currency codes supported by the seller.\"\n },\n \"supported_locales\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"BCP 47 locale tag (e.g., \\\"en-US\\\", \\\"fr-FR\\\")\"\n },\n \"uniqueItems\": true,\n \"description\": \"BCP 47 locale tags supported by the seller for localized responses.\"\n }\n },\n \"required\": [\"services\"],\n \"example\": {\n \"services\": [\"checkout\", \"orders\", \"delegate_payment\", \"carts\"],\n \"extensions\": [{ \"name\": \"discount\", \"spec\": \"https://agenticcommerce.dev/specs/discount\", \"schema\": \"https://agenticcommerce.dev/schemas/discount.json\" }],\n \"intervention_types\": [\"3ds\"],\n \"supported_currencies\": [\"usd\", \"eur\"],\n \"supported_locales\": [\"en-US\"]\n }\n },\n \"DiscoveryProtocol\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Protocol identification and version information.\",\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"const\": \"acp\",\n \"description\": \"Protocol identifier. Always \\\"acp\\\".\"\n },\n \"version\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{4}-\\\\d{2}-\\\\d{2}$\",\n \"description\": \"The current (latest) API version supported by the seller, in YYYY-MM-DD format.\"\n },\n \"supported_versions\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{4}-\\\\d{2}-\\\\d{2}$\",\n \"description\": \"API version in YYYY-MM-DD format\"\n },\n \"uniqueItems\": true,\n \"description\": \"All API versions the seller currently supports, in chronological order (oldest first). Agents SHOULD use the API-Version header to request a specific version. The last element is always the latest supported version.\"\n },\n \"documentation_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the seller's ACP documentation.\"\n }\n },\n \"required\": [\"name\", \"version\", \"supported_versions\"],\n \"example\": {\n \"name\": \"acp\",\n \"version\": \"2026-04-17\",\n \"supported_versions\": [\"2025-09-29\", \"2026-01-30\", \"2026-04-17\"],\n \"documentation_url\": \"https://agenticcommerce.dev\"\n }\n },\n \"DiscoveryExtension\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"High-level extension declaration in the discovery document. Identifies the extension and provides a spec URL, but does not include session-level details like schema or extends fields.\",\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Extension identifier (e.g., \\\"discount\\\", \\\"fulfillment\\\").\"\n },\n \"spec\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the extension's specification document.\"\n },\n \"schema\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the extension's JSON Schema definition for programmatic validation.\"\n }\n },\n \"required\": [\"name\"],\n \"example\": {\n \"name\": \"discount\",\n \"spec\": \"https://agenticcommerce.dev/specs/discount\",\n \"schema\": \"https://agenticcommerce.dev/schemas/discount.json\"\n }\n },\n \"Error\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Protocol-level error returned in 4xx/5xx responses when the server cannot return a valid CheckoutSession at all (e.g. malformed request or unexpected failure). Use Error—not MessageError—when there is no valid session state to return. type semantics: invalid_request — malformed request, missing required fields, invalid JSON, or idempotency violations (codes: idempotency_key_required, idempotency_in_flight, idempotency_conflict); processing_error — unexpected server-side failure; service_unavailable — temporary unavailability.\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"invalid_request\",\n \"processing_error\",\n \"service_unavailable\"\n ],\n \"description\": \"Error type indicating the category of protocol-level error\"\n },\n \"code\": {\n \"type\": \"string\",\n \"description\": \"Implementation-defined error code\"\n },\n \"message\": {\n \"type\": \"string\",\n \"description\": \"Human-readable error message\"\n },\n \"param\": {\n \"type\": \"string\",\n \"description\": \"RFC 9535 JSONPath (optional)\"\n },\n \"supported_versions\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{4}-\\\\d{2}-\\\\d{2}$\",\n \"description\": \"Supported API version in YYYY-MM-DD format\"\n },\n \"description\": \"List of API versions supported by the server, ordered by preference (newest first). Only included in version-related errors.\"\n }\n },\n \"required\": [\n \"type\",\n \"code\",\n \"message\"\n ],\n \"example\": {\n \"type\": \"invalid_request\",\n \"code\": \"invalid_email\",\n \"message\": \"The email address format is invalid\",\n \"param\": \"$.buyer.email\"\n }\n }\n }\n}\n","/**\n * Wire validation against the vendored ACP checkout schema.\n *\n * ACP documents need far more of JSON Schema than the subset\n * `src/core/execution` validates canonical input with, so the pinned official\n * schema is compiled with Ajv rather than restated by hand.\n *\n * The schema is imported, not read from disk: bundling collapses `src/**` into\n * a few files under `dist/`, where a relative `readFileSync` resolves from the\n * wrong depth.\n */\n\nimport type { ErrorObject, ValidateFunction } from 'ajv';\nimport Ajv2020 from 'ajv/dist/2020.js';\nimport addFormats from 'ajv-formats';\nimport { CommerceError } from '../../core';\n// The snapshot directory is part of the path on purpose: a new ACP version is\n// a new import beside this one, never an edit to the vendored file\nimport schemaDocument from './spec/2026-04-17/schema.agentic_checkout.json' with { type: 'json' };\n\n/**\n * A validation failure, reduced to what may safely cross the adapter\n * boundary. Ajv messages and schema paths describe *our* compiled schema and\n * never reach a client; the adapter turns this into an ACP `Error`.\n */\nexport interface AcpValidationFailure {\n /** The JSON Schema keyword that failed: spec vocabulary, not an Ajv internal */\n readonly code: string;\n /** `$.buyer.email`-style pointer to the offending value. Omitted at the document root */\n readonly path?: string;\n}\n\n/**\n * The released `$defs` this adapter validates against, keyed by the role it\n * uses them in. Values are the exact snapshot names; all are compiled on first\n * use, which the adapter's start-up discovery check triggers, so a typo fails\n * the adapter at start rather than on a checkout request.\n */\nexport const ACP_DEFINITIONS = {\n createRequest: 'CheckoutSessionCreateRequest',\n updateRequest: 'CheckoutSessionUpdateRequest',\n completeRequest: 'CheckoutSessionCompleteRequest',\n cancelRequest: 'CancelSessionRequest',\n checkoutSession: 'CheckoutSession',\n checkoutSessionWithOrder: 'CheckoutSessionWithOrder',\n discoveryResponse: 'DiscoveryResponse',\n error: 'Error',\n} as const;\n\nexport type AcpDefinition = keyof typeof ACP_DEFINITIONS;\n\nlet validators: ReadonlyMap<AcpDefinition, ValidateFunction> | undefined;\n\n// Compiled once per process, on first use rather than at import, so a gateway\n// with ACP disabled never pays for it\nfunction acpValidators(): ReadonlyMap<AcpDefinition, ValidateFunction> {\n if (validators !== undefined) return validators;\n\n const ajv = new Ajv2020({\n // The vendored document is the released spec; unknown annotations in it\n // are no reason to refuse to start\n strict: false,\n // Only one failure leaves the adapter, and collecting every error in a\n // deeply nested cart is work a caller could request repeatedly\n allErrors: false,\n });\n addFormats(ajv);\n\n const document = relaxExtensibleEnums(structuredClone(schemaDocument)) as Record<string, unknown>;\n openCapabilityValues(document);\n const schemaId = typeof document['$id'] === 'string' ? document['$id'] : '';\n ajv.addSchema(document as Parameters<typeof ajv.addSchema>[0]);\n\n const compiled = new Map<AcpDefinition, ValidateFunction>();\n for (const [name, definition] of Object.entries(ACP_DEFINITIONS)) {\n const validate = ajv.getSchema(`${schemaId}#/$defs/${definition}`);\n if (validate === undefined) {\n throw new CommerceError(\n 'PROTOCOL_UNSUPPORTED',\n `The vendored ACP schema has no definition \"${definition}\" - the pinned snapshot and this adapter disagree`,\n { details: { definition } },\n );\n }\n compiled.set(name as AcpDefinition, validate);\n }\n\n validators = compiled;\n return compiled;\n}\n\n/**\n * Drops the `enum` constraint from the fields whose description says the enum\n * is extensible (\"servers SHOULD accept unrecognized values and treat them as\n * 'other'\"). Enums ACP calls closed per API version stay closed; this only\n * avoids refusing, say, a cancel over a reason code the buyer's agent knows\n * and this snapshot does not.\n */\nfunction relaxExtensibleEnums(node: unknown): unknown {\n if (Array.isArray(node)) {\n for (const entry of node) relaxExtensibleEnums(entry);\n return node;\n }\n if (node === null || typeof node !== 'object') return node;\n\n const record = node as Record<string, unknown>;\n const description = record['description'];\n if (\n Array.isArray(record['enum']) &&\n typeof description === 'string' &&\n /enum is extensible/i.test(description)\n ) {\n delete record['enum'];\n }\n for (const value of Object.values(record)) relaxExtensibleEnums(value);\n return node;\n}\n\n/**\n * Allow unknown intervention values in negotiated `supported` and `required`\n * lists, as ACP requires. The snapshot schema closes these enums; other\n * fields remain strict.\n */\nfunction openCapabilityValues(document: Record<string, unknown>): void {\n const defs = document['$defs'] as Record<string, { properties?: Record<string, unknown> }>;\n const properties = defs['InterventionCapabilities']?.properties ?? {};\n for (const list of ['supported', 'required']) {\n const items = (properties[list] as { items?: Record<string, unknown> } | undefined)?.items;\n if (items !== undefined) delete items['enum'];\n }\n}\n\n/**\n * Validates one ACP document against a released definition: `undefined` when\n * it conforms, otherwise the first failure. Inbound, a failure is a 400 and no\n * pipeline call; outbound, the merchant's body is not ACP and is not forwarded.\n */\nexport function validateAcpDocument(\n definition: AcpDefinition,\n value: unknown,\n): AcpValidationFailure | undefined {\n const validate = acpValidators().get(definition);\n /* c8 ignore next -- unreachable: every AcpDefinition is compiled above */\n if (validate === undefined) return { code: 'unknown_definition' };\n\n if (validate(value)) return undefined;\n const error = validate.errors?.[0];\n if (error === undefined) return { code: 'invalid' };\n\n const path = failurePath(error);\n return { code: error.keyword, ...(path !== undefined ? { path } : {}) };\n}\n\n/**\n * Ajv's JSON Pointer, rewritten in the `$.a.b[0]` form ACP errors use in `param`.\n * `required` and `additionalProperties` failures point at the parent object,\n * so the offending key is appended: `$.buyer.email` rather than `$.buyer`.\n */\nfunction failurePath(error: ErrorObject): string | undefined {\n const segments = error.instancePath\n .split('/')\n .filter((segment) => segment.length > 0)\n .map((segment) => segment.replaceAll('~1', '/').replaceAll('~0', '~'));\n\n const params = error.params as { missingProperty?: unknown; additionalProperty?: unknown };\n const key = params.missingProperty ?? params.additionalProperty;\n if (typeof key === 'string') segments.push(key);\n\n if (segments.length === 0) return undefined;\n return segments.reduce(\n (path, segment) => (/^\\d+$/.test(segment) ? `${path}[${segment}]` : `${path}.${segment}`),\n '$',\n );\n}\n","/**\n * Everything that must hold before an ACP request reaches the pipeline, in a\n * fixed order that fails closed at the first step that does not hold: route ->\n * bearer auth -> API-Version -> Idempotency-Key -> body size -> content type\n * -> JSON -> ACP request schema. A request failing any step never reaches the\n * pipeline.\n */\nimport type { IncomingMessage } from 'node:http';\nimport { readCappedBody } from '../http';\nimport {\n ACP_API_VERSION,\n ACP_API_VERSION_HEADER,\n ACP_FORWARDED_HEADERS,\n ACP_IDEMPOTENCY_KEY_HEADER,\n ACP_MAX_FORWARDED_HEADER_LENGTH,\n ACP_MAX_REQUEST_ID_LENGTH,\n ACP_REQUEST_ID_HEADER,\n} from './constants';\nimport { type AcpFailure, type AcpResponseHeaders, acpFailure } from './errors';\nimport { ACP_MAX_IDEMPOTENCY_KEY_LENGTH } from './idempotency/store';\nimport { type AcpRouteMatch, matchAcpRoute } from './router';\nimport { type AcpDefinition, validateAcpDocument } from './validation';\n\n// A second line behind the gateway mount's cap, bounding what this adapter\n// buffers if it is mounted without that guard\nconst ACP_MAX_REQUEST_BODY_BYTES = 256 * 1024;\n\n// Which released request definition each operation's body is validated against\nconst REQUEST_DEFINITIONS: Readonly<Record<AcpRouteMatch['operation'], AcpDefinition | undefined>> =\n {\n createCheckoutSession: 'createRequest',\n updateCheckoutSession: 'updateRequest',\n completeCheckoutSession: 'completeRequest',\n cancelCheckoutSession: 'cancelRequest',\n getCheckoutSession: undefined,\n };\n\nexport interface AcpGuardedRequest {\n readonly route: AcpRouteMatch;\n /** Validated ACP request document. `{}` for a body-less route */\n readonly body: Record<string, unknown>;\n /** The caller's `Request-Id`, bounded and filtered, when it sent a usable one */\n readonly requestId?: string;\n /** Present on every body-bearing route, where ACP makes it mandatory */\n readonly idempotencyKey?: string;\n /**\n * Usable caller headers for the merchant. `Signature` and `Timestamp` pass\n * through unverified. The gateway re-serializes JSON, so raw-byte signatures\n * will not survive; canonical JSON signatures may.\n */\n readonly forwardedHeaders?: Readonly<Record<string, string>>;\n}\n\nexport type AcpGuardResult =\n | { readonly ok: true; readonly value: AcpGuardedRequest }\n | ({ readonly ok: false; readonly headers: AcpResponseHeaders } & AcpFailure);\n\nexport interface AcpGuardOptions {\n readonly mountPath: string;\n /** `createBearerCheck` over the configured token */\n readonly isAuthorized: (authorizationHeader: string | undefined) => boolean;\n readonly maxBodyBytes?: number;\n}\n\n/**\n * The correlation headers a checkout response echoes: a filtered `Request-Id`,\n * and on a POST an `Idempotency-Key` that passes its own syntax check. Read\n * from the raw request, so a refusal before or outside the guard can echo them.\n */\nexport function acpEchoHeaders(req: IncomingMessage): AcpResponseHeaders {\n const echo: Record<string, string> = {};\n const presentedRequestId = normalizeRequestId(header(req, ACP_REQUEST_ID_HEADER));\n if (presentedRequestId !== undefined) echo[ACP_REQUEST_ID_HEADER] = presentedRequestId;\n const presentedKey = header(req, ACP_IDEMPOTENCY_KEY_HEADER)?.trim();\n if (req.method === 'POST' && presentedKey !== undefined && isUsableIdempotencyKey(presentedKey)) {\n echo[ACP_IDEMPOTENCY_KEY_HEADER] = presentedKey;\n }\n return echo;\n}\n\nexport async function guardAcpRequest(\n req: IncomingMessage,\n options: AcpGuardOptions,\n): Promise<AcpGuardResult> {\n const echo = acpEchoHeaders(req);\n const failed = (failure: AcpFailure, extra: AcpResponseHeaders = {}): AcpGuardResult => ({\n ok: false,\n ...failure,\n headers: { ...echo, ...extra },\n });\n\n const matched = matchAcpRoute(req.method, req.url, options.mountPath);\n if (matched.kind === 'not-found') {\n return failed(acpFailure(404, 'invalid_request', 'not_found', 'Unknown ACP route.'));\n }\n if (matched.kind === 'method-not-allowed') {\n return failed(\n acpFailure(\n 405,\n 'invalid_request',\n 'method_not_allowed',\n `This ACP route accepts ${matched.allow.join(', ')}.`,\n ),\n { allow: matched.allow.join(', ') },\n );\n }\n const route = matched.route;\n\n // Before any body is read, so an unauthenticated caller cannot make this\n // adapter buffer or parse. Only the bearer token authenticates: a\n // `Signature` header is not verified and never stands in for it.\n if (!options.isAuthorized(header(req, 'authorization'))) {\n return failed(\n acpFailure(\n 401,\n 'invalid_request',\n 'unauthorized',\n 'A valid \"Authorization: Bearer <token>\" header is required.',\n ),\n // RFC 9110 requires a challenge on every 401\n { 'www-authenticate': 'Bearer' },\n );\n }\n\n const version = header(req, ACP_API_VERSION_HEADER);\n if (version === undefined || version.trim().length === 0) {\n return failed(\n acpFailure(\n 400,\n 'invalid_request',\n 'missing_api_version',\n `The ${ACP_API_VERSION_HEADER} header is required.`,\n { supportedVersions: [ACP_API_VERSION] },\n ),\n );\n }\n if (version.trim() !== ACP_API_VERSION) {\n // Never mapped to the pinned version: \"latest\", an older snapshot and a\n // typo get the same answer\n return failed(\n acpFailure(\n 400,\n 'invalid_request',\n 'unsupported_api_version',\n 'The requested API version is not supported.',\n { supportedVersions: [ACP_API_VERSION] },\n ),\n );\n }\n\n // Checked before the body is read: a POST without a usable key can never be\n // executed, so reading its body would be wasted work\n let idempotencyKey: string | undefined;\n if (route.acceptsBody) {\n const presentedKey = header(req, ACP_IDEMPOTENCY_KEY_HEADER)?.trim();\n if (presentedKey === undefined || presentedKey.length === 0) {\n return failed(\n acpFailure(\n 400,\n 'invalid_request',\n 'idempotency_key_required',\n `The ${ACP_IDEMPOTENCY_KEY_HEADER} header is required on this ACP operation.`,\n ),\n );\n }\n // Bounded and printable ASCII like Request-Id: the key is echoed in a\n // response header, where a CRLF would split the response\n if (!isUsableIdempotencyKey(presentedKey)) {\n return failed(\n acpFailure(\n 400,\n 'invalid_request',\n 'idempotency_key_invalid',\n `The ${ACP_IDEMPOTENCY_KEY_HEADER} header must be 1-${ACP_MAX_IDEMPOTENCY_KEY_LENGTH} printable ASCII characters.`,\n ),\n );\n }\n idempotencyKey = presentedKey;\n }\n\n const read = await readCappedBody(req, options.maxBodyBytes ?? ACP_MAX_REQUEST_BODY_BYTES);\n if (read.kind === 'too-large') {\n return failed(\n acpFailure(\n 413,\n 'invalid_request',\n 'request_body_too_large',\n 'The request body is too large.',\n ),\n );\n }\n if (read.kind === 'unreadable') {\n return failed(\n acpFailure(\n 400,\n 'invalid_request',\n 'invalid_request_body',\n 'Could not read the request body.',\n ),\n );\n }\n\n const raw = read.text;\n const contentTypeFailure = checkContentType(header(req, 'content-type'), raw, route);\n if (contentTypeFailure !== undefined) return failed(contentTypeFailure);\n\n const definition = REQUEST_DEFINITIONS[route.operation];\n if (definition === undefined) {\n // GET carries no document; a body on it is ignored, not validated\n return ok(route, {}, req, idempotencyKey);\n }\n\n let body: unknown;\n if (raw.trim().length === 0) {\n // An absent body is an empty document, which the schema accepts (cancel)\n // or rejects (create) on its own terms\n body = {};\n } else {\n try {\n body = JSON.parse(raw);\n } catch {\n return failed(\n acpFailure(400, 'invalid_request', 'invalid_json', 'The request body is not valid JSON.'),\n );\n }\n }\n\n const failure = validateAcpDocument(definition, body);\n if (failure !== undefined) {\n // Only the pointer into the caller's document travels, not the Ajv message\n return failed(\n acpFailure(400, 'invalid_request', 'invalid_request_body', 'The request body is invalid.', {\n ...(failure.path !== undefined ? { param: failure.path } : {}),\n }),\n );\n }\n\n return ok(route, body as Record<string, unknown>, req, idempotencyKey);\n}\n\nfunction checkContentType(\n contentType: string | undefined,\n raw: string,\n route: AcpRouteMatch,\n): AcpFailure | undefined {\n if (!route.acceptsBody) return undefined;\n if (contentType === undefined) {\n // A POST with no body at all (a bare cancel) needs no content type\n return raw.trim().length === 0\n ? undefined\n : acpFailure(\n 415,\n 'invalid_request',\n 'unsupported_media_type',\n 'ACP request bodies must be sent as \"application/json\".',\n );\n }\n const mediaType = contentType.split(';')[0]?.trim().toLowerCase();\n if (mediaType === 'application/json' || mediaType?.endsWith('+json')) return undefined;\n return acpFailure(\n 415,\n 'invalid_request',\n 'unsupported_media_type',\n 'ACP request bodies must be sent as \"application/json\".',\n );\n}\n\nfunction ok(\n route: AcpRouteMatch,\n body: Record<string, unknown>,\n req: IncomingMessage,\n idempotencyKey: string | undefined,\n): AcpGuardResult {\n const requestId = normalizeRequestId(header(req, ACP_REQUEST_ID_HEADER));\n return {\n ok: true,\n value: {\n route,\n body,\n ...(requestId !== undefined ? { requestId } : {}),\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n forwardedHeaders: forwardedHeaders(req, requestId),\n },\n };\n}\n\n// Forward only bounded, printable caller headers. Request-Id is filtered\n// for echoing; API-Version has already passed validation.\nfunction forwardedHeaders(\n req: IncomingMessage,\n requestId: string | undefined,\n): Readonly<Record<string, string>> {\n const forwarded: Record<string, string> = {};\n for (const name of ACP_FORWARDED_HEADERS) {\n const value = name === ACP_REQUEST_ID_HEADER ? requestId : header(req, name)?.trim();\n if (\n value !== undefined &&\n value.length > 0 &&\n value.length <= ACP_MAX_FORWARDED_HEADER_LENGTH &&\n isVisibleAscii(value)\n ) {\n forwarded[name] = value;\n }\n }\n return forwarded;\n}\n\nfunction isUsableIdempotencyKey(value: string): boolean {\n return (\n value.length > 0 && value.length <= ACP_MAX_IDEMPOTENCY_KEY_LENGTH && isVisibleAscii(value)\n );\n}\n\n/**\n * The caller's correlation id, echoed back but never used as the gateway's own\n * request id. It is caller-controlled text bound for a response header, so it\n * is truncated and dropped unless it is printable ASCII.\n */\nfunction normalizeRequestId(value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n const trimmed = value.trim().slice(0, ACP_MAX_REQUEST_ID_LENGTH);\n if (trimmed.length === 0) return undefined;\n if (!isVisibleAscii(trimmed)) return undefined;\n return trimmed;\n}\n\nfunction isVisibleAscii(value: string): boolean {\n return !/[^\\x20-\\x7e]/.test(value);\n}\n\nfunction header(req: IncomingMessage, name: string): string | undefined {\n const value = req.headers[name];\n return Array.isArray(value) ? value[0] : value;\n}\n","/**\n * Execution outcome -> ACP response, under two rules. A successful answer must\n * be a document the pinned snapshot accepts, on the status ACP fixes for the\n * route, because a merchant backend is not automatically ACP-conformant. A\n * failure uses ACP's error shape. Only selected fields of a valid merchant\n * ACP error and a capped `Retry-After` delay can cross this boundary; internal\n * details stay in logs.\n */\nimport type { CommerceError, DeliveredOutcome } from '../../core';\nimport { BackendErrorResponse } from '../../core/execution/backend-http';\nimport { isRecord } from '../../core/is-record';\nimport {\n ACP_MERCHANT_RETRY_AFTER_DEFAULT_SECONDS,\n ACP_MERCHANT_RETRY_AFTER_MAX_SECONDS,\n type AcpCheckoutOperation,\n} from './constants';\nimport { type AcpErrorType, type AcpFailure, acpFailure } from './errors';\nimport { type AcpDefinition, validateAcpDocument } from './validation';\n\n/** One ACP answer, as a value: it may have to be stored before it is written */\nexport interface AcpResponse {\n readonly status: number;\n readonly body: unknown;\n /** True when this answer came from the idempotency store rather than work done now */\n readonly replayed?: boolean;\n /**\n * Seconds for `Retry-After`, set only where a retry is the right move. Not\n * derived from the status: two of the 409s this adapter returns must not\n * invite a retry.\n */\n readonly retryAfterSeconds?: number;\n}\n\n/**\n * The status each route answers on success, fixed by ACP. A merchant backend\n * that succeeded with a different one has not implemented the operation ACP\n * describes, so its answer is refused rather than quietly renumbered.\n */\nexport const ACP_SUCCESS_STATUS: Readonly<Record<AcpCheckoutOperation, number>> = {\n createCheckoutSession: 201,\n updateCheckoutSession: 200,\n getCheckoutSession: 200,\n completeCheckoutSession: 200,\n cancelCheckoutSession: 200,\n};\n\n/**\n * A mapped response, plus what the operator needs in the log to understand a\n * refusal. `logDetail` is kept apart from `response` so it never reaches the\n * client.\n */\nexport interface AcpMappedResponse {\n readonly response: AcpResponse;\n readonly logDetail?: Readonly<Record<string, unknown>>;\n}\n\nconst PROCESSING_ERROR = acpFailure(\n 500,\n 'processing_error',\n 'processing_error',\n 'The server could not process this checkout operation.',\n);\n\nexport function toAcpResponse(\n operation: AcpCheckoutOperation,\n outcome: DeliveredOutcome,\n): AcpMappedResponse {\n const expected = ACP_SUCCESS_STATUS[operation];\n if (outcome.backendStatus !== expected) {\n return {\n response: asResponse(PROCESSING_ERROR),\n logDetail: {\n reason: 'unexpected-backend-status',\n operation,\n backendStatus: outcome.backendStatus,\n expected,\n },\n };\n }\n\n const definition = responseDefinition(operation, outcome.body);\n const failure = validateAcpDocument(definition, outcome.body);\n if (failure !== undefined) {\n // Not ACP, so not forwarded, and the caller learns nothing of its shape:\n // the pointer is into the merchant's document, ours to fix, not theirs\n return {\n response: asResponse(PROCESSING_ERROR),\n logDetail: {\n reason: 'backend-response-not-acp',\n operation,\n definition,\n path: failure.path ?? '$',\n keyword: failure.code,\n },\n };\n }\n\n const htmlPath = rawHtmlPath(outcome.body, '$');\n if (htmlPath !== undefined) {\n // Reject detected HTML markup before forwarding merchant markdown\n return {\n response: asResponse(PROCESSING_ERROR),\n logDetail: { reason: 'backend-markdown-has-raw-html', operation, path: htmlPath },\n };\n }\n\n return { response: { status: expected, body: outcome.body } };\n}\n\n// Detect common HTML markup: tags, comments, processing instructions,\n// declarations and CDATA. Autolinks such as <https://x> do not match.\nconst RAW_HTML = /<\\/?[A-Za-z][A-Za-z0-9-]*(?=[\\s/>]|$)|<!--|<\\?|<![A-Za-z]|<!\\[CDATA\\[/;\n\n// Ignore backtick-delimited code spans when checking for HTML markup\nconst CODE_SPAN = /(`+)[\\s\\S]*?\\1/g;\n\n// Path to the first markdown `content` with detected HTML markup\nfunction rawHtmlPath(node: unknown, path: string): string | undefined {\n if (Array.isArray(node)) {\n for (const [index, item] of node.entries()) {\n const found = rawHtmlPath(item, `${path}[${index}]`);\n if (found !== undefined) return found;\n }\n return undefined;\n }\n if (!isRecord(node)) return undefined;\n const content = node['content'];\n if (\n node['content_type'] === 'markdown' &&\n typeof content === 'string' &&\n RAW_HTML.test(content.replace(CODE_SPAN, ''))\n ) {\n return `${path}.content`;\n }\n for (const [key, value] of Object.entries(node)) {\n const found = rawHtmlPath(value, `${path}.${key}`);\n if (found !== undefined) return found;\n }\n return undefined;\n}\n\n/**\n * Completion is the one route with two shapes, chosen by the session's own\n * `status`. A completed session must carry its order\n * (`CheckoutSessionWithOrder`, where `Order` requires an id), but a completion\n * that ends in a declined payment or an out-of-stock item answers 200 with an\n * ordinary session and no order, as the snapshot's own examples show.\n */\nfunction responseDefinition(operation: AcpCheckoutOperation, body: unknown): AcpDefinition {\n if (operation !== 'completeCheckoutSession') return 'checkoutSession';\n const status = (body as { status?: unknown } | null)?.status;\n return status === 'completed' ? 'checkoutSessionWithOrder' : 'checkoutSession';\n}\n\n/**\n * Map pipeline failures to ACP errors. For relayed merchant statuses, a\n * valid ACP error can contribute its type, safe code and optional param. The\n * merchant's message and remaining body fields stay out of the response.\n */\nexport function mapCommerceErrorToAcp(\n error: CommerceError,\n operation: AcpCheckoutOperation,\n): AcpFailure {\n switch (error.code) {\n case 'INPUT_INVALID':\n // The ACP schema accepted the document, so the resource's own input\n // schema rejected it: reported without naming its internal fields\n return acpFailure(\n 400,\n 'invalid_request',\n 'invalid_request_body',\n 'The request could not be accepted for this checkout operation.',\n );\n case 'BACKEND_TIMEOUT':\n return acpFailure(\n 504,\n 'service_unavailable',\n 'service_unavailable',\n 'The merchant did not respond in time.',\n );\n case 'GATEWAY_BUSY':\n return acpFailure(\n 503,\n 'service_unavailable',\n 'service_unavailable',\n 'The gateway is busy; retry shortly.',\n );\n case 'BACKEND_ERROR':\n return fromBackendStatus(error, operation);\n default:\n // RESOURCE_NOT_FOUND means the mapping points at a resource that is gone;\n // a PAYMENT_* code means a checkout resource was configured as paid.\n // Both are broken deployments, not something the caller did.\n return PROCESSING_ERROR;\n }\n}\n\n/**\n * Relay compatible merchant statuses and map merchant 429/503 to ACP 503.\n * Merchant 401/403 maps to 502 so it does not suggest the agent's bearer\n * token failed.\n */\nfunction fromBackendStatus(error: CommerceError, operation: AcpCheckoutOperation): AcpFailure {\n const failure = statusFailure(error, operation);\n return failure.status < 500 ? withMerchantError(failure, error) : failure;\n}\n\n/** True for merchant 429, which the adapter treats as unprocessed */\nexport function isMerchantRateLimit(error: CommerceError): boolean {\n return error.code === 'BACKEND_ERROR' && error.details?.['status'] === 429;\n}\n\n// Parse whole seconds, cap the delay, and use the default for other forms\nfunction merchantRetryAfterSeconds(error: CommerceError): number {\n const value =\n error.cause instanceof BackendErrorResponse ? error.cause.headers['retry-after'] : undefined;\n if (value === undefined || !/^\\d{1,9}$/.test(value.trim())) {\n return ACP_MERCHANT_RETRY_AFTER_DEFAULT_SECONDS;\n }\n return Math.min(Math.max(Number(value), 1), ACP_MERCHANT_RETRY_AFTER_MAX_SECONDS);\n}\n\n// Limit merchant codes to snake_case and params to short printable text\n// beginning with `$`. The `idempotency_` codes describe the caller's own key\n// and only the gateway issues them.\nconst MERCHANT_CODE = /^(?!idempotency_)[a-z][a-z0-9_]{0,63}$/;\nconst MERCHANT_PARAM = /^\\$[\\x20-\\x7e]{0,255}$/;\n\n/**\n * Keep the type and safe code from a valid merchant ACP error on a relayed\n * status. Include a safe param when present; retain the gateway's message.\n */\nfunction withMerchantError(failure: AcpFailure, error: CommerceError): AcpFailure {\n const body = error.cause instanceof BackendErrorResponse ? error.cause.body : undefined;\n if (!isRecord(body) || validateAcpDocument('error', body) !== undefined) return failure;\n const { type, code, param } = body;\n if (typeof code !== 'string' || !MERCHANT_CODE.test(code)) return failure;\n const relayParam = typeof param === 'string' && MERCHANT_PARAM.test(param) ? param : undefined;\n return acpFailure(\n failure.status,\n type as AcpErrorType,\n code,\n failure.error.message,\n relayParam !== undefined ? { param: relayParam } : {},\n );\n}\n\nfunction statusFailure(error: CommerceError, operation: AcpCheckoutOperation): AcpFailure {\n const merchantStatus = error.details?.['status'];\n const status = typeof merchantStatus === 'number' ? merchantStatus : 0;\n switch (status) {\n case 404:\n return acpFailure(\n 404,\n 'invalid_request',\n 'checkout_session_not_found',\n 'No such checkout session.',\n );\n case 405:\n return operation === 'cancelCheckoutSession'\n ? acpFailure(\n 405,\n 'invalid_request',\n 'checkout_session_not_cancelable',\n 'This checkout session can no longer be canceled.',\n )\n : acpFailure(\n 405,\n 'invalid_request',\n 'method_not_allowed',\n 'The merchant does not allow this operation on this checkout session.',\n );\n case 400:\n case 422:\n // Relayed on the merchant's own status: the snapshot's 3DS refusal is a\n // 400, and its only 422 is the idempotency conflict\n return acpFailure(\n status,\n 'invalid_request',\n 'invalid_request_body',\n 'The merchant rejected this checkout request.',\n );\n case 409:\n return acpFailure(\n 409,\n 'invalid_request',\n 'checkout_session_conflict',\n 'This checkout session is in a state that does not allow this operation.',\n );\n case 429:\n case 503:\n return {\n ...acpFailure(\n 503,\n 'service_unavailable',\n 'service_unavailable',\n 'The merchant is temporarily unavailable.',\n ),\n retryAfterSeconds: merchantRetryAfterSeconds(error),\n };\n default:\n return acpFailure(\n 502,\n 'processing_error',\n 'processing_error',\n 'The merchant could not process this checkout operation.',\n );\n }\n}\n\nexport function asResponse(failure: AcpFailure): AcpResponse {\n return {\n status: failure.status,\n body: failure.error,\n ...(failure.retryAfterSeconds !== undefined\n ? { retryAfterSeconds: failure.retryAfterSeconds }\n : {}),\n };\n}\n","/**\n * ACP (Agentic Commerce Protocol) adapter, experimental.\n *\n * Serves two paths: the configured mount (`/acp`), where the five stable\n * checkout routes live, and the specification-fixed `/.well-known/acp.json`,\n * declared through `additionalHttpRoutes` so the gateway needs no ACP-specific\n * routing.\n *\n * A request that passes every protocol guard runs its mapped resource through\n * the pipeline, under an idempotency claim when it carries a key. This file\n * never calls a merchant backend and never inspects a payment object.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport {\n type AdapterDescriptor,\n type AdapterHealth,\n type AdapterHttpRoute,\n CommerceError,\n type CommerceResource,\n type DeliveredOutcome,\n type HttpProtocolAdapter,\n type ProtocolAdapterContext,\n toCommerceError,\n} from '../../core';\nimport { toLogInfo } from '../../core/errors';\nimport { PACKAGE_VERSION } from '../../version';\nimport { createBearerCheck } from '../http';\nimport { toCanonicalRequest } from './checkout-mapping';\nimport {\n ACP_CHECKOUT_OPERATIONS,\n ACP_IDEMPOTENCY_KEY_HEADER,\n ACP_IDEMPOTENT_REPLAYED_HEADER,\n ACP_IN_FLIGHT_RETRY_AFTER_SECONDS,\n ACP_REQUEST_ID_HEADER,\n ACP_WELL_KNOWN_PATH,\n type AcpCheckoutOperation,\n} from './constants';\nimport { buildDescriptor } from './descriptor';\nimport { type AcpDiscoveryMetadata, buildAcpDiscoveryDocument } from './discovery';\nimport {\n type AcpFailure,\n type AcpResponseHeaders,\n acpFailure,\n writeAcpFailure,\n writeAcpJson,\n} from './errors';\nimport { operationKey, requestFingerprint } from './idempotency/fingerprint';\nimport {\n type AcpIdempotencyScope,\n type AcpIdempotencyStore,\n createAcpIdempotencyStore,\n} from './idempotency/store';\nimport { type AcpGuardedRequest, acpEchoHeaders, guardAcpRequest } from './request-guards';\nimport {\n type AcpResponse,\n asResponse,\n isMerchantRateLimit,\n mapCommerceErrorToAcp,\n toAcpResponse,\n} from './response-mapping';\nimport { validateAcpDocument } from './validation';\n\n// Discovery is fixed for the life of the process, so edge caches may keep it\nconst DISCOVERY_CACHE_CONTROL = 'public, max-age=3600';\n\n/**\n * Whether this attempt could have changed anything at the merchant. `no` must\n * be proven, because only `no` frees an idempotency key for a retry; `unknown`\n * and `yes` are treated alike and differ only in the log.\n */\ntype MerchantReach = 'no' | 'unknown' | 'yes';\n\ninterface AcpCheckoutAttempt {\n readonly response: AcpResponse;\n readonly reached: MerchantReach;\n}\n\n/**\n * The codes the pipeline raises strictly before it calls the merchant. An\n * allowlist, so a new code counts as ambiguous rather than freeing a key.\n * `STORAGE_ERROR` is absent: the pipeline raises it only when reserving a\n * payment attempt, which a free checkout resource never does, so on this route\n * it can only be unexpected and counts as ambiguous.\n */\nconst PRE_BACKEND_ERROR_CODES: ReadonlySet<string> = new Set([\n 'CONFIG_INVALID',\n 'RESOURCE_NOT_FOUND',\n 'INPUT_INVALID',\n 'PROTOCOL_UNSUPPORTED',\n 'GATEWAY_BUSY',\n 'PAYMENT_REQUIRED',\n 'PAYMENT_INVALID',\n 'PAYMENT_REPLAYED',\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'PAYMENT_SETTLEMENT_FAILED',\n 'AUTHORIZATION_REQUIRED',\n 'AUTHORIZATION_INVALID',\n 'AUTHORIZATION_REPLAYED',\n 'AUTHORIZATION_PROVIDER_UNAVAILABLE',\n]);\n\n// Treat merchant 429 as unprocessed and release the key. A 503 may follow\n// partial work, so its outcome stays unknown.\nfunction reachedFor(error: CommerceError): MerchantReach {\n return PRE_BACKEND_ERROR_CODES.has(error.code) || isMerchantRateLimit(error) ? 'no' : 'unknown';\n}\n\nfunction notReached(failure: AcpFailure): AcpCheckoutAttempt {\n return { response: asResponse(failure), reached: 'no' };\n}\n\nexport interface AcpAdapterOptions {\n readonly mountPath: string;\n /** The configured bearer token. Never logged, never echoed, never published */\n readonly token: string;\n /** Which canonical resource implements each ACP checkout operation */\n readonly operations: Readonly<Record<AcpCheckoutOperation, string>>;\n /** Where checkout idempotency records live, and how long they are kept */\n readonly idempotency: {\n readonly path: string;\n readonly retentionHours: number;\n /**\n * Declare that the merchant deduplicates by the derived `Idempotency-Key`.\n * Allows a fresh retry after a 5xx. Defaults to false.\n */\n readonly merchantIdempotent?: boolean;\n };\n readonly discovery?: AcpDiscoveryMetadata;\n}\n\nexport class AcpProtocolAdapter implements HttpProtocolAdapter {\n readonly name = 'acp' as const;\n readonly mountPath: string;\n readonly descriptor: AdapterDescriptor;\n readonly additionalHttpRoutes: readonly AdapterHttpRoute[];\n\n private readonly isAuthorized: (authorizationHeader: string | undefined) => boolean;\n private readonly operations: Readonly<Record<AcpCheckoutOperation, string>>;\n private readonly idempotencyOptions: AcpAdapterOptions['idempotency'];\n /**\n * The deployment an idempotency claim is scoped to, `context.publicBaseUrl`.\n * Not readonly because it is known only once the adapter starts.\n */\n private deployment: string | undefined;\n private readonly discoveryMetadata: AcpDiscoveryMetadata | undefined;\n private idempotency: AcpIdempotencyStore | undefined;\n private resources: ReadonlyMap<AcpCheckoutOperation, CommerceResource> = new Map();\n\n private context: ProtocolAdapterContext | undefined;\n private started = false;\n // Built once at start: the document is fixed by config, and a per-request\n // build would be work an unauthenticated GET could trigger at will\n private discovery: Record<string, unknown> | undefined;\n\n constructor(options: AcpAdapterOptions) {\n this.mountPath = options.mountPath;\n this.isAuthorized = createBearerCheck(options.token);\n this.operations = options.operations;\n this.idempotencyOptions = options.idempotency;\n this.discoveryMetadata = options.discovery;\n this.descriptor = buildDescriptor(PACKAGE_VERSION);\n this.additionalHttpRoutes = [\n {\n method: 'GET',\n path: ACP_WELL_KNOWN_PATH,\n handleHttp: (req, res) => this.handleDiscovery(req, res),\n },\n ];\n }\n\n async start(context: ProtocolAdapterContext): Promise<void> {\n this.context = context;\n this.started = false;\n\n const document = buildAcpDiscoveryDocument({\n publicBaseUrl: context.publicBaseUrl,\n mountPath: this.mountPath,\n ...(this.discoveryMetadata !== undefined ? { metadata: this.discoveryMetadata } : {}),\n });\n // Configured metadata is free text (a currency that is not ISO 4217, an\n // intervention type ACP does not define), so the document is validated\n // against the pinned snapshot before it is published. A failure stops only\n // this adapter.\n const invalid = validateAcpDocument('discoveryResponse', document);\n if (invalid !== undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `ACP discovery document does not conform to the ${this.descriptor.supportedSpec} snapshot at \"${invalid.path ?? '$'}\" (${invalid.code}) - check protocols.acp.discovery`,\n { details: { path: invalid.path ?? '$', code: invalid.code } },\n );\n }\n\n // Config already refuses a mapping to a resource that is not acp-exposed;\n // the adapter checks again, as MCP and A2A do\n const exposed = new Map(\n context.resources.listExposedVia('acp').map((resource) => [resource.id, resource]),\n );\n const resolved = new Map<AcpCheckoutOperation, CommerceResource>();\n for (const operation of ACP_CHECKOUT_OPERATIONS) {\n const resourceId = this.operations[operation];\n const resource = exposed.get(resourceId);\n if (resource === undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `ACP operation \"${operation}\" is mapped to resource \"${resourceId}\", which is not exposed via acp`,\n { details: { operation, resourceId } },\n );\n }\n resolved.set(operation, resource);\n }\n this.resources = resolved;\n\n this.deployment = context.publicBaseUrl;\n this.idempotency = createAcpIdempotencyStore({\n path: this.idempotencyOptions.path,\n retentionHours: this.idempotencyOptions.retentionHours,\n releaseOrphans: this.idempotencyOptions.merchantIdempotent === true,\n logger: context.logger,\n });\n\n this.discovery = document;\n this.started = true;\n context.logger.info(\n {\n mountPath: this.mountPath,\n discoveryPath: ACP_WELL_KNOWN_PATH,\n idempotencyRetentionHours: this.idempotencyOptions.retentionHours,\n },\n 'acp adapter started',\n );\n }\n\n /** `GET /.well-known/acp.json`: public, unauthenticated, cacheable */\n async handleDiscovery(req: IncomingMessage, res: ServerResponse): Promise<void> {\n try {\n if (!this.started || this.discovery === undefined) {\n writeAcpFailure(\n res,\n acpFailure(\n 503,\n 'service_unavailable',\n 'service_unavailable',\n 'The ACP adapter is not running.',\n ),\n );\n return;\n }\n if (req.method !== 'GET') {\n writeAcpFailure(\n res,\n acpFailure(\n 405,\n 'invalid_request',\n 'method_not_allowed',\n 'The ACP discovery document is read-only.',\n ),\n { allow: 'GET' },\n );\n return;\n }\n writeAcpJson(res, 200, this.discovery, { 'cache-control': DISCOVERY_CACHE_CONTROL });\n } catch (err) {\n this.fail(res, err, 'acp adapter: discovery request failed');\n }\n }\n\n /** `<mountPath>/checkout_sessions...`: the five stable checkout routes */\n async handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void> {\n try {\n if (!this.started) {\n // Reachable during shutdown, which stops adapters before the server\n writeAcpFailure(\n res,\n acpFailure(\n 503,\n 'service_unavailable',\n 'service_unavailable',\n 'The ACP adapter is not running.',\n ),\n acpEchoHeaders(req),\n );\n return;\n }\n\n const guarded = await guardAcpRequest(req, {\n mountPath: this.mountPath,\n isAuthorized: this.isAuthorized,\n });\n if (!guarded.ok) {\n writeAcpFailure(res, guarded, guarded.headers);\n return;\n }\n\n const request = guarded.value;\n const response = await this.dispatch(request);\n writeAcpJson(res, response.status, response.body, this.responseHeaders(request, response));\n } catch (err) {\n this.fail(res, err, 'acp adapter: request handling failed', acpEchoHeaders(req));\n }\n }\n\n /**\n * One request, at most one execution. A body-bearing route claims its\n * idempotency key before the work starts, so a retry arriving meanwhile finds\n * the claim; the read-only GET carries no key.\n */\n private async dispatch(request: AcpGuardedRequest): Promise<AcpResponse> {\n const store = this.idempotency;\n const deployment = this.deployment;\n const key = request.idempotencyKey;\n if (store === undefined || deployment === undefined || key === undefined) {\n return (await this.runCheckout(request)).response;\n }\n\n const scope: AcpIdempotencyScope = { deployment, endpoint: request.route.path, key };\n const claim = store.claim(scope, requestFingerprint(request.body));\n\n switch (claim.kind) {\n case 'in-flight':\n return {\n ...asResponse(\n acpFailure(\n 409,\n 'invalid_request',\n 'idempotency_in_flight',\n 'A request with this Idempotency-Key is still being processed.',\n ),\n ),\n retryAfterSeconds: ACP_IN_FLIGHT_RETRY_AFTER_SECONDS,\n };\n case 'unresolved':\n // Neither re-run nor replayed: an earlier attempt reached the merchant\n // and its outcome is unknown (see the idempotency store)\n return asResponse(\n acpFailure(\n 409,\n 'invalid_request',\n 'idempotency_unresolved',\n 'An earlier request with this Idempotency-Key reached the merchant and its outcome is unknown. Check the operation with the merchant before retrying.',\n ),\n );\n case 'conflict':\n return asResponse(\n acpFailure(\n 422,\n 'invalid_request',\n 'idempotency_conflict',\n 'This Idempotency-Key was already used for a different request body.',\n ),\n );\n case 'replay':\n return { status: claim.status, body: claim.body, replayed: true };\n default:\n break;\n }\n\n let outcome: AcpCheckoutAttempt;\n try {\n outcome = await this.runCheckout(request, operationKey(scope));\n } catch (err) {\n // An adapter bug, not a merchant verdict; the merchant may have been\n // called, so the claim is kept\n store.markUnresolved(scope);\n throw err;\n }\n\n // A 2xx or 4xx is an outcome, even a refusal, and answers every retry\n if (outcome.response.status < 500) {\n store.complete(scope, outcome.response);\n } else if (outcome.reached === 'no' || this.idempotencyOptions.merchantIdempotent === true) {\n // Release when no call ran, the merchant returned 429, or the merchant\n // deduplicates retries by the derived key\n store.release(scope);\n } else {\n // A timeout, a merchant status ACP cannot relay or a non-ACP reply: the\n // merchant may have acted, and freeing the key could turn one checkout\n // into two orders\n store.markUnresolved(scope);\n }\n return outcome.response;\n }\n\n // One accepted request, one `pipeline.execute()`\n private async runCheckout(\n request: AcpGuardedRequest,\n idempotencyKey?: string,\n ): Promise<AcpCheckoutAttempt> {\n const context = this.context;\n const resource = this.resources.get(request.route.operation);\n if (context === undefined || resource === undefined) {\n return notReached(\n acpFailure(\n 503,\n 'service_unavailable',\n 'service_unavailable',\n 'The ACP adapter is not running.',\n ),\n );\n }\n\n const canonical = toCanonicalRequest({\n request,\n resourceId: resource.id,\n requestId: context.ids.next('acp'),\n receivedAt: context.clock.nowIso(),\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n });\n\n try {\n const outcome = await context.pipeline.execute(canonical);\n if (outcome.kind === 'payment-required') {\n // Config refuses a paid checkout resource and ACP cannot carry a\n // gateway challenge, so this is a broken deployment. Nothing about the\n // challenge is disclosed.\n context.logger.error(\n { resourceId: resource.id, requestId: canonical.requestId },\n 'acp adapter: mapped checkout resource returned payment-required - it must be priced free',\n );\n return notReached(\n acpFailure(\n 500,\n 'processing_error',\n 'processing_error',\n 'The server could not process this checkout operation.',\n ),\n );\n }\n const mapped = toAcpResponse(request.route.operation, outcome as DeliveredOutcome);\n if (mapped.logDetail !== undefined) {\n // The merchant answered, but not with ACP: the details go to the log,\n // the caller gets the refusal in `response`\n context.logger.error(\n { resourceId: resource.id, requestId: canonical.requestId, ...mapped.logDetail },\n 'acp adapter: refusing to forward a non-conformant merchant response',\n );\n }\n // Delivered, so the merchant ran the operation even if its answer is\n // refused as non-ACP; the order may exist, so the key is not freed\n return { response: mapped.response, reached: 'yes' };\n } catch (err) {\n const error = toCommerceError(err);\n context.logger.warn(\n {\n resourceId: resource.id,\n requestId: canonical.requestId,\n reached: reachedFor(error),\n err: toLogInfo(error),\n },\n 'acp adapter: checkout execution failed',\n );\n return {\n response: asResponse(mapCommerceErrorToAcp(error, request.route.operation)),\n reached: reachedFor(error),\n };\n }\n }\n\n // Protocol-owned headers only. No merchant header is proxied: `Retry-After`\n // is written from seconds the mapping parsed and capped.\n private responseHeaders(\n request: AcpGuardedRequest,\n response?: AcpResponse,\n ): Readonly<Record<string, string>> {\n const replayed = response?.replayed === true;\n return {\n ...(request.requestId !== undefined ? { [ACP_REQUEST_ID_HEADER]: request.requestId } : {}),\n ...(request.idempotencyKey !== undefined\n ? { [ACP_IDEMPOTENCY_KEY_HEADER]: request.idempotencyKey }\n : {}),\n ...(replayed ? { [ACP_IDEMPOTENT_REPLAYED_HEADER]: 'true' } : {}),\n ...(response?.retryAfterSeconds !== undefined\n ? { 'retry-after': String(response.retryAfterSeconds) }\n : {}),\n };\n }\n\n private fail(\n res: ServerResponse,\n err: unknown,\n message: string,\n headers: AcpResponseHeaders = {},\n ): void {\n // Nothing from `err` reaches the client\n this.context?.logger.error({ err: toLogInfo(err) }, message);\n writeAcpFailure(\n res,\n acpFailure(500, 'processing_error', 'internal_error', 'Internal server error.'),\n headers,\n );\n }\n\n async health(): Promise<AdapterHealth> {\n const checkedAt = this.context?.clock.nowIso() ?? new Date().toISOString();\n if (!this.started || this.discovery === undefined) {\n return { status: 'fail', detail: 'ACP adapter has not been started.', checkedAt };\n }\n return {\n status: 'pass',\n detail: `checkout service published at ${this.mountPath}.`,\n checkedAt,\n };\n }\n\n async stop(): Promise<void> {\n this.started = false;\n this.discovery = undefined;\n this.resources = new Map();\n this.idempotency?.close();\n this.idempotency = undefined;\n this.deployment = undefined;\n this.context = undefined;\n }\n}\n\nexport function createAcpAdapter(options: AcpAdapterOptions): AcpProtocolAdapter {\n return new AcpProtocolAdapter(options);\n}\n","/**\n * Defense in depth against persisting secrets. Receipt, event and payment\n * metadata must not carry secrets (docs/contracts.md, \"Store no secrets\"); at\n * the persistence boundary this module replaces secret-shaped values rather\n * than rejecting the write, because event persistence must not break a\n * commerce flow.\n */\n\n// Matches anywhere in the key (only `auth` and `proof` must be the whole key),\n// so an audit field whose name contains \"token\", \"session\", \"jwt\" or similar\n// persists as [REDACTED]\nconst SECRET_KEY_PATTERN =\n /private[-_ ]?key|secret|password|mnemonic|seed[-_ ]?phrase|api[-_ ]?key|authoriz(e|ation)|^auth$|auth[-_]?header|payment[-_ ]?proof|^proof$|x-payment|signature|signed[-_ ]?message|token|bearer|credential|cookie|session|jwt/i;\n\nconst REDACTED = '[REDACTED]';\n\n/** True if `key` looks like it names a secret value */\nexport function isSecretKey(key: string): boolean {\n return SECRET_KEY_PATTERN.test(key);\n}\n\n/**\n * Returns a copy with every value under a secret-shaped key replaced, at any\n * depth. Clean input comes back equal to itself.\n */\nexport function redact<T>(value: T): T {\n return redactValue(value) as T;\n}\n\nfunction redactValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(redactValue);\n }\n if (value !== null && typeof value === 'object') {\n const out: Record<string, unknown> = {};\n for (const [key, inner] of Object.entries(value as Record<string, unknown>)) {\n out[key] = isSecretKey(key) ? REDACTED : redactValue(inner);\n }\n return out;\n }\n return value;\n}\n","/**\n * SQLite row shapes and their mapping to and from the canonical model. Under\n * `exactOptionalPropertyTypes`, an optional field is set only when present.\n */\nimport type {\n AuthorizationRecord,\n CommerceEvent,\n CommerceEventType,\n CommerceReceipt,\n PaymentAttempt,\n PaymentResult,\n} from '../../core';\nimport { redact } from './redact';\n\nexport interface ReceiptRow {\n readonly id: string;\n readonly request_id: string;\n readonly resource_id: string;\n readonly payment_json: string | null;\n readonly delivered_at: string;\n readonly backend_status: number;\n readonly duration_ms: number | null;\n readonly protocol: string | null;\n readonly metadata_json: string | null;\n readonly authorization_json: string | null;\n}\n\nexport interface EventRow {\n readonly id: string;\n readonly type: string;\n readonly request_id: string;\n readonly resource_id: string | null;\n readonly at: string;\n readonly adapter: string | null;\n readonly payment_provider: string | null;\n readonly duration_ms: number | null;\n readonly status: string | null;\n readonly data_json: string | null;\n}\n\nexport interface PaymentAttemptRow {\n readonly id: string;\n readonly request_id: string;\n readonly resource_id: string;\n readonly provider: string;\n readonly replay_key: string;\n readonly status: string;\n readonly amount: string;\n readonly currency: string;\n readonly payer: string | null;\n readonly payee: string | null;\n readonly external_reference: string | null;\n readonly rejection_reason: string | null;\n readonly created_at: string;\n readonly updated_at: string;\n}\n\nexport function receiptToRow(receipt: CommerceReceipt): {\n id: string;\n request_id: string;\n resource_id: string;\n payment_json: string | null;\n delivered_at: string;\n backend_status: number;\n duration_ms: number | null;\n protocol: string | null;\n metadata_json: string | null;\n authorization_json: string | null;\n} {\n return {\n id: receipt.id,\n request_id: receipt.requestId,\n resource_id: receipt.resourceId,\n payment_json: receipt.payment !== undefined ? JSON.stringify(redact(receipt.payment)) : null,\n delivered_at: receipt.deliveredAt,\n backend_status: receipt.backendStatus,\n duration_ms: receipt.durationMs ?? null,\n protocol: receipt.protocol ?? null,\n metadata_json: receipt.metadata !== undefined ? JSON.stringify(redact(receipt.metadata)) : null,\n authorization_json:\n receipt.authorization !== undefined ? JSON.stringify(redact(receipt.authorization)) : null,\n };\n}\n\nexport function rowToReceipt(row: ReceiptRow): CommerceReceipt {\n const payment =\n row.payment_json !== null ? (JSON.parse(row.payment_json) as PaymentResult) : undefined;\n const metadata =\n row.metadata_json !== null\n ? (JSON.parse(row.metadata_json) as Record<string, unknown>)\n : undefined;\n // Null for a receipt written before this column existed and for a resource\n // that requires no authorization\n const authorization =\n row.authorization_json !== null\n ? (JSON.parse(row.authorization_json) as AuthorizationRecord)\n : undefined;\n return {\n id: row.id,\n requestId: row.request_id,\n resourceId: row.resource_id,\n deliveredAt: row.delivered_at,\n backendStatus: row.backend_status,\n ...(payment !== undefined ? { payment } : {}),\n ...(row.duration_ms !== null ? { durationMs: row.duration_ms } : {}),\n ...(row.protocol !== null ? { protocol: row.protocol } : {}),\n ...(metadata !== undefined ? { metadata } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n };\n}\n\nexport function eventToRow(event: CommerceEvent): {\n id: string;\n type: string;\n request_id: string;\n resource_id: string | null;\n at: string;\n adapter: string | null;\n payment_provider: string | null;\n duration_ms: number | null;\n status: string | null;\n data_json: string | null;\n} {\n return {\n id: event.id,\n type: event.type,\n request_id: event.requestId,\n resource_id: event.resourceId ?? null,\n at: event.at,\n adapter: event.adapter ?? null,\n payment_provider: event.paymentProvider ?? null,\n duration_ms: event.durationMs ?? null,\n status: event.status ?? null,\n data_json: event.data !== undefined ? JSON.stringify(redact(event.data)) : null,\n };\n}\n\nexport function rowToEvent(row: EventRow): CommerceEvent {\n const data =\n row.data_json !== null ? (JSON.parse(row.data_json) as Record<string, unknown>) : undefined;\n return {\n id: row.id,\n type: row.type as CommerceEventType,\n requestId: row.request_id,\n at: row.at,\n ...(row.resource_id !== null ? { resourceId: row.resource_id } : {}),\n ...(row.adapter !== null ? { adapter: row.adapter } : {}),\n ...(row.payment_provider !== null ? { paymentProvider: row.payment_provider } : {}),\n ...(row.duration_ms !== null ? { durationMs: row.duration_ms } : {}),\n ...(row.status !== null ? { status: row.status as 'ok' | 'error' } : {}),\n ...(data !== undefined ? { data } : {}),\n };\n}\n\nexport function rowToPaymentAttempt(row: PaymentAttemptRow): PaymentAttempt {\n return {\n id: row.id,\n requestId: row.request_id,\n resourceId: row.resource_id,\n provider: row.provider,\n replayKey: row.replay_key,\n status: row.status as PaymentAttempt['status'],\n amount: row.amount,\n currency: row.currency,\n ...(row.payer !== null ? { payer: row.payer } : {}),\n ...(row.payee !== null ? { payee: row.payee } : {}),\n ...(row.external_reference !== null ? { externalReference: row.external_reference } : {}),\n ...(row.rejection_reason !== null ? { rejectionReason: row.rejection_reason } : {}),\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n","/**\n * Receipt-store schema migrations. `PRAGMA user_version` records the applied\n * version, so a restart against an existing file keeps its data.\n */\nimport type Database from 'better-sqlite3';\n\ninterface Migration {\n readonly version: number;\n up(db: Database.Database): void;\n}\n\nconst MIGRATIONS: readonly Migration[] = [\n {\n version: 1,\n up(db) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS receipts (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n request_id TEXT NOT NULL,\n resource_id TEXT NOT NULL,\n payment_json TEXT,\n delivered_at TEXT NOT NULL,\n backend_status INTEGER NOT NULL,\n duration_ms INTEGER,\n protocol TEXT,\n metadata_json TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_receipts_request_id ON receipts(request_id);\n CREATE INDEX IF NOT EXISTS idx_receipts_delivered_at ON receipts(delivered_at);\n\n CREATE TABLE IF NOT EXISTS events (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n type TEXT NOT NULL,\n request_id TEXT NOT NULL,\n resource_id TEXT,\n at TEXT NOT NULL,\n adapter TEXT,\n payment_provider TEXT,\n duration_ms INTEGER,\n status TEXT,\n data_json TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_events_request_id ON events(request_id);\n CREATE INDEX IF NOT EXISTS idx_events_at ON events(at);\n\n CREATE TABLE IF NOT EXISTS payment_attempts (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n request_id TEXT NOT NULL,\n resource_id TEXT NOT NULL,\n provider TEXT NOT NULL,\n replay_key TEXT NOT NULL UNIQUE,\n status TEXT NOT NULL,\n amount TEXT NOT NULL,\n currency TEXT NOT NULL,\n payer TEXT,\n payee TEXT,\n external_reference TEXT,\n rejection_reason TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_payment_attempts_request_id ON payment_attempts(request_id);\n CREATE INDEX IF NOT EXISTS idx_payment_attempts_created_at ON payment_attempts(created_at);\n `);\n },\n },\n {\n version: 2,\n up(db) {\n // Not folded into v1: an existing database keeps its rows, and a receipt\n // written before this column has no authorization to record\n db.exec(`ALTER TABLE receipts ADD COLUMN authorization_json TEXT;`);\n },\n },\n {\n version: 3,\n up(db) {\n // Archive rejected attempts before reclaim overwrites them. replay_key\n // is not unique here: one authorization can be rejected and reclaimed\n // repeatedly.\n db.exec(`\n CREATE TABLE IF NOT EXISTS payment_attempt_history (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL,\n request_id TEXT NOT NULL,\n resource_id TEXT NOT NULL,\n provider TEXT NOT NULL,\n replay_key TEXT NOT NULL,\n status TEXT NOT NULL,\n amount TEXT NOT NULL,\n currency TEXT NOT NULL,\n payer TEXT,\n payee TEXT,\n external_reference TEXT,\n rejection_reason TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n superseded_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_replay_key ON payment_attempt_history(replay_key);\n CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_request_id ON payment_attempt_history(request_id);\n `);\n },\n },\n];\n\n/** Target schema version: the version of the last migration */\nexport const SCHEMA_VERSION = MIGRATIONS.at(-1)?.version ?? 0;\n\n/**\n * Brings `db` up to {@link SCHEMA_VERSION}, one transaction per migration.\n * On an already-migrated file it only reads `PRAGMA user_version`.\n */\nexport function migrate(db: Database.Database): void {\n const current = db.pragma('user_version', { simple: true }) as number;\n for (const migration of MIGRATIONS) {\n if (migration.version <= current) continue;\n const apply = db.transaction(() => {\n migration.up(db);\n db.pragma(`user_version = ${migration.version}`);\n });\n apply();\n }\n}\n","/**\n * SQLite implementation of the frozen ReceiptStore interface: a thin layer\n * over statements prepared once at open, with no ORM\n */\nimport { randomUUID } from 'node:crypto';\nimport { accessSync, constants as fsConstants } from 'node:fs';\nimport {\n type AdapterDescriptor,\n type AdapterHealth,\n type Clock,\n CommerceError,\n type CommerceEvent,\n type CommerceReceipt,\n type IdGenerator,\n type ListOptions,\n type Logger,\n NOOP_LOGGER,\n type PaymentAttempt,\n type PaymentAttemptReservation,\n type PaymentAttemptUpdate,\n type ReceiptStore,\n systemClock,\n toCommerceError,\n} from '../../core';\nimport { PACKAGE_VERSION } from '../../version';\nimport { openSqliteDatabase } from '../sqlite';\nimport {\n type EventRow,\n eventToRow,\n type PaymentAttemptRow,\n type ReceiptRow,\n receiptToRow,\n rowToEvent,\n rowToPaymentAttempt,\n rowToReceipt,\n} from './rows';\nimport { migrate, SCHEMA_VERSION } from './schema';\n\nconst DEFAULT_LIST_LIMIT = 50;\n/**\n * Ceiling on every list query, enforced in the store so every caller is\n * covered, not only the HTTP route. SQLite reads a negative `LIMIT` as no\n * limit, so `{ limit: -1 }` would otherwise return the whole table.\n */\nconst MAX_LIST_LIMIT = 500;\n\n// Clamps to a whole number in [1, MAX_LIST_LIMIT]. An absent or non-finite\n// limit (NaN, Infinity) takes the default, whether or not the caller filtered\n// it first.\nfunction clampListLimit(limit: number | undefined): number {\n const base = limit !== undefined && Number.isFinite(limit) ? limit : DEFAULT_LIST_LIMIT;\n return Math.min(Math.max(Math.trunc(base), 1), MAX_LIST_LIMIT);\n}\n\nexport interface SqliteReceiptStoreOptions {\n /** File path, or ':memory:' for tests. Parent directory is created if missing */\n readonly path: string;\n readonly logger?: Logger;\n readonly clock?: Clock;\n readonly ids?: IdGenerator;\n}\n\nconst defaultIds: IdGenerator = {\n next: (prefix) => (prefix !== undefined ? `${prefix}_${randomUUID()}` : randomUUID()),\n};\n\nfunction isUniqueConstraintOn(err: unknown, column: string): boolean {\n return (\n err instanceof Error &&\n 'code' in err &&\n (err as { code?: unknown }).code === 'SQLITE_CONSTRAINT_UNIQUE' &&\n err.message.includes(column)\n );\n}\n\nexport function createSqliteReceiptStore(options: SqliteReceiptStoreOptions): ReceiptStore {\n const logger = options.logger ?? NOOP_LOGGER;\n const clock = options.clock ?? systemClock;\n const ids = options.ids ?? defaultIds;\n const path = options.path;\n const isFileBacked = path !== ':memory:';\n\n // Shared with the ACP idempotency and AP2 replay stores, so the permission\n // hardening has one definition\n const db = openSqliteDatabase({ path, label: 'Receipt database', logger });\n migrate(db);\n\n const insertReceiptStmt = db.prepare(\n `INSERT INTO receipts (id, request_id, resource_id, payment_json, delivered_at, backend_status, duration_ms, protocol, metadata_json, authorization_json)\n VALUES (@id, @request_id, @resource_id, @payment_json, @delivered_at, @backend_status, @duration_ms, @protocol, @metadata_json, @authorization_json)`,\n );\n const getReceiptStmt = db.prepare<[string], ReceiptRow>('SELECT * FROM receipts WHERE id = ?');\n const listReceiptsStmt = db.prepare<[number], ReceiptRow>(\n 'SELECT * FROM receipts ORDER BY delivered_at DESC, seq DESC LIMIT ?',\n );\n const listReceiptsByRequestStmt = db.prepare<[string, number], ReceiptRow>(\n 'SELECT * FROM receipts WHERE request_id = ? ORDER BY delivered_at DESC, seq DESC LIMIT ?',\n );\n const countReceiptsStmt = db.prepare<[], { count: number }>(\n 'SELECT COUNT(*) AS count FROM receipts',\n );\n // backend_status is NOT NULL, so NOT BETWEEN cannot skip a row. 0 (no status\n // known) and every non-2xx status count as undelivered, the same rule as the\n // dashboard's deliveryResult() in ReceiptList.tsx.\n const countUndeliveredReceiptsStmt = db.prepare<[], { count: number }>(\n 'SELECT COUNT(*) AS count FROM receipts WHERE backend_status NOT BETWEEN 200 AND 299',\n );\n\n const insertEventStmt = db.prepare(\n `INSERT INTO events (id, type, request_id, resource_id, at, adapter, payment_provider, duration_ms, status, data_json)\n VALUES (@id, @type, @request_id, @resource_id, @at, @adapter, @payment_provider, @duration_ms, @status, @data_json)`,\n );\n const listEventsStmt = db.prepare<[number], EventRow>(\n 'SELECT * FROM events ORDER BY at DESC, seq DESC LIMIT ?',\n );\n const listEventsByRequestStmt = db.prepare<[string, number], EventRow>(\n 'SELECT * FROM events WHERE request_id = ? ORDER BY at DESC, seq DESC LIMIT ?',\n );\n\n const insertPaymentAttemptStmt = db.prepare<Record<string, unknown>, PaymentAttemptRow>(\n `INSERT INTO payment_attempts (id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at)\n VALUES (@id, @request_id, @resource_id, @provider, @replay_key, @status, @amount, @currency, @payer, @payee, @external_reference, @rejection_reason, @created_at, @updated_at)\n RETURNING *`,\n );\n // Keeps the rejected row a reclaim is about to overwrite\n const archiveRejectedAttemptStmt = db.prepare(\n `INSERT INTO payment_attempt_history (id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at, superseded_at)\n SELECT id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at, @created_at\n FROM payment_attempts\n WHERE replay_key = @replay_key AND provider = @provider AND status = 'rejected'`,\n );\n const reclaimPaymentAttemptStmt = db.prepare<Record<string, unknown>, PaymentAttemptRow>(\n `UPDATE payment_attempts SET id = @id, request_id = @request_id, resource_id = @resource_id,\n status = 'reserved', amount = @amount, currency = @currency,\n payer = @payer, payee = @payee, external_reference = NULL, rejection_reason = NULL,\n created_at = @created_at, updated_at = @updated_at\n WHERE replay_key = @replay_key AND provider = @provider AND status = 'rejected'\n RETURNING *`,\n );\n // COALESCE: an omitted field (bound as NULL by updatePaymentAttempt) keeps\n // its stored value. A status-only update must not erase external_reference,\n // which holds the tx hash of a settlement-uncertain attempt: the record that\n // the buyer's funds may have moved. Clearing a value would need an explicit\n // sentinel, not `undefined`.\n const updatePaymentAttemptStmt = db.prepare(\n `UPDATE payment_attempts SET status = @status,\n external_reference = COALESCE(@external_reference, external_reference),\n rejection_reason = COALESCE(@rejection_reason, rejection_reason),\n updated_at = @updated_at\n WHERE replay_key = @replay_key`,\n );\n const listPaymentAttemptsStmt = db.prepare<[number], PaymentAttemptRow>(\n 'SELECT * FROM payment_attempts ORDER BY created_at DESC, seq DESC LIMIT ?',\n );\n const listPaymentAttemptsByRequestStmt = db.prepare<[string, number], PaymentAttemptRow>(\n 'SELECT * FROM payment_attempts WHERE request_id = ? ORDER BY created_at DESC, seq DESC LIMIT ?',\n );\n const paymentAttemptStatusStmt = db.prepare<[string], Pick<PaymentAttemptRow, 'status'>>(\n 'SELECT status FROM payment_attempts WHERE replay_key = ?',\n );\n // IMMEDIATE takes the write lock before the read, so of two retries on one\n // file only one archives and reclaims. The other finds no rejected row, and\n // its insert hits the unique replay key.\n const reclaimRejectedAttempt = db.transaction(\n (params: Record<string, unknown>): PaymentAttemptRow | undefined => {\n archiveRejectedAttemptStmt.run(params);\n return reclaimPaymentAttemptStmt.get(params);\n },\n );\n\n let closed = false;\n\n const descriptor: AdapterDescriptor = {\n name: 'sqlite-receipt-store',\n kind: 'storage',\n implementationVersion: PACKAGE_VERSION,\n supportedSpec: `sqlite-schema-v${SCHEMA_VERSION}`,\n capabilities: ['receipts', 'events', 'payment-attempts'],\n status: 'stable',\n };\n\n const store: ReceiptStore = {\n async init(): Promise<void> {\n // Migration already ran synchronously at construction. This check keeps\n // init() a real, idempotent gate for callers that await it first.\n const version = db.pragma('user_version', { simple: true }) as number;\n if (version !== SCHEMA_VERSION) {\n throw new CommerceError(\n 'STORAGE_ERROR',\n `Receipt store schema version mismatch (found ${version}, expected ${SCHEMA_VERSION})`,\n );\n }\n },\n\n async appendEvent(event: CommerceEvent): Promise<void> {\n try {\n insertEventStmt.run(eventToRow(event));\n } catch (err) {\n logger.warn(\n {\n err: err instanceof Error ? err.message : String(err),\n eventId: event.id,\n requestId: event.requestId,\n },\n 'receipt-store: failed to persist commerce event',\n );\n }\n },\n\n async reservePaymentAttempt(reservation: PaymentAttemptReservation): Promise<PaymentAttempt> {\n const now = clock.nowIso();\n const params = {\n id: ids.next('attempt'),\n request_id: reservation.requestId,\n resource_id: reservation.resourceId,\n provider: reservation.provider,\n replay_key: reservation.replayKey,\n amount: reservation.amount,\n currency: reservation.currency,\n payer: reservation.payer ?? null,\n payee: reservation.payee ?? null,\n created_at: now,\n updated_at: now,\n };\n let row: PaymentAttemptRow;\n try {\n // Reclaim only if the rail permits reusing an authorization whose\n // attempt was rejected. NEAR client retries reuse the access key's\n // next nonce and therefore the replay key.\n row =\n (reservation.reclaimRejected === true\n ? reclaimRejectedAttempt.immediate(params)\n : undefined) ??\n // RETURNING on a successful insert always yields the inserted row\n (insertPaymentAttemptStmt.get({\n ...params,\n status: 'reserved' satisfies PaymentAttempt['status'],\n external_reference: null,\n rejection_reason: null,\n }) as PaymentAttemptRow);\n } catch (err) {\n if (isUniqueConstraintOn(err, 'payment_attempts.replay_key')) {\n // Report the existing status so the pipeline can choose a replay response\n const existing = paymentAttemptStatusStmt.get(reservation.replayKey);\n throw new CommerceError(\n 'PAYMENT_REPLAYED',\n `Payment authorization has already been used (replayKey=${reservation.replayKey})`,\n {\n requestId: reservation.requestId,\n resourceId: reservation.resourceId,\n ...(existing !== undefined ? { details: { attemptStatus: existing.status } } : {}),\n },\n );\n }\n throw toCommerceError(err, 'STORAGE_ERROR', 'Failed to reserve payment attempt');\n }\n return rowToPaymentAttempt(row);\n },\n\n async updatePaymentAttempt(update: PaymentAttemptUpdate): Promise<void> {\n try {\n const result = updatePaymentAttemptStmt.run({\n replay_key: update.replayKey,\n status: update.status,\n external_reference: update.externalReference ?? null,\n rejection_reason: update.rejectionReason ?? null,\n updated_at: clock.nowIso(),\n });\n if (result.changes === 0) {\n throw new CommerceError(\n 'STORAGE_ERROR',\n `No payment attempt found for replayKey=${update.replayKey}`,\n );\n }\n } catch (err) {\n throw toCommerceError(err, 'STORAGE_ERROR', 'Failed to update payment attempt');\n }\n },\n\n async saveReceipt(receipt: CommerceReceipt): Promise<void> {\n try {\n insertReceiptStmt.run(receiptToRow(receipt));\n } catch (err) {\n throw toCommerceError(err, 'STORAGE_ERROR', 'Failed to save receipt');\n }\n },\n\n async getReceipt(id: string): Promise<CommerceReceipt | undefined> {\n const row = getReceiptStmt.get(id);\n return row !== undefined ? rowToReceipt(row) : undefined;\n },\n\n async listReceipts(listOptions: ListOptions = {}): Promise<readonly CommerceReceipt[]> {\n const limit = clampListLimit(listOptions.limit);\n const rows =\n listOptions.requestId !== undefined\n ? listReceiptsByRequestStmt.all(listOptions.requestId, limit)\n : listReceiptsStmt.all(limit);\n return rows.map(rowToReceipt);\n },\n\n // Exact total, not bounded by the listReceipts clamp (see ReceiptStore.countReceipts)\n async countReceipts(): Promise<number> {\n return countReceiptsStmt.get()?.count ?? 0;\n },\n\n // Exact count of non-2xx receipts (see ReceiptStore.countUndeliveredReceipts)\n async countUndeliveredReceipts(): Promise<number> {\n return countUndeliveredReceiptsStmt.get()?.count ?? 0;\n },\n\n async listEvents(listOptions: ListOptions = {}): Promise<readonly CommerceEvent[]> {\n const limit = clampListLimit(listOptions.limit);\n const rows =\n listOptions.requestId !== undefined\n ? listEventsByRequestStmt.all(listOptions.requestId, limit)\n : listEventsStmt.all(limit);\n return rows.map(rowToEvent);\n },\n\n async listPaymentAttempts(listOptions: ListOptions = {}): Promise<readonly PaymentAttempt[]> {\n const limit = clampListLimit(listOptions.limit);\n const rows =\n listOptions.requestId !== undefined\n ? listPaymentAttemptsByRequestStmt.all(listOptions.requestId, limit)\n : listPaymentAttemptsStmt.all(limit);\n return rows.map(rowToPaymentAttempt);\n },\n\n descriptor,\n\n async health(): Promise<AdapterHealth> {\n // `detail` comes from a fixed vocabulary, never from a caught error: an\n // accessSync error carries an absolute host path, e.g. \"EACCES:\n // permission denied, access '/workspace/data/receipts.sqlite'\". The raw\n // message goes to the logger at warn.\n const startedAt = clock.monotonicMs();\n if (closed) {\n return { status: 'fail', detail: 'store-unavailable', checkedAt: clock.nowIso() };\n }\n if (isFileBacked) {\n try {\n accessSync(path, fsConstants.W_OK);\n } catch (err) {\n logger.warn(\n { err: err instanceof Error ? err.message : String(err) },\n 'receipt-store: health check failed (store not writable)',\n );\n return {\n status: 'fail',\n detail: 'store-unwritable',\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n }\n try {\n const version = db.pragma('user_version', { simple: true }) as number;\n if (version !== SCHEMA_VERSION) {\n logger.warn(\n { found: version, expected: SCHEMA_VERSION },\n 'receipt-store: health check failed (schema version mismatch)',\n );\n return {\n status: 'fail',\n detail: 'store-schema-mismatch',\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n return {\n status: 'pass',\n detail: `sqlite schema v${SCHEMA_VERSION} writable`,\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n } catch (err) {\n logger.warn(\n { err: err instanceof Error ? err.message : String(err) },\n 'receipt-store: health check failed (store unavailable)',\n );\n return {\n status: 'fail',\n detail: 'store-unavailable',\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n },\n\n async close(): Promise<void> {\n if (!closed) {\n closed = true;\n db.close();\n }\n },\n };\n\n return store;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/config/env.ts","../src/config/filename.ts","../src/protocols/acp/constants.ts","../src/config/schema/values.ts","../src/config/schema/acp.ts","../src/config/schema/ap2.ts","../src/config/schema/x402.ts","../src/config/schema/mpp.ts","../src/config/schema/raw.ts","../src/core/execution/backend-request.ts","../src/core/execution/backend-http.ts","../src/core/execution/validation.ts","../src/core/execution/pipeline/authorization.ts","../src/core/execution/pipeline/challenge.ts","../src/core/execution/pipeline/admission.ts","../src/core/execution/pipeline/context.ts","../src/core/execution/pipeline/settlement.ts","../src/core/execution/pipeline/index.ts","../src/core/execution/registry.ts","../src/core/execution/store-event-sink.ts","../src/config/schema/backend.ts","../src/config/schema/resource-schema.ts","../src/config/schema/resources.ts","../src/config/schema/normalize.ts","../src/config/schema/index.ts","../src/config/load.ts","../src/gateway/access-control.ts","../src/gateway/adapters.ts","../src/gateway/ids.ts","../src/gateway/logger.ts","../src/gateway/public-resource.ts","../src/gateway/readiness.ts","../src/gateway/well-known.ts","../src/gateway/routes.ts","../src/gateway/server.ts","../src/protocols/a2a/constants.ts","../src/protocols/a2a/jsonrpc.ts","../src/protocols/a2a/message-mapping.ts","../src/protocols/a2a/x402-extension.ts","../src/protocols/a2a/agent-card.ts","../src/protocols/a2a/descriptor.ts","../src/protocols/a2a/task-mapping.ts","../src/protocols/a2a/payment-resume.ts","../src/protocols/a2a/adapter.ts","../src/protocols/acp/checkout-mapping.ts","../src/protocols/acp/descriptor.ts","../src/protocols/acp/discovery.ts","../src/protocols/acp/errors.ts","../src/protocols/acp/idempotency/fingerprint.ts","../src/protocols/acp/idempotency/store.ts","../src/protocols/acp/router.ts","../src/protocols/acp/spec/2026-04-17/schema.agentic_checkout.json","../src/protocols/acp/validation.ts","../src/protocols/acp/request-guards.ts","../src/protocols/acp/response-mapping.ts","../src/protocols/acp/adapter.ts","../src/storage/receipts/redact.ts","../src/storage/receipts/rows.ts","../src/storage/receipts/schema.ts","../src/storage/receipts/store.ts"],"names":["path","options","url","invalid","durationMs","validators","flowOverrides","fs","parseYaml","header","value","z","task","buildDescriptor","createHash","changes","failure","SCHEMA_VERSION","migrate","randomUUID","fsConstants"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqBA,IAAM,mBAAA,GAAsB,6CAAA;AAG5B,IAAM,WAAA,GAAc,eAAA;AAGpB,IAAM,eAAA,GAAkB,0CAAA;AAGxB,IAAM,kBAAA,GAAqB,gBAAA;AAEpB,SAAS,aAAA,CAAc,KAAA,EAAgB,GAAA,EAAwBA,KAAAA,GAAO,GAAA,EAAc;AACzF,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,gBAAA,CAAiB,KAAA,EAAO,GAAA,EAAKA,KAAI,CAAA;AAAA,EAC1C;AACA,EAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,KAAK,C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A,UACxB,UAAA,EAAY,KAAA,CAAM,WAAA,EAAY,GAAI;AAAA,SACpC;AAAA,MACF;AAAA,IACF,CAAA;AAAA,IAEA,MAAM,KAAA,GAAuB;AAC3B,MAAA,IAAI,CAAC,MAAA,EAAQ;AACX,QAAA,MAAA,GAAS,IAAA;AACT,QAAA,EAAA,CAAG,KAAA,EAAM;AAAA,MACX;AAAA,IACF;AAAA,GACF;AAEA,EAAA,OAAO,KAAA;AACT","file":"index.js","sourcesContent":["/**\n * `${VAR}` / `${VAR:-default}` substitution over a parsed YAML value.\n *\n * Only string leaves change; the caller coerces numeric and boolean strings\n * afterwards. `${VAR}` requires `VAR` in `env`, where an empty string counts as\n * present. `${VAR:-default}` uses `default` when `VAR` is absent or empty, as a\n * shell does. An unresolved placeholder fails config loading, so startup never\n * proceeds with a missing secret. There is no escape for a literal `${NAME}`.\n *\n * Anything else brace-shaped is refused, including nesting (`${A:-${B}}`) and\n * shell forms (`${VAR-x}`, `${VAR:=x}`, `${VAR:?x}`) that would otherwise load\n * as literal text: `adminToken: ${ADMIN_TOKEN-fallback}` would make that\n * literal the ledger credential. A bare `$VAR` is left alone, so values may\n * contain a dollar sign.\n *\n * The template rules are checked before substitution, and errors name the\n * variable and the config path, never a resolved value.\n */\nimport { CommerceError } from '../core';\nimport { isRecord } from '../core/is-record';\n\nconst PLACEHOLDER_PATTERN = /\\$\\{([A-Za-z_][A-Za-z0-9_]*)(:-([^}]*))?\\}/g;\n\n// An innermost brace token: `${`, then no braces, then `}`\nconst BRACE_TOKEN = /\\$\\{[^{}]*\\}/g;\n\n// PLACEHOLDER_PATTERN's grammar, anchored, for validating one token\nconst SUPPORTED_TOKEN = /^\\$\\{[A-Za-z_][A-Za-z0-9_]*(:-[^}]*)?\\}$/;\n\n// A placeholder whose default segment opens another placeholder\nconst NESTED_PLACEHOLDER = /\\$\\{[^{}]*\\$\\{/;\n\nexport function substituteEnv(value: unknown, env: NodeJS.ProcessEnv, path = '$'): unknown {\n if (typeof value === 'string') {\n return substituteString(value, env, path);\n }\n if (Array.isArray(value)) {\n return value.map((entry, index) => substituteEnv(entry, env, `${path}[${index}]`));\n }\n if (isRecord(value)) {\n const result: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n result[key] = substituteEnv(entry, env, `${path}.${key}`);\n }\n return result;\n }\n return value;\n}\n\nfunction substituteString(value: string, env: NodeJS.ProcessEnv, path: string): string {\n assertTemplateIsSupported(value, path);\n return substituteOnce(value, env, path);\n}\n\n/**\n * Refuses a template this module cannot honor, before any substitution runs.\n *\n * For `${A:-${B}}`, `[^}]*` cannot span the inner `}`, so the match consumes\n * `${A:-${B` and leaves a stray `}`. With `A` set, substitution would succeed\n * and append that `}` to the value unnoticed, so `adminToken` would become a\n * credential the operator does not hold.\n */\nfunction assertTemplateIsSupported(value: string, path: string): void {\n if (NESTED_PLACEHOLDER.test(value)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" nests placeholders (e.g. \"\\${A:-\\${B}}\"), which is not supported: the inner one is not resolved and its closing brace ends up in the value. Use a plain default, or set the variable.`,\n { details: { path } },\n );\n }\n\n for (const [token] of value.matchAll(BRACE_TOKEN)) {\n if (SUPPORTED_TOKEN.test(token)) continue;\n // Quotes the token, not the value; before substitution it holds no secret\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" contains \"${token}\", which is not a supported placeholder. Only \"\\${VAR}\" and \"\\${VAR:-default}\" are recognized; shell forms such as \"\\${VAR-default}\", \"\\${VAR:=default}\" and \"\\${VAR:?message}\" would load as literal text.`,\n { details: { path, token } },\n );\n }\n}\n\nfunction substituteOnce(value: string, env: NodeJS.ProcessEnv, path: string): string {\n return value.replace(\n PLACEHOLDER_PATTERN,\n (_match, name: string, hasDefault: string | undefined, def: string | undefined) => {\n const envValue = env[name];\n\n if (hasDefault !== undefined) {\n if (envValue === undefined || envValue === '') return def ?? '';\n return envValue;\n }\n\n if (envValue === undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Unresolved environment variable \"\\${${name}}\" referenced at config path \"${path}\"`,\n { details: { variable: name, path } },\n );\n }\n return envValue;\n },\n );\n}\n","/**\n * The default configuration filename, shared by the loader, `init`'s default\n * output path and the `--config` help text.\n *\n * Its own module with no imports: `src/cli` loads the rest of `src/config`\n * only through a dynamic import (`src/cli/lib/config-client.ts`), so a broken\n * config module cannot take down commands that never read configuration. A\n * leaf with no module graph can be imported statically without undoing that.\n */\nexport const DEFAULT_CONFIG_FILENAME = 'config.yaml';\n","/**\n * ACP protocol constants shared by the config layer and the adapter.\n *\n * Kept dependency-free: `src/config` reads the operation set at load time, so\n * anything imported here would become a config-load dependency too.\n */\n\n/**\n * The ACP stable snapshot this adapter implements, and the only value accepted\n * in the `API-Version` request header. Both name the same released snapshot;\n * they are separate constants because ACP versions the wire contract and the\n * header independently, and a future snapshot may accept more than one.\n *\n * Changing either means vendoring a new schema directory beside\n * `spec/2026-04-17/` - never editing the vendored one in place.\n */\nexport const ACP_SPEC_VERSION = '2026-04-17';\nexport const ACP_API_VERSION = '2026-04-17';\n\n/** Discovery path fixed by the ACP specification, never a configurable mount */\nexport const ACP_WELL_KNOWN_PATH = '/.well-known/acp.json';\n\n/**\n * The stable checkout operations, by ACP operation id. All five are required\n * when ACP is enabled: a partially configured checkout lifecycle would be\n * advertised as a whole service the seller cannot actually serve.\n */\nexport const ACP_CHECKOUT_OPERATIONS = [\n 'createCheckoutSession',\n 'updateCheckoutSession',\n 'getCheckoutSession',\n 'completeCheckoutSession',\n 'cancelCheckoutSession',\n] as const;\n\nexport type AcpCheckoutOperation = (typeof ACP_CHECKOUT_OPERATIONS)[number];\n\n/**\n * Top-level canonical-input properties each operation always supplies.\n *\n * `path` carries `{ checkout_session_id }`, `body` the ACP request document.\n */\nexport const ACP_OPERATION_INPUT_KEYS: Readonly<\n Record<AcpCheckoutOperation, readonly ('path' | 'body')[]>\n> = {\n createCheckoutSession: ['body'],\n updateCheckoutSession: ['path', 'body'],\n getCheckoutSession: ['path'],\n completeCheckoutSession: ['path', 'body'],\n cancelCheckoutSession: ['path'],\n};\n\n/**\n * Canonical-input properties an operation supplies only when the caller sends\n * them. The pinned schema lets a cancel omit its body, so a bare cancel has no\n * `body`, but one carrying `intent_trace` passes it on.\n */\nexport const ACP_OPERATION_OPTIONAL_INPUT_KEYS: Readonly<\n Partial<Record<AcpCheckoutOperation, readonly 'body'[]>>\n> = {\n cancelCheckoutSession: ['body'],\n};\n\n/** The key inside `path` that carries the checkout session id from the route */\nexport const ACP_SESSION_ID_INPUT_KEY = 'checkout_session_id';\n\n/** Media type for every ACP request and response body */\nexport const ACP_JSON_MEDIA_TYPE = 'application/json';\n\n/**\n * Protocol headers, lowercased as Node delivers them.\n *\n * `API-Version` is mandatory on checkout requests and is never defaulted:\n * answering an unversioned request as if it named the pinned snapshot would be\n * guessing on the caller's behalf about a contract that changes.\n */\nexport const ACP_API_VERSION_HEADER = 'api-version';\nexport const ACP_REQUEST_ID_HEADER = 'request-id';\nexport const ACP_IDEMPOTENCY_KEY_HEADER = 'idempotency-key';\nexport const ACP_IDEMPOTENT_REPLAYED_HEADER = 'idempotent-replayed';\n\n/**\n * Seconds a client is told to wait before retrying a key whose first request is\n * still running. Short: the original is a live HTTP call, not a queue.\n */\nexport const ACP_IN_FLIGHT_RETRY_AFTER_SECONDS = 1;\n\n/**\n * Longest `Request-Id` echoed back. The value is the caller's, so it is\n * bounded and filtered before it is ever written into a response header.\n */\nexport const ACP_MAX_REQUEST_ID_LENGTH = 128;\n\n/** Caller headers forwarded to the merchant; the bearer token stays at the gateway */\nexport const ACP_FORWARDED_HEADERS = [\n 'accept-language',\n 'user-agent',\n ACP_REQUEST_ID_HEADER,\n ACP_API_VERSION_HEADER,\n 'signature',\n 'timestamp',\n] as const;\n\n/** Maximum forwarded header value length; longer values are dropped */\nexport const ACP_MAX_FORWARDED_HEADER_LENGTH = 2048;\n\n/** Fallback and maximum `Retry-After` seconds for merchant 429 or 503 */\nexport const ACP_MERCHANT_RETRY_AFTER_DEFAULT_SECONDS = 5;\nexport const ACP_MERCHANT_RETRY_AFTER_MAX_SECONDS = 300;\n","// Readers for leaves that env substitution may have turned into strings, and addresses\nimport { CommerceError } from '../../core';\nimport { isEvmAddress, isEvmZeroAddress } from '../../payments/x402/addresses';\n\nexport function toNumber(\n value: number | string,\n path: string,\n bounds: { min?: number; max?: number } = {},\n): number {\n // Plain decimal digits only. `Number('')` is 0, which `server.port` accepts\n // (\"let the OS pick\"), so an empty `${PORT:-}` would bind a random port.\n // `Number` also accepts `\"0x50\"` and `\"1e3\"` for fields documented as decimal.\n if (typeof value === 'string' && !/^\\s*\\d+\\s*$/.test(value)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" must be an integer written in decimal digits (got ${value === '' ? 'an empty string' : `\"${value}\"`})`,\n { details: { path } },\n );\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n) || !Number.isInteger(n)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" must be an integer`,\n {\n details: { path },\n },\n );\n }\n if (bounds.min !== undefined && n < bounds.min) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" must be >= ${bounds.min}`,\n {\n details: { path },\n },\n );\n }\n if (bounds.max !== undefined && n > bounds.max) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" must be <= ${bounds.max}`,\n {\n details: { path },\n },\n );\n }\n return n;\n}\n\nexport function toBoolean(value: boolean | string, path: string): boolean {\n if (typeof value === 'boolean') return value;\n const normalized = value.trim().toLowerCase();\n if (normalized === 'true') return true;\n if (normalized === 'false') return false;\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" must be a boolean (\"true\" or \"false\")`,\n { details: { path } },\n );\n}\n\nexport function validateAddress(path: string, value: string): void {\n if (!isEvmAddress(value)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" is not a plausible address (expected \"0x\" followed by 40 hex characters)`,\n { details: { path } },\n );\n }\n if (isEvmZeroAddress(value)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" must not be the zero address`,\n {\n details: { path },\n },\n );\n }\n}\n","// The ACP checkout adapter's settings and its operation-to-resource mapping\nimport { CommerceError, type CommerceResource } from '../../core';\nimport { isRecord } from '../../core/is-record';\nimport {\n ACP_CHECKOUT_OPERATIONS,\n ACP_OPERATION_INPUT_KEYS,\n ACP_OPERATION_OPTIONAL_INPUT_KEYS,\n ACP_SESSION_ID_INPUT_KEY,\n type AcpCheckoutOperation,\n} from '../../protocols/acp/constants';\nimport type { RawConfig } from './raw';\nimport type { AcpProtocolConfig } from './types';\nimport { toBoolean, toNumber } from './values';\n\n// Applied when `protocols.acp` is absent or names no mount\nconst DEFAULT_ACP_MOUNT_PATH = '/acp';\n\n// Idempotency records must outlive ACP's 24-hour retry window, or a replayed\n// key could pass an expired record and run a checkout side effect twice. It is\n// both the default and the floor.\nconst ACP_RETENTION_HOURS = 24;\n\ntype RawAcp = NonNullable<RawConfig['protocols']['acp']>;\n\ntype EnabledAcpConfig = Extract<AcpProtocolConfig, { enabled: true }>;\n\nfunction acpInvalid(\n path: string,\n message: string,\n extra: Record<string, unknown> = {},\n): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, { details: { path, ...extra } });\n}\n\nexport function normalizeAcp(raw: RawAcp | undefined): AcpProtocolConfig {\n const mountPath = raw?.mountPath ?? DEFAULT_ACP_MOUNT_PATH;\n if (raw === undefined || !toBoolean(raw.enabled, 'protocols.acp.enabled')) {\n return { enabled: false, mountPath };\n }\n\n if (raw.auth === undefined) {\n throw acpInvalid(\n 'protocols.acp.auth',\n 'protocols.acp.auth is required when ACP is enabled - every ACP checkout endpoint is authenticated, and \"bearer\" is the only scheme supported in this release',\n );\n }\n if (raw.idempotency === undefined) {\n throw acpInvalid(\n 'protocols.acp.idempotency',\n 'protocols.acp.idempotency is required when ACP is enabled - it names the SQLite file holding checkout idempotency records, and ACP makes the Idempotency-Key mandatory on every checkout POST',\n );\n }\n\n const discovery = raw.discovery;\n\n return {\n enabled: true,\n mountPath,\n auth: raw.auth,\n idempotency: {\n path: raw.idempotency.path,\n retentionHours: toNumber(\n raw.idempotency.retentionHours ?? ACP_RETENTION_HOURS,\n 'protocols.acp.idempotency.retentionHours',\n { min: ACP_RETENTION_HOURS },\n ),\n merchantIdempotent: raw.idempotency.merchantIdempotent ?? false,\n },\n checkout: { operations: normalizeAcpOperations(raw.checkout) },\n // Built key by key so absent metadata stays absent rather than `undefined`\n ...(discovery !== undefined\n ? {\n discovery: {\n ...(discovery.documentationUrl !== undefined\n ? { documentationUrl: discovery.documentationUrl }\n : {}),\n ...(discovery.supportedCurrencies !== undefined\n ? { supportedCurrencies: discovery.supportedCurrencies }\n : {}),\n ...(discovery.supportedLocales !== undefined\n ? { supportedLocales: discovery.supportedLocales }\n : {}),\n ...(discovery.interventionTypes !== undefined\n ? { interventionTypes: discovery.interventionTypes }\n : {}),\n },\n }\n : {}),\n };\n}\n\n// All five operations, each on its own resource. ACP discovery advertises\n// `checkout` as one service, so a partial mapping is refused. Operations differ\n// in method, input and success status, so one resource cannot serve two.\nfunction normalizeAcpOperations(\n checkout: RawAcp['checkout'],\n): Readonly<Record<AcpCheckoutOperation, string>> {\n const configured: Record<string, string> = checkout?.operations ?? {};\n\n for (const key of Object.keys(configured)) {\n if (!(ACP_CHECKOUT_OPERATIONS as readonly string[]).includes(key)) {\n throw acpInvalid(\n `protocols.acp.checkout.operations.${key}`,\n `protocols.acp.checkout.operations names unknown ACP checkout operation \"${key}\". Supported: ${ACP_CHECKOUT_OPERATIONS.join(', ')}.`,\n );\n }\n }\n\n const operations: Record<string, string> = {};\n const claimedBy = new Map<string, AcpCheckoutOperation>();\n for (const operation of ACP_CHECKOUT_OPERATIONS) {\n const path = `protocols.acp.checkout.operations.${operation}`;\n const resourceId = configured[operation];\n if (resourceId === undefined) {\n throw acpInvalid(\n path,\n `${path} is required when ACP is enabled - all five checkout operations must be mapped, since ACP discovery advertises the checkout service as a whole`,\n );\n }\n const claimed = claimedBy.get(resourceId);\n if (claimed !== undefined) {\n throw acpInvalid(\n path,\n `${path} maps resource \"${resourceId}\", which is already mapped to \"${claimed}\" - each ACP checkout operation needs its own resource`,\n { resourceId },\n );\n }\n claimedBy.set(resourceId, operation);\n operations[operation] = resourceId;\n }\n return operations as Record<AcpCheckoutOperation, string>;\n}\n\nexport function validateAcpCheckoutMapping(\n acp: EnabledAcpConfig,\n resources: readonly CommerceResource[],\n): void {\n const byId = new Map(resources.map((resource) => [resource.id, resource]));\n\n for (const operation of ACP_CHECKOUT_OPERATIONS) {\n const resourceId = acp.checkout.operations[operation];\n const path = `protocols.acp.checkout.operations.${operation}`;\n const resource = byId.get(resourceId);\n if (resource === undefined) {\n throw acpInvalid(\n path,\n `${path} maps resource \"${resourceId}\", which is not defined under \"resources\"`,\n { resourceId },\n );\n }\n if (!resource.exposedVia.includes('acp')) {\n throw acpInvalid(\n path,\n `Resource \"${resourceId}\" implements ACP operation \"${operation}\" but does not list \"acp\" in its expose - the mapping says which resource serves the operation, expose says ACP may invoke it, and both are required`,\n { resourceId },\n );\n }\n // ACP checkout carries the merchant's own purchase payment (`payment_data`\n // on completion), and ACP has no wire form for our payment-required\n // outcome, so the invocation itself must be free\n if (resource.pricing.type !== 'free' || resource.paymentMethods.length > 0) {\n throw acpInvalid(\n path,\n `Resource \"${resourceId}\" implements ACP operation \"${operation}\" and must use pricing.type \"free\" with no \"payments\" - ACP checkout carries the merchant's own purchase payment, so the gateway does not also charge for the invocation`,\n { resourceId },\n );\n }\n validateAcpOperationInput(path, operation, resource);\n }\n}\n\n// A schema that forbids a key the adapter sends, or requires one it may not\n// send, fails requests with INPUT_INVALID. Refused at load instead. An optional\n// key counts as sent: a closed cancel schema without `body` would pass a bare\n// cancel and refuse every one that carries `intent_trace`. Normalization has\n// already closed every object node that omits additionalProperties, so the\n// check also looks inside `path` and `body`: a bare `body: { type: object }`\n// arrives here accepting no key at all.\nfunction validateAcpOperationInput(\n path: string,\n operation: AcpCheckoutOperation,\n resource: CommerceResource,\n): void {\n const schema = resource.inputSchema;\n if (schema === undefined) return;\n const keys: readonly string[] = ACP_OPERATION_INPUT_KEYS[operation];\n const optionalKeys: readonly string[] = ACP_OPERATION_OPTIONAL_INPUT_KEYS[operation] ?? [];\n const sent = [...keys, ...optionalKeys];\n\n const topLevel = closedObjectProperties(schema);\n if (topLevel !== undefined) {\n for (const key of sent) {\n if (!Object.hasOwn(topLevel, key)) {\n const when = keys.includes(key) ? 'always sends' : 'sends when the caller supplies it';\n throw acpInvalid(\n path,\n `Resource \"${resource.id}\" implements ACP operation \"${operation}\" but its input schema sets additionalProperties: false without declaring \"${key}\", which the adapter ${when} for this operation`,\n { resourceId: resource.id },\n );\n }\n }\n }\n\n const declared = isRecord(schema['properties']) ? schema['properties'] : {};\n const pathKeys = closedObjectProperties(declared['path']);\n if (\n sent.includes('path') &&\n pathKeys !== undefined &&\n !Object.hasOwn(pathKeys, ACP_SESSION_ID_INPUT_KEY)\n ) {\n throw acpInvalid(\n path,\n `Resource \"${resource.id}\" implements ACP operation \"${operation}\" but its \"path\" schema sets additionalProperties: false without declaring \"${ACP_SESSION_ID_INPUT_KEY}\", which the adapter always sends inside \"path\"`,\n { resourceId: resource.id },\n );\n }\n const bodyKeys = closedObjectProperties(declared['body']);\n if (sent.includes('body') && bodyKeys !== undefined && Object.keys(bodyKeys).length === 0) {\n throw acpInvalid(\n path,\n `Resource \"${resource.id}\" implements ACP operation \"${operation}\" but its \"body\" schema accepts no keys, so it refuses every ACP document. Config load closes an object schema that omits additionalProperties: declare body as { type: object, additionalProperties: true }`,\n { resourceId: resource.id },\n );\n }\n\n const required = schema['required'];\n if (Array.isArray(required)) {\n for (const entry of required) {\n if (typeof entry === 'string' && !keys.includes(entry)) {\n throw acpInvalid(\n path,\n `Resource \"${resource.id}\" implements ACP operation \"${operation}\" but its input schema requires \"${entry}\", which that operation does not always supply (it always sends: ${keys.join(', ')})`,\n { resourceId: resource.id },\n );\n }\n }\n }\n}\n\n// The declared properties of a closed object schema, or undefined when the\n// schema accepts keys it does not declare\nfunction closedObjectProperties(schema: unknown): Record<string, unknown> | undefined {\n if (!isRecord(schema) || schema['additionalProperties'] !== false) return undefined;\n return isRecord(schema['properties']) ? schema['properties'] : {};\n}\n","// AP2 mandate verification settings and each resource's authorization requirement\nimport type { z } from 'zod';\nimport {\n AP2_DEFAULT_CLOCK_SKEW_SECONDS,\n AP2_JWK_COORDINATE_BYTES,\n AP2_JWK_CURVE,\n AP2_JWK_MEMBERS,\n AP2_KEY_TYPE,\n AP2_MAX_CLOCK_SKEW_SECONDS,\n AP2_MODES,\n AP2_SIGNING_ALGORITHM,\n AP2_SPEC_VERSION,\n} from '../../authorization/ap2/constants';\nimport type {\n Ap2AuthorizationConfig,\n Ap2Mode,\n Ap2TrustedIssuer,\n} from '../../authorization/ap2/types';\nimport {\n type AuthorizationMethodName,\n CommerceError,\n type CommerceResource,\n type Pricing,\n} from '../../core';\nimport type { Ap2IssuerSchema, RawConfig, RawResourceEntry } from './raw';\nimport type { AcpProtocolConfig } from './types';\nimport { toBoolean, toNumber } from './values';\n\nconst SUPPORTED_AUTHORIZATION_METHODS: ReadonlySet<string> = new Set(['ap2']);\n\ntype RawAp2 = NonNullable<NonNullable<RawConfig['authorization']>['ap2']>;\n\nfunction ap2Invalid(\n path: string,\n message: string,\n extra: Record<string, unknown> = {},\n): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, { details: { path, ...extra } });\n}\n\nexport function normalizeAp2(raw: RawAp2 | undefined): Ap2AuthorizationConfig | undefined {\n if (raw === undefined) return undefined;\n if (!toBoolean(raw.enabled, 'authorization.ap2.enabled')) return { enabled: false };\n\n const specVersion = raw.specVersion ?? AP2_SPEC_VERSION;\n if (specVersion !== AP2_SPEC_VERSION) {\n throw ap2Invalid(\n 'authorization.ap2.specVersion',\n `authorization.ap2.specVersion \"${specVersion}\" is not supported - this gateway verifies against the tagged AP2 release ${AP2_SPEC_VERSION} only`,\n );\n }\n\n const mode = raw.mode ?? AP2_MODES[0];\n if (!(AP2_MODES as readonly string[]).includes(mode)) {\n throw ap2Invalid(\n 'authorization.ap2.mode',\n `authorization.ap2.mode \"${mode}\" is not supported. Supported: ${AP2_MODES.join(', ')}. Autonomous mode needs open mandates, agent key binding and constraint evaluation, none of which this release implements.`,\n );\n }\n\n if (raw.replay === undefined) {\n throw ap2Invalid(\n 'authorization.ap2.replay',\n 'authorization.ap2.replay is required when AP2 is enabled - it names the SQLite file recording which mandates have been spent, and without it a verified mandate could authorize a second settlement',\n );\n }\n\n const mandateIssuers = normalizeIssuers(\n raw.trust?.mandateIssuers,\n 'authorization.ap2.trust.mandateIssuers',\n );\n const checkoutIssuers = normalizeIssuers(\n raw.trust?.checkoutIssuers,\n 'authorization.ap2.trust.checkoutIssuers',\n );\n\n return {\n enabled: true,\n specVersion: AP2_SPEC_VERSION,\n mode: mode as Ap2Mode,\n trust: { mandateIssuers, checkoutIssuers },\n clockSkewSeconds: toNumber(\n raw.clockSkewSeconds ?? AP2_DEFAULT_CLOCK_SKEW_SECONDS,\n 'authorization.ap2.clockSkewSeconds',\n { min: 0, max: AP2_MAX_CLOCK_SKEW_SECONDS },\n ),\n requireMandateAudience: toBoolean(\n raw.requireMandateAudience ?? false,\n 'authorization.ap2.requireMandateAudience',\n ),\n requireMandateExpiry: toBoolean(\n raw.requireMandateExpiry ?? false,\n 'authorization.ap2.requireMandateExpiry',\n ),\n replay: { path: raw.replay.path },\n };\n}\n\n// Both issuer lists must be non-empty when AP2 is on: verification checks the\n// issuer's signature over the Checkout Mandate and the merchant's over the\n// checkout JWT it binds. An empty list would fail every mandate at request\n// time instead of at load.\nfunction normalizeIssuers(\n raw: readonly z.infer<typeof Ap2IssuerSchema>[] | undefined,\n path: string,\n): readonly Ap2TrustedIssuer[] {\n if (raw === undefined || raw.length === 0) {\n throw ap2Invalid(\n path,\n `${path} is required when AP2 is enabled and must name at least one issuer - trust is operator-configured and static, so an empty list means no mandate can ever verify`,\n );\n }\n\n const seen = new Set<string>();\n return raw.map((entry, index) => {\n const entryPath = `${path}.${index}`;\n if (seen.has(entry.issuer)) {\n throw ap2Invalid(\n `${entryPath}.issuer`,\n `${entryPath}.issuer \"${entry.issuer}\" is listed twice - key lookup resolves by issuer, so a second entry for the same one is silently unreachable. Merge the keys into one entry instead (which is also how a rotation overlaps an old and a new key).`,\n { issuer: entry.issuer },\n );\n }\n seen.add(entry.issuer);\n\n const kids = new Set<string>();\n const keys = entry.keys.map((key, keyIndex) => {\n const keyPath = `${entryPath}.keys.${keyIndex}`;\n if (kids.has(key.kid)) {\n throw ap2Invalid(\n `${keyPath}.kid`,\n `${keyPath}.kid \"${key.kid}\" is listed twice for issuer \"${entry.issuer}\" - a kid selects exactly one key, so which of the two verifies a signature would be undefined`,\n { issuer: entry.issuer, kid: key.kid },\n );\n }\n kids.add(key.kid);\n return { kid: key.kid, jwk: validateJwk(key.jwk, key.kid, keyPath) };\n });\n\n return { issuer: entry.issuer, audience: entry.audience, keys };\n });\n}\n\n// Accepts only a public P-256 key. Every member is checked at load rather than\n// by the JOSE library at the first purchase, so a bad key fails the deploy\n// instead of a buyer's valid mandate.\nfunction validateJwk(\n jwk: Record<string, unknown>,\n kid: string,\n path: string,\n): Readonly<Record<string, string>> {\n const fail = (detail: string): never => {\n throw ap2Invalid(`${path}.jwk`, `${path}.jwk (kid \"${kid}\") ${detail}`, { kid });\n };\n\n for (const member of Object.keys(jwk)) {\n if ((AP2_JWK_MEMBERS as readonly string[]).includes(member)) continue;\n // `d` (an EC private scalar) or `k` (a symmetric key) means signing\n // material was pasted where only verification material belongs, which the\n // operator needs to hear about specifically\n if (member === 'd' || member === 'k') {\n fail(\n `carries private key material (\"${member}\"). The gateway verifies signatures and never produces them; publish only the public half. Treat the pasted key as compromised and rotate it.`,\n );\n }\n fail(\n `has unsupported member \"${member}\". Allowed: ${AP2_JWK_MEMBERS.join(', ')}. Members naming a URL are refused on purpose - keys are configured inline and never fetched.`,\n );\n }\n\n const value = (member: string): string => {\n const raw = jwk[member];\n if (typeof raw !== 'string' || raw.length === 0) {\n fail(`must give \"${member}\" as a non-empty string`);\n }\n return raw as string;\n };\n\n if (value('kty') !== AP2_KEY_TYPE) {\n fail(\n `must have kty \"${AP2_KEY_TYPE}\" (got \"${value('kty')}\") - ${AP2_SIGNING_ALGORITHM} is the only accepted algorithm`,\n );\n }\n if (value('crv') !== AP2_JWK_CURVE) {\n fail(\n `must be on curve \"${AP2_JWK_CURVE}\" (got \"${value('crv')}\") - ${AP2_SIGNING_ALGORITHM} is the only accepted algorithm`,\n );\n }\n for (const coordinate of ['x', 'y'] as const) {\n const encoded = value(coordinate);\n if (!/^[A-Za-z0-9_-]+$/.test(encoded)) {\n fail(`coordinate \"${coordinate}\" is not base64url (no padding, no \"+\" or \"/\")`);\n }\n if (Buffer.from(encoded, 'base64url').length !== AP2_JWK_COORDINATE_BYTES) {\n fail(\n `coordinate \"${coordinate}\" decodes to ${Buffer.from(encoded, 'base64url').length} bytes; a ${AP2_JWK_CURVE} coordinate is ${AP2_JWK_COORDINATE_BYTES}`,\n );\n }\n }\n if (jwk['alg'] !== undefined && value('alg') !== AP2_SIGNING_ALGORITHM) {\n fail(`declares alg \"${value('alg')}\"; only ${AP2_SIGNING_ALGORITHM} is accepted`);\n }\n if (jwk['use'] !== undefined && value('use') !== 'sig') {\n fail(`declares use \"${value('use')}\"; a verification key must be \"sig\"`);\n }\n if (jwk['kid'] !== undefined && value('kid') !== kid) {\n fail(`declares kid \"${value('kid')}\", which disagrees with the configured kid \"${kid}\"`);\n }\n\n const normalized: Record<string, string> = {};\n for (const member of AP2_JWK_MEMBERS) {\n if (jwk[member] !== undefined) normalized[member] = value(member);\n }\n return normalized;\n}\n\n// The AP2 replay store gets its own SQLite file. Reserved mandates, payment\n// attempts and ACP idempotency records have different schemas and retention\n// rules, and a shared file means a migration conflict at startup or a shared\n// write lock on the settlement path.\nexport function validateReplayStoreIsolated(\n replayPath: string,\n receiptsPath: string,\n acp: AcpProtocolConfig,\n): void {\n // Every `:memory:` handle is its own private database, so equal strings do\n // not collide\n if (replayPath === ':memory:') return;\n\n const others: [string, string][] = [['storage.receipts.path', receiptsPath]];\n if (acp.enabled) others.push(['protocols.acp.idempotency.path', acp.idempotency.path]);\n\n for (const [otherPath, other] of others) {\n if (replayPath !== other) continue;\n throw ap2Invalid(\n 'authorization.ap2.replay.path',\n `authorization.ap2.replay.path is the same file as ${otherPath} (\"${replayPath}\") - the AP2 replay store keeps its own schema and must not share a database with another store`,\n );\n }\n}\n\n// Resolves a resource's `authorization.required` list against the configured\n// provider. A requirement that cannot be enforced is refused: the resource\n// would look protected in config and settle unprotected.\nexport function normalizeResourceAuthorization(\n id: string,\n entry: RawResourceEntry,\n pricing: Pricing,\n ap2: Ap2AuthorizationConfig | undefined,\n): CommerceResource['authorization'] | undefined {\n const required = entry.authorization?.required;\n if (required === undefined) return undefined;\n\n const path = `resources.${id}.authorization.required`;\n const methods: AuthorizationMethodName[] = [];\n for (const method of required) {\n if (!SUPPORTED_AUTHORIZATION_METHODS.has(method)) {\n throw ap2Invalid(\n path,\n `Resource \"${id}\" requires unsupported authorization method \"${method}\". Supported: ${[...SUPPORTED_AUTHORIZATION_METHODS].join(', ')}.`,\n { resourceId: id, method },\n );\n }\n if (methods.includes(method as AuthorizationMethodName)) {\n throw ap2Invalid(path, `Resource \"${id}\" lists authorization method \"${method}\" twice`, {\n resourceId: id,\n method,\n });\n }\n if (method === 'ap2' && (ap2 === undefined || !ap2.enabled)) {\n throw ap2Invalid(\n path,\n `Resource \"${id}\" requires authorization method \"ap2\", which is not configured or not enabled under authorization.ap2`,\n { resourceId: id, method },\n );\n }\n methods.push(method as AuthorizationMethodName);\n }\n\n // A mandate binds an exact amount and currency and never unlocks a resource\n // by itself, so it only means something on a fixed-price resource\n if (pricing.type !== 'fixed') {\n throw ap2Invalid(\n path,\n `Resource \"${id}\" requires authorization but its pricing is \"${pricing.type}\" - authorization proves a purchase was approved and never replaces payment, so it applies to fixed-price paid resources only in this release`,\n { resourceId: id },\n );\n }\n\n return { required: methods };\n}\n","// The x402 rail: direct or listed options, declared networks and the facilitator\nimport type { z } from 'zod';\nimport { CommerceError } from '../../core';\nimport { resolveX402Deployment, type X402FacilitatorConfig } from '../../payments/x402/guardrails';\nimport {\n type CustomNetworkDeclaration,\n findX402Network,\n validateCustomNetworks,\n} from '../../payments/x402/networks';\nimport { resolveX402Option, type X402OptionInput } from '../../payments/x402/options';\nimport { X402_DEFAULT_PAYMENT_FLOW } from '../../payments/x402/payment-flow';\nimport type { FacilitatorSchema, RawConfig } from './raw';\nimport type { GatewayConfig, X402OptionConfig } from './types';\nimport { toBoolean, toNumber } from './values';\n\ntype X402Config = NonNullable<GatewayConfig['payments']['x402']>;\n\n// One offer list: the rail's options or a resource's own accepts\nexport interface X402OfferTerms {\n /** Every option, resolved, in order */\n readonly options: readonly X402OptionConfig[];\n /**\n * Default symbols for options omitting `asset`; prices must use USD or\n * the shared symbol\n */\n readonly defaultAssetSymbols: readonly string[];\n}\n\nexport interface NormalizedX402 extends X402OfferTerms {\n readonly config: X402Config;\n /** Resources with their own `x402.accepts`, by id; each replaces the rail's options */\n readonly resources: Readonly<Record<string, X402OfferTerms>>;\n}\n\nfunction x402Invalid(message: string, path: string): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, { details: { path } });\n}\n\n// The fields of one option, as they appear directly under `payments.x402`\nconst DIRECT_OPTION_FIELDS = [\n 'network',\n 'payTo',\n 'asset',\n 'assetName',\n 'assetVersion',\n 'assetDecimals',\n 'assetTransferMethod',\n] as const;\n\ntype RawX402 = NonNullable<RawConfig['payments']['x402']>;\n\n// An entry of `options`, or `payments.x402` itself in the direct form\ninterface RawX402Option {\n readonly scheme?: string | undefined;\n readonly network?: string | undefined;\n readonly payTo?: string | undefined;\n readonly asset?: string | undefined;\n readonly assetName?: string | undefined;\n readonly assetVersion?: string | undefined;\n readonly assetDecimals?: number | string | undefined;\n readonly assetTransferMethod?: string | undefined;\n}\n\nfunction x402OptionInput(raw: RawX402Option, path: string): X402OptionInput {\n return {\n ...(raw.scheme !== undefined ? { scheme: raw.scheme } : {}),\n network: raw.network as string,\n payTo: raw.payTo as string,\n ...(raw.asset !== undefined ? { asset: raw.asset } : {}),\n ...(raw.assetName !== undefined ? { assetName: raw.assetName } : {}),\n ...(raw.assetVersion !== undefined ? { assetVersion: raw.assetVersion } : {}),\n ...(raw.assetTransferMethod !== undefined\n ? { assetTransferMethod: raw.assetTransferMethod }\n : {}),\n ...(raw.assetDecimals !== undefined\n ? {\n assetDecimals: toNumber(raw.assetDecimals, `${path}.assetDecimals`, { min: 0, max: 36 }),\n }\n : {}),\n };\n}\n\n/**\n * Resolves direct `payments.x402` fields like a one-entry `options` array,\n * preserving config form. Resource `x402.accepts` uses the same resolution\n * and rail-level networks, RPC endpoints, facilitator and mainnet settings.\n */\nexport function normalizeX402(raw: RawX402, resources: RawConfig['resources']): NormalizedX402 {\n const at = 'payments.x402';\n const direct = DIRECT_OPTION_FIELDS.filter((field) => raw[field] !== undefined);\n if (raw.options !== undefined && direct.length > 0) {\n throw x402Invalid(\n `${at}: give the option either under ${at}.options or directly (${direct.join(', ')}), not both`,\n `${at}.options`,\n );\n }\n if (raw.options?.length === 0) {\n throw x402Invalid(`${at}.options is empty; list at least one option`, `${at}.options`);\n }\n if (raw.options === undefined) {\n for (const field of ['network', 'payTo'] as const) {\n if (raw[field] === undefined) {\n throw x402Invalid(\n `${at}.${field} is required, unless the options are listed under ${at}.options`,\n `${at}.${field}`,\n );\n }\n }\n }\n\n // `kind` and `displayName` declare a network; `rpcUrl` alone sets the\n // endpoint of a built-in or declared one\n const settings = raw.networks ?? {};\n const declared: Record<string, CustomNetworkDeclaration> = {};\n for (const [id, entry] of Object.entries(settings)) {\n if (entry.kind === undefined && entry.displayName === undefined) continue;\n if (entry.kind === undefined || entry.displayName === undefined) {\n const path = `${at}.networks.${id}`;\n throw x402Invalid(`${path}: declaring a network needs both kind and displayName`, path);\n }\n declared[id] = { kind: entry.kind, displayName: entry.displayName };\n }\n const networks = Object.keys(declared).length > 0 ? declared : undefined;\n if (networks !== undefined) validateCustomNetworks(networks, `${at}.networks`);\n for (const id of Object.keys(settings)) {\n if (!findX402Network(id, networks)) {\n const path = `${at}.networks.${id}`;\n throw x402Invalid(\n `${path}: \"${id}\" is not a known network; declare it with kind and displayName`,\n path,\n );\n }\n }\n\n const facilitator = normalizeFacilitator(raw.facilitator);\n const allowMainnet =\n raw.allowMainnet !== undefined ? toBoolean(raw.allowMainnet, `${at}.allowMainnet`) : undefined;\n const allowUnauthenticatedFacilitator =\n raw.allowUnauthenticatedFacilitator !== undefined\n ? toBoolean(raw.allowUnauthenticatedFacilitator, `${at}.allowUnauthenticatedFacilitator`)\n : undefined;\n\n // Shared by every list, so the rail and its resources use one RPC endpoint\n // per network and one deployment mode\n const rpcOwners = new Map<string, string>();\n let firstMode: string | undefined;\n const resolveList = (entries: readonly (readonly [string, RawX402Option])[]): X402OfferTerms => {\n const resolved = entries.map(([path, entry]) =>\n resolveX402Option(x402OptionInput(entry, path), path, networks),\n );\n const seen = new Set<string>();\n const options = resolved.map((option, i): X402OptionConfig => {\n const path = entries[i]?.[0] as string;\n const network = option.network.id;\n // Require distinct RPC endpoints so each network's health check reads its chain\n const rpcUrl = settings[network]?.rpcUrl ?? raw.rpcUrl;\n if (rpcUrl === undefined) {\n throw x402Invalid(\n `${path}.network: no RPC endpoint for ${network}; set ${at}.rpcUrl or ${at}.networks.${network}.rpcUrl`,\n `${at}.rpcUrl`,\n );\n }\n // Parsed, so `https://rpc.example` and `https://rpc.example/` are one endpoint\n const endpoint = new URL(rpcUrl).href;\n const owner = rpcOwners.get(endpoint);\n if (owner !== undefined && owner !== network) {\n throw x402Invalid(\n `${at}: ${owner} and ${network} would use the same RPC endpoint; give each network its own ${at}.networks.<id>.rpcUrl`,\n `${at}.networks`,\n );\n }\n rpcOwners.set(endpoint, network);\n\n // EVM addresses compare case-insensitively; Solana and NEAR exactly\n const comparable = (value: string) =>\n option.network.family === 'evm' ? value.toLowerCase() : value;\n const key = `${network}|${comparable(option.asset)}|${comparable(option.payTo)}`;\n if (seen.has(key)) {\n throw x402Invalid(\n `${path}: repeats an earlier option, the same asset to the same payTo on ${network}`,\n path,\n );\n }\n seen.add(key);\n\n // The provider makes the same call at construction; running it here lets\n // `agent-commerce validate` report an unsafe deployment before boot\n const { mode } = resolveX402Deployment({\n network,\n payTo: option.payTo,\n asset: option.asset,\n ...(option.assetName !== undefined ? { assetName: option.assetName } : {}),\n ...(option.assetVersion !== undefined ? { assetVersion: option.assetVersion } : {}),\n facilitator,\n ...(allowMainnet !== undefined ? { allowMainnet } : {}),\n ...(allowUnauthenticatedFacilitator !== undefined\n ? { allowUnauthenticatedFacilitator }\n : {}),\n ...(networks !== undefined ? { customNetworks: networks } : {}),\n });\n // Keep all offers in one deployment mode: local, testnet or mainnet\n if (firstMode !== undefined && mode !== firstMode) {\n throw x402Invalid(\n `${path}.network: ${network} is a ${mode} network, but the first option is on a ${firstMode} one; every option must be on the same kind of network`,\n `${path}.network`,\n );\n }\n firstMode = mode;\n\n return {\n network,\n rpcUrl,\n asset: option.asset,\n ...(option.assetName !== undefined ? { assetName: option.assetName } : {}),\n ...(option.assetVersion !== undefined ? { assetVersion: option.assetVersion } : {}),\n assetDecimals: option.assetDecimals,\n payTo: option.payTo,\n ...(option.assetTransferMethod === 'permit2'\n ? { assetTransferMethod: 'permit2' as const }\n : {}),\n };\n });\n return {\n options,\n defaultAssetSymbols: [\n ...new Set(resolved.flatMap((option) => option.defaultAssetSymbol ?? [])),\n ],\n };\n };\n\n const rail = resolveList(\n raw.options !== undefined\n ? raw.options.map((option, i) => [`${at}.options[${i}]`, option] as const)\n : [[at, raw]],\n );\n const resourceTerms: Record<string, X402OfferTerms> = {};\n for (const [id, entry] of Object.entries(resources)) {\n const accepts = entry.x402?.accepts;\n if (accepts === undefined) continue;\n const path = `resources.${id}.x402.accepts`;\n if (accepts.length === 0) {\n throw x402Invalid(`${path} is empty; list at least one option`, path);\n }\n resourceTerms[id] = resolveList(accepts.map((option, i) => [`${path}[${i}]`, option] as const));\n }\n const options = rail.options;\n const first = options[0] as X402OptionConfig;\n const resourceOptions = Object.fromEntries(\n Object.entries(resourceTerms).map(([id, terms]) => [id, terms.options]),\n );\n\n const config: X402Config = {\n enabled: toBoolean(raw.enabled, `${at}.enabled`),\n ...first,\n maxTimeoutSeconds: toNumber(raw.maxTimeoutSeconds, `${at}.maxTimeoutSeconds`, { min: 1 }),\n paymentFlow: raw.paymentFlow ?? X402_DEFAULT_PAYMENT_FLOW,\n facilitator,\n ...(allowMainnet !== undefined ? { allowMainnet } : {}),\n ...(allowUnauthenticatedFacilitator !== undefined ? { allowUnauthenticatedFacilitator } : {}),\n ...(networks !== undefined ? { networks } : {}),\n options,\n ...(Object.keys(resourceOptions).length > 0 ? { resourceOptions } : {}),\n };\n\n return { config, ...rail, resources: resourceTerms };\n}\n\nexport function normalizeFacilitator(\n raw: z.infer<typeof FacilitatorSchema>,\n): X402FacilitatorConfig {\n return raw.mode === 'local'\n ? { mode: 'local', signerPrivateKey: raw.signerPrivateKey }\n : { mode: 'remote', url: raw.url, auth: raw.auth ?? { type: 'none' } };\n}\n","// The MPP rail's settings\nimport { CommerceError } from '../../core';\nimport {\n isMppNetwork,\n MPP_DEFAULT_NETWORK,\n MPP_DEFAULT_PAYMENT_FLOW,\n MPP_MIN_CHALLENGE_SECRET_LENGTH,\n MPP_NETWORKS,\n} from '../../payments/mpp/constants';\nimport { resolveX402Deployment } from '../../payments/x402/guardrails';\nimport type { RawConfig } from './raw';\nimport type { GatewayConfig } from './types';\nimport { toBoolean, toNumber, validateAddress } from './values';\nimport { normalizeFacilitator } from './x402';\n\nexport type NormalizedMpp = NonNullable<GatewayConfig['payments']['mpp']>;\n\nexport function normalizeMpp(raw: RawConfig['payments']['mpp']): NormalizedMpp | undefined {\n if (raw === undefined) return undefined;\n const network = raw.network ?? MPP_DEFAULT_NETWORK;\n if (!isMppNetwork(network)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `payments.mpp.network must be one of ${MPP_NETWORKS.join(', ')}`,\n { details: { path: 'payments.mpp.network' } },\n );\n }\n const mpp: NormalizedMpp = {\n enabled: toBoolean(raw.enabled, 'payments.mpp.enabled'),\n network,\n rpcUrl: raw.rpcUrl,\n asset: raw.asset,\n assetName: raw.assetName,\n assetVersion: raw.assetVersion,\n recipient: raw.recipient,\n realm: raw.realm,\n challengeSecret: raw.challengeSecret,\n ...(raw.challengeTtlSeconds !== undefined\n ? {\n challengeTtlSeconds: toNumber(\n raw.challengeTtlSeconds,\n 'payments.mpp.challengeTtlSeconds',\n { min: 1 },\n ),\n }\n : {}),\n paymentFlow: raw.paymentFlow ?? MPP_DEFAULT_PAYMENT_FLOW,\n facilitator: normalizeFacilitator(raw.facilitator),\n ...(raw.allowMainnet !== undefined\n ? { allowMainnet: toBoolean(raw.allowMainnet, 'payments.mpp.allowMainnet') }\n : {}),\n ...(raw.allowUnauthenticatedFacilitator !== undefined\n ? {\n allowUnauthenticatedFacilitator: toBoolean(\n raw.allowUnauthenticatedFacilitator,\n 'payments.mpp.allowUnauthenticatedFacilitator',\n ),\n }\n : {}),\n };\n validateAddress('payments.mpp.recipient', mpp.recipient);\n validateAddress('payments.mpp.asset', mpp.asset);\n // mppx refuses CR or LF in a quoted challenge parameter\n if (/[\\r\\n]/.test(mpp.realm)) {\n throw new CommerceError('CONFIG_INVALID', 'payments.mpp.realm must be a single line', {\n details: { path: 'payments.mpp.realm' },\n });\n }\n // Length only: the secret itself never appears in an error\n if (mpp.challengeSecret.length < MPP_MIN_CHALLENGE_SECRET_LENGTH) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `payments.mpp.challengeSecret must have length at least ${MPP_MIN_CHALLENGE_SECRET_LENGTH}`,\n { details: { path: 'payments.mpp.challengeSecret' } },\n );\n }\n // The shared x402 address, facilitator and mainnet guards, reported under the\n // MPP config path\n resolveX402Deployment({\n network: mpp.network,\n payTo: mpp.recipient,\n asset: mpp.asset,\n assetName: mpp.assetName,\n assetVersion: mpp.assetVersion,\n facilitator: mpp.facilitator,\n ...(mpp.allowMainnet !== undefined ? { allowMainnet: mpp.allowMainnet } : {}),\n ...(mpp.allowUnauthenticatedFacilitator !== undefined\n ? { allowUnauthenticatedFacilitator: mpp.allowUnauthenticatedFacilitator }\n : {}),\n configPath: 'payments.mpp',\n payToField: 'recipient',\n });\n return mpp;\n}\n","// The Zod schemas for `config.yaml`: shape only, before any business rule\nimport { type ZodTypeAny, z } from 'zod';\nimport { X402_PAYMENT_FLOWS } from '../../payments/x402/payment-flow';\nimport { ACP_WELL_KNOWN_PATH } from '../../protocols/acp/constants';\n\nexport const SUPPORTED_CONFIG_VERSION = 1;\n\n// A number, or a numeric string from env substitution\nconst NumberOrString = z.union([z.number(), z.string()]);\n\n// A boolean, or a \"true\"/\"false\" string from env substitution\nconst BooleanOrString = z.union([z.boolean(), z.string()]);\n\n// A media type as in a Content-Type header: `type/subtype`, then any parameters\nconst MediaType = z\n .string()\n .regex(/^[A-Za-z0-9][\\w!#$&^.+-]*\\/[A-Za-z0-9][\\w!#$&^.+-]*(?:[ \\t]*;.*)?$/, {\n message: 'must be a media type such as application/json',\n });\n\n// An RPC endpoint. The message never echoes the value, which can carry an API key\nconst RpcUrl = z\n .string()\n .min(1)\n .refine(isHttpUrl, { message: 'must be an http:// or https:// URL' });\n\nfunction isHttpUrl(value: string): boolean {\n try {\n const { protocol } = new URL(value);\n return protocol === 'http:' || protocol === 'https:';\n } catch {\n return false;\n }\n}\n\nconst MerchantSchema = z\n .object({\n id: z.string().min(1),\n name: z.string().min(1),\n publicBaseUrl: z.string().min(1),\n })\n .strict();\n\nconst ServerSchema = z\n .object({\n port: NumberOrString,\n host: z.string().min(1),\n // Shared secret gating /api/receipts and /api/events. Without it both\n // routes 404.\n adminToken: z.string().min(1).optional(),\n // Browser origins allowed to call the gateway; none by default. A request\n // with any other `Origin` gets 403 on every route. Entries match the\n // `Origin` header exactly (ignoring case), so `\"*\"` and a trailing slash\n // would match nothing: a silent lockout that an operator might \"fix\" by\n // disabling the check. Both are refused with a pointer.\n allowedOrigins: z\n .array(\n z\n .string()\n .min(1)\n .refine((origin) => origin !== '*', {\n message:\n 'wildcard \"*\" is not supported - allowedOrigins entries are matched literally against the browser\\'s Origin header, so \"*\" would match nothing. List each scheme://host[:port] explicitly.',\n })\n .refine((origin) => !origin.endsWith('/'), {\n message:\n 'must not end with \"/\" - a browser Origin header never has a trailing slash, so this entry would match nothing. Use e.g. \"http://localhost:5173\".',\n }),\n )\n .optional(),\n })\n .strict();\n\nconst StorageSchema = z\n .object({\n receipts: z\n .object({\n driver: z.literal('sqlite'),\n path: z.string().min(1),\n })\n .strict(),\n })\n .strict();\n\n// Every path the gateway registers (`src/gateway/routes.ts`), plus the fixed\n// discovery paths adapters own. A mount equal to one duplicates that route; a\n// mount that is a prefix of one swallows it through its `${mountPath}/*` wildcard.\nconst RESERVED_GATEWAY_PATHS = [\n '/health',\n '/ready',\n '/.well-known/agent-commerce',\n // Fixed by the A2A specification and served by the adapter\n '/.well-known/agent-card.json',\n // Fixed by the ACP specification\n ACP_WELL_KNOWN_PATH,\n '/api/resources',\n '/api/resources/:id/invoke',\n '/api/receipts',\n '/api/events',\n] as const;\n\n// A bad `mountPath` would throw inside Fastify route registration at\n// `server.ready()`, failing the whole gateway with an opaque `FST_ERR_*`.\n// Checked here it is a CONFIG_INVALID naming the value. Pattern syntax (`:`,\n// `*`) is refused because the mount registers its own wildcard.\nconst MountPathSchema = z\n .string()\n .min(1)\n .refine((value) => value.startsWith('/'), {\n message: 'must start with \"/\" - it is an absolute gateway path, e.g. \"/mcp\".',\n })\n .refine((value) => !/[:*?\\s]/.test(value), {\n message:\n 'must not contain \":\", \"*\", \"?\" or whitespace - the mount is a literal path prefix, not a Fastify route pattern, and registers its own wildcard.',\n })\n .refine(\n (value) => {\n const base = value.replace(/\\/+$/, '');\n return !RESERVED_GATEWAY_PATHS.some(\n (reserved) => reserved === base || reserved.startsWith(`${base}/`),\n );\n },\n {\n message: `must not collide with a route the gateway already serves (${RESERVED_GATEWAY_PATHS.join(', ')}); pick a dedicated prefix such as \"/mcp\".`,\n },\n );\n\n// Bearer is the only ACP auth scheme; there is no `none`\nconst AcpAuthSchema = z.object({ type: z.literal('bearer'), token: z.string().min(1) }).strict();\n\nconst AcpIdempotencySchema = z\n .object({\n path: z.string().min(1),\n retentionHours: NumberOrString.optional(),\n merchantIdempotent: z.boolean().optional(),\n })\n .strict();\n\n// Operation names are checked against `ACP_CHECKOUT_OPERATIONS` in the\n// business pass, which names a missing or misspelled operation\nconst AcpCheckoutSchema = z.object({ operations: z.record(z.string().min(1)) }).strict();\n\n// Optional discovery metadata, omitted when not configured\nconst AcpDiscoverySchema = z\n .object({\n documentationUrl: z.string().min(1).optional(),\n supportedCurrencies: z.array(z.string().min(1)).optional(),\n supportedLocales: z.array(z.string().min(1)).optional(),\n interventionTypes: z.array(z.string().min(1)).optional(),\n })\n .strict();\n\nconst ProtocolsSchema = z\n .object({\n http: z.object({ enabled: BooleanOrString }).strict(),\n mcp: z\n .object({\n enabled: BooleanOrString,\n mountPath: MountPathSchema,\n })\n .strict(),\n // Optional; A2A is off unless configured\n a2a: z\n .object({\n enabled: BooleanOrString,\n mountPath: MountPathSchema.optional(),\n })\n .strict()\n .optional(),\n // Optional and off by default. The business pass requires the sub-blocks\n // only when ACP is enabled, so a disabled placeholder stays valid and an\n // enabled block gets a message naming what it lacks.\n acp: z\n .object({\n enabled: BooleanOrString,\n mountPath: MountPathSchema.optional(),\n auth: AcpAuthSchema.optional(),\n idempotency: AcpIdempotencySchema.optional(),\n checkout: AcpCheckoutSchema.optional(),\n discovery: AcpDiscoverySchema.optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\n\nconst BackendMethodSchema = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);\n\n// Strict, so a typo like `bodyy` fails at load instead of silently meaning\n// \"no body binding\"\nconst BackendInputBindingsSchema = z\n .object({\n path: z.string().min(1).optional(),\n query: z.string().min(1).optional(),\n body: z.string().min(1).optional(),\n })\n .strict();\n\nconst BackendHandlerSchema = z\n .object({\n type: z.literal('http'),\n method: BackendMethodSchema,\n url: z.string().min(1),\n headers: z.record(z.string(), z.string()).optional(),\n timeoutMs: NumberOrString.optional(),\n inputBindings: BackendInputBindingsSchema.optional(),\n })\n .strict();\n\nconst PricingSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('free') }).strict(),\n z\n .object({\n type: z.literal('fixed'),\n amount: z.string().min(1),\n currency: z.string().min(1),\n })\n .strict(),\n z\n .object({\n type: z.literal('dynamic'),\n resolver: z.string().min(1),\n })\n .strict(),\n]);\n\nconst JsonSchemaValueSchema: ZodTypeAny = z.record(z.string(), z.unknown());\n\n// Settlement network, payee and token, resolved by x402/options.ts. Network\n// and payee fields follow the SDK's `PaymentOption`; asset fields override defaults\nconst X402OptionSchema = z\n .object({\n scheme: z.string().min(1).optional(),\n network: z.string().min(1),\n payTo: z.string().min(1),\n asset: z.string().min(1).optional(),\n assetName: z.string().min(1).optional(),\n assetVersion: z.string().min(1).optional(),\n assetDecimals: NumberOrString.optional(),\n assetTransferMethod: z.string().min(1).optional(),\n })\n .strict();\n\nconst ResourceEntrySchema = z\n .object({\n name: z.string().min(1),\n description: z.string().optional(),\n input: JsonSchemaValueSchema.optional(),\n output: JsonSchemaValueSchema.optional(),\n // What the backend returns; x402 challenges declare it, `application/json` by default\n mimeType: MediaType.optional(),\n backend: BackendHandlerSchema,\n pricing: PricingSchema,\n expose: z.array(z.string().min(1)).min(1),\n payments: z.array(z.string().min(1)).optional(),\n paymentFlow: z.enum(X402_PAYMENT_FLOWS).optional(),\n // This resource's own x402 offers, in place of `payments.x402` options\n x402: z\n .object({ accepts: z.array(X402OptionSchema) })\n .strict()\n .optional(),\n authorization: z\n .object({ required: z.array(z.string().min(1)).min(1) })\n .strict()\n .optional(),\n })\n .strict();\n\nconst ResourcesMapSchema = z.record(z.string().min(1), ResourceEntrySchema);\n\n// Facilitator credentials. `none` and `bearer` fit any facilitator; `cdp` is\n// the one vendor-specific type. Any other type is refused at load.\nconst FacilitatorAuthSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('none') }).strict(),\n z.object({ type: z.literal('bearer'), token: z.string().min(1) }).strict(),\n // Coinbase Developer Platform. Needs the optional peer `@coinbase/x402`,\n // which signs a fresh JWT per request.\n z\n .object({\n type: z.literal('cdp'),\n apiKeyId: z.string().min(1),\n apiKeySecret: z.string().min(1),\n })\n .strict(),\n]);\n\nexport const FacilitatorSchema = z.discriminatedUnion('mode', [\n z\n .object({\n mode: z.literal('local'),\n signerPrivateKey: z.string().min(1),\n })\n .strict(),\n z\n .object({\n mode: z.literal('remote'),\n url: z.string().min(1),\n // Absent auth sends no credential and normalizes to `{ type: 'none' }`,\n // which on mainnet requires `allowUnauthenticatedFacilitator`\n auth: FacilitatorAuthSchema.optional(),\n })\n .strict(),\n]);\n\n// Per-network settings: `kind` and `displayName` declare a network outside\n// the registry; `rpcUrl` is that network's endpoint, built in or declared\nconst X402NetworkSettingsSchema = z\n .object({\n kind: z.enum(['testnet', 'mainnet']).optional(),\n displayName: z.string().min(1).optional(),\n rpcUrl: RpcUrl.optional(),\n })\n .strict();\n\nconst X402Schema = z\n .object({\n enabled: BooleanOrString,\n // Accept direct fields or an `options` array, never both\n network: z.string().min(1).optional(),\n payTo: z.string().min(1).optional(),\n asset: z.string().min(1).optional(),\n assetName: z.string().min(1).optional(),\n assetVersion: z.string().min(1).optional(),\n assetDecimals: NumberOrString.optional(),\n assetTransferMethod: z.string().min(1).optional(),\n options: z.array(X402OptionSchema).optional(),\n networks: z.record(z.string().min(1), X402NetworkSettingsSchema).optional(),\n // The RPC for every network without its own `networks.<id>.rpcUrl`\n rpcUrl: RpcUrl.optional(),\n maxTimeoutSeconds: NumberOrString,\n // `authorization` (the x402 default) settles after the backend call\n paymentFlow: z.enum(X402_PAYMENT_FLOWS).optional(),\n facilitator: FacilitatorSchema,\n // Real funds. Never defaulted; see src/payments/x402/guardrails.ts\n allowMainnet: BooleanOrString.optional(),\n // Accepts credential-free facilitator access on mainnet. Never defaulted\n allowUnauthenticatedFacilitator: BooleanOrString.optional(),\n })\n .strict();\n\nconst MppSchema = z\n .object({\n enabled: BooleanOrString,\n network: z.string().min(1).optional(),\n rpcUrl: RpcUrl,\n asset: z.string().min(1),\n assetName: z.string().min(1),\n assetVersion: z.string().min(1),\n recipient: z.string().min(1),\n realm: z.string().min(1),\n challengeSecret: z.string().min(1),\n challengeTtlSeconds: NumberOrString.optional(),\n // Same values as `payments.x402.paymentFlow`; the default is `upfront`\n paymentFlow: z.enum(X402_PAYMENT_FLOWS).optional(),\n facilitator: FacilitatorSchema,\n // Real funds. Never defaulted; see src/payments/x402/guardrails.ts\n allowMainnet: BooleanOrString.optional(),\n // Accepts credential-free facilitator access on mainnet. Never defaulted\n allowUnauthenticatedFacilitator: BooleanOrString.optional(),\n })\n .strict();\n\nconst PaymentsSchema = z\n .object({\n x402: X402Schema.optional(),\n mpp: MppSchema.optional(),\n })\n .strict();\n\n// A public verification key, inline only: no `jwksUri`, `jku` or discovery\n// URL. AP2 leaves secure key distribution open, and fetching keys would mean\n// fetching from a location a mandate can influence. The business pass checks\n// the JWK's members against `AP2_JWK_MEMBERS`, which also keeps out `x5u`.\nconst Ap2KeySchema = z\n .object({\n kid: z.string().min(1),\n jwk: z.record(z.string(), z.unknown()),\n })\n .strict();\n\nexport const Ap2IssuerSchema = z\n .object({\n issuer: z.string().min(1),\n // Required, not defaulted: without it a mandate minted for another\n // merchant would verify here\n audience: z.string().min(1),\n keys: z.array(Ap2KeySchema).min(1),\n })\n .strict();\n\nconst Ap2Schema = z\n .object({\n enabled: BooleanOrString,\n specVersion: z.string().min(1).optional(),\n mode: z.string().min(1).optional(),\n trust: z\n .object({\n mandateIssuers: z.array(Ap2IssuerSchema).optional(),\n checkoutIssuers: z.array(Ap2IssuerSchema).optional(),\n })\n .strict()\n .optional(),\n clockSkewSeconds: NumberOrString.optional(),\n requireMandateAudience: BooleanOrString.optional(),\n requireMandateExpiry: BooleanOrString.optional(),\n replay: z\n .object({ path: z.string().min(1) })\n .strict()\n .optional(),\n })\n .strict();\n\n// Optional and off by default. The business pass requires the sub-blocks only\n// when AP2 is enabled, and names the missing piece.\nconst AuthorizationSchema = z.object({ ap2: Ap2Schema.optional() }).strict();\n\nexport const RawConfigSchema = z\n .object({\n version: z.literal(SUPPORTED_CONFIG_VERSION),\n merchant: MerchantSchema,\n server: ServerSchema,\n storage: StorageSchema,\n protocols: ProtocolsSchema,\n resources: ResourcesMapSchema,\n payments: PaymentsSchema,\n authorization: AuthorizationSchema.optional(),\n })\n .strict();\n\nexport type RawConfig = z.infer<typeof RawConfigSchema>;\n\nexport type RawResourceEntry = z.infer<typeof ResourceEntrySchema>;\n","/**\n * Shapes a backend request from validated input: the path template, query,\n * body and forwarded headers. The pipeline checks the shape before pricing, so\n * a request the backend cannot receive fails before any payment.\n */\nimport type { BackendHandler, BackendMethod } from '../domain/resource';\nimport { CommerceError } from '../errors';\nimport { isRecord } from '../is-record';\n\n// Never forward credentials, transport headers or fields set by the executor\nconst NEVER_FORWARDED_HEADER =\n /^(authorization|cookie|set-cookie|host|content-length|content-type|connection|keep-alive|te|trailer|transfer-encoding|upgrade|idempotency-key|proxy-.*)$/;\n\n// The one `{param}` grammar, shared by substitution, config, `doctor` and the\n// OpenAPI importer. It admits `-` and `.` because\n// `/report/{report-id}` is ordinary REST. Config refuses any other brace\n// (findUnparsedBraceToken).\nconst PATH_PARAM_PATTERN = /\\{([a-zA-Z0-9_.-]+)\\}/g;\n\n/**\n * `{param}` names in a `backend.url` template, in declaration order. Config,\n * `doctor` and the OpenAPI importer use it so they read the same grammar as\n * substitution.\n */\nexport function extractPathParameterNames(url: string): string[] {\n return [...url.matchAll(PATH_PARAM_PATTERN)].map((match) => match[1] as string);\n}\n\n/**\n * A brace left over after every legal `{param}` is removed, or `undefined`.\n *\n * `{report id}`, `{a/b}`, `{}` and an unbalanced `{` match no parameter and\n * would reach the backend as literals, which on a paid resource means payment\n * without delivery. Config refuses any such residue, and the OpenAPI importer\n * skips the operation.\n */\nexport function findUnparsedBraceToken(url: string): string | undefined {\n const residue = url.replace(PATH_PARAM_PATTERN, '');\n const index = residue.search(/[{}]/);\n if (index === -1) return undefined;\n // Report the offending run, not just the character, so the error is fixable\n const token = /\\{[^{}]*\\}?|\\}/.exec(residue.slice(index));\n return token?.[0] ?? residue[index];\n}\n\n/**\n * Check path values, query collisions and headers before pricing. `call()`\n * repeats these checks. Invalid input or forwarded headers raise\n * `INPUT_INVALID`; invalid configured headers raise `BACKEND_ERROR`.\n * An unparseable URL remains a call-time error. Does no I/O.\n */\nexport function validateBackendRequestShape(\n handler: BackendHandler,\n input: unknown,\n context: ShapeContext,\n backendHeaders?: Readonly<Record<string, string>>,\n): void {\n const inputRecord = isRecord(input) ? input : {};\n\n // Every shape error (missing or invalid path parameter, a bound group that is\n // not an object) throws INPUT_INVALID here\n const parts = buildBackendRequestParts(handler, inputRecord, context);\n // Config refuses a bad header at load; this covers a hand-built resource\n buildHeaders(handler, context, backendHeaders);\n\n let target: URL;\n try {\n target = new URL(parts.url);\n } catch {\n return; // call() raises BACKEND_ERROR for an unparseable URL\n }\n checkQueryCollision(target, parts.query, context);\n}\n\ntype ShapeContext = { readonly requestId: string; readonly resourceId: string };\n\n// The path-templated URL plus the query and body values a request carries\ninterface BackendRequestParts {\n readonly url: string;\n readonly query: Record<string, unknown>;\n // Present when a JSON body should be sent; `value` is what gets encoded\n readonly body?: { readonly value: unknown };\n}\n\nfunction acceptsBody(method: BackendMethod): boolean {\n return method !== 'GET' && method !== 'DELETE';\n}\n\n/**\n * Split validated input into URL, query and body according to\n * `handler.inputBindings`. `call()` and `validateBackendRequestShape()` both\n * use it, so they cannot disagree about the request an input describes. Throws\n * only `CommerceError('INPUT_INVALID')`.\n */\nexport function buildBackendRequestParts(\n handler: BackendHandler,\n input: Record<string, unknown>,\n context: ShapeContext,\n): BackendRequestParts {\n const bindings = handler.inputBindings;\n if (bindings === undefined) {\n const { url, remaining } = applyPathTemplate(handler.url, input, context);\n return acceptsBody(handler.method)\n ? { url, query: {}, body: { value: remaining } }\n : { url, query: remaining };\n }\n\n const pathValues =\n bindings.path === undefined ? {} : resolveBoundGroup(input, bindings.path, 'path', context);\n const { url } = applyPathTemplate(handler.url, pathValues, context);\n const query =\n bindings.query === undefined ? {} : resolveBoundGroup(input, bindings.query, 'query', context);\n\n // An absent body value sends no body rather than `null`. A required body is\n // enforced earlier, by `required` in the resource's input schema.\n const bodyValue = bindings.body === undefined ? undefined : input[bindings.body];\n if (bodyValue === undefined || !acceptsBody(handler.method)) return { url, query };\n return { url, query, body: { value: bodyValue } };\n}\n\nfunction resolveBoundGroup(\n input: Record<string, unknown>,\n key: string,\n kind: 'path' | 'query',\n context: ShapeContext,\n): Record<string, unknown> {\n const value = input[key];\n if (value === undefined) return {};\n if (!isRecord(value)) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Input \"${key}\" must be an object of ${kind} parameters`,\n { ...context, details: { field: key } },\n );\n }\n return value;\n}\n\nexport function checkQueryCollision(\n target: URL,\n remaining: Record<string, unknown>,\n context: { readonly requestId: string; readonly resourceId: string },\n): void {\n const templateKeys = new Set(target.searchParams.keys());\n for (const key of Object.keys(remaining)) {\n if (templateKeys.has(key)) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Input key \"${key}\" collides with a query parameter already set on backend.url`,\n { requestId: context.requestId, resourceId: context.resourceId, details: { field: key } },\n );\n }\n }\n}\n\n// encodeURIComponent leaves \".\" alone, and new URL() then resolves a \".\" or\n// \"..\" segment, stepping outside the template's directory. Slashes are\n// escaped, so only these exact values (and \"\", an empty segment) need refusing.\nconst TRAVERSAL_PATH_VALUES = new Set(['', '.', '..']);\n\nfunction applyPathTemplate(\n template: string,\n input: Record<string, unknown>,\n context: ShapeContext,\n): { url: string; remaining: Record<string, unknown> } {\n const remaining: Record<string, unknown> = { ...input };\n let missing: string | undefined;\n let invalid: string | undefined;\n const url = template.replace(PATH_PARAM_PATTERN, (_match, key: string) => {\n // Object.hasOwn, not `in`: a parameter named \"constructor\" or \"toString\"\n // would otherwise resolve to the inherited Object.prototype member\n if (!Object.hasOwn(remaining, key)) {\n missing = key;\n return '';\n }\n const value = remaining[key];\n delete remaining[key];\n const raw = stringifyPrimitive(value);\n if (TRAVERSAL_PATH_VALUES.has(raw)) {\n invalid = key;\n return '';\n }\n return encodeURIComponent(raw);\n });\n if (missing !== undefined) {\n // Config refuses a template parameter the input schema cannot supply.\n // This covers a hand-built `CommerceResource` that skipped config: through\n // validateBackendRequestShape it fails before payment, instead of calling\n // the backend with an empty path segment.\n throw new CommerceError('INPUT_INVALID', `Path parameter \"${missing}\" was not supplied`, {\n ...context,\n details: { field: missing },\n });\n }\n if (invalid !== undefined) {\n throw new CommerceError('INPUT_INVALID', `Path parameter \"${invalid}\" is not a valid value`, {\n ...context,\n details: { field: invalid },\n });\n }\n return { url, remaining };\n}\n\nexport function stringifyPrimitive(value: unknown): string {\n if (value === undefined || value === null) return '';\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n// `Headers` throws a TypeError on an illegal name or value. The error is\n// rethrown typed and without `cause`: the TypeError quotes the value, which may\n// be a credential.\nexport function buildHeaders(\n handler: BackendHandler,\n context: ShapeContext,\n forwarded: Readonly<Record<string, string>> = {},\n): Headers {\n let headers: Headers;\n try {\n headers = new Headers(handler.headers);\n } catch {\n throw invalidHeaderError(context);\n }\n // Caller headers cannot replace operator-configured backend credentials\n for (const [name, value] of Object.entries(forwarded)) {\n if (NEVER_FORWARDED_HEADER.test(name.toLowerCase())) continue;\n try {\n if (!headers.has(name)) headers.set(name, value);\n } catch {\n throw new CommerceError('INPUT_INVALID', 'A forwarded request header is invalid', {\n ...context,\n details: { reason: 'invalid-forwarded-header' },\n });\n }\n }\n return headers;\n}\n\nexport function setHeader(\n headers: Headers,\n name: string,\n value: string,\n context: ShapeContext,\n): void {\n try {\n headers.set(name, value);\n } catch {\n throw invalidHeaderError(context);\n }\n}\n\nfunction invalidHeaderError(context: ShapeContext): CommerceError {\n return new CommerceError('BACKEND_ERROR', 'Backend request headers are invalid', {\n ...context,\n details: { reason: 'invalid-header' },\n });\n}\n","/**\n * The built-in outbound HTTP path to a merchant backend.\n *\n * - Global `fetch`, always bounded by `AbortSignal.timeout`.\n * - `redirect: 'manual'`: a 3xx response is a `BACKEND_ERROR`, never followed\n * (SSRF hardening).\n * - `{param}` segments in `handler.url` are filled from validated input and\n * URL-encoded; the rest is mapped as `BackendHandler.inputBindings`\n * describes (see `backend-request.ts`).\n */\nimport { type BackendHandler, DEFAULT_BACKEND_TIMEOUT_MS } from '../domain/resource';\nimport { CommerceError, isCommerceError } from '../errors';\nimport type { BackendExecutor, BackendRequest, BackendResponse } from '../interfaces/backend';\nimport { type Logger, NOOP_LOGGER } from '../interfaces/logger';\nimport { isRecord } from '../is-record';\nimport {\n buildBackendRequestParts,\n buildHeaders,\n checkQueryCollision,\n setHeader,\n stringifyPrimitive,\n} from './backend-request';\n\nconst MAX_BODY_SNIPPET_LENGTH = 512;\n\n// How a merchant recognizes a repeat of an operation. The de facto standard\n// name, and the one ACP requires inbound.\nconst IDEMPOTENCY_KEY_HEADER = 'idempotency-key';\n\n// The timeout bounds a response by time, not bytes; this stops a hostile or\n// broken backend from filling memory\nconst MAX_RESPONSE_BODY_BYTES = 1024 * 1024;\n\nexport interface HttpBackendExecutorOptions {\n /** Override for `fetch`, used in tests. Defaults to the global implementation */\n readonly fetchImpl?: typeof fetch;\n /** Receives a non-2xx backend body at debug level; it never reaches the client */\n readonly logger?: Logger;\n}\n\n/**\n * Merchant non-2xx response attached as the `BACKEND_ERROR` cause. Adapters\n * can inspect its body and headers; client errors omit the cause.\n */\nexport class BackendErrorResponse {\n constructor(\n readonly status: number,\n readonly body: unknown,\n /** Lowercase names, as `Headers` yields them */\n readonly headers: Readonly<Record<string, string>> = {},\n ) {}\n}\n\nexport class HttpBackendExecutor implements BackendExecutor {\n private readonly fetchImpl: typeof fetch;\n private readonly logger: Logger;\n\n constructor(options: HttpBackendExecutorOptions = {}) {\n this.fetchImpl = options.fetchImpl ?? fetch;\n this.logger = options.logger ?? NOOP_LOGGER;\n }\n\n async call(handler: BackendHandler, request: BackendRequest): Promise<BackendResponse> {\n const timeoutMs = handler.timeoutMs ?? DEFAULT_BACKEND_TIMEOUT_MS;\n const inputRecord = isRecord(request.input) ? request.input : {};\n\n const context = { requestId: request.requestId, resourceId: request.resourceId };\n // Throws INPUT_INVALID for every shape problem. The pipeline already ran it\n // before payment through validateBackendRequestShape(); this copy covers a\n // caller that bypasses the pipeline.\n const parts = buildBackendRequestParts(handler, inputRecord, context);\n\n let target: URL;\n try {\n target = new URL(parts.url);\n } catch (error) {\n throw new CommerceError('BACKEND_ERROR', 'Backend URL could not be constructed from input', {\n ...context,\n details: { reason: 'invalid-url' },\n cause: error,\n });\n }\n\n // Beyond the per-parameter check: the resolved path must stay under the\n // template's literal prefix (everything before the first `{`)\n const prefixPathname = literalPrefixPathname(handler);\n if (prefixPathname !== undefined && !target.pathname.startsWith(prefixPathname)) {\n throw new CommerceError(\n 'INPUT_INVALID',\n 'Path parameters resolved outside the configured backend path',\n context,\n );\n }\n\n const headers = buildHeaders(handler, context, request.backendHeaders);\n // Replaces a configured header of the same name, unlike content-type below:\n // a static key would make every request look like a retry of the first\n if (request.idempotencyKey !== undefined) {\n setHeader(headers, IDEMPOTENCY_KEY_HEADER, request.idempotencyKey, context);\n }\n let body: string | undefined;\n\n // searchParams.set() replaces an existing param, so a caller key named\n // like an operator's query param (`?apikey=SECRET` in handler.url) would\n // overwrite it. validateBackendRequestShape() runs the same check before\n // payment.\n checkQueryCollision(target, parts.query, context);\n for (const [key, value] of Object.entries(parts.query)) {\n target.searchParams.set(key, stringifyPrimitive(value));\n }\n if (parts.body !== undefined) {\n body = JSON.stringify(parts.body.value);\n // A configured Content-Type, such as `application/vnd.x+json`, wins\n if (!headers.has('content-type')) headers.set('content-type', 'application/json');\n }\n\n const started = performance.now();\n let response: Response;\n try {\n response = await this.fetchImpl(target, {\n method: handler.method,\n headers,\n ...(body !== undefined ? { body } : {}),\n redirect: 'manual',\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n const durationMs = Math.round(performance.now() - started);\n if (isAbortError(error)) {\n throw new CommerceError(\n 'BACKEND_TIMEOUT',\n `Backend request timed out after ${timeoutMs}ms`,\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { timeoutMs, durationMs },\n cause: error,\n },\n );\n }\n throw new CommerceError('BACKEND_ERROR', 'Backend request failed (transport error)', {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { durationMs },\n cause: error,\n });\n }\n const durationMs = Math.round(performance.now() - started);\n\n const isRedirect =\n response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400);\n if (isRedirect) {\n throw new CommerceError(\n 'BACKEND_ERROR',\n 'Backend responded with a redirect, which is not followed',\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { status: response.status, reason: 'redirect-not-followed' },\n },\n );\n }\n\n const responseHeaders = Object.fromEntries(response.headers);\n const contentType = response.headers.get('content-type') ?? '';\n let parsedBody: unknown;\n try {\n parsedBody = await parseBody(response, contentType);\n } catch (error) {\n const tooLarge = isCommerceError(error);\n throw new CommerceError(\n 'BACKEND_ERROR',\n tooLarge\n ? 'Backend response exceeded the maximum allowed size'\n : 'Backend response could not be read',\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: tooLarge\n ? { reason: 'response-too-large', maxBytes: MAX_RESPONSE_BODY_BYTES }\n : { reason: 'read-error' },\n cause: error,\n },\n );\n }\n\n if (response.status < 200 || response.status >= 300) {\n // The status may reach the client, but the body is logged at debug level\n // only: a backend in verbose error mode emits stack traces, hostnames or\n // SQL fragments, and the caller may be anonymous\n this.logger.debug(\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n status: response.status,\n bodySnippet: truncateSnippet(parsedBody),\n },\n 'Backend responded with a non-2xx status',\n );\n throw new CommerceError('BACKEND_ERROR', `Backend responded with status ${response.status}`, {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { status: response.status },\n cause: new BackendErrorResponse(response.status, parsedBody, responseHeaders),\n });\n }\n\n return {\n status: response.status,\n headers: responseHeaders,\n body: parsedBody,\n durationMs,\n };\n }\n}\n\n// `handler.url` never changes, so its literal prefix is parsed once per handler.\n// `null` records a prefix that is not a URL, as when a parameter sits in the\n// host (which config refuses); the containment check is then skipped.\nconst prefixPathnames = new WeakMap<BackendHandler, string | null>();\n\nfunction literalPrefixPathname(handler: BackendHandler): string | undefined {\n let cached = prefixPathnames.get(handler);\n if (cached === undefined) {\n try {\n cached = new URL(handler.url.split('{')[0] ?? handler.url).pathname;\n } catch {\n cached = null;\n }\n prefixPathnames.set(handler, cached);\n }\n return cached ?? undefined;\n}\n\nasync function readBodyCapped(response: Response, maxBytes: number): Promise<string> {\n if (!response.body) return '';\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n // The only CommerceError parseBody can throw, which is how its caller\n // tells an oversized body from a read failure\n throw new CommerceError('BACKEND_ERROR', `response body exceeded ${maxBytes} bytes`);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks).toString('utf8');\n}\n\nasync function parseBody(response: Response, contentType: string): Promise<unknown> {\n const text = await readBodyCapped(response, MAX_RESPONSE_BODY_BYTES);\n if (text.length === 0) return text;\n if (contentType.includes('json')) {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n return text;\n}\n\nfunction truncateSnippet(body: unknown): string {\n const text = typeof body === 'string' ? body : safeStringify(body);\n return text.length > MAX_BODY_SNIPPET_LENGTH\n ? `${text.slice(0, MAX_BODY_SNIPPET_LENGTH)}…`\n : text;\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError');\n}\n","/**\n * A small JSON Schema validator for resource input.\n *\n * Supported subset (draft 2020-12 vocabulary, structural only):\n * - `type`: \"object\" | \"string\" | \"number\" | \"integer\" | \"boolean\" | \"array\" |\n * \"null\", or an array of those (e.g. `[\"object\", \"null\"]`)\n * - `properties` (validated recursively)\n * - `required` (string[])\n * - `additionalProperties` (boolean, or a schema applied to extra properties)\n * - `enum` (allowed values; objects and arrays compared structurally, in any key\n * order)\n * - `items` (one schema applied to every array element, no tuple form)\n *\n * Not enforced: `minLength`, `maxLength`, `pattern`, `format`, `minimum`,\n * `maximum`, `exclusiveMinimum/Maximum`, `multipleOf`, `oneOf`, `anyOf`,\n * `allOf`, `not`, `$ref`, `const`, `patternProperties`, `minItems`,\n * `maxItems`, `uniqueItems`, tuple-form `items`, and a `type` naming anything\n * outside the list above. Config warns at load when a schema uses one of these\n * keywords or a tuple `items`.\n */\nimport { isDeepStrictEqual } from 'node:util';\nimport type { JsonSchema } from '../domain/common';\nimport { isRecord } from '../is-record';\n\nexport interface FieldError {\n readonly path: string;\n readonly message: string;\n}\n\nexport type ValidationResult =\n | { readonly valid: true; readonly value: unknown }\n | { readonly valid: false; readonly errors: readonly FieldError[] };\n\nexport type Validator = (input: unknown) => ValidationResult;\n\nconst SUPPORTED_TYPES = new Set([\n 'object',\n 'string',\n 'number',\n 'integer',\n 'boolean',\n 'array',\n 'null',\n]);\n\n/** Wrap a resource `inputSchema` in a reusable validator function */\nexport function compileJsonSchema(schema: JsonSchema | undefined): Validator {\n return (input: unknown): ValidationResult => {\n if (schema === undefined) return { valid: true, value: input };\n const errors = validateNode(schema, input, '$');\n return errors.length === 0 ? { valid: true, value: input } : { valid: false, errors };\n };\n}\n\nfunction matchesType(type: string, value: unknown): boolean {\n switch (type) {\n case 'object':\n return isRecord(value);\n case 'array':\n return Array.isArray(value);\n case 'string':\n return typeof value === 'string';\n case 'boolean':\n return typeof value === 'boolean';\n case 'number':\n return typeof value === 'number' && Number.isFinite(value);\n case 'integer':\n return typeof value === 'number' && Number.isInteger(value);\n case 'null':\n return value === null;\n default:\n return true;\n }\n}\n\nfunction describeType(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n return typeof value;\n}\n\n// `===` first keeps a top-level -0 equal to 0; isDeepStrictEqual alone would not\nfunction deepEqual(a: unknown, b: unknown): boolean {\n return a === b || isDeepStrictEqual(a, b);\n}\n\nfunction own(obj: Record<string, unknown>, key: string): unknown {\n return Object.hasOwn(obj, key) ? obj[key] : undefined;\n}\n\n// `type` may be a string or an array of strings, e.g. `[\"object\", \"null\"]`. An\n// array with a non-string entry is ignored rather than guessed at.\nfunction typeList(raw: unknown): string[] | undefined {\n if (typeof raw === 'string') return [raw];\n if (Array.isArray(raw) && raw.every((entry): entry is string => typeof entry === 'string')) {\n return raw;\n }\n return undefined;\n}\n\n/**\n * Whether a schema node is an object schema: its `type` includes \"object\"\n * (`[\"object\", \"null\"]` counts), or it has no `type` and declares `properties`\n * or `required`.\n *\n * Config's `defaultClosedObjectSchema` uses it to close schemas and this\n * validator uses it to enforce them. With two definitions, a node could stay\n * open while config believes it closed.\n */\nexport function isObjectSchemaNode(schema: Record<string, unknown>): boolean {\n const types = typeList(schema['type']);\n if (types !== undefined) return types.includes('object');\n return Object.hasOwn(schema, 'properties') || Object.hasOwn(schema, 'required');\n}\n\nfunction validateNode(schema: JsonSchema, value: unknown, path: string): FieldError[] {\n const errors: FieldError[] = [];\n const types = typeList(own(schema, 'type'));\n const recognizedTypes = types?.filter((entry) => SUPPORTED_TYPES.has(entry));\n\n if (\n types !== undefined &&\n recognizedTypes !== undefined &&\n recognizedTypes.length === types.length &&\n types.length > 0\n ) {\n if (!types.some((entry) => matchesType(entry, value))) {\n errors.push({\n path,\n message: `expected type \"${types.join(' | ')}\" but got ${describeType(value)}`,\n });\n return errors;\n }\n }\n\n const enumRaw = own(schema, 'enum');\n if (Array.isArray(enumRaw)) {\n const allowed = enumRaw as unknown[];\n if (!allowed.some((candidate) => deepEqual(candidate, value))) {\n errors.push({ path, message: `must be one of ${JSON.stringify(allowed)}` });\n }\n }\n\n if (isObjectSchemaNode(schema) && isRecord(value)) {\n errors.push(...validateObject(schema, value, path));\n } else if ((types?.includes('array') ?? false) && Array.isArray(value)) {\n errors.push(...validateArray(schema, value, path));\n }\n\n return errors;\n}\n\nfunction validateObject(\n schema: JsonSchema,\n value: Record<string, unknown>,\n path: string,\n): FieldError[] {\n const errors: FieldError[] = [];\n const propsRaw = own(schema, 'properties');\n const properties = isRecord(propsRaw) ? propsRaw : {};\n const requiredRaw = own(schema, 'required');\n const required = Array.isArray(requiredRaw)\n ? requiredRaw.filter((entry): entry is string => typeof entry === 'string')\n : [];\n\n for (const key of required) {\n // Object.hasOwn, not `in`: `in` walks the prototype chain, so a required\n // \"toString\" or \"__proto__\" would always look present\n if (!Object.hasOwn(value, key)) {\n errors.push({ path: `${path}.${key}`, message: 'is required' });\n }\n }\n\n const additional = own(schema, 'additionalProperties');\n\n for (const key of Object.keys(value)) {\n // Own-property lookup: `properties[\"toString\"]` would find the inherited\n // member and skip the additionalProperties check below\n const propSchemaRaw = own(properties, key);\n if (propSchemaRaw !== undefined) {\n if (isRecord(propSchemaRaw)) {\n errors.push(...validateNode(propSchemaRaw, value[key], `${path}.${key}`));\n }\n continue;\n }\n if (additional === false) {\n errors.push({ path: `${path}.${key}`, message: 'additional property not allowed' });\n } else if (isRecord(additional)) {\n errors.push(...validateNode(additional, value[key], `${path}.${key}`));\n }\n }\n\n return errors;\n}\n\nfunction validateArray(schema: JsonSchema, value: unknown[], path: string): FieldError[] {\n const errors: FieldError[] = [];\n const itemsRaw = own(schema, 'items');\n if (isRecord(itemsRaw)) {\n value.forEach((item, index) => {\n errors.push(...validateNode(itemsRaw, item, `${path}[${index}]`));\n });\n }\n return errors;\n}\n","// Verifies and reserves the authorization a resource requires, before its payment is reserved\nimport type { AuthorizationProvider, AuthorizationVerification } from '../../domain/authorization';\nimport type { AuthorizationMethodName } from '../../domain/common';\nimport type { PaymentRequirement } from '../../domain/payment';\nimport type { CanonicalRequest } from '../../domain/request';\nimport type { CommerceResource } from '../../domain/resource';\nimport { CommerceError, describeError, isCommerceError } from '../../errors';\nimport type { AuthorizationHold, PipelineContext } from './context';\n\n// The provider for each method a resource requires, in the resource's order.\n// Config refuses a method that is not enabled at load; it is checked again\n// because missing it here would serve the resource with no authorization.\nexport function resolveAuthorizationProviders(\n providers: readonly AuthorizationProvider[],\n resource: CommerceResource,\n requestId: string,\n): readonly AuthorizationProvider[] {\n const required = resource.authorization?.required ?? [];\n return required.map((method: AuthorizationMethodName) => {\n const found = providers.find((provider) => provider.name === method);\n if (!found) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${resource.id}\" requires authorization method \"${method}\", which is not enabled`,\n { requestId, resourceId: resource.id },\n );\n }\n return found;\n });\n}\n\nexport type AuthorizeAndReserve = (\n request: CanonicalRequest,\n resource: CommerceResource,\n providers: readonly AuthorizationProvider[],\n requirement: PaymentRequirement,\n input: unknown,\n) => Promise<AuthorizationHold | undefined>;\n\nexport function createAuthorizeAndReserve(ctx: PipelineContext): AuthorizeAndReserve {\n const { options, safeEmit, buildEvent } = ctx;\n\n // Verify and reserve what the resource requires, or undefined if it requires\n // none. Runs after payment verification, which has no side effect, so a bad\n // payment proof cannot burn a reservation.\n async function authorizeAndReserve(\n request: CanonicalRequest,\n resource: CommerceResource,\n providers: readonly AuthorizationProvider[],\n requirement: PaymentRequirement,\n input: unknown,\n ): Promise<AuthorizationHold | undefined> {\n if (providers.length === 0) return undefined;\n\n const submission = request.authorization;\n const provider = providers.find((candidate) => candidate.name === submission?.method);\n // A request carries one proof, so a resource requiring two methods is\n // refused here rather than half-checked\n const unmet = providers.filter((candidate) => candidate !== provider).map((c) => c.name);\n\n if (submission === undefined || provider === undefined || unmet.length > 0) {\n await safeEmit(\n buildEvent({\n type: 'authorization.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'error',\n data: { reason: 'AUTHORIZATION_REQUIRED', methods: unmet },\n }),\n );\n throw new CommerceError(\n 'AUTHORIZATION_REQUIRED',\n `Resource \"${resource.id}\" requires authorization: ${unmet.join(', ')}`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n details: { required: providers.map((candidate) => candidate.name), missing: unmet },\n },\n );\n }\n\n let verification: AuthorizationVerification;\n try {\n verification = await provider.verifyAndReserve({\n requestId: request.requestId,\n resourceId: resource.id,\n input,\n submission,\n requirement,\n });\n } catch (error) {\n // An untyped throw says nothing about whose fault it was. Unavailable is\n // honest and retryable; invalid would blame the buyer for our outage.\n const mapped = isCommerceError(error)\n ? error\n : new CommerceError(\n 'AUTHORIZATION_PROVIDER_UNAVAILABLE',\n 'Authorization provider is unavailable',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n },\n );\n await safeEmit(\n buildEvent({\n type: 'authorization.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'error',\n data: { reason: mapped.code, method: provider.name },\n }),\n );\n throw mapped;\n }\n\n await safeEmit(\n buildEvent({\n type: 'authorization.verified',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'ok',\n data: { method: verification.method, reference: verification.reference },\n }),\n );\n\n const context = { requestId: request.requestId, resourceId: resource.id };\n return {\n record: {\n method: verification.method,\n reference: verification.reference,\n ...(verification.metadata !== undefined ? { metadata: verification.metadata } : {}),\n },\n async finalize(action) {\n try {\n await provider[action](verification.reservationId, context);\n } catch (error) {\n // A failure leaves the reservation reserved, which is still\n // unspendable, so the caller's outcome stands\n options.logger.error(\n { err: describeError(error), requestId: request.requestId, action },\n 'Authorization finalization failed; the reservation stays reserved',\n );\n }\n },\n };\n }\n\n return authorizeAndReserve;\n}\n","// What a refused or replayed payment answers with: the unused challenge, when one may be retried\nimport type { PaymentRequirement } from '../../domain/payment';\nimport { CommerceError } from '../../errors';\n\n// A refusal leaves this request's challenge unused. Return it with the\n// provider's reason so the client can retry without fetching another challenge\nexport function retryChallenge(\n requirement: PaymentRequirement,\n reason?: string,\n): { details?: Record<string, unknown> } {\n const envelope = requirement.challenge.envelope;\n if (envelope === undefined && reason === undefined) return {};\n return {\n details: {\n ...(envelope !== undefined ? { challenge: envelope } : {}),\n ...(reason !== undefined ? { reason } : {}),\n },\n };\n}\n\n// Attempt statuses the pipeline treats as finished when handling a replay. The\n// legacy `failed` is not one: it recorded any throw from settle(), so it may\n// hide a transfer, like `settlement-uncertain`.\nconst FINISHED_ATTEMPT_STATUSES: ReadonlySet<string> = new Set(['settled', 'rejected']);\n\n// Include the paid offer's network for the rail's replay code. Finished\n// attempts get 402 with a fresh challenge; unfinished or unreadable attempts\n// keep 409 to avoid prompting a second payment.\nexport function replayError(error: CommerceError, requirement: PaymentRequirement): CommerceError {\n if (error.code !== 'PAYMENT_REPLAYED') return error;\n const status = error.details?.['attemptStatus'];\n const finished = typeof status === 'string' && FINISHED_ATTEMPT_STATUSES.has(status);\n const network = requirement.network;\n if (!finished && network === undefined) return error;\n return new CommerceError('PAYMENT_REPLAYED', error.message, {\n ...(error.requestId !== undefined ? { requestId: error.requestId } : {}),\n ...(error.resourceId !== undefined ? { resourceId: error.resourceId } : {}),\n ...(finished ? { httpStatus: 402 } : {}),\n details: {\n ...error.details,\n ...(network !== undefined ? { network } : {}),\n ...(finished ? retryChallenge(requirement).details : {}),\n },\n });\n}\n","// The payment phase: challenge, offer selection, verification, and the authorization and replay reservations\n\nimport type { PaymentMethodName } from '../../domain/common';\nimport type { PaymentProvider, PaymentRequirement, PaymentResult } from '../../domain/payment';\nimport type { CanonicalRequest, PaymentRequiredOutcome } from '../../domain/request';\nimport type { CommerceResource, Pricing } from '../../domain/resource';\nimport { CommerceError, isCommerceError, toCommerceError } from '../../errors';\nimport { REUSE_REJECTED_AUTHORIZATION_METADATA_KEY } from '../settlement-order';\nimport { type AuthorizeAndReserve, resolveAuthorizationProviders } from './authorization';\nimport { replayError, retryChallenge } from './challenge';\nimport type { PipelineContext, SettleArgs } from './context';\n\n/** A verified payment whose authorization and replay identity are reserved */\nexport interface AdmittedPayment {\n readonly kind: 'admitted';\n readonly settleArgs: SettleArgs;\n}\n\nexport type AdmitPayment = (\n request: CanonicalRequest,\n resource: CommerceResource,\n pricing: Extract<Pricing, { type: 'fixed' }>,\n validInput: unknown,\n) => Promise<PaymentRequiredOutcome | AdmittedPayment>;\n\n/**\n * Builds the payment phase. It returns the challenge when the request carries\n * no proof, and otherwise verifies the proof and reserves the authorization\n * and replay identity, or throws.\n */\nexport function createPaymentAdmission(\n ctx: PipelineContext,\n authorizeAndReserve: AuthorizeAndReserve,\n): AdmitPayment {\n const { options, safeEmit, buildEvent } = ctx;\n\n return async function admitPayment(request, resource, pricing, validInput) {\n const provider = pickProvider(options.paymentProviders, resource.paymentMethods);\n if (!provider) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n `No enabled payment provider for resource \"${resource.id}\"`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n details: { paymentMethods: resource.paymentMethods },\n },\n );\n }\n\n // Resolved before the challenge so the 402 can name what the retry must\n // also carry, and so an uncheckable method fails before payment starts\n const authProviders = resolveAuthorizationProviders(\n options.authorizationProviders ?? [],\n resource,\n request.requestId,\n );\n\n let requirement: PaymentRequirement;\n try {\n requirement = await provider.createRequirement({\n requestId: request.requestId,\n resource,\n amount: pricing.amount,\n currency: pricing.currency,\n requestedAt: options.clock.nowIso(),\n // Transport facts a rail may bind into its challenge, such as a body digest\n ...(request.metadata !== undefined ? { metadata: request.metadata } : {}),\n });\n } catch (error) {\n throw isCommerceError(error)\n ? error\n : new CommerceError('PAYMENT_PROVIDER_UNAVAILABLE', 'Payment provider is unavailable', {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n });\n }\n\n if (!request.payment) {\n await safeEmit(\n buildEvent({\n type: 'payment.required',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n }),\n );\n return {\n kind: 'payment-required',\n requestId: request.requestId,\n resourceId: resource.id,\n requirement,\n ...(authProviders.length > 0\n ? { authorization: authProviders.map((p) => p.requirement) }\n : {}),\n };\n }\n\n const payment = request.payment;\n\n let verification: PaymentResult;\n try {\n // Later steps, including authorization and settlement order, use the\n // selected requirement with its full retry challenge\n if (provider.selectRequirement) {\n requirement = await provider.selectRequirement({\n requestId: request.requestId,\n resource,\n requirement,\n submission: payment,\n });\n }\n verification = await provider.verify({\n requestId: request.requestId,\n resource,\n requirement,\n submission: payment,\n });\n } catch (error) {\n // A typed CommerceError is rethrown as is, keeping its code and its\n // possibly retryable status. Only an untyped throw is mapped, with a\n // fixed client-facing message.\n const mapped = isCommerceError(error)\n ? error\n : new CommerceError('PAYMENT_INVALID', 'Payment verification failed', {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n ...retryChallenge(requirement),\n });\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: mapped.code },\n }),\n );\n throw mapped;\n }\n\n if (verification.status !== 'verified') {\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: verification.rejectionReason ? { reason: verification.rejectionReason } : {},\n }),\n );\n throw new CommerceError(\n 'PAYMENT_INVALID',\n verification.rejectionReason ?? 'Payment was rejected',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n ...retryChallenge(requirement, verification.rejectionReason),\n },\n );\n }\n\n if (!verification.replayKey) {\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: 'missing-replay-key' },\n }),\n );\n throw new CommerceError('PAYMENT_INVALID', 'Payment provider did not return a replay key', {\n requestId: request.requestId,\n resourceId: resource.id,\n });\n }\n const replayKey = verification.replayKey;\n\n const hold = await authorizeAndReserve(\n request,\n resource,\n authProviders,\n requirement,\n validInput,\n );\n\n try {\n await options.store.reservePaymentAttempt({\n requestId: request.requestId,\n resourceId: resource.id,\n provider: provider.name,\n replayKey,\n amount: verification.amount,\n currency: verification.currency,\n ...(verification.payer !== undefined ? { payer: verification.payer } : {}),\n ...(verification.payee !== undefined ? { payee: verification.payee } : {}),\n ...(requirement.metadata?.[REUSE_REJECTED_AUTHORIZATION_METADATA_KEY] === true\n ? { reclaimRejected: true }\n : {}),\n });\n } catch (error) {\n // A duplicate replayKey arrives as PAYMENT_REPLAYED and is kept. Any\n // other failure (a full disk, a dropped connection) is STORAGE_ERROR,\n // never a replay.\n const mapped = toCommerceError(\n error,\n 'STORAGE_ERROR',\n 'Payment attempt could not be recorded',\n );\n await hold?.finalize('release');\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: mapped.code },\n }),\n );\n throw replayError(mapped, requirement);\n }\n\n await safeEmit(\n buildEvent({\n type: 'payment.verified',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'ok',\n }),\n );\n\n return {\n kind: 'admitted',\n settleArgs: {\n request,\n resource,\n provider,\n requirement,\n payment,\n verification,\n replayKey,\n hold,\n },\n };\n };\n}\n\nfunction pickProvider(\n providers: readonly PaymentProvider[],\n methods: readonly PaymentMethodName[],\n): PaymentProvider | undefined {\n for (const method of methods) {\n const found = providers.find((provider) => provider.name === method);\n if (found) return found;\n }\n return undefined;\n}\n","// What the pipeline's stages share: its options, and event and persistence writes that never fail a flow\nimport type { AuthorizationProvider, AuthorizationRecord } from '../../domain/authorization';\nimport type { CommerceEvent, EventSink } from '../../domain/event';\nimport type {\n PaymentProvider,\n PaymentRequirement,\n PaymentResult,\n PaymentSubmission,\n} from '../../domain/payment';\nimport type { CanonicalRequest } from '../../domain/request';\nimport type { CommerceResource, ResourceRegistry } from '../../domain/resource';\nimport { describeError } from '../../errors';\nimport type { BackendExecutor } from '../../interfaces/backend';\nimport type { Logger } from '../../interfaces/logger';\nimport type { Clock, IdGenerator } from '../../interfaces/runtime';\nimport type { ReceiptStore } from '../../interfaces/store';\n\nexport interface CreateExecutionPipelineOptions {\n readonly resources: ResourceRegistry;\n readonly paymentProviders: readonly PaymentProvider[];\n /** Defaults to none */\n readonly authorizationProviders?: readonly AuthorizationProvider[];\n readonly store: ReceiptStore;\n readonly backend: BackendExecutor;\n readonly events: EventSink;\n readonly logger: Logger;\n readonly clock: Clock;\n readonly ids: IdGenerator;\n}\n\n/**\n * A reservation held across settlement, plus the summary the receipt keeps.\n * `finalize` ends it.\n */\nexport interface AuthorizationHold {\n readonly record: AuthorizationRecord;\n finalize(action: 'consume' | 'release' | 'markUncertain'): Promise<void>;\n}\n\n/** A verified, reserved payment and everything its settlement needs */\nexport interface SettleArgs {\n readonly request: CanonicalRequest;\n readonly resource: CommerceResource;\n readonly provider: PaymentProvider;\n readonly requirement: PaymentRequirement;\n readonly payment: PaymentSubmission;\n readonly verification: PaymentResult;\n readonly replayKey: string;\n readonly hold: AuthorizationHold | undefined;\n}\n\nexport interface PipelineContext {\n readonly options: CreateExecutionPipelineOptions;\n /** Emits an event; a failing sink is logged, never thrown */\n readonly safeEmit: (event: CommerceEvent) => Promise<void>;\n /** Runs a store write; a failure is logged, never thrown */\n readonly safePersist: (\n op: () => Promise<void>,\n label: string,\n requestId: string,\n ) => Promise<void>;\n readonly buildEvent: (partial: Omit<CommerceEvent, 'id' | 'at'>) => CommerceEvent;\n}\n\nexport function createPipelineContext(options: CreateExecutionPipelineOptions): PipelineContext {\n async function safeEmit(event: CommerceEvent): Promise<void> {\n try {\n await options.events.emit(event);\n } catch (error) {\n options.logger.error(\n { err: describeError(error), eventType: event.type, requestId: event.requestId },\n 'Event sink failed; commerce flow continues',\n );\n }\n }\n\n async function safePersist(\n op: () => Promise<void>,\n label: string,\n requestId: string,\n ): Promise<void> {\n try {\n await op();\n } catch (error) {\n options.logger.error(\n { err: describeError(error), requestId },\n `Persistence failed: ${label}`,\n );\n }\n }\n\n function buildEvent(partial: Omit<CommerceEvent, 'id' | 'at'>): CommerceEvent {\n return { id: options.ids.next('evt'), at: options.clock.nowIso(), ...partial };\n }\n\n return { options, safeEmit, safePersist, buildEvent };\n}\n","// Settles a verified, reserved payment, or records that the backend failed before it could\nimport type { PaymentRequirement, PaymentResult } from '../../domain/payment';\nimport { CommerceError, isCommerceError } from '../../errors';\nimport { retryChallenge } from './challenge';\nimport type { PipelineContext, SettleArgs } from './context';\n\nexport interface Settlement {\n /** Settles and finalizes the authorization; a refusal or unknown outcome throws */\n readonly settle: (args: SettleArgs) => Promise<PaymentResult>;\n /** Records a backend failure before settlement and releases the authorization */\n readonly abandonSettlement: (args: SettleArgs, backendErrorCode: string) => Promise<void>;\n}\n\nexport function createSettlement(ctx: PipelineContext): Settlement {\n const { options, safeEmit, safePersist, buildEvent } = ctx;\n\n // Settle a verified, reserved payment and finalize its authorization.\n // Rejected or uncertain settlement throws before any response is delivered.\n async function settle(args: SettleArgs): Promise<PaymentResult> {\n const { request, resource, provider, requirement, payment, verification, replayKey, hold } =\n args;\n let settlement: PaymentResult;\n try {\n settlement = await provider.settle({\n requestId: request.requestId,\n resource,\n requirement,\n submission: payment,\n verification,\n });\n } catch (error) {\n // Confirmed non-submission leaves the authorization spendable. Release\n // it for retry and report the provider failure.\n const notSubmitted = notSubmittedReason(error);\n if (notSubmitted !== undefined) {\n await hold?.finalize('release');\n await safePersist(\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'rejected',\n rejectionReason: notSubmitted,\n }),\n 'updatePaymentAttempt(not-submitted)',\n request.requestId,\n );\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: 'settlement-not-submitted', providerReason: notSubmitted },\n }),\n );\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'The payment provider could not settle the payment; nothing was charged',\n { requestId: request.requestId, resourceId: resource.id, cause: error },\n );\n }\n // A throw gives no settlement verdict. The facilitator may have\n // broadcast before losing its response, even without a transaction\n // hash. Keep the authorization uncertain so it cannot be spent again.\n const txHash = settlementTxHash(error);\n await hold?.finalize('markUncertain');\n await safePersist(\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'settlement-uncertain',\n ...(txHash !== undefined ? { externalReference: txHash } : {}),\n ...(error instanceof Error ? { rejectionReason: error.message } : {}),\n }),\n 'updatePaymentAttempt(settlement-uncertain)',\n request.requestId,\n );\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: {\n reason: 'settlement-uncertain',\n ...(txHash !== undefined ? { transactionHash: txHash } : {}),\n },\n }),\n );\n // The replay key remains reserved, so report an uncertain, non-retryable\n // outcome. Expose only the transaction hash from the underlying error.\n throw new CommerceError('PAYMENT_SETTLEMENT_FAILED', 'Settlement could not be confirmed', {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n details: {\n settlementUncertain: true,\n ...(txHash !== undefined ? { transactionHash: txHash } : {}),\n ...settlementParties(requirement, verification),\n },\n });\n }\n\n if (settlement.status !== 'settled') {\n await hold?.finalize('release');\n await safePersist(\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'rejected',\n ...(settlement.rejectionReason !== undefined\n ? { rejectionReason: settlement.rejectionReason }\n : {}),\n ...(settlement.externalReference !== undefined\n ? { externalReference: settlement.externalReference }\n : {}),\n }),\n 'updatePaymentAttempt(rejected)',\n request.requestId,\n );\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: settlement.rejectionReason ? { reason: settlement.rejectionReason } : {},\n }),\n );\n // A returned rejection confirms no settlement. Both rails return 402.\n const rejectionDetails = retryChallenge(requirement, settlement.rejectionReason).details;\n throw new CommerceError(\n 'PAYMENT_SETTLEMENT_FAILED',\n settlement.rejectionReason ?? 'Settlement was rejected',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n httpStatus: 402,\n details: {\n ...rejectionDetails,\n ...settlementParties(requirement, settlement, verification),\n },\n },\n );\n }\n\n await hold?.finalize('consume');\n await safePersist(\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'settled',\n ...(settlement.externalReference !== undefined\n ? { externalReference: settlement.externalReference }\n : {}),\n }),\n 'updatePaymentAttempt(settled)',\n request.requestId,\n );\n await safeEmit(\n buildEvent({\n type: 'payment.settled',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'ok',\n }),\n );\n\n return settlement;\n }\n\n // Record the pre-settlement backend failure and release the authorization\n // hold. Rails with reuse metadata can reserve the unspent replay key again,\n // as after any rejection.\n async function abandonSettlement(args: SettleArgs, backendErrorCode: string): Promise<void> {\n const { request, resource, provider, replayKey, hold } = args;\n await hold?.finalize('release');\n await safePersist(\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'rejected',\n rejectionReason: 'backend_failed',\n }),\n 'updatePaymentAttempt(backend-failed)',\n request.requestId,\n );\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: 'backend-failed', backendErrorCode },\n }),\n );\n }\n\n return { settle, abandonSettlement };\n}\n\n// The reason a provider gave when it threw before submitting anything\nfunction notSubmittedReason(error: unknown): string | undefined {\n if (!isCommerceError(error) || error.details?.['settlementNotSubmitted'] !== true) {\n return undefined;\n }\n const reason = error.details['reason'];\n return typeof reason === 'string' ? reason : 'settlement_not_submitted';\n}\n\n// The broadcast transaction hash a provider attached to a settlement throw,\n// when it knows one\nfunction settlementTxHash(error: unknown): string | undefined {\n const hash = isCommerceError(error) ? error.details?.['transactionHash'] : undefined;\n return typeof hash === 'string' ? hash : undefined;\n}\n\n// Prefer the network and payer reported by settlement or verification, then\n// fall back to the requirement's network\nfunction settlementParties(\n requirement: PaymentRequirement,\n ...results: readonly PaymentResult[]\n): { network?: string; payer?: string } {\n const network = results.find((r) => r.network !== undefined)?.network ?? requirement.network;\n const payer = results.find((r) => r.payer !== undefined)?.payer;\n return {\n ...(network !== undefined ? { network } : {}),\n ...(payer !== undefined ? { payer } : {}),\n };\n}\n","/**\n * The single execution path every protocol adapter converges on. The order is a\n * security boundary; do not reorder:\n *\n * 1. resolve resource (RESOURCE_NOT_FOUND)\n * 2. strip reserved input fields, validate input and the backend request shape\n * (INPUT_INVALID, or BACKEND_ERROR for an illegal configured header)\n * 3. resolve price\n * 4. free: straight to the backend\n * 5. paid: pick provider and createRequirement, then return a challenge, or\n * select the offer the proof pays, verify it, and reserve authorization and\n * replay identities\n * 6. settle before calling the backend, or call the backend first and settle\n * only if it succeeds. Finalize authorization according to the outcome\n * (BACKEND_TIMEOUT / BACKEND_ERROR)\n * 7. persist receipt, emit events, return outcome\n */\n\nimport type { AuthorizationRecord } from '../../domain/authorization';\nimport type { PaymentResult } from '../../domain/payment';\nimport type { CommerceReceipt } from '../../domain/receipt';\nimport type { CanonicalRequest, ExecutionOutcome, ExecutionPipeline } from '../../domain/request';\nimport type { CommerceResource } from '../../domain/resource';\nimport { RESERVED_INPUT_FIELDS } from '../../domain/wire';\nimport { CommerceError, toCommerceError } from '../../errors';\nimport type { BackendResponse } from '../../interfaces/backend';\nimport { isRecord } from '../../is-record';\nimport { validateBackendRequestShape } from '../backend-request';\nimport { SETTLE_AFTER_BACKEND_METADATA_KEY } from '../settlement-order';\nimport { compileJsonSchema, type Validator } from '../validation';\nimport { createPaymentAdmission } from './admission';\nimport { createAuthorizeAndReserve } from './authorization';\nimport {\n type CreateExecutionPipelineOptions,\n createPipelineContext,\n type SettleArgs,\n} from './context';\nimport { createSettlement } from './settlement';\n\nexport type { CreateExecutionPipelineOptions } from './context';\n\nexport function createExecutionPipeline(\n options: CreateExecutionPipelineOptions,\n): ExecutionPipeline {\n const validators = new Map<string, Validator>();\n\n function getValidator(resource: CommerceResource): Validator {\n const cached = validators.get(resource.id);\n if (cached) return cached;\n const compiled = compileJsonSchema(resource.inputSchema);\n validators.set(resource.id, compiled);\n return compiled;\n }\n\n const ctx = createPipelineContext(options);\n const { safeEmit, safePersist, buildEvent } = ctx;\n const { settle, abandonSettlement } = createSettlement(ctx);\n const admitPayment = createPaymentAdmission(ctx, createAuthorizeAndReserve(ctx));\n\n async function execute(request: CanonicalRequest): Promise<ExecutionOutcome> {\n const pipelineStart = options.clock.monotonicMs();\n\n // 1. resolve resource\n const resource = options.resources.get(request.resourceId);\n // Same code and message as an unknown id: a caller on a protocol the\n // resource is not exposed via must not learn that it exists\n if (!resource?.exposedVia.includes(request.protocol)) {\n throw new CommerceError(\n 'RESOURCE_NOT_FOUND',\n `Resource \"${request.resourceId}\" was not found`,\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n },\n );\n }\n\n await safeEmit(\n buildEvent({\n type: 'resource.requested',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n }),\n );\n\n // 2. strip reserved gateway fields, then validate input\n const strippedInput = stripReservedFields(request.input);\n const validation = getValidator(resource)(strippedInput);\n if (!validation.valid) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Input for resource \"${resource.id}\" failed validation`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n details: { errors: validation.errors },\n },\n );\n }\n const validInput = validation.value;\n\n // Before pricing, so a request the backend cannot receive fails before\n // payment (see validateBackendRequestShape)\n validateBackendRequestShape(\n resource.handler,\n validInput,\n { requestId: request.requestId, resourceId: resource.id },\n request.backendHeaders,\n );\n\n // 3. resolve price\n if (resource.pricing.type === 'dynamic') {\n // Config validation rejects this at load; this is defense in depth\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${resource.id}\" uses unsupported dynamic pricing`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n },\n );\n }\n\n // Authorization gates settlement, so on a free resource nothing would read\n // the proof. Config refuses this at load; this is defense in depth.\n if (resource.pricing.type !== 'fixed' && (resource.authorization?.required.length ?? 0) > 0) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${resource.id}\" requires authorization but is not a paid resource`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n },\n );\n }\n\n let paymentResult: PaymentResult | undefined;\n let authorization: AuthorizationRecord | undefined;\n let deferredSettlement: SettleArgs | undefined;\n\n if (resource.pricing.type === 'fixed') {\n const admission = await admitPayment(request, resource, resource.pricing, validInput);\n if (admission.kind === 'payment-required') return admission;\n const { settleArgs } = admission;\n authorization = settleArgs.hold?.record;\n if (settleArgs.requirement.metadata?.[SETTLE_AFTER_BACKEND_METADATA_KEY] === true) {\n deferredSettlement = settleArgs;\n } else {\n paymentResult = await settle(settleArgs);\n }\n }\n\n // 6. call backend\n const backendStart = options.clock.monotonicMs();\n let backendResponse: BackendResponse;\n try {\n backendResponse = await options.backend.call(resource.handler, {\n requestId: request.requestId,\n resourceId: resource.id,\n input: validInput,\n ...(request.idempotencyKey !== undefined ? { idempotencyKey: request.idempotencyKey } : {}),\n ...(request.backendHeaders !== undefined ? { backendHeaders: request.backendHeaders } : {}),\n });\n } catch (error) {\n const commerceError = toCommerceError(error, 'BACKEND_ERROR', 'Backend call failed');\n await safeEmit(\n buildEvent({\n type: 'backend.failed',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'error',\n durationMs: Math.round(options.clock.monotonicMs() - backendStart),\n data: { code: commerceError.code },\n }),\n );\n\n if (deferredSettlement !== undefined) {\n await abandonSettlement(deferredSettlement, commerceError.code);\n throw commerceError;\n }\n\n if (paymentResult !== undefined) {\n // The payment settled and the backend then failed. Record an\n // undelivered receipt for the merchant and tell the buyer what they\n // paid, including the settlement reference.\n const failedReceipt: CommerceReceipt = {\n id: options.ids.next('receipt'),\n requestId: request.requestId,\n resourceId: resource.id,\n deliveredAt: options.clock.nowIso(),\n backendStatus: backendErrorStatus(commerceError),\n protocol: request.protocol,\n payment: paymentResult,\n ...(authorization !== undefined ? { authorization } : {}),\n metadata: { delivered: false, backendErrorCode: commerceError.code },\n };\n await safePersist(\n () => options.store.saveReceipt(failedReceipt),\n 'saveReceipt(backend-failed-after-settlement)',\n request.requestId,\n );\n\n throw new CommerceError(\n 'BACKEND_ERROR',\n 'Payment settled but the backend call failed; the payment was not refunded automatically',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: commerceError,\n details: {\n payment: {\n status: paymentResult.status,\n provider: paymentResult.provider,\n amount: paymentResult.amount,\n currency: paymentResult.currency,\n ...(paymentResult.network !== undefined ? { network: paymentResult.network } : {}),\n ...(paymentResult.externalReference !== undefined\n ? { externalReference: paymentResult.externalReference }\n : {}),\n ...(paymentResult.payer !== undefined ? { payer: paymentResult.payer } : {}),\n ...(typeof paymentResult.metadata?.['amountBaseUnits'] === 'string'\n ? { amountBaseUnits: paymentResult.metadata['amountBaseUnits'] }\n : {}),\n ...(typeof paymentResult.metadata?.['receipt'] === 'string'\n ? { receipt: paymentResult.metadata['receipt'] }\n : {}),\n },\n },\n },\n );\n }\n\n throw commerceError;\n }\n\n await safeEmit(\n buildEvent({\n type: 'backend.called',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'ok',\n durationMs: backendResponse.durationMs,\n data: { status: backendResponse.status },\n }),\n );\n\n // Hold the backend response until settlement succeeds. A refusal or\n // uncertain outcome throws before delivery.\n if (deferredSettlement !== undefined) {\n paymentResult = await settle(deferredSettlement);\n }\n\n // 7. persist receipt, emit final event, return outcome\n const receipt: CommerceReceipt = {\n id: options.ids.next('receipt'),\n requestId: request.requestId,\n resourceId: resource.id,\n deliveredAt: options.clock.nowIso(),\n backendStatus: backendResponse.status,\n durationMs: backendResponse.durationMs,\n protocol: request.protocol,\n ...(paymentResult !== undefined ? { payment: paymentResult } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n };\n\n await safePersist(() => options.store.saveReceipt(receipt), 'saveReceipt', request.requestId);\n\n const totalDurationMs = Math.round(options.clock.monotonicMs() - pipelineStart);\n\n await safeEmit(\n buildEvent({\n type: 'resource.delivered',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'ok',\n durationMs: totalDurationMs,\n }),\n );\n\n return {\n kind: 'delivered',\n requestId: request.requestId,\n resourceId: resource.id,\n backendStatus: backendResponse.status,\n body: backendResponse.body,\n headers: backendResponse.headers,\n ...(paymentResult !== undefined ? { payment: paymentResult } : {}),\n receipt,\n durationMs: totalDurationMs,\n };\n }\n\n return { execute };\n}\n\n// The status the backend returned, which backend-http.ts puts on\n// `details.status` for a non-2xx or redirect response. 0 means no status is\n// known, as after a timeout, a transport failure or an unreadable or oversized\n// body.\nfunction backendErrorStatus(error: CommerceError): number {\n const status = error.details?.['status'];\n return typeof status === 'number' ? status : 0;\n}\n\nconst RESERVED_INPUT_KEYS: readonly string[] = [...RESERVED_INPUT_FIELDS, '__proto__'];\n\nfunction stripReservedFields(input: unknown): unknown {\n if (!isRecord(input)) return input;\n // Object.hasOwn, not `in`, which also matches inherited names\n if (!RESERVED_INPUT_KEYS.some((key) => Object.hasOwn(input, key))) return input;\n const rest: Record<string, unknown> = {};\n for (const key of Object.keys(input)) {\n // \"__proto__\" is dropped too: assigning it would call the inherited setter\n // and replace `rest`'s prototype instead of creating a data property.\n // validation.ts's own-property lookups are the primary control.\n if (!RESERVED_INPUT_KEYS.includes(key)) rest[key] = input[key];\n }\n return rest;\n}\n","// In-memory implementation of the frozen `ResourceRegistry` interface\nimport type { ProtocolName } from '../domain/common';\nimport type { CommerceResource, ResourceRegistry } from '../domain/resource';\nimport { CommerceError } from '../errors';\n\nclass ResourceRegistryImpl implements ResourceRegistry {\n private readonly byId = new Map<string, CommerceResource>();\n private readonly ordered: readonly CommerceResource[];\n\n constructor(resources: readonly CommerceResource[]) {\n for (const resource of resources) {\n if (this.byId.has(resource.id)) {\n throw new CommerceError('CONFIG_INVALID', `Duplicate resource id \"${resource.id}\"`, {\n details: { resourceId: resource.id },\n });\n }\n this.byId.set(resource.id, resource);\n }\n this.ordered = [...resources];\n }\n\n get(id: string): CommerceResource | undefined {\n return this.byId.get(id);\n }\n\n list(): readonly CommerceResource[] {\n return this.ordered;\n }\n\n listExposedVia(protocol: ProtocolName): readonly CommerceResource[] {\n return this.ordered.filter((resource) => resource.exposedVia.includes(protocol));\n }\n\n has(id: string): boolean {\n return this.byId.has(id);\n }\n}\n\n/** Build a `ResourceRegistry` from a validated list of canonical resources */\nexport function createResourceRegistry(resources: readonly CommerceResource[]): ResourceRegistry {\n return new ResourceRegistryImpl(resources);\n}\n","/**\n * `EventSink` that persists every event to the receipt store. A store failure\n * is logged, never thrown to the caller.\n */\nimport type { CommerceEvent, EventSink } from '../domain/event';\nimport { describeError } from '../errors';\nimport type { Logger } from '../interfaces/logger';\nimport type { ReceiptStore } from '../interfaces/store';\n\nexport interface CreateStoreEventSinkOptions {\n readonly store: ReceiptStore;\n readonly logger: Logger;\n}\n\nexport function createStoreEventSink(options: CreateStoreEventSinkOptions): EventSink {\n return {\n async emit(event: CommerceEvent): Promise<void> {\n try {\n await options.store.appendEvent(event);\n } catch (error) {\n options.logger.error(\n { err: describeError(error), eventType: event.type, requestId: event.requestId },\n 'Failed to persist commerce event',\n );\n }\n },\n };\n}\n","// A resource's backend request: input bindings, path parameters, URL and headers\nimport { CommerceError, RESERVED_INPUT_FIELDS } from '../../core';\nimport {\n extractPathParameterNames,\n findUnparsedBraceToken,\n isObjectSchemaNode,\n} from '../../core/execution';\nimport { isRecord } from '../../core/is-record';\nimport type { RawResourceEntry } from './raw';\n\n/**\n * Checks `backend.inputBindings` against the input schema at load. Schemas are\n * closed by default at every depth, so a binding naming an undeclared property\n * could never be supplied, and on a paid resource the backend would get an\n * incomplete request after payment.\n *\n * Returns the schema node `{param}` names must be declared in: the path group\n * with bindings, the whole input without.\n */\nexport function validateInputBindings(\n id: string,\n backend: RawResourceEntry['backend'],\n input: Record<string, unknown> | undefined,\n): { readonly schema: Record<string, unknown> | undefined; readonly where: string } {\n const legacy = { schema: input, where: 'its input schema' } as const;\n const bindings = backend.inputBindings;\n const templated = extractPathParameterNames(backend.url).length > 0;\n if (bindings === undefined) return legacy;\n\n const path = `resources.${id}.backend.inputBindings`;\n const fail = (message: string, details: Record<string, unknown> = {}): never => {\n throw new CommerceError('CONFIG_INVALID', `Resource \"${id}\" ${message}`, {\n details: { path, resourceId: id, ...details },\n });\n };\n\n const entries = Object.entries(bindings).filter(\n (entry): entry is [string, string] => entry[1] !== undefined,\n );\n if (entries.length === 0) {\n fail('has an empty backend.inputBindings - remove the block to use the default mapping');\n }\n if (backend.method === 'GET' || backend.method === 'DELETE') {\n if (bindings.body !== undefined) {\n fail(\n `binds a request body on a ${backend.method}, which sends none - the value would be silently dropped`,\n );\n }\n }\n if (templated && bindings.path === undefined) {\n fail(\n 'has backend.url path parameters but no \"path\" binding - in explicit binding mode nothing else supplies them, so every call would fail to reach the backend',\n );\n }\n\n const seen = new Map<string, string>();\n const properties = isRecord(input?.['properties']) ? input['properties'] : {};\n const required = new Set(\n Array.isArray(input?.['required'])\n ? input['required'].filter((value): value is string => typeof value === 'string')\n : [],\n );\n\n for (const [location, property] of entries) {\n if (RESERVED_INPUT_FIELDS.includes(property)) {\n fail(`binds \"${location}\" to \"${property}\", which is reserved by the gateway`, { location });\n }\n const other = seen.get(property);\n if (other !== undefined) {\n fail(`binds both \"${other}\" and \"${location}\" to the input property \"${property}\"`, {\n location,\n property,\n });\n }\n seen.set(property, location);\n\n if (!Object.hasOwn(properties, property)) {\n fail(\n `binds \"${location}\" to input property \"${property}\", which the input schema does not declare - the schema is closed, so a caller could never supply it`,\n { location, property },\n );\n }\n // `body` may be any JSON value; only the path and query groups are read as\n // name/value pairs\n const declared = properties[property];\n if (location !== 'body' && isRecord(declared) && !isObjectSchemaNode(declared)) {\n fail(\n `binds \"${location}\" to input property \"${property}\", which is not an object schema - ${location} parameters are read as an object of name/value pairs`,\n { location, property },\n );\n }\n }\n\n if (templated && bindings.path !== undefined && !required.has(bindings.path)) {\n fail(\n `binds path parameters to input property \"${bindings.path}\" without listing it in the input schema's \"required\" - a caller that omits it cannot supply any path parameter, so the request could never be built`,\n { property: bindings.path },\n );\n }\n\n if (bindings.path === undefined) return { schema: undefined, where: 'its input schema' };\n const group = properties[bindings.path];\n return {\n schema: isRecord(group) ? group : undefined,\n where: `input.properties.${bindings.path}`,\n };\n}\n\n/**\n * Every `{param}` in `backend.url` must be declared in `properties` and listed\n * in `required`. Otherwise a call can arrive without it, and core's\n * `validateBackendRequestShape` rejects the request, which for a schema that\n * never declares the parameter means every call. Checked at load so\n * `validate` and `doctor` report it; the runtime check covers a hand-built\n * `CommerceResource`.\n */\nexport function validatePathParametersDeclared(\n id: string,\n url: string,\n input: Record<string, unknown> | undefined,\n where: string,\n): void {\n // A brace token the grammar does not recognize is neither extracted nor\n // substituted, so it would reach the backend as a percent-encoded literal\n const stray = findUnparsedBraceToken(url);\n if (stray !== undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has backend.url containing \"${stray}\", which is not a valid path parameter (allowed characters: A-Z a-z 0-9 _ . -). It would reach the backend as literal text, so a paid resource would take payment for a request the backend cannot serve`,\n { details: { path: `resources.${id}.backend.url`, resourceId: id, token: stray } },\n );\n }\n\n const params = extractPathParameterNames(url);\n if (params.length === 0) return;\n\n // Everything before the first `{` must be a complete origin followed by the\n // path's leading `/`. In the host, every other `{param}` defense fails open:\n // `http://{host}/api` parses, the runtime prefix check skips a prefix that\n // is not a URL, and `encodeURIComponent` keeps dots. Caller input would pick\n // the host the gateway calls, such as a metadata service or an internal\n // address, and `http://{region}.api.internal/...` looks ordinary enough to\n // be written by mistake.\n const firstBrace = url.indexOf('{');\n if (firstBrace !== -1) {\n const prefix = url.slice(0, firstBrace);\n let origin: string | undefined;\n try {\n const parsedPrefix = new URL(prefix);\n origin = parsedPrefix.hostname === '' ? undefined : parsedPrefix.origin;\n } catch {\n // Not a URL: the parameter starts before the authority is complete\n }\n if (origin === undefined || !prefix.startsWith(`${origin}/`)) {\n // The URL is not quoted: it may carry a key substituted from the environment\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has a backend.url parameter before the end of the host. A caller-supplied value would choose which host the gateway calls, which is request forgery with the gateway's own network position. Parameters are supported inside the path and query only`,\n { details: { path: `resources.${id}.backend.url`, resourceId: id } },\n );\n }\n }\n\n const propertiesRaw = input?.['properties'];\n const properties = isRecord(propertiesRaw) ? propertiesRaw : {};\n const requiredRaw = input?.['required'];\n const required = new Set(\n Array.isArray(requiredRaw)\n ? requiredRaw.filter((entry): entry is string => typeof entry === 'string')\n : [],\n );\n\n for (const param of params) {\n const path = `resources.${id}.backend.url`;\n if (!Object.hasOwn(properties, param)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has backend.url path parameter \"{${param}}\" which is not declared in ${where} - the caller has no way to supply it, so every call would be refused`,\n { details: { path, resourceId: id, param } },\n );\n }\n if (!required.has(param)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has backend.url path parameter \"{${param}}\" declared in ${where} but not listed in its \"required\" - a call that omits it would be refused`,\n { details: { path, resourceId: id, param } },\n );\n }\n }\n}\n\n// `{param}` templates parse as URLs (the WHATWG parser percent-encodes the\n// braces), so this refuses only malformed URLs and non-http(s) schemes\nexport function validateBackendUrl(id: string, url: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n // The URL is not quoted: it may carry a key substituted from the environment\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has an invalid backend.url: must be an absolute http:// or https:// URL`,\n { details: { path: `resources.${id}.backend.url`, resourceId: id } },\n );\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has a backend.url with scheme \"${parsed.protocol}\": must be http:// or https://`,\n { details: { path: `resources.${id}.backend.url`, resourceId: id } },\n );\n }\n}\n\n// Checked with fetch's own `Headers` rules. Otherwise an illegal name, or a\n// substituted value with a line break inside it, would load cleanly and then\n// refuse every call. The error names the key, never the value, which may be a\n// credential.\nexport function validateBackendHeaders(\n id: string,\n headers: Record<string, string> | undefined,\n): void {\n for (const [name, value] of Object.entries(headers ?? {})) {\n try {\n new Headers([[name, value]]);\n } catch {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has backend header \"${name}\" with an illegal name or value (a name must be an HTTP token; a value must not contain NUL, a character above U+00FF, or a line break except at either end, which fetch trims)`,\n { details: { path: `resources.${id}.backend.headers.${name}`, resourceId: id } },\n );\n }\n }\n}\n","// A resource's input schema: the default closed object and the keywords the validator supports\nimport { CommerceError } from '../../core';\nimport { isObjectSchemaNode } from '../../core/execution';\nimport { isRecord } from '../../core/is-record';\n\n/**\n * Closes every object schema at every depth: a node without\n * `additionalProperties` gets `false`, so unknown keys never reach the\n * merchant's API. An explicit value, including `true`, is kept.\n *\n * JSON Schema itself defaults to open, and core's validator enforces\n * `additionalProperties` only where a node states it, so this recurses into\n * `properties`, `items` and schema-valued `additionalProperties`, the same\n * places the validator descends. Object-ness comes from `isObjectSchemaNode`,\n * the validator's own definition.\n */\nexport function defaultClosedObjectSchema(\n schema: Record<string, unknown>,\n): Record<string, unknown> {\n const isObjectSchema = isObjectSchemaNode(schema);\n const result: Record<string, unknown> = { ...schema };\n\n if (isObjectSchema) {\n const properties = schema['properties'];\n if (isRecord(properties)) {\n result['properties'] = Object.fromEntries(\n Object.entries(properties).map(([key, sub]) => [\n key,\n isRecord(sub) ? defaultClosedObjectSchema(sub) : sub,\n ]),\n );\n }\n if (!Object.hasOwn(schema, 'additionalProperties')) {\n result['additionalProperties'] = false;\n }\n }\n\n const items = schema['items'];\n if (isRecord(items)) {\n result['items'] = defaultClosedObjectSchema(items);\n }\n\n // `additionalProperties: {schema}` (a map of typed objects) is closed too.\n // Not conditional on `isObjectSchema`: the validator applies the subschema\n // wherever it finds one.\n const additional = schema['additionalProperties'];\n if (isRecord(additional)) {\n result['additionalProperties'] = defaultClosedObjectSchema(additional);\n }\n\n return result;\n}\n\n// The input schema of a resource that declares no `input:`. Declaring nothing\n// accepts nothing: without this, `compileJsonSchema(undefined)` would accept\n// any input and forward every key to the backend. A no-argument resource\n// omitting `input:` is a legitimate shape, so it is not refused.\nexport const EMPTY_CLOSED_OBJECT_SCHEMA: Record<string, unknown> = {\n type: 'object',\n properties: {},\n additionalProperties: false,\n};\n\n// Keywords core's validator ignores (see `execution/validation.ts` for the\n// enforced subset). Config warns at load, since an operator who writes\n// `pattern` cannot otherwise tell that it is not enforced.\nconst UNSUPPORTED_SCHEMA_KEYWORDS = [\n 'pattern',\n 'minLength',\n 'maxLength',\n 'format',\n 'minimum',\n 'maximum',\n 'exclusiveMinimum',\n 'exclusiveMaximum',\n 'multipleOf',\n 'oneOf',\n 'anyOf',\n 'allOf',\n 'not',\n '$ref',\n 'const',\n 'patternProperties',\n 'minItems',\n 'maxItems',\n 'uniqueItems',\n];\n\n// `type` set to something that rules out \"object\". No `type` at all does not\n// exclude it: the validator treats `properties`/`required` alone as an object\n// schema.\nfunction excludesObjectType(schema: Record<string, unknown>): boolean {\n const type = schema['type'];\n if (type === undefined || type === 'object') return false;\n if (Array.isArray(type)) return !type.includes('object');\n return true;\n}\n\n/**\n * Walks a resource's input schema once. Warns about unenforced keywords and\n * tuple `items`. Rejects a node whose `type` rules out \"object\" while it\n * declares `properties` or `required`, which then go unchecked (often a\n * copy-pasted sibling whose `type` was never updated), and a closed node\n * requiring a property it never declares, which no input can satisfy.\n */\nexport function validateResourceSchemaKeywords(\n id: string,\n path: string,\n schema: Record<string, unknown>,\n): void {\n for (const keyword of UNSUPPORTED_SCHEMA_KEYWORDS) {\n if (Object.hasOwn(schema, keyword)) {\n console.warn(\n `[agent-commerce] resource \"${id}\" ${path} uses JSON Schema keyword \"${keyword}\", which this gateway does not enforce (see src/core/execution/validation.ts for the supported subset). Remove it or treat it as documentation only.`,\n );\n }\n }\n if (\n (Object.hasOwn(schema, 'properties') || Object.hasOwn(schema, 'required')) &&\n excludesObjectType(schema)\n ) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" ${path} declares \"properties\" and/or \"required\" but its \"type\" (${JSON.stringify(schema['type'])}) does not include \"object\" - the validator will never route a value through either check under that type, so this schema claims to constrain input it does not actually enforce. Remove \"properties\"/\"required\", or include \"object\" in \"type\".`,\n { details: { path: `resources.${id}.${path}`, resourceId: id } },\n );\n }\n // A closed node that requires a property it never declares rejects that\n // property as unknown, so no input can satisfy it and every call would 400.\n // Only when the node is closed: an explicit `additionalProperties`\n // other than `false` leaves the name reachable.\n const requiredRaw = schema['required'];\n const closed = !Object.hasOwn(schema, 'additionalProperties')\n ? true\n : schema['additionalProperties'] === false;\n if (Array.isArray(requiredRaw) && closed && isObjectSchemaNode(schema)) {\n const declared = isRecord(schema['properties']) ? schema['properties'] : {};\n const undeclared = requiredRaw.filter(\n (name): name is string => typeof name === 'string' && !Object.hasOwn(declared, name),\n );\n if (undeclared.length > 0) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" ${path} lists ${undeclared.map((n) => `\"${n}\"`).join(', ')} in \"required\" but does not declare ${undeclared.length === 1 ? 'it' : 'them'} in \"properties\". The schema is closed (additionalProperties: false), so ${undeclared.length === 1 ? 'that name is' : 'those names are'} rejected as an unknown key and no input can ever satisfy this schema. Declare ${undeclared.length === 1 ? 'it' : 'them'} in \"properties\".`,\n { details: { path: `resources.${id}.${path}`, resourceId: id, undeclared } },\n );\n }\n }\n\n const properties = schema['properties'];\n if (isRecord(properties)) {\n for (const [key, sub] of Object.entries(properties)) {\n if (isRecord(sub)) validateResourceSchemaKeywords(id, `${path}.properties.${key}`, sub);\n }\n }\n const additional = schema['additionalProperties'];\n if (isRecord(additional)) {\n validateResourceSchemaKeywords(id, `${path}.additionalProperties`, additional);\n }\n const items = schema['items'];\n if (isRecord(items)) {\n validateResourceSchemaKeywords(id, `${path}.items`, items);\n } else if (Array.isArray(items)) {\n // Tuple-form `items` is valid JSON Schema, but the validator supports only\n // one schema for every element, so a tuple enforces nothing\n console.warn(\n `[agent-commerce] resource \"${id}\" ${path}.items is a tuple (an array of schemas), which this gateway does not enforce - only a single schema applied to every array element is supported (see src/core/execution/validation.ts). Each position's schema is unenforced; treat it as documentation only.`,\n );\n }\n}\n","// Resources: exposure, pricing, payment rails and backend handler\nimport type { Ap2AuthorizationConfig } from '../../authorization/ap2/types';\nimport {\n CommerceError,\n type CommerceResource,\n PAYMENT_METHOD_NAMES,\n PROTOCOL_NAMES,\n type Pricing,\n RESERVED_INPUT_FIELDS,\n} from '../../core';\nimport { MPP_PROFILE } from '../../payments/mpp/constants';\nimport { MCP_TOOL_NAME_PATTERN } from '../../protocols/mcp/constants';\nimport { normalizeResourceAuthorization } from './ap2';\nimport {\n validateBackendHeaders,\n validateBackendUrl,\n validateInputBindings,\n validatePathParametersDeclared,\n} from './backend';\nimport type { NormalizedMpp } from './mpp';\nimport type { RawResourceEntry } from './raw';\nimport {\n defaultClosedObjectSchema,\n EMPTY_CLOSED_OBJECT_SCHEMA,\n validateResourceSchemaKeywords,\n} from './resource-schema';\nimport type { NormalizedProtocols } from './types';\nimport { toNumber } from './values';\nimport type { NormalizedX402 } from './x402';\n\nconst SUPPORTED_PROTOCOLS: ReadonlySet<string> = new Set(PROTOCOL_NAMES);\n\nconst SUPPORTED_PAYMENT_METHODS: ReadonlySet<string> = new Set(PAYMENT_METHOD_NAMES);\n\nexport function normalizeResource(\n id: string,\n entry: RawResourceEntry,\n protocols: NormalizedProtocols,\n x402: NormalizedX402 | undefined,\n mpp: NormalizedMpp | undefined,\n ap2: Ap2AuthorizationConfig | undefined,\n): CommerceResource {\n if (entry.input !== undefined) validateResourceSchemaKeywords(id, 'input', entry.input);\n\n const inputProperties = entry.input?.['properties'];\n if (inputProperties && typeof inputProperties === 'object') {\n for (const reserved of RESERVED_INPUT_FIELDS) {\n if (!(reserved in inputProperties)) continue;\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" declares an input property \"${reserved}\", which is reserved by the gateway`,\n {\n details: {\n path: `resources.${id}.input.properties.${reserved}`,\n resourceId: id,\n },\n },\n );\n }\n }\n\n for (const protocol of entry.expose) {\n if (!SUPPORTED_PROTOCOLS.has(protocol)) {\n const hint = protocol === 'ucp' ? ' (UCP is planned, not supported in this release)' : '';\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" exposes unsupported protocol \"${protocol}\"${hint}. Supported: ${PROTOCOL_NAMES.join(', ')}.`,\n { details: { path: `resources.${id}.expose`, resourceId: id, protocol } },\n );\n }\n }\n if (entry.expose.includes('mcp')) {\n if (!protocols.mcp.enabled) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is exposed via \"mcp\" but protocols.mcp.enabled is false`,\n { details: { path: `resources.${id}.expose`, resourceId: id } },\n );\n }\n if (!MCP_TOOL_NAME_PATTERN.test(id)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is exposed via \"mcp\" but its id is not a legal MCP tool name (allowed: A-Z, a-z, 0-9, \"_\", \"-\", \".\", 1-128 chars)`,\n { details: { path: `resources.${id}`, resourceId: id } },\n );\n }\n }\n if (entry.expose.includes('a2a') && !protocols.a2a.enabled) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is exposed via \"a2a\" but protocols.a2a.enabled is false`,\n { details: { path: `resources.${id}.expose`, resourceId: id } },\n );\n }\n if (entry.expose.includes('acp') && !protocols.acp.enabled) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is exposed via \"acp\" but protocols.acp.enabled is false`,\n { details: { path: `resources.${id}.expose`, resourceId: id } },\n );\n }\n if (entry.expose.includes('http') && !protocols.http.enabled) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is exposed via \"http\" but protocols.http.enabled is false`,\n { details: { path: `resources.${id}.expose`, resourceId: id } },\n );\n }\n\n validateBackendUrl(id, entry.backend.url);\n validateBackendHeaders(id, entry.backend.headers);\n const pathScope = validateInputBindings(id, entry.backend, entry.input);\n validatePathParametersDeclared(id, entry.backend.url, pathScope.schema, pathScope.where);\n\n if (entry.pricing.type === 'dynamic') {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" uses pricing.type \"dynamic\", which is not supported in this release`,\n { details: { path: `resources.${id}.pricing.type`, resourceId: id } },\n );\n }\n\n const paymentMethods = entry.payments ?? [];\n\n if (entry.x402 !== undefined) {\n const at = `resources.${id}.x402`;\n if (x402 === undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" sets x402.accepts, but payments.x402 is not configured`,\n { details: { path: at, resourceId: id } },\n );\n }\n if (entry.pricing.type !== 'fixed' || !paymentMethods.includes('x402')) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" sets x402.accepts, which requires fixed pricing and \"x402\" in payments`,\n { details: { path: at, resourceId: id } },\n );\n }\n }\n // The resource's own offers, or the rail's\n const offers = x402 !== undefined ? (x402.resources[id] ?? x402) : undefined;\n\n if (entry.pricing.type === 'fixed') {\n // An x402 price is charged in every option's token, so the coarsest one\n // bounds it. MPP checks its own token's decimals below.\n const decimals = paymentMethods.includes('x402')\n ? offers?.options.map((option) => option.assetDecimals)\n : undefined;\n validatePricingAmount(id, entry.pricing.amount, decimals && Math.min(...decimals));\n }\n\n if (entry.pricing.type === 'fixed') {\n if (paymentMethods.length === 0) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has fixed pricing but declares no \"payments\" (a paid resource must name at least one payment method)`,\n { details: { path: `resources.${id}.payments`, resourceId: id } },\n );\n }\n for (const method of paymentMethods) {\n if (!SUPPORTED_PAYMENT_METHODS.has(method)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" names unsupported payment method \"${method}\". Supported: ${PAYMENT_METHOD_NAMES.join(', ')}.`,\n { details: { path: `resources.${id}.payments`, resourceId: id, method } },\n );\n }\n }\n // At least one named rail must be enabled, not every one. `runGateway`\n // checks again at composition as defense in depth.\n const enabledRails = [\n ...(x402?.config.enabled ? ['x402'] : []),\n ...(mpp?.enabled ? ['mpp'] : []),\n ];\n if (!paymentMethods.some((method) => enabledRails.includes(method))) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" names payment method(s) \"${paymentMethods.join(', ')}\", none of which is configured and enabled under \"payments\"`,\n { details: { path: `resources.${id}.payments`, resourceId: id, paymentMethods } },\n );\n }\n // An offer in the network's default stablecoin, named or not, charges the\n // price in that token, so the price must name that token or USD\n const symbols = offers?.defaultAssetSymbols ?? [];\n const currency = entry.pricing.currency;\n if (\n x402?.config.enabled &&\n symbols.length > 0 &&\n paymentMethods.includes('x402') &&\n currency !== 'USD' &&\n !(symbols.length === 1 && currency === symbols[0])\n ) {\n const tokens = symbols.join(' and ');\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is priced in ${currency}, but x402 settles in ${tokens}, the default asset of its network. Price it in ${symbols.length === 1 ? `${tokens} or ` : ''}USD.`,\n { details: { path: `resources.${id}.pricing.currency`, resourceId: id } },\n );\n }\n // MPP fixes the currency label and decimal precision for every resource it serves\n if (mpp?.enabled && paymentMethods.includes('mpp')) {\n if (entry.pricing.currency !== MPP_PROFILE.assetSymbol) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is priced in ${entry.pricing.currency}, but MPP charges ${MPP_PROFILE.assetSymbol}`,\n { details: { path: `resources.${id}.pricing.currency`, resourceId: id } },\n );\n }\n validatePricingAmount(id, entry.pricing.amount, MPP_PROFILE.assetDecimals);\n }\n }\n\n if (\n entry.paymentFlow !== undefined &&\n (entry.pricing.type !== 'fixed' ||\n !paymentMethods.some((method) => method === 'x402' || method === 'mpp'))\n ) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" sets paymentFlow, which requires fixed pricing and \"x402\" or \"mpp\" in payments`,\n { details: { path: `resources.${id}.paymentFlow`, resourceId: id } },\n );\n }\n\n if (\n entry.mimeType !== undefined &&\n (entry.pricing.type !== 'fixed' || !paymentMethods.includes('x402'))\n ) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" sets mimeType, which requires fixed pricing and \"x402\" in payments`,\n { details: { path: `resources.${id}.mimeType`, resourceId: id } },\n );\n }\n\n const pricing: Pricing =\n entry.pricing.type === 'free'\n ? { type: 'free' }\n : { type: 'fixed', amount: entry.pricing.amount, currency: entry.pricing.currency };\n\n const authorization = normalizeResourceAuthorization(id, entry, pricing, ap2);\n\n return {\n id,\n name: entry.name,\n ...(entry.description !== undefined ? { description: entry.description } : {}),\n inputSchema:\n entry.input !== undefined\n ? defaultClosedObjectSchema(entry.input)\n : EMPTY_CLOSED_OBJECT_SCHEMA,\n ...(entry.output !== undefined ? { outputSchema: entry.output } : {}),\n handler: {\n type: 'http',\n method: entry.backend.method,\n url: entry.backend.url,\n ...(entry.backend.headers !== undefined ? { headers: entry.backend.headers } : {}),\n ...(entry.backend.timeoutMs !== undefined\n ? {\n timeoutMs: toNumber(entry.backend.timeoutMs, `resources.${id}.backend.timeoutMs`, {\n min: 1,\n }),\n }\n : {}),\n ...(entry.backend.inputBindings !== undefined\n ? { inputBindings: pickDefined(entry.backend.inputBindings) }\n : {}),\n },\n pricing,\n exposedVia: entry.expose as CommerceResource['exposedVia'],\n paymentMethods: paymentMethods as CommerceResource['paymentMethods'],\n ...(authorization !== undefined ? { authorization } : {}),\n };\n}\n\n// A plain decimal: no currency symbol, thousands separator, sign or exponent.\n// \"0,01\", \"$0.01\", \"1e-2\" and \"-1\" would otherwise load and then fail every\n// purchase.\nconst PRICING_AMOUNT_PATTERN = /^\\d+(?:\\.\\d+)?$/;\n\nconst ZERO_AMOUNT_PATTERN = /^0(?:\\.0+)?$/;\n\nfunction validatePricingAmount(id: string, amount: string, decimals: number | undefined): void {\n const path = `resources.${id}.pricing.amount`;\n if (!PRICING_AMOUNT_PATTERN.test(amount)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has pricing.amount \"${amount}\", which is not a plain positive decimal (no currency symbol, no thousands separator, no exponent - e.g. \"0.01\")`,\n { details: { path, resourceId: id } },\n );\n }\n if (ZERO_AMOUNT_PATTERN.test(amount)) {\n // A zero-priced paid resource would settle a zero-value transfer\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has pricing.amount \"0\" - a paid resource cannot cost zero; use \"pricing: { type: free }\" instead`,\n { details: { path, resourceId: id } },\n );\n }\n if (decimals !== undefined) {\n const fractionalDigits = amount.includes('.') ? (amount.split('.')[1]?.length ?? 0) : 0;\n if (fractionalDigits > decimals) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has pricing.amount \"${amount}\" with more precision (${fractionalDigits} fractional digits) than the configured asset supports (${decimals} decimals)`,\n { details: { path, resourceId: id } },\n );\n }\n }\n}\n\n// Strips absent optional keys so the result satisfies `exactOptionalPropertyTypes`\nfunction pickDefined<T extends Record<string, string | undefined>>(\n value: T,\n): { [K in keyof T]?: string } {\n return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined)) as {\n [K in keyof T]?: string;\n };\n}\n","// The business-rule pass: coerces leaves and checks cross-references across sections\nimport { CommerceError } from '../../core';\nimport { normalizeAcp, validateAcpCheckoutMapping } from './acp';\nimport { normalizeAp2, validateReplayStoreIsolated } from './ap2';\nimport { normalizeMpp } from './mpp';\nimport { type RawConfig, SUPPORTED_CONFIG_VERSION } from './raw';\nimport { normalizeResource } from './resources';\nimport type { GatewayConfig, NormalizedProtocols } from './types';\nimport { toBoolean, toNumber } from './values';\nimport { normalizeX402 } from './x402';\n\n// Applied when `protocols.a2a` is absent or names no mount\nconst DEFAULT_A2A_MOUNT_PATH = '/a2a';\n\nexport function normalize(raw: RawConfig): GatewayConfig {\n const protocols = {\n http: { enabled: toBoolean(raw.protocols.http.enabled, 'protocols.http.enabled') },\n mcp: {\n enabled: toBoolean(raw.protocols.mcp.enabled, 'protocols.mcp.enabled'),\n mountPath: raw.protocols.mcp.mountPath,\n },\n a2a: {\n enabled: toBoolean(raw.protocols.a2a?.enabled ?? false, 'protocols.a2a.enabled'),\n mountPath: raw.protocols.a2a?.mountPath ?? DEFAULT_A2A_MOUNT_PATH,\n },\n acp: normalizeAcp(raw.protocols.acp),\n };\n validateMountPaths(protocols);\n\n const x402Settings =\n raw.payments.x402 !== undefined ? normalizeX402(raw.payments.x402, raw.resources) : undefined;\n const x402 = x402Settings?.config;\n\n const mpp = normalizeMpp(raw.payments.mpp);\n\n const ap2 = normalizeAp2(raw.authorization?.ap2);\n if (ap2?.enabled) {\n validateReplayStoreIsolated(ap2.replay.path, raw.storage.receipts.path, protocols.acp);\n }\n\n const resources = Object.entries(raw.resources).map(([id, entry]) =>\n normalizeResource(id, entry, protocols, x402Settings, mpp, ap2),\n );\n // CommerceResource has no payment-flow field. Each listed rail carries the\n // overrides; the selected rail applies them.\n const flowOverrides = (rail: 'x402' | 'mpp') => {\n const flows = Object.fromEntries(\n resources.flatMap((resource) => {\n const flow = raw.resources[resource.id]?.paymentFlow;\n return flow !== undefined && resource.paymentMethods.includes(rail)\n ? [[resource.id, flow]]\n : [];\n }),\n );\n return Object.keys(flows).length > 0 ? { resourcePaymentFlows: flows } : {};\n };\n // The same holds for media types, which only x402 challenges carry\n const mimeTypes = Object.fromEntries(\n resources.flatMap((resource) => {\n const mimeType = raw.resources[resource.id]?.mimeType;\n return mimeType !== undefined ? [[resource.id, mimeType]] : [];\n }),\n );\n const x402WithFlows =\n x402 !== undefined\n ? {\n ...x402,\n ...flowOverrides('x402'),\n ...(Object.keys(mimeTypes).length > 0 ? { resourceMimeTypes: mimeTypes } : {}),\n }\n : x402;\n const mppWithFlows = mpp !== undefined ? { ...mpp, ...flowOverrides('mpp') } : mpp;\n if (protocols.acp.enabled) validateAcpCheckoutMapping(protocols.acp, resources);\n // Require an exposed resource so the enabled adapter publishes a skill\n if (protocols.a2a.enabled && !resources.some((r) => r.exposedVia.includes('a2a'))) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'protocols.a2a.enabled is true but no resource lists \"a2a\" in its expose',\n { details: { path: 'protocols.a2a.enabled' } },\n );\n }\n\n return {\n version: SUPPORTED_CONFIG_VERSION,\n merchant: {\n id: raw.merchant.id,\n name: raw.merchant.name,\n publicBaseUrl: raw.merchant.publicBaseUrl,\n },\n // Port 0 lets the OS pick a free port, for tests and throwaway instances\n server: {\n port: toNumber(raw.server.port, 'server.port', { min: 0, max: 65535 }),\n host: raw.server.host,\n ...(raw.server.adminToken !== undefined ? { adminToken: raw.server.adminToken } : {}),\n allowedOrigins: raw.server.allowedOrigins ?? [],\n },\n storage: { receipts: { driver: 'sqlite', path: raw.storage.receipts.path } },\n protocols,\n resources,\n payments: {\n ...(x402WithFlows !== undefined ? { x402: x402WithFlows } : {}),\n ...(mppWithFlows !== undefined ? { mpp: mppWithFlows } : {}),\n },\n ...(ap2 !== undefined ? { authorization: { ap2 } } : {}),\n };\n}\n\n// Two enabled mounts may not overlap: each registers a `${mountPath}/*`\n// wildcard, so a shared prefix lets one adapter answer for the other. Disabled\n// protocols mount nothing and are not compared.\nfunction validateMountPaths(protocols: NormalizedProtocols): void {\n const mounts = (\n [\n ['mcp', protocols.mcp],\n ['a2a', protocols.a2a],\n ['acp', protocols.acp],\n ] as const\n ).filter(([, p]) => p.enabled);\n\n for (const [index, [nameA, a]] of mounts.entries()) {\n for (const [nameB, b] of mounts.slice(index + 1)) {\n const baseA = a.mountPath.replace(/\\/+$/, '');\n const baseB = b.mountPath.replace(/\\/+$/, '');\n if (baseA === baseB || baseA.startsWith(`${baseB}/`) || baseB.startsWith(`${baseA}/`)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `protocols.${nameA}.mountPath (\"${a.mountPath}\") collides with protocols.${nameB}.mountPath (\"${b.mountPath}\") - each mount registers a wildcard, so overlapping prefixes cannot both be served`,\n { details: { path: `protocols.${nameA}.mountPath` } },\n );\n }\n }\n }\n}\n","/**\n * `config.yaml` schema, validation and normalization into the canonical\n * `GatewayConfig` (docs/contracts.md).\n *\n * 1. Zod validates shape: types, required fields, unknown keys. Numeric and\n * boolean leaves accept their native type or a string, because env\n * substitution produces strings. Zod transforms interact badly with\n * `.strict()` inference, so coercion happens in plain TypeScript in step 2.\n * 2. A business-rule pass coerces those leaves and checks what needs a\n * specific message: cross-references, disabled protocols and payment\n * methods, dynamic pricing, addresses, duplicate trust entries.\n *\n * Env substitution (`${VAR}` / `${VAR:-default}`) runs over the raw value\n * before both steps, so numeric and boolean fields can be templated. The one\n * exception is `version:`, checked before substitution: it decides whether this\n * parser understands the document at all, so it cannot depend on the\n * environment.\n */\nimport type { ZodError, ZodIssue, z } from 'zod';\nimport { CommerceError } from '../../core';\nimport { isRecord } from '../../core/is-record';\nimport { substituteEnv } from '../env';\nimport { normalize } from './normalize';\nimport { RawConfigSchema, SUPPORTED_CONFIG_VERSION } from './raw';\nimport type { GatewayConfig } from './types';\n\nexport function parseConfig(raw: unknown, env: NodeJS.ProcessEnv): GatewayConfig {\n if (!isRecord(raw)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'Configuration root must be a mapping (object) at \"$\"',\n {\n details: { path: '$' },\n },\n );\n }\n\n checkVersion(raw);\n\n const substituted = substituteEnv(raw, env);\n const parsed = parseWithZod(RawConfigSchema, substituted);\n return normalize(parsed);\n}\n\nfunction checkVersion(raw: Record<string, unknown>): void {\n if (!('version' in raw)) {\n throw new CommerceError('CONFIG_INVALID', 'Configuration is missing required field \"version\"', {\n details: { path: 'version' },\n });\n }\n const version = raw['version'];\n if (version !== SUPPORTED_CONFIG_VERSION) {\n const hint = typeof version === 'string' ? ', written as a number without quotes' : '';\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Unsupported config version \"${String(version)}\": this gateway only supports version ${SUPPORTED_CONFIG_VERSION}${hint}`,\n { details: { path: 'version', supported: SUPPORTED_CONFIG_VERSION } },\n );\n }\n}\n\nfunction parseWithZod<T>(schema: z.ZodType<T>, value: unknown): T {\n const result = schema.safeParse(value);\n if (!result.success) {\n throw zodErrorToConfigError(result.error);\n }\n return result.data;\n}\n\nfunction zodErrorToConfigError(error: ZodError): CommerceError {\n const issues = error.issues.map(describeIssue);\n const first = issues[0];\n const message = first\n ? `Configuration invalid at \"${first.path}\": ${first.message}`\n : 'Configuration invalid';\n return new CommerceError('CONFIG_INVALID', message, { details: { issues } });\n}\n\nfunction describeIssue(issue: ZodIssue): { path: string; message: string; code: string } {\n const path = issue.path.length > 0 ? issue.path.join('.') : '$';\n return { path, message: issue.message, code: issue.code };\n}\n\nexport type {\n AcpDiscoveryConfig,\n AcpProtocolConfig,\n GatewayConfig,\n X402OptionConfig,\n} from './types';\n","/**\n * Locates and parses `config.yaml`, then hands the raw value to `parseConfig`\n * for validation\n */\nimport { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport { parse as parseYaml, YAMLError } from 'yaml';\nimport { CommerceError } from '../core';\nimport { DEFAULT_CONFIG_FILENAME } from './filename';\nimport { type GatewayConfig, parseConfig } from './schema';\n\nconst CONFIG_PATH_ENV_VAR = 'AGENT_COMMERCE_CONFIG';\n\nexport interface LoadConfigOptions {\n readonly path?: string;\n readonly env?: NodeJS.ProcessEnv;\n readonly cwd?: string;\n}\n\nexport async function loadConfig(options: LoadConfigOptions = {}): Promise<GatewayConfig> {\n const env = options.env ?? process.env;\n const cwd = options.cwd ?? process.cwd();\n const configPath = resolveConfigPath(options.path, env, cwd);\n\n let text: string;\n try {\n text = await fs.readFile(configPath, 'utf8');\n } catch (error) {\n throw new CommerceError('CONFIG_INVALID', `Could not read configuration file \"${configPath}\"`, {\n details: { path: configPath },\n cause: error,\n });\n }\n\n let raw: unknown;\n try {\n raw = parseYaml(text);\n } catch (error) {\n const { reason, details } = describeYamlError(error);\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration file \"${configPath}\" is not valid YAML: ${reason}`,\n {\n details: { path: configPath, ...details },\n // Kept for programmatic callers. Never print it: its `.message` quotes\n // the source line (see describeYamlError).\n cause: error,\n },\n );\n }\n\n return parseConfig(raw, env);\n}\n\n// Plain-English phrasing for common YAML error codes. Fixed strings, so they\n// never carry file content; an unlisted code is shown bare.\nconst YAML_ERROR_EXPLANATIONS: Readonly<Record<string, string>> = {\n DUPLICATE_KEY: 'map keys must be unique',\n BAD_INDENT: 'bad indentation',\n TAB_AS_INDENT: 'tabs cannot be used for indentation',\n MISSING_CHAR: 'a required character is missing',\n BLOCK_AS_IMPLICIT_KEY: 'a block value cannot be used as a key (missing quotes, or a stray colon)',\n MULTILINE_IMPLICIT_KEY: 'a key spans multiple lines (missing quotes, or a stray colon)',\n UNEXPECTED_TOKEN: 'unexpected token',\n};\n\n/**\n * Describes a YAML failure from the error's structured `code` and `linePos`\n * only. The `yaml` package's `message` quotes the source line, and a syntax\n * error next to an inline secret (`server.adminToken`, a facilitator\n * `signerPrivateKey`) would print it in `validate` and `doctor` output.\n */\nfunction describeYamlError(error: unknown): {\n reason: string;\n details: Record<string, unknown>;\n} {\n if (!(error instanceof YAMLError)) {\n return { reason: 'unknown YAML parse error', details: {} };\n }\n const start = error.linePos?.[0];\n const where =\n start === undefined ? '' : ` at line ${String(start.line)}, column ${String(start.col)}`;\n const explanation = YAML_ERROR_EXPLANATIONS[error.code];\n const what = explanation === undefined ? error.code : `${error.code} (${explanation})`;\n return {\n reason: `${what}${where}`,\n details: {\n yamlErrorCode: error.code,\n ...(start === undefined ? {} : { line: start.line, column: start.col }),\n },\n };\n}\n\nfunction resolveConfigPath(\n explicitPath: string | undefined,\n env: NodeJS.ProcessEnv,\n cwd: string,\n): string {\n if (explicitPath) return path.resolve(cwd, explicitPath);\n const fromEnv = env[CONFIG_PATH_ENV_VAR];\n if (fromEnv) return path.resolve(cwd, fromEnv);\n return path.resolve(cwd, DEFAULT_CONFIG_FILENAME);\n}\n","/**\n * Two `onRequest` hooks with separate jobs:\n * - `buildAccessControlHook`, registered once on the server: the DNS-rebinding\n * Host check and allowlisted CORS. Neither depends on the path.\n * - `buildOperatorTokenHook`, registered on each operator route (`/api/receipts`,\n * `/api/events`): the `server.adminToken` gate.\n *\n * The token gate is per route because a global hook could only compare\n * `request.url`, which is still percent-encoded, while Fastify's router\n * decodes before matching: `/api/%72eceipts` would pass such a gate and still\n * route to `/api/receipts`. A per-route hook runs only after the router has\n * matched its route, so no path string is compared at all.\n */\nimport type { FastifyReply, FastifyRequest } from 'fastify';\nimport { AUTHORIZATION_HEADER, PAYMENT_HEADER } from '../core';\nimport { createBearerCheck } from '../protocols/http';\n\nconst CORS_METHODS = 'GET,POST,OPTIONS';\n// Allow payment and protocol headers in browser preflights. The gateway does\n// not verify ACP `signature` or `timestamp`. x402 fetch and axios clients also\n// send `access-control-expose-headers` on paid retries.\nconst CORS_HEADERS = [\n 'content-type',\n PAYMENT_HEADER,\n AUTHORIZATION_HEADER,\n 'x-request-id',\n 'authorization',\n 'mcp-protocol-version',\n 'mcp-method',\n 'mcp-name',\n 'a2a-version',\n 'a2a-extensions',\n 'api-version',\n 'idempotency-key',\n 'request-id',\n 'signature',\n 'timestamp',\n 'access-control-expose-headers',\n].join(',');\n// Cross-origin JS sees only CORS-safelisted response headers unless they are\n// named here, so a browser client could read neither the challenge, the\n// settlement result, nor ACP's echoed correlation and replay headers\nconst CORS_EXPOSED_HEADERS = [\n 'payment-required',\n 'payment-response',\n 'www-authenticate',\n 'payment-receipt',\n 'idempotency-key',\n 'request-id',\n 'idempotent-replayed',\n 'retry-after',\n].join(',');\n\nexport interface AccessControlOptions {\n readonly publicBaseUrl: string;\n readonly allowedOrigins: readonly string[];\n}\n\nexport function buildAccessControlHook(\n options: AccessControlOptions,\n): (request: FastifyRequest, reply: FastifyReply) => Promise<void> {\n // Matched case-insensitively, like Host, so a mis-cased allowedOrigins entry\n // does not lock out the dashboard. The response echoes the browser's Origin\n // verbatim, because CORS compares it byte for byte.\n const allowedOrigins = new Set(options.allowedOrigins.map((origin) => origin.toLowerCase()));\n const publicHostname = hostnameOf(options.publicBaseUrl);\n\n return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n // 1. Host check (DNS-rebinding defense), for every request\n const host = request.headers.host;\n if (!isAllowedHost(host, publicHostname)) {\n reply.status(403).send({ status: 'error', code: 'FORBIDDEN', message: 'Host not allowed' });\n return;\n }\n\n // 2. CORS, only for requests carrying an Origin. Agents and MCP clients\n // normally send none and get no CORS headers.\n const origin = request.headers.origin;\n if (origin !== undefined) {\n if (!allowedOrigins.has(origin.toLowerCase())) {\n reply\n .status(403)\n .send({ status: 'error', code: 'FORBIDDEN', message: 'Origin not allowed' });\n return;\n }\n reply.header('access-control-allow-origin', origin);\n reply.header('access-control-allow-methods', CORS_METHODS);\n reply.header('access-control-allow-headers', CORS_HEADERS);\n reply.header('access-control-expose-headers', CORS_EXPOSED_HEADERS);\n reply.header('vary', 'Origin');\n if (request.method === 'OPTIONS') {\n // A preflight carries no credentials, so it is answered here, before\n // any per-route token gate\n reply.status(204).send();\n }\n }\n };\n}\n\n/**\n * Per-route `server.adminToken` gate, registered on each operator route's own\n * definition. With no token configured every request gets a 404, as if the\n * route did not exist; a missing or wrong token gets a 401.\n *\n * Header only: a token in a query string leaks through Referer, history and\n * proxy logs.\n */\nexport function buildOperatorTokenHook(\n adminToken: string | undefined,\n): (request: FastifyRequest, reply: FastifyReply) => Promise<void> {\n const isValidAdminToken = adminToken ? createBearerCheck(adminToken) : undefined;\n // async: Fastify waits for a `done` callback from a hook that returns no\n // Promise, and this one takes none\n return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n if (isValidAdminToken === undefined) {\n reply.status(404).send();\n return;\n }\n if (!isValidAdminToken(request.headers.authorization)) {\n reply\n .status(401)\n .send({ status: 'error', code: 'UNAUTHORIZED', message: 'Admin token required' });\n }\n };\n}\n\n// `new URL()` strips the port and parses IPv6 bracket notation\nfunction hostnameOf(value: string): string {\n try {\n const hostname = new URL(\n value.includes('://') ? value : `http://${value}`,\n ).hostname.toLowerCase();\n // URL#hostname keeps the brackets on an IPv6 literal (\"[::1]\"); strip them\n // so it compares equal to the plain \"::1\" form\n return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;\n } catch {\n return '';\n }\n}\n\n// Loopback names are always accepted, whatever publicBaseUrl says. A\n// DNS-rebinding page sends its own hostname as Host, never one of these, and\n// local setups often bind 127.0.0.1 while publicBaseUrl says localhost.\nconst LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1']);\n\nfunction isAllowedHost(hostHeader: string | undefined, publicHostname: string): boolean {\n if (!hostHeader) return false;\n const hostname = hostnameOf(hostHeader);\n return hostname !== '' && (hostname === publicHostname || LOOPBACK_HOSTNAMES.has(hostname));\n}\n","/**\n * Starts protocol adapters and mounts the HTTP ones. An adapter that fails to\n * start is reported unhealthy; it never stops the server or the other adapters.\n *\n * An `HttpProtocolAdapter` reads `request.raw` itself (MCP's Streamable HTTP\n * transport does), so its mount registers no-op content-type parsers, hands\n * the adapter the raw Node req/res, and calls `reply.hijack()` so Fastify\n * sends no second response.\n *\n * Fastify enforces `bodyLimit` inside the content-type parser, so a no-op\n * parser enforces none, and the MCP SDK's own 4 MB cap is far looser than\n * this one. The mount counts bytes on the socket's 'data' events instead and\n * destroys the connection past MOUNT_BODY_LIMIT_BYTES; `Content-Length` alone\n * would miss a chunked body. Node's HTTP parser already keeps the socket\n * flowing, so the extra listener only observes bytes and never takes one the\n * adapter needs.\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';\nimport {\n type AdapterHealth,\n type Clock,\n CommerceError,\n type HttpProtocolAdapter,\n isHttpProtocolAdapter,\n type Logger,\n type ProtocolAdapter,\n type ProtocolAdapterContext,\n toErrorEnvelope,\n} from '../core';\n\n/**\n * Body cap for adapter mounts, also used by `server.ts` as Fastify's\n * `bodyLimit`, so both surfaces enforce one number. MCP tool payloads could\n * justify more, but a whole JSON-RPC batch is parsed in memory, and this cap\n * bounds that spike.\n */\nexport const MOUNT_BODY_LIMIT_BYTES = 256 * 1024;\n\nexport interface AdapterRuntime {\n readonly adapter: ProtocolAdapter;\n /** Set only when `start()` threw; a failed adapter is never re-queried live */\n readonly startFailure?: AdapterHealth;\n}\n\nexport interface StartAndMountOptions {\n readonly server: FastifyInstance;\n readonly adapters: readonly ProtocolAdapter[];\n readonly context: ProtocolAdapterContext;\n readonly logger: Logger;\n readonly clock: Clock;\n}\n\nexport async function startAndMountAdapters(\n options: StartAndMountOptions,\n): Promise<AdapterRuntime[]> {\n // Checked before any adapter starts: a path claimed twice is a composition\n // bug, and Fastify would only report it at `server.ready()` as an\n // FST_ERR_DUPLICATED_ROUTE naming neither adapter\n assertNoRouteConflicts(options.adapters);\n\n const runtimes: AdapterRuntime[] = [];\n\n for (const adapter of options.adapters) {\n // Every log line the adapter writes carries `adapter: <name>`\n const adapterLogger = options.logger.child({ adapter: adapter.name });\n const adapterContext: ProtocolAdapterContext = { ...options.context, logger: adapterLogger };\n\n try {\n await adapter.start(adapterContext);\n } catch (error) {\n const detail = errorMessage(error);\n adapterLogger.error(\n { err: detail },\n 'Protocol adapter failed to start; gateway continues without it',\n );\n runtimes.push({\n adapter,\n startFailure: { status: 'fail', detail, checkedAt: options.clock.nowIso() },\n });\n continue;\n }\n\n if (isHttpProtocolAdapter(adapter)) {\n mountHttpAdapter(options.server, adapter, adapterLogger);\n }\n runtimes.push({ adapter });\n }\n\n return runtimes;\n}\n\ninterface RouteClaim {\n readonly adapter: string;\n readonly path: string;\n // A mount also owns everything below its path, through its `/*` wildcard\n readonly wildcard: boolean;\n readonly method: 'ALL' | 'GET' | 'POST';\n}\n\nfunction routeClaims(adapters: readonly ProtocolAdapter[]): RouteClaim[] {\n const claims: RouteClaim[] = [];\n for (const adapter of adapters) {\n if (!isHttpProtocolAdapter(adapter)) continue;\n claims.push({\n adapter: adapter.name,\n path: adapter.mountPath.replace(/\\/+$/, ''),\n wildcard: true,\n method: 'ALL',\n });\n for (const route of adapter.additionalHttpRoutes ?? []) {\n claims.push({\n adapter: adapter.name,\n path: route.path.replace(/\\/+$/, ''),\n wildcard: false,\n method: route.method,\n });\n }\n }\n return claims;\n}\n\nfunction claimsCollide(a: RouteClaim, b: RouteClaim): boolean {\n if (a.wildcard && (b.path === a.path || b.path.startsWith(`${a.path}/`))) return true;\n if (b.wildcard && a.path.startsWith(`${b.path}/`)) return true;\n return a.path === b.path && (a.method === b.method || a.method === 'ALL' || b.method === 'ALL');\n}\n\n/**\n * Only claims from different adapters conflict. An adapter may serve a fixed\n * route under its own mount, because Fastify prefers a static route over a\n * wildcard; that is how a protocol that pins a sub-path stays self-contained.\n */\nfunction assertNoRouteConflicts(adapters: readonly ProtocolAdapter[]): void {\n const claims = routeClaims(adapters);\n for (const [index, a] of claims.entries()) {\n for (const b of claims.slice(index + 1)) {\n if (a.adapter === b.adapter || !claimsCollide(a, b)) continue;\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Protocol adapters \"${a.adapter}\" and \"${b.adapter}\" both claim the HTTP path \"${b.path}\"; each adapter path must be served by exactly one adapter`,\n { details: { adapters: [a.adapter, b.adapter], path: b.path } },\n );\n }\n }\n}\n\n/**\n * Requests one adapter may handle at once. The body cap bounds a single\n * request, while the MCP tool-call cap applies after the SDK parses its body.\n * This limit rejects excess requests before those parses can run together.\n * Measured on Node 24: 20 concurrent 256 KiB `tools/call` batches raised RSS\n * from about 135 MB to 470 MB, and the heap returned to its idle size after GC.\n */\nexport const MOUNT_MAX_CONCURRENT_REQUESTS = 20;\n// Ask clients to retry shortly after load shedding\nconst MOUNT_BUSY_RETRY_AFTER_SECONDS = 1;\n\nfunction mountHttpAdapter(\n server: FastifyInstance,\n adapter: HttpProtocolAdapter,\n logger: Logger,\n): void {\n const mountPath = adapter.mountPath;\n const wildcard = mountPath.endsWith('/') ? `${mountPath}*` : `${mountPath}/*`;\n const additionalRoutes = adapter.additionalHttpRoutes ?? [];\n // One counter per adapter, shared by the mount and its fixed routes, so a\n // second route into the same adapter is not a way around the cap\n let inFlight = 0;\n\n void server.register(async (instance) => {\n // Fastify's built-in application/json and text/plain parsers take\n // precedence over '*'. Without exact no-ops here, the JSON parser would\n // drain request.raw and the adapter's transport would read an empty stream.\n instance.addContentTypeParser(\n ['application/json', 'text/plain'],\n (_request, _payload, done) => {\n done(null);\n },\n );\n instance.addContentTypeParser('*', (_request, _payload, done) => {\n done(null);\n });\n\n const makeHandler =\n (handleHttp: (req: IncomingMessage, res: ServerResponse) => Promise<void>) =>\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n if (inFlight >= MOUNT_MAX_CONCURRENT_REQUESTS) {\n // Rejected before a byte of the body is read, so no parse starts\n const error = new CommerceError(\n 'GATEWAY_BUSY',\n 'Too many requests already parsing on this mount; retry shortly.',\n );\n reply\n .status(error.httpStatus)\n .header('retry-after', String(MOUNT_BUSY_RETRY_AFTER_SECONDS))\n .send(toErrorEnvelope(error));\n return;\n }\n inFlight += 1;\n try {\n const stopEnforcing = enforceMountBodyLimit(\n request.raw,\n reply.raw,\n MOUNT_BODY_LIMIT_BYTES,\n logger,\n );\n try {\n await handleHttp(request.raw, reply.raw);\n } catch (error) {\n logger.error({ err: errorMessage(error) }, 'Protocol adapter request handler threw');\n if (!reply.raw.headersSent) {\n reply.raw.statusCode = 500;\n reply.raw.end();\n }\n }\n stopEnforcing();\n reply.hijack();\n } finally {\n // Always released: a stranded count shrinks the cap for good and\n // eventually refuses every request on this mount\n inFlight -= 1;\n }\n };\n\n const mountHandler = makeHandler((req, res) => adapter.handleHttp(req, res));\n instance.all(mountPath, mountHandler);\n instance.all(wildcard, mountHandler);\n\n for (const route of additionalRoutes) {\n instance.route({\n method: route.method,\n url: route.path,\n handler: makeHandler((req, res) => route.handleHttp(req, res)),\n });\n }\n });\n}\n\nfunction enforceMountBodyLimit(\n req: IncomingMessage,\n res: ServerResponse,\n maxBytes: number,\n logger: Logger,\n): () => void {\n const socket = req.socket;\n let total = 0;\n let stopped = false;\n const onData = (chunk: Buffer): void => {\n total += chunk.length;\n if (total > maxBytes) {\n stop();\n logger.warn({ maxBytes }, 'Request body exceeded the mount body limit; connection closed');\n // A bare destroy gives a legitimate client an ECONNRESET that never\n // names the cap, so try a 413 with a JSON-RPC error first. If the\n // adapter already started its own response, just destroy. The rest of\n // the oversized body is never read.\n if (!res.headersSent) {\n const body = JSON.stringify({\n jsonrpc: '2.0',\n id: null,\n error: { code: -32600, message: `Request body exceeds the ${maxBytes}-byte mount limit` },\n });\n try {\n res.writeHead(413, {\n 'content-type': 'application/json',\n 'content-length': Buffer.byteLength(body),\n });\n // The callback fires once the write reaches the OS, not the peer,\n // so the destroy can still truncate the 413 into an ECONNRESET.\n // Accepted: leaving the read side open would let the oversized\n // body keep flowing to whatever reads `req`.\n res.end(body, () => socket.destroy());\n return;\n } catch {\n // The socket may already be gone; fall through to a bare destroy\n }\n }\n socket.destroy();\n }\n };\n const stop = (): void => {\n if (stopped) return;\n stopped = true;\n // A keep-alive socket serves many requests and each adds both listeners.\n // Leaving the 'close' ones behind piles them up until MaxListenersExceeded.\n socket.removeListener('data', onData);\n socket.removeListener('close', stop);\n };\n socket.on('data', onData);\n socket.once('close', stop);\n return stop;\n}\n\nexport async function getAdapterHealth(\n runtime: AdapterRuntime,\n clock: Clock,\n): Promise<AdapterHealth> {\n if (runtime.startFailure) return runtime.startFailure;\n try {\n return await runtime.adapter.health();\n } catch (error) {\n return { status: 'fail', detail: errorMessage(error), checkedAt: clock.nowIso() };\n }\n}\n\nexport async function stopAdapters(\n runtimes: readonly AdapterRuntime[],\n logger: Logger,\n): Promise<void> {\n for (const runtime of runtimes) {\n try {\n await runtime.adapter.stop();\n } catch (error) {\n logger\n .child({ adapter: runtime.adapter.name })\n .error({ err: errorMessage(error) }, 'Protocol adapter failed to stop cleanly');\n }\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","// Default `IdGenerator`, used when the caller injects none\nimport { randomUUID } from 'node:crypto';\nimport type { IdGenerator } from '../core';\n\nexport function createDefaultIdGenerator(): IdGenerator {\n return {\n next(prefix?: string): string {\n const id = randomUUID();\n return prefix ? `${prefix}_${id}` : id;\n },\n };\n}\n","/**\n * Pino logger factory that redacts the credential and proof headers in\n * `SECRET_HEADERS` and the fields named in `SECRET_FIELD_NAMES`.\n *\n * Two separate pino instances, because Fastify's `loggerInstance` option forces\n * its generic `Logger` type into `FastifyInstance`, which conflicts with our\n * `Logger` shape under `exactOptionalPropertyTypes`:\n * - `fastifyLoggerOptions()`: options for Fastify's `logger` option, so\n * Fastify builds its own instance for HTTP access logs.\n * - `createGatewayLogger()`: a standalone instance wrapped to the `src/core`\n * `Logger` shape, injected into the pipeline and protocol adapters.\n * Both share the redaction paths and the level and pretty-print policy.\n */\n\nimport { createRequire } from 'node:module';\nimport type { FastifyReply, FastifyRequest } from 'fastify';\nimport pino, { type LoggerOptions, type Logger as PinoLogger } from 'pino';\nimport { AUTHORIZATION_HEADER, type Logger, PAYMENT_HEADER } from '../core';\n\n/**\n * Absolute path to pino-pretty, or `undefined` when it is not installed.\n *\n * pino-pretty is a devDependency, so a consumer of the published package\n * usually lacks it, yet an unset `NODE_ENV` still selects the pretty default.\n * An unresolvable transport makes `pino()` throw and takes `createGateway()`\n * down with it. Passing the absolute path also stops pino resolving the\n * target from a different directory than this module.\n */\nconst PINO_PRETTY_PATH: string | undefined = (() => {\n try {\n return createRequire(import.meta.url).resolve('pino-pretty');\n } catch {\n return undefined;\n }\n})();\n\n// Each name is redacted at the top level and one level down ('*.privateKey'\n// matches `wallet.privateKey`). Pino's redact wildcards are single-level, so\n// `a.b.privateKey` is not covered: never put a secret in error details or log\n// a raw object that may nest one deeper without extending these paths.\nconst SECRET_FIELD_NAMES = [\n 'privateKey',\n 'signerPrivateKey',\n 'signature',\n 'seed',\n 'mnemonic',\n 'secret',\n 'challengeSecret',\n 'apiKey',\n 'adminToken',\n 'token',\n] as const;\n\n// Credential and proof headers. The proof headers come from the wire constants,\n// so a renamed one stays redacted; `agent-authorization` carries an AP2 mandate.\nconst SECRET_HEADERS = ['authorization', PAYMENT_HEADER, AUTHORIZATION_HEADER] as const;\n\nexport const REDACT_PATHS: readonly string[] = [\n ...SECRET_HEADERS.map((name) => `req.headers[${JSON.stringify(name)}]`),\n ...SECRET_FIELD_NAMES,\n ...SECRET_FIELD_NAMES.map((name) => `*.${name}`),\n];\n\nexport interface CreateGatewayLoggerOptions {\n readonly level?: string;\n readonly name?: string;\n readonly nodeEnv?: string;\n readonly prettyPrint?: boolean;\n}\n\nexport interface CreatedGatewayLogger {\n /** Raw pino instance, not shared with Fastify (see file header) */\n readonly pino: PinoLogger;\n /** `src/core` `Logger`-shaped wrapper */\n readonly core: Logger;\n}\n\nfunction baseLoggerOptions(options: CreateGatewayLoggerOptions): LoggerOptions {\n const nodeEnv = options.nodeEnv ?? process.env['NODE_ENV'] ?? 'development';\n // No pino-pretty worker thread in tests, which create many short-lived loggers\n const wantPretty = options.prettyPrint ?? (nodeEnv !== 'production' && nodeEnv !== 'test');\n // Even an explicit `prettyPrint: true` falls back to JSON when pino-pretty\n // is missing, rather than throwing\n const usePretty = wantPretty && PINO_PRETTY_PATH !== undefined;\n\n return {\n level: options.level ?? process.env['LOG_LEVEL'] ?? (nodeEnv === 'test' ? 'silent' : 'info'),\n ...(options.name !== undefined ? { name: options.name } : {}),\n redact: { paths: [...REDACT_PATHS], censor: '[REDACTED]' },\n ...(usePretty ? { transport: { target: PINO_PRETTY_PATH as string } } : {}),\n };\n}\n\n/**\n * Replaces a URL's query string with `?[REDACTED]` before it reaches a log line\n * or a response body: the admin token is header only, but any query parameter\n * on any route may carry something sensitive. Every place that shows a request\n * URL to a log or a client calls this instead of redacting its own way.\n */\nfunction sanitizeUrl(url: string | undefined): string | undefined {\n if (url === undefined) return undefined;\n const queryIndex = url.indexOf('?');\n return queryIndex === -1 ? url : `${url.slice(0, queryIndex)}?[REDACTED]`;\n}\n\n// Replaces Fastify's default `req` serializer, so the logged URL is sanitized\nfunction redactedReqSerializer(req: {\n method?: string;\n url?: string;\n host?: string;\n ip?: string;\n socket?: { remotePort?: number };\n}): Record<string, unknown> {\n return {\n method: req.method,\n url: sanitizeUrl(req.url),\n host: req.host,\n remoteAddress: req.ip,\n remotePort: req.socket?.remotePort,\n };\n}\n\n/** Options for Fastify's own `logger` option (see file header) */\nexport function fastifyLoggerOptions(options: CreateGatewayLoggerOptions = {}): LoggerOptions {\n return {\n ...baseLoggerOptions(options),\n serializers: { req: redactedReqSerializer },\n };\n}\n\n/**\n * Replaces Fastify's default 404 handler, whose log line interpolates\n * `request.raw.url` into a plain string and so bypasses the `req` serializer.\n * Exported so the tests exercise the handler that ships.\n */\nexport function buildNotFoundHandler(): (request: FastifyRequest, reply: FastifyReply) => void {\n return (request, reply) => {\n const safeUrl = sanitizeUrl(request.raw.url) ?? '';\n const message = `Route ${request.method}:${safeUrl} not found`;\n request.log.info(message);\n reply.code(404).send({ message, error: 'Not Found', statusCode: 404 });\n };\n}\n\nexport function createGatewayLogger(\n options: CreateGatewayLoggerOptions = {},\n): CreatedGatewayLogger {\n const instance = pino(baseLoggerOptions(options));\n return { pino: instance, core: wrapPino(instance) };\n}\n\nfunction wrapPino(instance: PinoLogger): Logger {\n const logger: Logger = {\n debug: (obj, msg) => instance.debug(obj, msg),\n info: (obj, msg) => instance.info(obj, msg),\n warn: (obj, msg) => instance.warn(obj, msg),\n error: (obj, msg) => instance.error(obj, msg),\n child: (bindings) => wrapPino(instance.child(bindings)),\n };\n return logger;\n}\n","/**\n * Secret-free projection of a `CommerceResource`, served by the public\n * `GET /api/resources`. `handler.headers` may carry resolved backend secrets,\n * such as an `Authorization` value built from `${API_KEY}`, so no handler\n * field except the method is copied.\n */\nimport type { CommerceResource } from '../core';\n\nexport interface PublicResource {\n readonly id: string;\n readonly name: string;\n readonly description?: string;\n readonly inputSchema?: Record<string, unknown>;\n readonly outputSchema?: Record<string, unknown>;\n readonly method: string;\n readonly pricing: CommerceResource['pricing'];\n readonly exposedVia: readonly string[];\n readonly paymentMethods: readonly string[];\n}\n\nexport function toPublicResource(resource: CommerceResource): PublicResource {\n return {\n id: resource.id,\n name: resource.name,\n ...(resource.description !== undefined ? { description: resource.description } : {}),\n ...(resource.inputSchema !== undefined ? { inputSchema: resource.inputSchema } : {}),\n ...(resource.outputSchema !== undefined ? { outputSchema: resource.outputSchema } : {}),\n method: resource.handler.method,\n pricing: resource.pricing,\n exposedVia: resource.exposedVia,\n paymentMethods: resource.paymentMethods,\n };\n}\n","/**\n * `GET /ready`: 503 when the store, a protocol adapter, or a payment or\n * authorization provider reports `fail`; `warn` still counts as serving.\n * Providers count because a payment provider that cannot reach its RPC would\n * otherwise leave the gateway ready while it serves 402 challenges it cannot\n * honor.\n *\n * The route is unauthenticated, so a health `detail` or a thrown message never\n * reaches the client, only a fixed vocabulary.\n *\n * An evaluation calls every dependency's `health()`, some of which make\n * upstream RPC calls. `createReadinessProbe` memoizes it for\n * READINESS_TTL_MS and collapses concurrent callers onto one evaluation, which\n * `/ready` and `/.well-known/agent-commerce` share.\n */\nimport type {\n AdapterDescriptor,\n AdapterHealth,\n AuthorizationProvider,\n Clock,\n Logger,\n PaymentProvider,\n ReceiptStore,\n} from '../core';\nimport { type AdapterRuntime, getAdapterHealth } from './adapters';\n\nexport interface ReadinessCheck {\n readonly name: string;\n readonly status: AdapterHealth['status'];\n readonly detail?: string;\n}\n\nexport interface ReadinessResult {\n readonly ready: boolean;\n readonly store: ReadinessCheck;\n readonly adapters: readonly ReadinessCheck[];\n readonly paymentProviders: readonly ReadinessCheck[];\n readonly authorizationProviders: readonly ReadinessCheck[];\n}\n\nexport interface CheckReadinessOptions {\n readonly store: ReceiptStore;\n readonly adapterRuntimes: readonly AdapterRuntime[];\n readonly paymentProviders: readonly PaymentProvider[];\n readonly authorizationProviders: readonly AuthorizationProvider[];\n readonly clock: Clock;\n readonly logger: Logger;\n}\n\nexport interface ProbedAdapter {\n readonly descriptor: AdapterDescriptor;\n readonly health: AdapterHealth;\n}\n\n// The client-facing detail per status; `threw` covers a health() that threw\n// and defaults to the `fail` detail\ntype HealthDetails = Readonly<Record<AdapterHealth['status'], string | undefined>> & {\n readonly threw?: string;\n};\n\nconst STORE_DETAIL: HealthDetails = {\n pass: undefined,\n warn: 'store-degraded',\n fail: 'store-unwritable',\n threw: 'store-unreachable',\n};\n\nconst ADAPTER_DETAIL: HealthDetails = {\n pass: undefined,\n warn: 'adapter-degraded',\n fail: 'adapter-unreachable',\n};\n\nconst PAYMENT_PROVIDER_DETAIL: HealthDetails = {\n pass: undefined,\n warn: 'payment-provider-degraded',\n fail: 'payment-provider-unreachable',\n};\n\nconst AUTHORIZATION_PROVIDER_DETAIL: HealthDetails = {\n pass: undefined,\n warn: 'authorization-provider-degraded',\n fail: 'authorization-provider-unreachable',\n};\n\n// A readiness check plus the health it came from, detail included. Only the\n// check reaches /ready; the well-known document publishes adapter health\n// without its detail.\ninterface Probed {\n readonly check: ReadinessCheck;\n readonly health: AdapterHealth;\n}\n\n/**\n * One probe for the store, the adapters and both provider kinds. A `health()`\n * that throws counts as failing and is logged at error; a returned detail is\n * logged at debug.\n */\nasync function probe(\n target: { readonly name: string; health(): Promise<AdapterHealth> },\n kind: string,\n details: HealthDetails,\n options: Pick<CheckReadinessOptions, 'clock' | 'logger'>,\n): Promise<Probed> {\n let health: AdapterHealth;\n let threw = false;\n try {\n health = await target.health();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n options.logger.error({ err: message, name: target.name }, `${kind} health() threw`);\n health = { status: 'fail', checkedAt: options.clock.nowIso() };\n threw = true;\n }\n if (health.detail !== undefined) {\n options.logger.debug(\n { name: target.name, detail: health.detail },\n `${kind} health detail (not sent to the client)`,\n );\n }\n const detail = threw ? (details.threw ?? details.fail) : details[health.status];\n return {\n check: {\n name: target.name,\n status: health.status,\n ...(detail !== undefined ? { detail } : {}),\n },\n health,\n };\n}\n\ninterface Evaluation {\n readonly result: ReadinessResult;\n readonly adapters: readonly ProbedAdapter[];\n readonly paymentProviders: readonly ProbedProvider[];\n}\n\n/** A payment provider's health, detail and components included */\nexport interface ProbedProvider {\n readonly name: string;\n readonly health: AdapterHealth;\n}\n\nasync function evaluate(options: CheckReadinessOptions): Promise<Evaluation> {\n const [store, adapters, paymentProviders, authorizationProviders] = await Promise.all([\n probe({ name: 'store', health: () => options.store.health() }, 'store', STORE_DETAIL, options),\n Promise.all(\n options.adapterRuntimes.map(async (runtime) => ({\n runtime,\n probed: await probe(\n // getAdapterHealth turns a throw into a failed result, so an adapter\n // failure is logged at debug as a detail rather than at error\n { name: runtime.adapter.name, health: () => getAdapterHealth(runtime, options.clock) },\n 'adapter',\n ADAPTER_DETAIL,\n options,\n ),\n })),\n ),\n Promise.all(\n options.paymentProviders.map((provider) =>\n probe(provider, 'payment provider', PAYMENT_PROVIDER_DETAIL, options),\n ),\n ),\n // An unusable authorization provider blocks readiness on the same threshold\n // as a payment one: a resource that requires a mandate cannot be served\n // without it, and serving the challenge anyway promises what we cannot honor\n Promise.all(\n options.authorizationProviders.map((provider) =>\n probe(provider, 'authorization provider', AUTHORIZATION_PROVIDER_DETAIL, options),\n ),\n ),\n ]);\n\n const checks = [\n store,\n ...adapters.map((a) => a.probed),\n ...paymentProviders,\n ...authorizationProviders,\n ];\n return {\n result: {\n ready: checks.every((probed) => probed.check.status !== 'fail'),\n store: store.check,\n adapters: adapters.map((a) => a.probed.check),\n paymentProviders: paymentProviders.map((p) => p.check),\n authorizationProviders: authorizationProviders.map((p) => p.check),\n },\n adapters: adapters.map(({ runtime, probed }) => ({\n descriptor: runtime.adapter.descriptor,\n health: probed.health,\n })),\n paymentProviders: paymentProviders.map((probed, index) => ({\n name: (options.paymentProviders[index] as PaymentProvider).name,\n health: probed.health,\n })),\n };\n}\n\n// Short enough that an outage or a recovery shows within one window\nconst READINESS_TTL_MS = 2_000;\n\nexport interface ReadinessProbe {\n check(): Promise<ReadinessResult>;\n /** All adapter health results, including detail, from the cached evaluation */\n adapterHealth(): Promise<readonly ProbedAdapter[]>;\n /** All payment provider health results from that evaluation */\n paymentHealth(): Promise<readonly ProbedProvider[]>;\n}\n\nexport function createReadinessProbe(\n options: CheckReadinessOptions,\n ttlMs: number = READINESS_TTL_MS,\n): ReadinessProbe {\n let cached: { readonly evaluation: Evaluation; readonly at: number } | undefined;\n let inFlight: Promise<Evaluation> | undefined;\n\n const current = async (): Promise<Evaluation> => {\n const now = options.clock.monotonicMs();\n if (cached && now - cached.at < ttlMs) return cached.evaluation;\n if (inFlight) return inFlight;\n\n inFlight = evaluate(options)\n .then((evaluation) => {\n cached = { evaluation, at: options.clock.monotonicMs() };\n return evaluation;\n })\n .finally(() => {\n inFlight = undefined;\n });\n return inFlight;\n };\n\n return {\n check: async () => (await current()).result,\n adapterHealth: async () => (await current()).adapters,\n paymentHealth: async () => (await current()).paymentProviders,\n };\n}\n","/**\n * `GET /.well-known/agent-commerce`: the merchant, the `AdapterDescriptor` of\n * every adapter, provider and store, and the protocol and spec versions. The\n * route is unauthenticated, so nothing here may be a credential.\n *\n * The settlement destination, `network` and `asset` are public: a payer needs\n * them to build a payment, and the destination is visible on-chain after any\n * transfer. `rpcUrl` and the facilitator URL are withheld, because commercial\n * providers embed an API key in the URL (Alchemy's `/v2/<KEY>`, Infura's\n * `/v3/<KEY>`, QuickNode's per-endpoint token). The facilitator private key\n * never appears.\n */\n\nimport type { GatewayConfig } from '../config';\nimport type { X402OptionConfig } from '../config/schema';\nimport type {\n AdapterDescriptor,\n AdapterHealth,\n AuthorizationProvider,\n PaymentProvider,\n ReceiptStore,\n} from '../core';\nimport { MPP_DEFAULT_PAYMENT_FLOW, MPP_PROFILE } from '../payments/mpp/constants';\nimport {\n type DeploymentMode,\n requireX402Network,\n resolveDeploymentMode,\n} from '../payments/x402/networks';\nimport { x402OfferName } from '../payments/x402/options';\nimport { X402_DEFAULT_PAYMENT_FLOW, type X402PaymentFlow } from '../payments/x402/payment-flow';\nimport { PACKAGE_VERSION } from '../version';\nimport type { ProbedAdapter, ProbedProvider } from './readiness';\n\n// Not derived from `PACKAGE_VERSION`: it names the wire contract a client\n// negotiates against, which changes only when that contract does\nconst GATEWAY_SUPPORTED_SPEC = 'agent-commerce/v1.0.0';\n\n/**\n * The protocol block as published, not as configured.\n *\n * Built field by field rather than spread from `config.protocols`, because that\n * object carries `protocols.acp.auth.token` - a live credential - plus the\n * idempotency database path and the operation-to-resource mapping. This route\n * is unauthenticated, so a future config field must be added here deliberately\n * to become public, never by inheriting a shape.\n */\nexport interface WellKnownProtocols {\n readonly http: { readonly enabled: boolean };\n readonly mcp: { readonly enabled: boolean; readonly mountPath: string };\n readonly a2a: { readonly enabled: boolean; readonly mountPath: string };\n readonly acp: { readonly enabled: boolean; readonly mountPath: string };\n}\n\nexport interface WellKnownDocument {\n readonly gateway: { readonly implementationVersion: string; readonly supportedSpec: string };\n readonly merchant: GatewayConfig['merchant'];\n readonly protocols: WellKnownProtocols;\n readonly adapters: ReadonlyArray<AdapterDescriptor & { readonly health: AdapterHealth }>;\n readonly paymentProviders: readonly AdapterDescriptor[];\n /**\n * Empty unless the gateway has an authorization provider (`authorization.ap2.enabled`).\n * Listed apart from `paymentProviders` because an authorization method is not\n * a payment rail and must never be selectable as one.\n */\n readonly authorizationProviders: readonly AdapterDescriptor[];\n readonly store: AdapterDescriptor;\n readonly payments: {\n readonly x402?: {\n readonly enabled: boolean;\n readonly network: string;\n readonly asset: string;\n /** Absent for a Permit2 token that has no EIP-712 domain */\n readonly assetName?: string;\n readonly assetVersion?: string;\n readonly assetDecimals: number;\n readonly payTo: string;\n /** Absent for EIP-3009, the default */\n readonly assetTransferMethod?: 'permit2';\n readonly maxTimeoutSeconds: number;\n readonly facilitator: { readonly mode: 'local' | 'remote' };\n /** `local`, `testnet` or `mainnet`, from the network */\n readonly mode: DeploymentMode;\n /** `authorization` settles after the backend; `upfront` before it */\n readonly paymentFlow: X402PaymentFlow;\n /** Resources that set their own flow, by id; absent when none does */\n readonly resourcePaymentFlows?: Readonly<Record<string, X402PaymentFlow>>;\n /** All rail offers when multiple exist; top-level fields mirror the first */\n readonly options?: readonly WellKnownX402Offer[];\n /** Resource offer overrides by id, replacing the rail's offers */\n readonly resourceOptions?: Readonly<Record<string, readonly WellKnownX402Offer[]>>;\n };\n /** Public settlement fields; excludes the challenge secret and facilitator credentials */\n readonly mpp?: {\n readonly enabled: boolean;\n readonly network: string;\n readonly asset: string;\n readonly assetName: string;\n readonly assetVersion: string;\n readonly assetDecimals: number;\n readonly recipient: string;\n readonly facilitator: { readonly mode: 'local' | 'remote' };\n readonly mode: DeploymentMode;\n /** `upfront` settles before the backend; `authorization` after it */\n readonly paymentFlow: X402PaymentFlow;\n /** Resources that set their own flow, by id; absent when none does */\n readonly resourcePaymentFlows?: Readonly<Record<string, X402PaymentFlow>>;\n };\n };\n}\n\n/** One x402 offer's public terms */\nexport interface WellKnownX402Offer {\n readonly network: string;\n readonly asset: string;\n readonly assetName?: string;\n readonly assetVersion?: string;\n readonly assetDecimals: number;\n readonly payTo: string;\n readonly assetTransferMethod?: 'permit2';\n /** Last reported health status, excluding diagnostic detail */\n readonly status?: AdapterHealth['status'];\n}\n\nexport interface BuildWellKnownOptions {\n readonly config: GatewayConfig;\n readonly paymentProviders: readonly PaymentProvider[];\n readonly authorizationProviders: readonly AuthorizationProvider[];\n readonly store: ReceiptStore;\n /** From the readiness cache, sharing `/ready`'s `health()` calls */\n readonly adapters: readonly ProbedAdapter[];\n /** From the same probe; the x402 provider's components give each offer's status */\n readonly paymentHealth?: readonly ProbedProvider[];\n}\n\n/**\n * Drops `detail` from a health result; `/ready` replaces it with a fixed\n * vocabulary. For a thrown `health()` or a start failure `detail` holds the\n * raw error message, often a module path or an internal hostname, and\n * `createGateway` accepts arbitrary adapters whose details this code cannot\n * vouch for.\n */\nfunction publicHealth(health: AdapterHealth): AdapterHealth {\n const { detail: _detail, ...rest } = health;\n return rest;\n}\n\nfunction publicProtocols(protocols: GatewayConfig['protocols']): WellKnownProtocols {\n return {\n http: { enabled: protocols.http.enabled },\n mcp: { enabled: protocols.mcp.enabled, mountPath: protocols.mcp.mountPath },\n a2a: { enabled: protocols.a2a.enabled, mountPath: protocols.a2a.mountPath },\n acp: { enabled: protocols.acp.enabled, mountPath: protocols.acp.mountPath },\n };\n}\n\n// Allowlist public offer fields: RPC URLs can contain API keys\nfunction publicOffer(\n option: X402OptionConfig,\n statuses: ReadonlyMap<string, AdapterHealth['status']>,\n): WellKnownX402Offer {\n const { network, asset, assetName, assetVersion, assetDecimals, payTo, assetTransferMethod } =\n option;\n const status = statuses.get(x402OfferName(option));\n return {\n network,\n asset,\n ...(assetName !== undefined ? { assetName } : {}),\n ...(assetVersion !== undefined ? { assetVersion } : {}),\n assetDecimals,\n payTo,\n ...(assetTransferMethod !== undefined ? { assetTransferMethod } : {}),\n ...(status !== undefined ? { status } : {}),\n };\n}\n\n// A rail's per-resource flows, or nothing when no resource overrides the rail\nfunction flowOverrides(flows: Readonly<Record<string, X402PaymentFlow>> | undefined): {\n readonly resourcePaymentFlows?: Readonly<Record<string, X402PaymentFlow>>;\n} {\n return flows !== undefined && Object.keys(flows).length > 0\n ? { resourcePaymentFlows: flows }\n : {};\n}\n\nexport function buildWellKnownDocument(options: BuildWellKnownOptions): WellKnownDocument {\n const adapters = options.adapters.map(({ descriptor, health }) => ({\n ...descriptor,\n health: publicHealth(health),\n }));\n\n const { x402, mpp } = options.config.payments;\n const x402Health = options.paymentHealth?.find((probed) => probed.name === 'x402')?.health;\n const offerStatuses = new Map(\n (x402Health?.components ?? []).map((component) => [component.name, component.status]),\n );\n\n return {\n gateway: {\n implementationVersion: PACKAGE_VERSION,\n supportedSpec: GATEWAY_SUPPORTED_SPEC,\n },\n merchant: options.config.merchant,\n protocols: publicProtocols(options.config.protocols),\n adapters,\n paymentProviders: options.paymentProviders.map((provider) => provider.descriptor),\n authorizationProviders: options.authorizationProviders.map((provider) => provider.descriptor),\n store: options.store.descriptor,\n payments: {\n ...(x402 !== undefined\n ? {\n x402: {\n enabled: x402.enabled,\n network: x402.network,\n asset: x402.asset,\n ...(x402.assetName !== undefined ? { assetName: x402.assetName } : {}),\n ...(x402.assetVersion !== undefined ? { assetVersion: x402.assetVersion } : {}),\n assetDecimals: x402.assetDecimals,\n payTo: x402.payTo,\n ...(x402.assetTransferMethod !== undefined\n ? { assetTransferMethod: x402.assetTransferMethod }\n : {}),\n maxTimeoutSeconds: x402.maxTimeoutSeconds,\n // Only local or remote is public: the facilitator URL can carry\n // a tenant path or an API key, and the signer key is secret\n facilitator: { mode: x402.facilitator.mode },\n mode: resolveDeploymentMode(\n requireX402Network(x402.network, 'payments.x402.network', x402.networks),\n ),\n paymentFlow: x402.paymentFlow ?? X402_DEFAULT_PAYMENT_FLOW,\n ...flowOverrides(x402.resourcePaymentFlows),\n ...(x402.options !== undefined && x402.options.length > 1\n ? { options: x402.options.map((option) => publicOffer(option, offerStatuses)) }\n : {}),\n ...(x402.resourceOptions !== undefined\n ? {\n resourceOptions: Object.fromEntries(\n Object.entries(x402.resourceOptions).map(([id, list]) => [\n id,\n list.map((option) => publicOffer(option, offerStatuses)),\n ]),\n ),\n }\n : {}),\n },\n }\n : {}),\n ...(mpp !== undefined\n ? {\n mpp: {\n enabled: mpp.enabled,\n network: mpp.network,\n asset: mpp.asset,\n assetName: mpp.assetName,\n assetVersion: mpp.assetVersion,\n assetDecimals: MPP_PROFILE.assetDecimals,\n recipient: mpp.recipient,\n facilitator: { mode: mpp.facilitator.mode },\n mode: resolveDeploymentMode(requireX402Network(mpp.network, 'payments.mpp.network')),\n paymentFlow: mpp.paymentFlow ?? MPP_DEFAULT_PAYMENT_FLOW,\n ...flowOverrides(mpp.resourcePaymentFlows),\n },\n }\n : {}),\n },\n };\n}\n","/**\n * The gateway's own HTTP surface (docs/contracts.md \"Gateway HTTP surface\").\n * Adapter mounting (e.g. `/mcp`) is handled separately in adapters.ts.\n */\n\nimport { Transform } from 'node:stream';\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';\nimport type { GatewayConfig } from '../config';\nimport {\n AUTHORIZATION_HEADER,\n type AuthorizationProvider,\n type CanonicalRequest,\n type Clock,\n CommerceError,\n type ExecutionPipeline,\n type Logger,\n PAYMENT_HEADER,\n PAYMENT_REQUIRED_HEADER,\n PAYMENT_RESPONSE_HEADER,\n type PaymentMethodName,\n type PaymentProvider,\n parseAuthorizationHeader,\n type ReceiptStore,\n type ResourceRegistry,\n toCommerceError,\n toErrorEnvelope,\n toPaymentRequiredEnvelope,\n} from '../core';\nimport { isRecord } from '../core/is-record';\nimport { mppProblem, mppProblemDetail } from '../payments/mpp/problems';\nimport { CONTENT_DIGEST_METADATA_KEY, contentDigest } from '../payments/mpp/transport';\nimport {\n settlementFailure,\n settlementResponse,\n settlementResponseFromDetails,\n x402ErrorCode,\n x402RefusalStatus,\n} from '../payments/x402/transport';\nimport { buildOperatorTokenHook } from './access-control';\nimport type { AdapterRuntime } from './adapters';\nimport { toPublicResource } from './public-resource';\nimport { createReadinessProbe } from './readiness';\nimport { buildWellKnownDocument } from './well-known';\n\n// Legacy x402 proof header; this gateway accepts v2 only\nconst X402_V1_PAYMENT_HEADER = 'x-payment';\n\nexport interface RegisterRoutesOptions {\n readonly server: FastifyInstance;\n readonly config: GatewayConfig;\n readonly pipeline: ExecutionPipeline;\n readonly resources: ResourceRegistry;\n readonly store: ReceiptStore;\n readonly paymentProviders: readonly PaymentProvider[];\n readonly authorizationProviders: readonly AuthorizationProvider[];\n readonly clock: Clock;\n readonly adapterRuntimes: readonly AdapterRuntime[];\n readonly logger: Logger;\n}\n\nexport function registerRoutes(options: RegisterRoutesOptions): void {\n const { server } = options;\n\n // `adapterRuntimes` is filled in place once adapters start, so the probe\n // reads the live list\n const readinessProbe = createReadinessProbe({\n store: options.store,\n adapterRuntimes: options.adapterRuntimes,\n paymentProviders: options.paymentProviders,\n authorizationProviders: options.authorizationProviders,\n clock: options.clock,\n logger: options.logger,\n });\n\n server.get('/health', async () => ({ status: 'ok' }));\n\n server.get('/ready', async (_request, reply) => {\n const readiness = await readinessProbe.check();\n reply.status(readiness.ready ? 200 : 503);\n return readiness;\n });\n\n server.get('/.well-known/agent-commerce', async () =>\n buildWellKnownDocument({\n config: options.config,\n paymentProviders: options.paymentProviders,\n authorizationProviders: options.authorizationProviders,\n store: options.store,\n adapters: await readinessProbe.adapterHealth(),\n paymentHealth: await readinessProbe.paymentHealth(),\n }),\n );\n\n // List provider-backed rails in challenge order\n const backed = (method: string) =>\n options.paymentProviders.some((provider) => provider.name === method);\n server.get('/api/resources', async () => ({\n resources: options.resources.list().map((resource) => {\n const listed = toPublicResource(resource);\n return { ...listed, paymentMethods: listed.paymentMethods.filter(backed) };\n }),\n }));\n\n server.post(\n '/api/resources/:id/invoke',\n { preParsing: async (request, _reply, payload) => payload.pipe(digestingStream(request)) },\n async (request, reply) => {\n await handleInvoke(request, reply, options);\n },\n );\n\n // The admin token gate is per route, not global; access-control.ts says why\n const tokenHook = buildOperatorTokenHook(options.config.server.adminToken);\n\n server.get(\n '/api/receipts',\n { onRequest: tokenHook },\n ledgerHandler('receipts', (list) => options.store.listReceipts(list)),\n );\n server.get(\n '/api/events',\n { onRequest: tokenHook },\n ledgerHandler('events', (list) => options.store.listEvents(list)),\n );\n}\n\n// Keep a digest of each invoke body's original bytes through parsing.\nconst bodyDigests = new WeakMap<FastifyRequest, string>();\n\n// Forward each body chunk unchanged and record the digest at the end.\nfunction digestingStream(request: FastifyRequest): Transform {\n const chunks: Buffer[] = [];\n return new Transform({\n transform(chunk: Buffer, _encoding, callback) {\n chunks.push(chunk);\n callback(null, chunk);\n },\n flush(callback) {\n if (chunks.length > 0) bodyDigests.set(request, contentDigest(Buffer.concat(chunks)));\n callback();\n },\n });\n}\n\n// `GET /api/receipts` and `GET /api/events`: one page of a ledger\nfunction ledgerHandler<K extends string>(\n key: K,\n list: (options: { limit?: number }) => Promise<unknown>,\n): (request: FastifyRequest, reply: FastifyReply) => Promise<Record<K, unknown> | undefined> {\n return async (request, reply) => {\n try {\n const limit = parseLimit((request.query as Record<string, unknown>)['limit']);\n return { [key]: await list(limit !== undefined ? { limit } : {}) } as Record<K, unknown>;\n } catch (error) {\n const commerceError = toCommerceError(error);\n reply.status(commerceError.httpStatus).send(toErrorEnvelope(commerceError));\n return undefined;\n }\n };\n}\n\nasync function handleInvoke(\n request: FastifyRequest,\n reply: FastifyReply,\n options: RegisterRoutesOptions,\n): Promise<void> {\n const resourceId = (request.params as { id: string }).id;\n // Track the selected rail so errors use its payment headers\n let paymentMethod: PaymentMethodName | undefined;\n\n try {\n const resource = options.resources.get(resourceId);\n if (!resource?.exposedVia.includes('http')) {\n throw new CommerceError('RESOURCE_NOT_FOUND', `Resource \"${resourceId}\" was not found`, {\n requestId: request.id,\n resourceId,\n });\n }\n\n // createGateway puts provider-backed methods first, so this label matches\n // the rail selected by the pipeline. Without a method, drop the proof\n // instead of inventing a rail; the pipeline receives an unpaid request.\n paymentMethod = resource.paymentMethods[0];\n const paymentValue = paymentProof(request, paymentMethod);\n const payment =\n paymentValue !== undefined && paymentMethod !== undefined\n ? { method: paymentMethod, payload: paymentValue }\n : undefined;\n\n // Its own header rather than a reserved body field: HTTP already carries\n // the payment proof out of band, and an authorization inside the body\n // would have to survive every backend input-binding mode intact\n const authorization = parseAuthorizationHeader(\n request.headers[AUTHORIZATION_HEADER],\n request.id,\n );\n\n const digest = bodyDigests.get(request);\n const canonicalRequest: CanonicalRequest = {\n requestId: request.id,\n resourceId,\n input: request.body ?? {},\n protocol: 'http',\n receivedAt: options.clock.nowIso(),\n ...(payment !== undefined ? { payment } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n ...(digest !== undefined ? { metadata: { [CONTENT_DIGEST_METADATA_KEY]: digest } } : {}),\n };\n\n const outcome = await options.pipeline.execute(canonicalRequest);\n\n if (outcome.kind === 'payment-required') {\n const envelope = toPaymentRequiredEnvelope(outcome);\n if (envelope.payment.provider === 'mpp') {\n const challenge = envelope.payment.envelope?.['wwwAuthenticate'];\n if (typeof challenge === 'string') reply.header('www-authenticate', challenge);\n } else if (envelope.payment.envelope !== undefined) {\n // v2 clients read this header. A v1-only proof gets a challenge\n // naming the unsupported version; the body keeps the full envelope.\n const v1Only =\n request.headers[X402_V1_PAYMENT_HEADER] !== undefined &&\n request.headers[PAYMENT_HEADER] === undefined;\n reply.header(\n PAYMENT_REQUIRED_HEADER,\n encodeHeaderDocument(\n v1Only\n ? { ...envelope.payment.envelope, error: 'invalid_x402_version' }\n : envelope.payment.envelope,\n ),\n );\n }\n // A challenge is per-request (fresh nonce window, fresh expiry). Caching\n // one would hand a later buyer an expired offer.\n reply.header('cache-control', 'no-store');\n if (envelope.payment.provider === 'mpp') {\n // Use Problem Details for unpaid MPP requests and refusals\n const { status: _envelopeStatus, ...members } = envelope;\n reply\n .header('content-type', 'application/problem+json')\n .status(402)\n .send({\n ...mppProblem(envelope.code, 402),\n status: 402,\n detail: envelope.message,\n ...members,\n });\n return;\n }\n reply.status(402).send(envelope);\n return;\n }\n\n if (outcome.payment) {\n reply.header(\n PAYMENT_RESPONSE_HEADER,\n encodeHeaderDocument(settlementResponse(outcome.payment)),\n );\n const receipt = outcome.payment.metadata?.['receipt'];\n if (outcome.payment.provider === 'mpp' && typeof receipt === 'string') {\n reply.header('payment-receipt', receipt);\n }\n // Payment headers identify this buyer's payment; MPP also requires\n // private caching for responses carrying `Payment-Receipt`\n reply.header('cache-control', 'private');\n }\n const contentType = relayedContentType(outcome.headers?.['content-type'], outcome.body);\n if (contentType !== undefined) reply.type(contentType);\n if (typeof outcome.body === 'string') {\n // Text from the backend, a page included, must not run as the gateway's origin\n reply.header('content-security-policy', 'sandbox');\n reply.header('x-content-type-options', 'nosniff');\n }\n reply.status(outcome.backendStatus).send(outcome.body);\n } catch (error) {\n sendInvokeError(reply, toCommerceError(error), paymentMethod);\n }\n}\n\n// The backend's own Content-Type, when it is a text type that fits the body as\n// relayed: a JSON type for a parsed JSON body, any other for a text body.\n// Fastify sends text as text/plain otherwise, and refuses an object under a\n// non-JSON type. The body always leaves as UTF-8, so a charset the backend\n// named gives way.\nfunction relayedContentType(header: string | undefined, body: unknown): string | undefined {\n if (header === undefined) return undefined;\n // Split on `;` outside quoted strings, so a quoted value keeps its own `;`\n const [essence = '', ...parameters] = (header.match(/(?:[^;\"]|\"(?:[^\"\\\\]|\\\\.)*\"?)+/g) ?? []).map(\n (part) => part.trim(),\n );\n const json = /[/+]json$/i.test(essence);\n if (!isTextType(essence) || json === (typeof body === 'string')) return undefined;\n const kept = parameters.filter(\n (parameter) => parameter !== '' && !/^charset\\s*=/i.test(parameter),\n );\n return [essence, ...kept, 'charset=utf-8'].join('; ');\n}\n\n// The executor decodes every backend body as UTF-8, so a binary body has\n// already changed by now and must not keep a binary type\nfunction isTextType(essence: string): boolean {\n return (\n /^text\\//i.test(essence) ||\n /[/+](?:json|xml)$/i.test(essence) ||\n /^application\\/(?:java|ecma)script$/i.test(essence)\n );\n}\n\n// A provider outage is no verdict on the payment, so the client may retry the\n// same proof after a short pause\nconst PROVIDER_UNAVAILABLE_CODES: ReadonlySet<string> = new Set([\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'AUTHORIZATION_PROVIDER_UNAVAILABLE',\n]);\nconst PROVIDER_RETRY_AFTER_SECONDS = 5;\n\n// Codes whose MPP response body is a Problem Details document\nconst MPP_PROBLEM_CODES: ReadonlySet<string> = new Set([\n 'PAYMENT_INVALID',\n 'PAYMENT_REPLAYED',\n 'PAYMENT_SETTLEMENT_FAILED',\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n]);\n\nfunction sendInvokeError(\n reply: FastifyReply,\n error: CommerceError,\n paymentMethod: PaymentMethodName | undefined,\n): void {\n const details = error.details;\n if (PROVIDER_UNAVAILABLE_CODES.has(error.code)) {\n reply.header('retry-after', String(PROVIDER_RETRY_AFTER_SECONDS));\n }\n // Report a settled payment even if backend delivery fails. MPP forbids a\n // `Payment-Receipt` header on error responses, so send only this summary\n const settled = settlementResponseFromDetails(details);\n if (settled !== undefined) {\n reply.header(PAYMENT_RESPONSE_HEADER, encodeHeaderDocument(settled));\n }\n if (error.code === 'PAYMENT_SETTLEMENT_FAILED') {\n reply.header(PAYMENT_RESPONSE_HEADER, encodeHeaderDocument(settlementFailure(details)));\n }\n // Attach a fresh challenge to a 402 when the rail provides one\n const challenge = details?.['challenge'];\n if (error.httpStatus === 402 && isRecord(challenge)) {\n if (paymentMethod === 'mpp' && typeof challenge['wwwAuthenticate'] === 'string') {\n reply.header('www-authenticate', challenge['wwwAuthenticate']);\n } else if (paymentMethod === 'x402' && error.code !== 'PAYMENT_SETTLEMENT_FAILED') {\n // x402 includes the reason in the challenge; settlement refusals use\n // `PAYMENT-RESPONSE` alone\n reply.header(\n PAYMENT_REQUIRED_HEADER,\n encodeHeaderDocument({\n ...challenge,\n error: x402ErrorCode(error.code, details?.['reason'], details?.['network']),\n }),\n );\n }\n reply.header('cache-control', 'no-store');\n }\n\n const envelope = toErrorEnvelope(error);\n if (paymentMethod === 'mpp' && MPP_PROBLEM_CODES.has(error.code)) {\n // RFC 9457 `status` is the HTTP status, so it replaces the envelope's\n // `status: 'error'`; the other envelope fields stay as extension members\n const { status: _envelopeStatus, ...members } = envelope;\n const reason = typeof details?.['reason'] === 'string' ? details['reason'] : undefined;\n reply\n .header('content-type', 'application/problem+json')\n .status(error.httpStatus)\n .send({\n ...mppProblem(error.code, error.httpStatus, reason),\n status: error.httpStatus,\n // The reason token stays in `message` and `details.reason`\n detail: mppProblemDetail(reason, error.message),\n ...members,\n });\n return;\n }\n // Preserve the challenge when a missing Permit2 allowance changes 402 to 412\n const status =\n paymentMethod === 'x402'\n ? x402RefusalStatus(error.code, error.httpStatus, details?.['reason'])\n : error.httpStatus;\n reply.status(status).send(envelope);\n}\n\n// Each rail has its own proof header. MPP uses HTTP authentication, and an\n// `Authorization` value in another scheme is not a payment proof.\nfunction paymentProof(\n request: FastifyRequest,\n method: PaymentMethodName | undefined,\n): string | undefined {\n if (method === 'mpp') {\n const value = request.headers.authorization;\n return value !== undefined && /^Payment\\s+\\S/i.test(value) ? value : undefined;\n }\n const value = request.headers[PAYMENT_HEADER];\n return Array.isArray(value) ? value[0] : value;\n}\n\n/**\n * Base64 of a JSON document, the encoding every x402 v2 payment header uses.\n * Not imported from the x402 SDK: this module is reachable from the main\n * entry point, which must import no optional peer.\n */\nfunction encodeHeaderDocument(document: unknown): string {\n return Buffer.from(JSON.stringify(document), 'utf8').toString('base64');\n}\n\n// Undefined when absent or unparseable, so the store applies its default. A\n// parseable value below 1 is INPUT_INVALID, because SQLite reads a negative\n// LIMIT as unbounded.\nfunction parseLimit(value: unknown): number | undefined {\n if (Array.isArray(value)) return parseLimit(value[0]);\n let n: number | undefined;\n if (typeof value === 'number' && Number.isFinite(value)) n = Math.trunc(value);\n else if (typeof value === 'string' && value.length > 0) {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) n = Math.trunc(parsed);\n }\n if (n === undefined) return undefined;\n if (n <= 0) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Query parameter \"limit\" must be a positive integer (got ${n})`,\n {\n details: { field: 'limit' },\n },\n );\n }\n return n;\n}\n","// `createGateway()`: the Fastify server, usable with injected fakes and without `run.ts`\n\nimport type { IncomingMessage } from 'node:http';\nimport Fastify, { type FastifyInstance } from 'fastify';\nimport type { GatewayConfig } from '../config';\nimport {\n type AuthorizationProvider,\n type BackendExecutor,\n type Clock,\n type CommerceResource,\n type ExecutionPipeline,\n type IdGenerator,\n type Logger,\n type PaymentProvider,\n type ProtocolAdapter,\n type ProtocolAdapterContext,\n type ReceiptStore,\n type ResourceRegistry,\n systemClock,\n} from '../core';\nimport {\n createExecutionPipeline,\n createResourceRegistry,\n createStoreEventSink,\n HttpBackendExecutor,\n} from '../core/execution';\nimport { buildAccessControlHook } from './access-control';\nimport {\n type AdapterRuntime,\n MOUNT_BODY_LIMIT_BYTES,\n startAndMountAdapters,\n stopAdapters,\n} from './adapters';\nimport { createDefaultIdGenerator } from './ids';\nimport { buildNotFoundHandler, createGatewayLogger, fastifyLoggerOptions } from './logger';\nimport { registerRoutes } from './routes';\n\nconst REQUEST_ID_HEADER = 'x-request-id';\n// The audit request id is always minted: a caller-chosen one could repeat\n// another flow's id and interleave its audit rows with that flow's. A\n// caller's X-Request-Id in this bounded form survives only as the\n// `clientRequestId` binding on the request's log lines.\nconst CLIENT_REQUEST_ID_PATTERN = /^[A-Za-z0-9._:-]{1,64}$/;\n\nfunction clientRequestIdOf(raw: IncomingMessage): string | undefined {\n const header = raw.headers[REQUEST_ID_HEADER];\n const value = Array.isArray(header) ? header[0] : header;\n return value !== undefined && CLIENT_REQUEST_ID_PATTERN.test(value) ? value : undefined;\n}\n\nexport interface GatewayOptions {\n readonly config: GatewayConfig;\n readonly store: ReceiptStore;\n readonly paymentProviders: readonly PaymentProvider[];\n /** Defaults to none; each resource declares the methods it requires */\n readonly authorizationProviders?: readonly AuthorizationProvider[];\n readonly protocolAdapters: readonly ProtocolAdapter[];\n readonly logger?: Logger;\n readonly clock?: Clock;\n readonly ids?: IdGenerator;\n /** Override for tests */\n readonly backend?: BackendExecutor;\n}\n\nexport interface GatewayInstance {\n readonly pipeline: ExecutionPipeline;\n readonly resources: ResourceRegistry;\n listen(): Promise<{ url: string }>;\n close(): Promise<void>;\n /** Fastify instance, for `.inject()` in tests */\n readonly server: FastifyInstance;\n}\n\n// Ingress labels a proof with `paymentMethods[0]`, while the pipeline selects\n// the first method backed by a provider. Move backed methods first, preserving\n// declared order within each group, so both paths select the same rail.\nfunction withProviderBackedMethodsFirst(\n resource: CommerceResource,\n providers: readonly PaymentProvider[],\n): CommerceResource {\n const backed = (method: string) => providers.some((provider) => provider.name === method);\n const ordered = [\n ...resource.paymentMethods.filter(backed),\n ...resource.paymentMethods.filter((method) => !backed(method)),\n ];\n return ordered.some((method, i) => method !== resource.paymentMethods[i])\n ? { ...resource, paymentMethods: ordered }\n : resource;\n}\n\nexport async function createGateway(options: GatewayOptions): Promise<GatewayInstance> {\n const clock = options.clock ?? systemClock;\n const ids = options.ids ?? createDefaultIdGenerator();\n const logger = options.logger ?? createGatewayLogger({ name: options.config.merchant.id }).core;\n const backend = options.backend ?? new HttpBackendExecutor({ logger });\n\n const authorizationProviders = options.authorizationProviders ?? [];\n\n const resources = createResourceRegistry(\n options.config.resources.map((resource) =>\n withProviderBackedMethodsFirst(resource, options.paymentProviders),\n ),\n );\n const events = createStoreEventSink({ store: options.store, logger });\n const pipeline = createExecutionPipeline({\n resources,\n paymentProviders: options.paymentProviders,\n authorizationProviders,\n store: options.store,\n backend,\n events,\n logger,\n clock,\n ids,\n });\n\n const server = Fastify({\n // Same cap as adapter mounts, which enforce it on the socket instead\n bodyLimit: MOUNT_BODY_LIMIT_BYTES,\n genReqId: () => ids.next('req'),\n childLoggerFactory: (parent, bindings, childOptions, rawReq) => {\n const clientRequestId = clientRequestIdOf(rawReq);\n return parent.child(\n clientRequestId !== undefined ? { ...bindings, clientRequestId } : bindings,\n childOptions,\n );\n },\n logger: fastifyLoggerOptions({ name: `${options.config.merchant.id}-http` }),\n });\n\n // Fastify's default 404 handler logs the raw URL, query string included\n server.setNotFoundHandler(buildNotFoundHandler());\n\n // Host check and CORS for every request. Closed by default: with no\n // allowedOrigins, every request carrying an Origin is refused. The admin\n // token gate is per route, in routes.ts.\n server.addHook(\n 'onRequest',\n buildAccessControlHook({\n publicBaseUrl: options.config.merchant.publicBaseUrl,\n allowedOrigins: options.config.server.allowedOrigins,\n }),\n );\n\n const adapterRuntimes: AdapterRuntime[] = [];\n\n registerRoutes({\n server,\n config: options.config,\n pipeline,\n resources,\n store: options.store,\n paymentProviders: options.paymentProviders,\n authorizationProviders,\n clock,\n adapterRuntimes,\n logger,\n });\n\n const context: ProtocolAdapterContext = {\n pipeline,\n resources,\n events,\n logger,\n clock,\n ids,\n publicBaseUrl: options.config.merchant.publicBaseUrl,\n };\n\n const started = await startAndMountAdapters({\n server,\n adapters: options.protocolAdapters,\n context,\n logger,\n clock,\n });\n adapterRuntimes.push(...started);\n\n await server.ready();\n\n return {\n pipeline,\n resources,\n async listen(): Promise<{ url: string }> {\n const url = await server.listen({\n port: options.config.server.port,\n host: options.config.server.host,\n });\n return { url };\n },\n async close(): Promise<void> {\n await stopAdapters(adapterRuntimes, logger);\n await server.close();\n },\n server,\n };\n}\n","/**\n * A2A pins, kept in one place so nothing infers one version from another.\n *\n * The specification revision and the negotiation version look alike but\n * differ: `1.0.1` names the document this adapter was written against, `1.0`\n * is what a client negotiates on the wire. Neither is this package's version\n * (`PACKAGE_VERSION`).\n */\n\n/** A2A specification revision this adapter targets */\nexport const A2A_SPEC_VERSION = '1.0.1';\n\n/** Protocol negotiation version carried on the wire */\nexport const A2A_PROTOCOL_VERSION = '1.0';\n\n/** The only transport binding this adapter serves */\nexport const A2A_PROTOCOL_BINDING = 'JSONRPC';\n\n/**\n * Fixed by the A2A specification: a client fetches the card from this exact\n * path, so it is not configurable. `src/config` reserves it against adapter\n * mounts for the same reason.\n */\nexport const A2A_AGENT_CARD_PATH = '/.well-known/agent-card.json';\n\n/** Mount serving the JSON-RPC endpoint, unless configuration says otherwise */\nexport const A2A_DEFAULT_MOUNT_PATH = '/a2a';\n\n/** Content type on both sides of every supported A2A exchange */\nexport const A2A_JSON_MEDIA_TYPE = 'application/json';\n\n/** Card identity when the operator names none. Matches the MCP adapter's default server name */\nexport const A2A_DEFAULT_AGENT_NAME = 'agent-commerce';\n\n/**\n * Version negotiation header. An absent or empty value means `0.3`, which\n * this adapter does not serve.\n */\nexport const A2A_VERSION_HEADER = 'a2a-version';\n\n/** The one JSON-RPC method this adapter serves, not the legacy `message/send` */\nexport const A2A_METHOD_SEND_MESSAGE = 'SendMessage';\n\n/**\n * Push notification configuration methods. The card declares no push\n * support, so these return `PushNotificationNotSupportedError`.\n */\nexport const A2A_PUSH_CONFIG_METHODS: readonly string[] = [\n 'CreateTaskPushNotificationConfig',\n 'GetTaskPushNotificationConfig',\n 'ListTaskPushNotificationConfigs',\n 'DeleteTaskPushNotificationConfig',\n];\n\n/**\n * A2A methods that exist and are not served here, kept apart from unknown\n * methods so a caller learns whether it hit a refused method or a typo. The\n * descriptor and the transport both read this one list.\n * `A2A_TASK_LOOKUP_METHODS` get a different error code on the wire.\n */\nexport const A2A_UNSUPPORTED_METHODS: readonly string[] = [\n 'SendStreamingMessage',\n 'GetTask',\n 'ListTasks',\n 'CancelTask',\n 'SubscribeToTask',\n ...A2A_PUSH_CONFIG_METHODS,\n 'GetExtendedAgentCard',\n];\n\n/**\n * Methods A2A gives an agent no capability flag to decline. No task can be\n * read back or canceled, so they answer `TaskNotFoundError`.\n */\nexport const A2A_TASK_LOOKUP_METHODS: readonly string[] = ['GetTask', 'CancelTask'];\n\n/**\n * Terminal states for completed and failed calls. An unpaid x402 extension\n * task instead waits in `TASK_STATE_INPUT_REQUIRED`. `GetTask` finds no task\n * in any state.\n */\nexport const A2A_TASK_STATE_COMPLETED = 'TASK_STATE_COMPLETED';\nexport const A2A_TASK_STATE_FAILED = 'TASK_STATE_FAILED';\n\n/** An unpaid x402 extension task waiting for a payment message */\nexport const A2A_TASK_STATE_INPUT_REQUIRED = 'TASK_STATE_INPUT_REQUIRED';\n\n/** Extension activation header, a comma-separated list of extension URIs */\nexport const A2A_EXTENSIONS_HEADER = 'a2a-extensions';\n","/**\n * JSON-RPC 2.0 framing for the A2A binding.\n *\n * Transport errors only: this file decides whether a request *is* a valid A2A\n * JSON-RPC call, never what the call means. Commerce outcomes are mapped\n * elsewhere, so a malformed frame and a refused purchase can never be\n * confused for one another.\n *\n * Every JSON-RPC-level failure is returned as a 200 with an `error` member,\n * per the JSON-RPC over HTTP convention A2A clients expect; HTTP status codes\n * are reserved for things that are not JSON-RPC at all (wrong verb, adapter\n * down).\n */\nimport { isRecord } from '../../core/is-record';\n\n/** JSON-RPC 2.0 reserved codes */\nexport const JSONRPC_PARSE_ERROR = -32700;\nexport const JSONRPC_INVALID_REQUEST = -32600;\nexport const JSONRPC_METHOD_NOT_FOUND = -32601;\nexport const JSONRPC_INVALID_PARAMS = -32602;\nexport const JSONRPC_INTERNAL_ERROR = -32603;\n\n/** A2A `TaskNotFoundError` for a task id this stateless adapter cannot find */\nexport const A2A_ERROR_TASK_NOT_FOUND = -32001;\n\n/** A2A `PushNotificationNotSupportedError` for push configuration methods */\nexport const A2A_ERROR_PUSH_NOTIFICATION_NOT_SUPPORTED = -32003;\n\n/**\n * A2A `UnsupportedOperationError` for a known operation or message feature\n * this adapter does not serve. Unknown methods use `METHOD_NOT_FOUND`.\n */\nexport const A2A_ERROR_UNSUPPORTED_OPERATION = -32004;\n\n/** A2A `ContentTypeNotSupportedError` for a non-JSON structured data part */\nexport const A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED = -32005;\n\n/** A2A `VersionNotSupportedError` when the requested major.minor is unsupported */\nexport const A2A_ERROR_VERSION_NOT_SUPPORTED = -32009;\n\n// Use the A2A error name without its `Error` suffix as the ErrorInfo reason.\n// Standard JSON-RPC codes carry no A2A error detail.\nconst A2A_ERROR_REASONS: ReadonlyMap<number, string> = new Map([\n [A2A_ERROR_TASK_NOT_FOUND, 'TASK_NOT_FOUND'],\n [A2A_ERROR_PUSH_NOTIFICATION_NOT_SUPPORTED, 'PUSH_NOTIFICATION_NOT_SUPPORTED'],\n [A2A_ERROR_UNSUPPORTED_OPERATION, 'UNSUPPORTED_OPERATION'],\n [A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED, 'CONTENT_TYPE_NOT_SUPPORTED'],\n [A2A_ERROR_VERSION_NOT_SUPPORTED, 'VERSION_NOT_SUPPORTED'],\n]);\n\n/** An id may legally be a string, a number or null; anything else is not one */\nexport type JsonRpcId = string | number | null;\n\nexport interface JsonRpcErrorBody {\n readonly code: number;\n readonly message: string;\n readonly data?: readonly Record<string, unknown>[];\n}\n\nexport interface JsonRpcRequest {\n readonly id: JsonRpcId;\n readonly method: string;\n readonly params: unknown;\n}\n\nexport type JsonRpcParseResult =\n | { readonly ok: true; readonly request: JsonRpcRequest }\n | { readonly ok: false; readonly id: JsonRpcId; readonly error: JsonRpcErrorBody };\n\n// Echoed back only when the request carried a usable one\nfunction readId(value: unknown): JsonRpcId {\n if (typeof value === 'string' || typeof value === 'number') return value;\n return null;\n}\n\nexport function jsonRpcResult(id: JsonRpcId, result: unknown): Record<string, unknown> {\n return { jsonrpc: '2.0', id, result };\n}\n\n/**\n * Add `google.rpc.ErrorInfo` to the detail array for A2A-specific errors.\n */\nexport function jsonRpcError(\n id: JsonRpcId,\n code: number,\n message: string,\n): Record<string, unknown> {\n const reason = A2A_ERROR_REASONS.get(code);\n const error: JsonRpcErrorBody = {\n code,\n message,\n ...(reason !== undefined\n ? {\n data: [\n {\n '@type': 'type.googleapis.com/google.rpc.ErrorInfo',\n reason,\n domain: 'a2a-protocol.org',\n },\n ],\n }\n : {}),\n };\n return { jsonrpc: '2.0', id, error };\n}\n\nexport function parseJsonRpcRequest(rawBody: string): JsonRpcParseResult {\n let payload: unknown;\n try {\n payload = JSON.parse(rawBody);\n } catch {\n // The parser's own message names offsets and input fragments; neither is\n // the caller's business, and echoing input is how bodies get reflected\n return { ok: false, id: null, error: { code: JSONRPC_PARSE_ERROR, message: 'Invalid JSON.' } };\n }\n\n if (Array.isArray(payload)) {\n return {\n ok: false,\n id: null,\n error: {\n code: JSONRPC_INVALID_REQUEST,\n message: 'Batch requests are not supported: send a single JSON-RPC request object.',\n },\n };\n }\n if (!isRecord(payload)) {\n return {\n ok: false,\n id: null,\n error: { code: JSONRPC_INVALID_REQUEST, message: 'Request must be a JSON-RPC 2.0 object.' },\n };\n }\n\n const id = readId(payload['id']);\n // Notifications have no reply. Reject them before they can run or charge.\n if (payload['id'] === undefined) {\n return {\n ok: false,\n id,\n error: {\n code: JSONRPC_INVALID_REQUEST,\n message: 'Request must include an \"id\"; notifications are unsupported.',\n },\n };\n }\n if (payload['jsonrpc'] !== '2.0') {\n return {\n ok: false,\n id,\n error: { code: JSONRPC_INVALID_REQUEST, message: 'Request must set \"jsonrpc\" to \"2.0\".' },\n };\n }\n const method = payload['method'];\n if (typeof method !== 'string' || method.length === 0) {\n return {\n ok: false,\n id,\n error: { code: JSONRPC_INVALID_REQUEST, message: 'Request must carry a \"method\" string.' },\n };\n }\n const params = payload['params'];\n if (params !== undefined && !isRecord(params)) {\n return {\n ok: false,\n id,\n error: {\n code: JSONRPC_INVALID_PARAMS,\n message: 'Request \"params\" must be an object.',\n },\n };\n }\n\n return { ok: true, request: { id, method, params: params ?? {} } };\n}\n","/**\n * The Agent Commerce invocation envelope for A2A.\n *\n * A2A has no `skillId` on a request: `SendMessage` carries a message, not a\n * tool call, so which canonical resource a caller wants has to be stated\n * somewhere the protocol leaves open. That place is a structured data part:\n *\n * ```json\n * { \"message\": { \"role\": \"ROLE_USER\", \"messageId\": \"msg-1\",\n * \"parts\": [{ \"data\": { \"resource\": \"market_report\",\n * \"input\": { \"symbol\": \"ETH\" } },\n * \"mediaType\": \"application/json\" }] } }\n * ```\n *\n * Payment and authorization proofs ride in the reserved `_payment` and\n * `_authorization` input fields, as over MCP; there is no A2A-specific\n * representation.\n *\n * The accepted shape is narrow on purpose. Everything richer that A2A allows\n * (text parts, files, multi-part messages, task continuation) is rejected:\n * `INPUT_INVALID` for a malformed envelope, `PROTOCOL_UNSUPPORTED` for a legal\n * A2A message this adapter does not serve. `details.a2aErrorCode` carries a\n * more specific JSON-RPC code when one applies. Taking the first of several\n * data parts, for example, could execute a paid call the buyer did not mean\n * to make.\n */\nimport { z } from 'zod';\nimport { CommerceError } from '../../core';\nimport { isRecord } from '../../core/is-record';\nimport { A2A_JSON_MEDIA_TYPE } from './constants';\nimport { A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED, A2A_ERROR_TASK_NOT_FOUND } from './jsonrpc';\n\n// The only role a request message may carry. A2A v1 spells roles this way\nconst A2A_USER_ROLE = 'ROLE_USER';\n\n/** The one message shape that calls a skill, as refusals and the Agent Card name it */\nexport const A2A_CALL_SHAPE = 'one data part {\"resource\": \"<skill id>\", \"input\": {...}}';\n\n/**\n * The refusal for a role other than `ROLE_USER`, or undefined. An A2A 0.x\n * client sends `user`, so this is what turns its messages away.\n */\nexport function userRoleProblem(role: unknown): string | undefined {\n return role === A2A_USER_ROLE\n ? undefined\n : `Unsupported message role \"${String(role)}\": only ${A2A_USER_ROLE} is accepted.`;\n}\n\n/** What a supported envelope reduces to. Nothing protocol-shaped survives */\nexport interface A2aInvocation {\n readonly resourceId: string;\n readonly input: Record<string, unknown>;\n /** Client-assigned message id */\n readonly messageId: string;\n}\n\n/**\n * Shape only; every semantic rule is checked below, where the failure can name\n * itself. Parts stay untyped records: zod would collapse a file part and a\n * malformed one into the same union failure.\n */\nconst UnknownRecord = z.record(z.string(), z.unknown());\n\nconst MessageSchema = z.object({\n role: z.string(),\n messageId: z.string().optional(),\n parts: z.array(UnknownRecord),\n taskId: z.string().optional(),\n contextId: z.string().optional(),\n referenceTaskIds: z.array(z.string()).optional(),\n});\n\nconst ParamsSchema = z.object({\n message: MessageSchema,\n taskId: z.string().optional(),\n contextId: z.string().optional(),\n});\n\nfunction invalid(message: string): CommerceError {\n return new CommerceError('INPUT_INVALID', message);\n}\n\nfunction unsupported(message: string, a2aErrorCode?: number): CommerceError {\n return new CommerceError(\n 'PROTOCOL_UNSUPPORTED',\n message,\n a2aErrorCode !== undefined ? { details: { a2aErrorCode } } : {},\n );\n}\n\n/**\n * Continuation is refused rather than ignored: a caller resuming a task would\n * otherwise get a fresh, independently billed execution back and no signal\n * that their task id meant nothing here. Since this adapter stores no tasks,\n * it returns `TaskNotFoundError` for every supplied task id.\n */\nfunction assertNoContinuation(params: z.infer<typeof ParamsSchema>): void {\n const message = params.message;\n if (params.taskId !== undefined || message.taskId !== undefined) {\n throw unsupported(\n 'Task not found: tasks are not persisted, so send a request with no taskId.',\n A2A_ERROR_TASK_NOT_FOUND,\n );\n }\n if (params.contextId !== undefined || message.contextId !== undefined) {\n throw unsupported(\n 'Multi-turn conversational continuation is not supported: send a request with no contextId.',\n );\n }\n if (message.referenceTaskIds !== undefined && message.referenceTaskIds.length > 0) {\n throw unsupported('Referencing previous tasks is not supported.');\n }\n}\n\n/**\n * Names the part kind so a caller learns which of theirs is the problem.\n *\n * A2A v1 gives `Part` a content oneof (`text`, `data`, `raw` for inline bytes,\n * or `url`) with `filename` and `mediaType` beside it, where v0.3 used a\n * nested `file` object. Both spellings are refused as unsupported, so a\n * v0.3-shaped client is not told its envelope is malformed.\n */\nfunction assertSupportedPart(part: Record<string, unknown>): void {\n if ('file' in part || 'raw' in part || 'url' in part) {\n throw unsupported(\n `File and URL parts are not supported: send ${A2A_CALL_SHAPE}.`,\n A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED,\n );\n }\n if ('text' in part) {\n throw unsupported(\n `Text parts are not supported: send ${A2A_CALL_SHAPE}.`,\n A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED,\n );\n }\n if (!('data' in part)) {\n throw invalid('Message part carries no \"data\": send a structured data part.');\n }\n const mediaType = part['mediaType'];\n if (mediaType !== undefined && mediaType !== A2A_JSON_MEDIA_TYPE) {\n throw unsupported(\n `Media type \"${String(mediaType)}\" is not supported: parts must be ${A2A_JSON_MEDIA_TYPE}.`,\n A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED,\n );\n }\n}\n\n/**\n * Turns `SendMessage` params into a resource id and an input object, or throws\n * a `CommerceError`. Pure: it resolves no resource and touches no payment.\n */\nexport function parseInvocation(rawParams: unknown): A2aInvocation {\n const parsed = ParamsSchema.safeParse(rawParams);\n if (!parsed.success) {\n throw invalid(\n 'Request must carry a \"message\" with a \"role\" and a \"parts\" array of structured data parts.',\n );\n }\n const params = parsed.data;\n const message = params.message;\n // A2A requires a message id. This adapter also rejects an empty one.\n if (message.messageId === undefined || message.messageId.length === 0) {\n throw invalid('Message must carry a non-empty \"messageId\".');\n }\n const messageId = message.messageId;\n\n assertNoContinuation(params);\n\n const roleProblem = userRoleProblem(message.role);\n if (roleProblem !== undefined) throw invalid(roleProblem);\n if (message.parts.length === 0) {\n throw invalid('Message carries no parts: send exactly one structured data part.');\n }\n if (message.parts.length > 1) {\n throw unsupported(\n `Multi-part messages are not supported: send exactly one structured data part (received ${message.parts.length}).`,\n );\n }\n\n const part = message.parts[0];\n if (part === undefined) throw invalid('Message carries no parts.');\n assertSupportedPart(part);\n\n const data = part['data'];\n if (!isRecord(data)) {\n throw invalid('Message part \"data\" must be a JSON object.');\n }\n\n const resourceId = data['resource'];\n if (typeof resourceId !== 'string') {\n throw invalid('Message part data must carry a \"resource\" string naming a canonical resource.');\n }\n if (resourceId.length === 0) {\n throw invalid('Message part data \"resource\" must not be empty.');\n }\n\n const rawInput = data['input'];\n // Absent means \"no arguments\", which is a real case for a zero-input\n // resource. Present-but-not-an-object is a mistake, never an empty call.\n if (rawInput !== undefined && !isRecord(rawInput)) {\n throw invalid('Message part data \"input\" must be a JSON object.');\n }\n\n return { resourceId, input: rawInput ?? {}, messageId };\n}\n","/**\n * x402 payment over A2A. The x402 v2 transport puts payment documents in\n * message metadata and resumes an input-required task with a payment message.\n * This adapter uses A2A 1.0 states, roles, parts and extension headers.\n * Clients that do not activate the extension use `_payment` on a new task.\n */\nimport {\n AUTHORIZATION_INPUT_FIELD,\n type AuthorizationSubmission,\n type Clock,\n type CommerceError,\n type PaymentResult,\n parseAuthorizationSubmission,\n} from '../../core';\nimport { isRecord } from '../../core/is-record';\nimport {\n settlementFailure,\n settlementResponse,\n settlementResponseFromDetails,\n x402ErrorCode,\n} from '../../payments/x402/transport';\n\n/** The URI the x402 A2A transport declares for the extension */\nexport const A2A_X402_EXTENSION_URI = 'https://github.com/google-a2a/a2a-x402/v0.1';\n\n/** The x402 protocol version of every document the extension carries */\nexport const A2A_X402_PROTOCOL_VERSION = 2;\n\nexport const X402_PAYMENT_STATUS_KEY = 'x402.payment.status';\nexport const X402_PAYMENT_REQUIRED_KEY = 'x402.payment.required';\nexport const X402_PAYMENT_PAYLOAD_KEY = 'x402.payment.payload';\nexport const X402_PAYMENT_RECEIPTS_KEY = 'x402.payment.receipts';\nexport const X402_PAYMENT_ERROR_KEY = 'x402.payment.error';\n\n// How long an unpaid task waits when the requirement names no expiry, and the\n// longest it waits regardless\nconst DEFAULT_PENDING_TTL_MS = 10 * 60 * 1000;\nconst MAX_PENDING_TTL_MS = 60 * 60 * 1000;\n\n// Bound memory used by unpaid tasks from unauthenticated callers. Each task\n// holds one request's input. A full store refuses new purchases rather than\n// evicting a live one, whose buyer may already have signed.\nconst MAX_PENDING_PAYMENTS = 256;\n\n/** `A2A-Extensions` is a comma-separated URI list, possibly repeated */\nexport function requestsX402Extension(header: string | readonly string[] | undefined): boolean {\n const values = typeof header === 'string' ? [header] : (header ?? []);\n return values.some((value) =>\n value.split(',').some((uri) => uri.trim() === A2A_X402_EXTENSION_URI),\n );\n}\n\n/** A purchase waiting for its payment, held between the two messages */\nexport interface PendingPayment {\n readonly contextId: string;\n readonly resourceId: string;\n /** Validated by the pipeline again when the payment arrives */\n readonly input: Record<string, unknown>;\n readonly authorization?: AuthorizationSubmission;\n /** Network of the requirement, for a failure receipt whose error names none */\n readonly network?: string;\n readonly expiresAtMs: number;\n}\n\n/**\n * Unpaid tasks, in memory and per process. A restart, or a payment routed to\n * another instance, loses the task: the client gets `TaskNotFoundError` before\n * anything is verified or settled, and starts over.\n */\nexport function createPendingPayments(clock: Clock, maxEntries = MAX_PENDING_PAYMENTS) {\n const tasks = new Map<string, PendingPayment>();\n const now = (): number => clock.now().getTime();\n\n function purgeExpired(): void {\n const at = now();\n for (const [taskId, pending] of tasks) {\n if (pending.expiresAtMs <= at) tasks.delete(taskId);\n }\n }\n\n return {\n /** Holds a purchase until `expiresAt`; returns false, holding nothing, when full */\n put(taskId: string, pending: Omit<PendingPayment, 'expiresAtMs'>, expiresAt?: string): boolean {\n purgeExpired();\n if (tasks.size >= maxEntries) return false;\n const requested = expiresAt !== undefined ? Date.parse(expiresAt) : Number.NaN;\n const ttl = Number.isFinite(requested) ? requested - now() : DEFAULT_PENDING_TTL_MS;\n const expiresAtMs = now() + Math.min(Math.max(ttl, 0), MAX_PENDING_TTL_MS);\n tasks.set(taskId, { ...pending, expiresAtMs });\n return true;\n },\n\n get(taskId: string): PendingPayment | undefined {\n const pending = tasks.get(taskId);\n if (pending === undefined) return undefined;\n if (pending.expiresAtMs <= now()) {\n tasks.delete(taskId);\n return undefined;\n }\n return pending;\n },\n\n delete(taskId: string): void {\n tasks.delete(taskId);\n },\n\n size(): number {\n return tasks.size;\n },\n\n clear(): void {\n tasks.clear();\n },\n };\n}\n\nexport type PendingPayments = ReturnType<typeof createPendingPayments>;\n\n/** What a follow-up message on a pending task asks for */\nexport type PaymentSubmissionMessage =\n | { readonly kind: 'submitted'; readonly payload: Record<string, unknown> }\n | { readonly kind: 'rejected' };\n\n/** Reads the payment status and payload from a message's metadata */\nexport function readPaymentSubmission(message: unknown): PaymentSubmissionMessage | undefined {\n const metadata = isRecord(message) ? message['metadata'] : undefined;\n if (!isRecord(metadata)) return undefined;\n const status = metadata[X402_PAYMENT_STATUS_KEY];\n if (status === 'payment-rejected') return { kind: 'rejected' };\n const payload = metadata[X402_PAYMENT_PAYLOAD_KEY];\n if (status === 'payment-submitted' && isRecord(payload)) return { kind: 'submitted', payload };\n return undefined;\n}\n\n/**\n * Read `input._authorization` from a payment message. Ignore other input;\n * the task already holds the purchase. Malformed mandates raise\n * `AUTHORIZATION_INVALID`.\n */\nexport function readFollowUpAuthorization(message: unknown): AuthorizationSubmission | undefined {\n const parts = isRecord(message) ? message['parts'] : undefined;\n if (!Array.isArray(parts)) return undefined;\n for (const part of parts) {\n const data: unknown = isRecord(part) ? part['data'] : undefined;\n const input = isRecord(data) ? data['input'] : undefined;\n if (isRecord(input) && input[AUTHORIZATION_INPUT_FIELD] !== undefined) {\n return parseAuthorizationSubmission(input[AUTHORIZATION_INPUT_FIELD]);\n }\n }\n return undefined;\n}\n\nexport function paymentRequiredMetadata(\n envelope: Record<string, unknown>,\n): Record<string, unknown> {\n return {\n [X402_PAYMENT_STATUS_KEY]: 'payment-required',\n [X402_PAYMENT_REQUIRED_KEY]: envelope,\n };\n}\n\nexport function paymentCompletedMetadata(payment: PaymentResult): Record<string, unknown> {\n return {\n [X402_PAYMENT_STATUS_KEY]: 'payment-completed',\n [X402_PAYMENT_RECEIPTS_KEY]: [settlementResponse(payment)],\n };\n}\n\n/**\n * A failure after a payment submission. A backend failure after settlement\n * still reports the payment as completed, with its receipt: the money moved.\n * `network` is the requirement's.\n */\nexport function paymentFailureMetadata(\n error: CommerceError,\n network?: string,\n): Record<string, unknown> {\n const settled = settlementResponseFromDetails(error.details);\n if (settled !== undefined && settled['success'] === true) {\n return {\n [X402_PAYMENT_STATUS_KEY]: 'payment-completed',\n [X402_PAYMENT_RECEIPTS_KEY]: [settled],\n };\n }\n // A backend failure before settlement keeps its own commerce error code.\n const code = error.code.startsWith('PAYMENT_')\n ? x402ErrorCode(error.code, error.details?.['reason'], error.details?.['network'])\n : error.code.toLowerCase();\n const failure = settlementFailure(error.details);\n const receipt =\n failure['network'] === '' && network !== undefined ? { ...failure, network } : failure;\n return {\n [X402_PAYMENT_STATUS_KEY]: 'payment-failed',\n [X402_PAYMENT_ERROR_KEY]: code,\n // Keep the failure reason, including `settlement_pending` when a hash is known\n [X402_PAYMENT_RECEIPTS_KEY]: [\n error.details?.['settlementUncertain'] === true ? receipt : { ...receipt, errorReason: code },\n ],\n };\n}\n\nexport function paymentRejectedMetadata(): Record<string, unknown> {\n return { [X402_PAYMENT_STATUS_KEY]: 'payment-rejected' };\n}\n","/**\n * Builds the A2A v1 Agent Card from canonical resources.\n *\n * One skill per resource exposed via `expose: [a2a]`, skill id = resource id.\n * A2A has no field for a skill's input schema, so the card shows the call\n * shape through fields it does define: a sentence in the agent description,\n * which also says where the schemas are published, and one example per skill.\n */\nimport { AUTHORIZATION_INPUT_FIELD, type CommerceResource, PAYMENT_INPUT_FIELD } from '../../core';\nimport { isRecord } from '../../core/is-record';\nimport { joinUrl } from '../http';\nimport { A2A_JSON_MEDIA_TYPE, A2A_PROTOCOL_BINDING, A2A_PROTOCOL_VERSION } from './constants';\nimport { A2A_CALL_SHAPE } from './message-mapping';\nimport type { A2aAgentCard, A2aAgentSkill } from './types';\nimport { A2A_X402_EXTENSION_URI, A2A_X402_PROTOCOL_VERSION } from './x402-extension';\n\n// The gateway route that lists every resource with its input schema\nconst RESOURCES_PATH = '/api/resources';\n\nexport interface AgentCardOptions {\n readonly name: string;\n readonly description: string;\n /** Version of this gateway build, not of the protocol */\n readonly version: string;\n /** Externally reachable gateway base URL, from configuration */\n readonly publicBaseUrl: string;\n /** Gateway path the JSON-RPC endpoint is mounted at */\n readonly mountPath: string;\n readonly resources: readonly CommerceResource[];\n}\n\n/**\n * Free/paid is on the card because a caller choosing between skills should not\n * have to attempt a call to discover one costs money. The price itself is in\n * the description, where a human-readable amount belongs.\n */\nfunction skillTags(resource: CommerceResource): string[] {\n return ['agent-commerce', resource.pricing.type === 'free' ? 'free' : 'paid'];\n}\n\nfunction skillDescription(resource: CommerceResource): string {\n const base = resource.description ?? resource.name;\n if (resource.pricing.type === 'fixed') {\n return `${base} Costs ${resource.pricing.amount} ${resource.pricing.currency} per call.`;\n }\n if (resource.pricing.type === 'dynamic') {\n return `${base} Requires payment (amount determined at request time).`;\n }\n return base;\n}\n\n/**\n * Build a sample from schema examples, defaults, enum values or the declared\n * type. Objects include required properties only. Other constraints may need\n * different input.\n */\nfunction exampleValue(schema: unknown, name: string): unknown {\n if (!isRecord(schema)) return `<${name}>`;\n const examples = schema['examples'];\n if (Array.isArray(examples) && examples.length > 0) return examples[0];\n if (schema['default'] !== undefined) return schema['default'];\n const allowed = schema['enum'];\n if (Array.isArray(allowed) && allowed.length > 0) return allowed[0];\n const declared = schema['type'];\n const type: unknown = Array.isArray(declared) ? declared[0] : declared;\n switch (type) {\n case 'object':\n return exampleObject(schema);\n case 'array':\n return schema['items'] !== undefined ? [exampleValue(schema['items'], name)] : [];\n case 'number':\n case 'integer':\n return 0;\n case 'boolean':\n return false;\n case 'null':\n return null;\n default:\n return `<${name}>`;\n }\n}\n\nfunction exampleObject(schema: Record<string, unknown>): Record<string, unknown> {\n const properties = isRecord(schema['properties']) ? schema['properties'] : {};\n const required = Array.isArray(schema['required']) ? schema['required'] : [];\n const example: Record<string, unknown> = {};\n for (const key of required) {\n // The reserved fields carry proofs, which no example can hold\n if (typeof key !== 'string' || key === PAYMENT_INPUT_FIELD || key === AUTHORIZATION_INPUT_FIELD)\n continue;\n example[key] = exampleValue(properties[key], key);\n }\n return example;\n}\n\n/** The `data` value of a data part that calls the skill, as JSON */\nfunction skillExample(resource: CommerceResource): string {\n return JSON.stringify({\n resource: resource.id,\n input: exampleObject(resource.inputSchema ?? {}),\n });\n}\n\nfunction buildAgentSkill(resource: CommerceResource): A2aAgentSkill {\n return {\n id: resource.id,\n name: resource.name,\n description: skillDescription(resource),\n tags: skillTags(resource),\n examples: [skillExample(resource)],\n inputModes: [A2A_JSON_MEDIA_TYPE],\n outputModes: [A2A_JSON_MEDIA_TYPE],\n };\n}\n\nfunction agentDescription(options: AgentCardOptions): string {\n const call = `Call a skill by sending ${A2A_CALL_SHAPE} with media type ${A2A_JSON_MEDIA_TYPE}. Each skill has an example; input schemas are at ${joinUrl(options.publicBaseUrl, RESOURCES_PATH)}.`;\n const pay = options.resources.some((resource) => resource.pricing.type !== 'free')\n ? ` For paid skills, retry with a payment proof in \"input.${PAYMENT_INPUT_FIELD}\".`\n : '';\n return `${options.description} ${call}${pay}`;\n}\n\nexport function buildAgentCard(options: AgentCardOptions): A2aAgentCard {\n return {\n name: options.name,\n description: agentDescription(options),\n version: options.version,\n supportedInterfaces: [\n {\n url: joinUrl(options.publicBaseUrl, options.mountPath),\n protocolBinding: A2A_PROTOCOL_BINDING,\n protocolVersion: A2A_PROTOCOL_VERSION,\n },\n ],\n capabilities: {\n streaming: false,\n pushNotifications: false,\n extendedAgentCard: false,\n // Only a skill whose rail is x402 can be paid through the extension.\n // Not required: `_payment` keeps working for clients without it.\n ...(options.resources.some((resource) => resource.paymentMethods[0] === 'x402')\n ? {\n extensions: [\n {\n uri: A2A_X402_EXTENSION_URI,\n description: 'x402 payments: input-required tasks carrying x402 v2 documents.',\n required: false,\n // Lets a client holding an x402 v1 library tell before it pays\n params: { x402Version: A2A_X402_PROTOCOL_VERSION },\n },\n ],\n }\n : {}),\n },\n defaultInputModes: [A2A_JSON_MEDIA_TYPE],\n defaultOutputModes: [A2A_JSON_MEDIA_TYPE],\n skills: options.resources.map(buildAgentSkill),\n };\n}\n","/**\n * Adapter self-description.\n *\n * `supportedSpec` is the A2A specification revision (`1.0.1`), never the\n * negotiation version (`1.0`) and never this package's version. Status is\n * `experimental` while the adapter lacks the features in the unsupported list\n * below; an entry leaves that list only when its feature is implemented.\n */\nimport type { AdapterDescriptor } from '../../core';\nimport { A2A_SPEC_VERSION, A2A_UNSUPPORTED_METHODS } from './constants';\n\n// What this adapter implements\nconst A2A_CAPABILITIES: readonly string[] = [\n 'agent-card',\n 'jsonrpc',\n 'SendMessage',\n // The x402 A2A transport, opt-in per request\n 'x402-extension',\n];\n\n/**\n * Major A2A features this adapter does not implement, served on\n * `/.well-known/agent-commerce` and printed by `doctor`, so no client assumes\n * full protocol support\n */\nexport const A2A_UNSUPPORTED: readonly string[] = [\n // Methods, as the protocol names them; the transport refuses the same list\n ...A2A_UNSUPPORTED_METHODS,\n // Transports other than the one binding served\n 'HTTP+JSON/REST binding',\n 'gRPC binding',\n // Behaviors\n 'SSE',\n 'long-running task persistence',\n 'task resumption other than an x402 extension payment',\n 'push notifications',\n 'multi-turn conversational continuation',\n 'authenticated extended agent cards',\n 'A2A authentication schemes',\n 'artifact types beyond Agent Commerce outcome data',\n // Pending x402 payments live in process memory\n 'x402 extension payments across gateway restarts or instances',\n];\n\nexport function buildDescriptor(implementationVersion: string): AdapterDescriptor {\n return {\n name: 'a2a',\n kind: 'protocol',\n implementationVersion,\n supportedSpec: A2A_SPEC_VERSION,\n capabilities: A2A_CAPABILITIES,\n status: 'experimental',\n unsupported: A2A_UNSUPPORTED,\n };\n}\n","/**\n * Execution outcomes as terminal A2A Tasks.\n *\n * A2A models an execution's output as a Task carrying Artifacts, so a\n * completed purchase comes back as one, not as a plain Message, which models\n * conversation.\n *\n * A commerce outcome is never a JSON-RPC error. Payment required, an unknown\n * resource, input the resource schema rejects and a broken backend are all\n * answers, returned as a terminal Task in the JSON-RPC `result`. Only a\n * malformed or unsupported A2A request gets a JSON-RPC error, so a client can\n * tell a refused purchase from a broken gateway.\n *\n * Every artifact payload is an existing canonical envelope, verbatim: there is\n * no A2A-specific delivery, payment-required or error schema.\n */\nimport {\n type CommerceError,\n DELIVERY_SUMMARY_META_KEY,\n type DeliveredOutcome,\n type PaymentRequiredOutcome,\n toDeliverySummary,\n toErrorEnvelope,\n toPaymentRequiredEnvelope,\n} from '../../core';\nimport { isRecord } from '../../core/is-record';\nimport {\n A2A_JSON_MEDIA_TYPE,\n A2A_TASK_STATE_COMPLETED,\n A2A_TASK_STATE_FAILED,\n A2A_TASK_STATE_INPUT_REQUIRED,\n} from './constants';\nimport type { A2aArtifact, A2aTask } from './types';\nimport { A2A_X402_EXTENSION_URI } from './x402-extension';\n\nexport interface TaskIdentity {\n /** Gateway request id, reused so a task correlates with receipts and events */\n readonly taskId: string;\n /** Fresh for each purchase; a pending x402 payment keeps this context */\n readonly contextId: string;\n readonly artifactId: string;\n /** Id of the agent message on the task status */\n readonly statusMessageId: string;\n readonly timestamp: string;\n}\n\n/**\n * A data part's payload must be a JSON object, but a merchant backend may\n * return a string, a number or an array. Those are wrapped under `value`, one\n * predictable rule a caller can code against.\n */\nfunction dataPayload(body: unknown): Record<string, unknown> {\n return isRecord(body) ? body : { value: body ?? null };\n}\n\nfunction task(\n identity: TaskIdentity,\n state: string,\n artifact: Omit<A2aArtifact, 'artifactId'>,\n): A2aTask {\n return {\n id: identity.taskId,\n contextId: identity.contextId,\n status: { state, timestamp: identity.timestamp },\n artifacts: [{ artifactId: identity.artifactId, ...artifact }],\n };\n}\n\nexport function completedTask(outcome: DeliveredOutcome, identity: TaskIdentity): A2aTask {\n return task(identity, A2A_TASK_STATE_COMPLETED, {\n name: outcome.resourceId,\n parts: [{ data: dataPayload(outcome.body), mediaType: A2A_JSON_MEDIA_TYPE }],\n // Same meta key MCP attaches its summary under, so a buyer reads the\n // record of their own purchase the same way on either protocol\n metadata: { [DELIVERY_SUMMARY_META_KEY]: { ...toDeliverySummary(outcome) } },\n });\n}\n\n/**\n * Without the x402 extension, payment required ends the task. The client\n * starts a new one with `_payment`. With the extension, `inputRequired` keeps\n * this task open for a payment message.\n */\nexport function paymentRequiredTask(\n outcome: PaymentRequiredOutcome,\n identity: TaskIdentity,\n): A2aTask {\n const envelope = toPaymentRequiredEnvelope(outcome);\n return withStatusMessage(\n task(identity, A2A_TASK_STATE_FAILED, {\n name: outcome.resourceId,\n parts: [{ data: { ...envelope }, mediaType: A2A_JSON_MEDIA_TYPE }],\n }),\n envelope.message,\n identity.statusMessageId,\n );\n}\n\n/** The same task waiting for payment, with the extension's metadata on its status message */\nexport function inputRequired(\n base: A2aTask,\n metadata: Record<string, unknown>,\n messageId: string,\n): A2aTask {\n return withStatusMessage(\n { ...base, status: { ...base.status, state: A2A_TASK_STATE_INPUT_REQUIRED } },\n 'Payment is required. Send the x402 payment payload on this task.',\n messageId,\n metadata,\n );\n}\n\n/** Set the agent status message; metadata marks x402 extension use */\nexport function withStatusMessage(\n base: A2aTask,\n text: string,\n messageId: string,\n metadata?: Record<string, unknown>,\n): A2aTask {\n return {\n ...base,\n status: {\n ...base.status,\n message: {\n role: 'ROLE_AGENT',\n messageId,\n contextId: base.contextId,\n taskId: base.id,\n parts: [{ text }],\n ...(metadata !== undefined ? { metadata, extensions: [A2A_X402_EXTENSION_URI] } : {}),\n },\n },\n };\n}\n\n/** Put the error envelope in the artifact and its message in task status */\nexport function failedTask(error: CommerceError, identity: TaskIdentity): A2aTask {\n const envelope = toErrorEnvelope(error);\n return withStatusMessage(\n task(identity, A2A_TASK_STATE_FAILED, {\n parts: [{ data: { ...envelope }, mediaType: A2A_JSON_MEDIA_TYPE }],\n }),\n envelope.message,\n identity.statusMessageId,\n );\n}\n","// Completing a purchase that waits for an x402 extension payment, from the follow-up message that pays or declines it\nimport type { CanonicalRequest, ProtocolAdapterContext } from '../../core';\nimport { CommerceError, toCommerceError } from '../../core';\nimport { toLogInfo } from '../../core/errors';\nimport { isRecord } from '../../core/is-record';\nimport { A2A_TASK_STATE_FAILED } from './constants';\nimport { JSONRPC_INVALID_PARAMS, type JsonRpcId, jsonRpcError, jsonRpcResult } from './jsonrpc';\nimport { userRoleProblem } from './message-mapping';\nimport { completedTask, failedTask, type TaskIdentity, withStatusMessage } from './task-mapping';\nimport type { A2aTask } from './types';\nimport {\n type PendingPayment,\n type PendingPayments,\n paymentCompletedMetadata,\n paymentFailureMetadata,\n paymentRejectedMetadata,\n readFollowUpAuthorization,\n readPaymentSubmission,\n X402_PAYMENT_PAYLOAD_KEY,\n X402_PAYMENT_STATUS_KEY,\n} from './x402-extension';\n\n/** A2A's JSON-RPC result wraps the terminal task */\nexport function taskResult(id: JsonRpcId, task: A2aTask): Record<string, unknown> {\n return jsonRpcResult(id, { task });\n}\n\n/**\n * A message on a task waiting for an x402 extension payment, recognized by\n * its `taskId` whether or not the header activated the extension again. Any\n * other task id falls through to `parseInvocation`, which answers TaskNotFoundError.\n */\nexport async function resumePayment(\n context: ProtocolAdapterContext | undefined,\n pendingPayments: PendingPayments | undefined,\n id: JsonRpcId,\n params: unknown,\n): Promise<Record<string, unknown> | undefined> {\n const message = isRecord(params) ? params['message'] : undefined;\n const taskId = isRecord(message) ? message['taskId'] : undefined;\n if (context === undefined || typeof taskId !== 'string') return undefined;\n const pending = pendingPayments?.get(taskId);\n if (pending === undefined) return undefined;\n\n const messageId = isRecord(message) ? message['messageId'] : undefined;\n if (typeof messageId !== 'string' || messageId.length === 0) {\n return jsonRpcError(id, JSONRPC_INVALID_PARAMS, 'Message must carry a non-empty \"messageId\".');\n }\n // Apply the same role check as a new purchase\n const roleProblem = userRoleProblem(isRecord(message) ? message['role'] : undefined);\n if (roleProblem !== undefined) return jsonRpcError(id, JSONRPC_INVALID_PARAMS, roleProblem);\n // Reject a mismatched context without consuming the pending task.\n const contextId = isRecord(message) ? message['contextId'] : undefined;\n if (contextId !== undefined && contextId !== pending.contextId) {\n return jsonRpcError(id, JSONRPC_INVALID_PARAMS, 'Message \"contextId\" does not match the task.');\n }\n const submission = readPaymentSubmission(message);\n if (submission === undefined) {\n // The task stays pending, so a corrected message can still pay it\n return jsonRpcError(\n id,\n JSONRPC_INVALID_PARAMS,\n `For a pending task, set \"${X402_PAYMENT_STATUS_KEY}\" to \"payment-submitted\" and provide a \"${X402_PAYMENT_PAYLOAD_KEY}\" object, or set it to \"payment-rejected\".`,\n );\n }\n // A mandate stored with the purchase wins. One sent here is verified\n // against the stored resource and input, like the payment.\n let authorization = pending.authorization;\n if (authorization === undefined && submission.kind === 'submitted') {\n try {\n authorization = readFollowUpAuthorization(message);\n } catch (err) {\n return jsonRpcError(id, JSONRPC_INVALID_PARAMS, toCommerceError(err).message);\n }\n }\n // Taken before execution, so a second payment message for the task finds\n // nothing and cannot run the purchase twice\n pendingPayments?.delete(taskId);\n const statusMessageId = context.ids.next('a2a-msg');\n const identity: TaskIdentity = {\n taskId,\n contextId: pending.contextId,\n artifactId: context.ids.next('a2a-artifact'),\n statusMessageId,\n timestamp: context.clock.nowIso(),\n };\n\n if (submission.kind === 'rejected') {\n const declined: A2aTask = {\n id: taskId,\n contextId: pending.contextId,\n status: { state: A2A_TASK_STATE_FAILED, timestamp: identity.timestamp },\n artifacts: [],\n };\n return taskResult(\n id,\n withStatusMessage(\n declined,\n 'Payment was declined.',\n statusMessageId,\n paymentRejectedMetadata(),\n ),\n );\n }\n return taskResult(\n id,\n await payPending(\n context,\n { ...pending, ...(authorization !== undefined ? { authorization } : {}) },\n submission.payload,\n identity,\n ),\n );\n}\n\n// The pending purchase, now with the x402 `PaymentPayload` as its proof\nasync function payPending(\n context: ProtocolAdapterContext,\n pending: PendingPayment,\n payload: Record<string, unknown>,\n identity: TaskIdentity,\n): Promise<A2aTask> {\n const requestId = context.ids.next('a2a');\n const request: CanonicalRequest = {\n requestId,\n resourceId: pending.resourceId,\n input: pending.input,\n protocol: 'a2a',\n receivedAt: context.clock.nowIso(),\n // The same encoding as the HTTP header's base64 PaymentPayload JSON\n payment: {\n method: 'x402',\n payload: Buffer.from(JSON.stringify(payload), 'utf8').toString('base64'),\n },\n ...(pending.authorization !== undefined ? { authorization: pending.authorization } : {}),\n };\n let error: CommerceError;\n try {\n const outcome = await context.pipeline.execute(request);\n if (outcome.kind === 'delivered' && outcome.payment !== undefined) {\n return withStatusMessage(\n completedTask(outcome, identity),\n 'Payment settled.',\n identity.statusMessageId,\n paymentCompletedMetadata(outcome.payment),\n );\n }\n // A proof was sent, so neither a free delivery nor a new challenge is a\n // payment this task can report\n error = new CommerceError('PAYMENT_INVALID', 'The payment was not accepted.', { requestId });\n } catch (err) {\n error = toCommerceError(err);\n context.logger.warn(\n { resourceId: pending.resourceId, requestId, err: toLogInfo(error) },\n 'a2a adapter: x402 extension payment failed',\n );\n }\n const metadata = paymentFailureMetadata(error, pending.network);\n let text = 'Payment failed.';\n if (metadata[X402_PAYMENT_STATUS_KEY] === 'payment-completed') {\n text = 'Payment settled, but the resource could not be delivered.';\n } else if (!error.code.startsWith('PAYMENT_')) {\n text = 'The resource could not be delivered.';\n }\n return withStatusMessage(failedTask(error, identity), text, identity.statusMessageId, metadata);\n}\n","/**\n * A2A (Agent2Agent) protocol adapter, experimental.\n *\n * Serves two paths: the configured mount (`/a2a`), where the JSON-RPC endpoint\n * lives, and the specification-fixed `/.well-known/agent-card.json`, declared\n * through `additionalHttpRoutes` so the gateway needs no A2A-specific routing.\n *\n * Only the synchronous `SendMessage` path is served; every other A2A method\n * is listed in `descriptor.unsupported`. This adapter maps reserved payment\n * fields but leaves verification, settlement and merchant calls to the pipeline.\n */\nimport { createHash } from 'node:crypto';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport {\n type AdapterDescriptor,\n type AdapterHealth,\n type AdapterHttpRoute,\n type CanonicalRequest,\n CommerceError,\n type CommerceResource,\n type ExecutionOutcome,\n extractReservedInputFields,\n type HttpProtocolAdapter,\n type ProtocolAdapterContext,\n toCommerceError,\n} from '../../core';\nimport { toLogInfo } from '../../core/errors';\nimport { isRecord } from '../../core/is-record';\nimport { PACKAGE_VERSION } from '../../version';\nimport { readCappedBody } from '../http';\nimport { buildAgentCard } from './agent-card';\nimport {\n A2A_AGENT_CARD_PATH,\n A2A_DEFAULT_AGENT_NAME,\n A2A_DEFAULT_MOUNT_PATH,\n A2A_EXTENSIONS_HEADER,\n A2A_JSON_MEDIA_TYPE,\n A2A_METHOD_SEND_MESSAGE,\n A2A_PROTOCOL_VERSION,\n A2A_PUSH_CONFIG_METHODS,\n A2A_TASK_LOOKUP_METHODS,\n A2A_UNSUPPORTED_METHODS,\n A2A_VERSION_HEADER,\n} from './constants';\nimport { buildDescriptor } from './descriptor';\nimport {\n A2A_ERROR_PUSH_NOTIFICATION_NOT_SUPPORTED,\n A2A_ERROR_TASK_NOT_FOUND,\n A2A_ERROR_UNSUPPORTED_OPERATION,\n A2A_ERROR_VERSION_NOT_SUPPORTED,\n JSONRPC_INTERNAL_ERROR,\n JSONRPC_INVALID_PARAMS,\n JSONRPC_INVALID_REQUEST,\n JSONRPC_METHOD_NOT_FOUND,\n JSONRPC_PARSE_ERROR,\n type JsonRpcId,\n jsonRpcError,\n parseJsonRpcRequest,\n} from './jsonrpc';\nimport { type A2aInvocation, parseInvocation } from './message-mapping';\nimport { resumePayment, taskResult } from './payment-resume';\nimport {\n completedTask,\n failedTask,\n inputRequired,\n paymentRequiredTask,\n type TaskIdentity,\n} from './task-mapping';\nimport type { A2aAgentCard, A2aTask } from './types';\nimport {\n A2A_X402_EXTENSION_URI,\n createPendingPayments,\n type PendingPayments,\n paymentRequiredMetadata,\n requestsX402Extension,\n} from './x402-extension';\n\n// A second line behind the gateway mount's cap, bounding what this adapter\n// buffers if it is mounted without that guard\nconst MAX_REQUEST_BODY_BYTES = 256 * 1024;\n\n// Accept patch suffixes; only major.minor determines the protocol version\nconst VERSION_PATTERN = /^(\\d+\\.\\d+)(?:\\.\\d+)?$/;\n\n// A2A version parameter; the header is matched case-insensitively\nconst A2A_VERSION_PARAMETER = 'A2A-Version';\n\n// Cache the card until the adapter starts again with new configuration\nconst AGENT_CARD_CACHE_CONTROL = 'public, max-age=300';\n\nexport interface A2aAdapterOptions {\n readonly mountPath?: string;\n /** Agent name published on the card */\n readonly agentName?: string;\n readonly agentDescription?: string;\n /** Version published on the card. Defaults to this package's version */\n readonly agentVersion?: string;\n}\n\nconst DEFAULT_AGENT_DESCRIPTION =\n 'Agent Commerce Gateway: canonical commerce resources exposed as A2A skills.';\n\nexport class A2aProtocolAdapter implements HttpProtocolAdapter {\n readonly name = 'a2a' as const;\n readonly mountPath: string;\n readonly descriptor: AdapterDescriptor;\n readonly additionalHttpRoutes: readonly AdapterHttpRoute[];\n\n private readonly agentName: string;\n private readonly agentDescription: string;\n private readonly agentVersion: string;\n\n private context: ProtocolAdapterContext | undefined;\n private started = false;\n // The card lists only a2a-exposed resources, but a caller can name any id,\n // so the adapter refuses another protocol's resource itself\n private skillsById: ReadonlyMap<string, CommerceResource> = new Map();\n // Built once at start: resources are fixed at config load, and a per-request\n // build would be work an unauthenticated GET could trigger at will\n private card: A2aAgentCard | undefined;\n private cardBody = '';\n private cardEtag = '';\n // Purchases waiting for an x402 extension payment\n private pendingPayments: PendingPayments | undefined;\n\n constructor(options: A2aAdapterOptions = {}) {\n this.mountPath = options.mountPath ?? A2A_DEFAULT_MOUNT_PATH;\n this.agentName = options.agentName ?? A2A_DEFAULT_AGENT_NAME;\n this.agentDescription = options.agentDescription ?? DEFAULT_AGENT_DESCRIPTION;\n this.agentVersion = options.agentVersion ?? PACKAGE_VERSION;\n this.descriptor = buildDescriptor(PACKAGE_VERSION);\n this.additionalHttpRoutes = [\n {\n method: 'GET',\n path: A2A_AGENT_CARD_PATH,\n handleHttp: (req, res) => this.handleAgentCard(req, res),\n },\n ];\n }\n\n async start(context: ProtocolAdapterContext): Promise<void> {\n this.context = context;\n this.started = false;\n\n let resources: readonly CommerceResource[] = [];\n try {\n resources = context.resources.listExposedVia('a2a');\n } catch (err) {\n context.logger.error(\n { err: toLogInfo(err) },\n 'a2a adapter: failed to list a2a-exposed resources',\n );\n resources = [];\n }\n\n this.skillsById = new Map(resources.map((resource) => [resource.id, resource]));\n this.card = buildAgentCard({\n name: this.agentName,\n description: this.agentDescription,\n version: this.agentVersion,\n publicBaseUrl: context.publicBaseUrl,\n mountPath: this.mountPath,\n resources,\n });\n this.pendingPayments = createPendingPayments(context.clock);\n this.cardBody = JSON.stringify(this.card);\n this.cardEtag = `\"${createHash('sha256').update(this.cardBody).digest('base64url')}\"`;\n this.started = true;\n\n context.logger.info(\n { mountPath: this.mountPath, cardPath: A2A_AGENT_CARD_PATH, skillCount: resources.length },\n 'a2a adapter started',\n );\n }\n\n /** `GET /.well-known/agent-card.json` */\n async handleAgentCard(req: IncomingMessage, res: ServerResponse): Promise<void> {\n try {\n if (!this.started || this.card === undefined) {\n this.writeJson(res, 503, { error: 'A2A adapter is not running.' });\n return;\n }\n if (req.method !== 'GET') {\n this.writeJson(res, 405, { error: 'Method not allowed. The Agent Card is read-only.' });\n return;\n }\n const cacheHeaders = { 'cache-control': AGENT_CARD_CACHE_CONTROL, etag: this.cardEtag };\n if (matchesEtag(req.headers['if-none-match'], this.cardEtag)) {\n res.writeHead(304, cacheHeaders);\n res.end();\n return;\n }\n res.writeHead(200, { 'content-type': A2A_JSON_MEDIA_TYPE, ...cacheHeaders });\n res.end(this.cardBody);\n } catch (err) {\n this.context?.logger.error({ err: toLogInfo(err) }, 'a2a adapter: agent card request failed');\n this.writeJson(res, 500, { error: 'Internal server error.' });\n }\n }\n\n /** `POST <mountPath>`: the A2A JSON-RPC endpoint */\n async handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void> {\n try {\n if (!this.started) {\n this.writeJson(\n res,\n 503,\n jsonRpcError(null, JSONRPC_INTERNAL_ERROR, 'A2A adapter is not running.'),\n );\n return;\n }\n if (req.method !== 'POST') {\n this.writeJson(\n res,\n 405,\n jsonRpcError(\n null,\n JSONRPC_INVALID_REQUEST,\n 'Method not allowed. This endpoint only accepts POST.',\n ),\n );\n return;\n }\n\n const read = await readCappedBody(req, MAX_REQUEST_BODY_BYTES);\n if (read.kind === 'too-large') {\n this.writeJson(\n res,\n 413,\n jsonRpcError(\n null,\n JSONRPC_INVALID_REQUEST,\n `Request body exceeds the ${MAX_REQUEST_BODY_BYTES}-byte limit.`,\n ),\n );\n return;\n }\n if (read.kind !== 'ok') {\n this.writeJson(\n res,\n 200,\n jsonRpcError(null, JSONRPC_PARSE_ERROR, 'Could not read the request body.'),\n );\n return;\n }\n\n const parsed = parseJsonRpcRequest(read.text);\n if (!parsed.ok) {\n this.writeJson(res, 200, jsonRpcError(parsed.id, parsed.error.code, parsed.error.message));\n return;\n }\n\n // Parse first to echo the request id on version errors. The query\n // parameter substitutes for an absent version header.\n const version = req.headers[A2A_VERSION_HEADER];\n const declared =\n (Array.isArray(version) ? version[0] : version) ??\n new URL(req.url ?? '/', 'http://localhost').searchParams.get(A2A_VERSION_PARAMETER);\n if (declared?.match(VERSION_PATTERN)?.[1] !== A2A_PROTOCOL_VERSION) {\n this.writeJson(\n res,\n 200,\n jsonRpcError(\n parsed.request.id,\n A2A_ERROR_VERSION_NOT_SUPPORTED,\n `Unsupported A2A protocol version. Send the ${A2A_VERSION_PARAMETER} header with \"${A2A_PROTOCOL_VERSION}\".`,\n ),\n );\n return;\n }\n\n const response = await this.dispatch(\n parsed.request.id,\n parsed.request.method,\n parsed.request.params,\n requestsX402Extension(req.headers[A2A_EXTENSIONS_HEADER]),\n );\n // Echo the extension when it shaped the task, even without the\n // request header on a payment follow-up\n this.writeJson(\n res,\n 200,\n response,\n usesX402Extension(response) ? { [A2A_EXTENSIONS_HEADER]: A2A_X402_EXTENSION_URI } : {},\n );\n } catch (err) {\n // Nothing from `err` reaches the client\n this.context?.logger.error({ err: toLogInfo(err) }, 'a2a adapter: request handling failed');\n this.writeJson(\n res,\n 200,\n jsonRpcError(null, JSONRPC_INTERNAL_ERROR, 'Internal server error.'),\n );\n }\n }\n\n private async dispatch(\n id: JsonRpcId,\n method: string,\n params: unknown,\n x402Extension: boolean,\n ): Promise<Record<string, unknown>> {\n if (A2A_PUSH_CONFIG_METHODS.includes(method)) {\n return jsonRpcError(\n id,\n A2A_ERROR_PUSH_NOTIFICATION_NOT_SUPPORTED,\n `A2A method \"${method}\" is not supported: this agent does not support push notifications.`,\n );\n }\n if (A2A_TASK_LOOKUP_METHODS.includes(method)) {\n return jsonRpcError(\n id,\n A2A_ERROR_TASK_NOT_FOUND,\n 'Task not found. Finished tasks are not retained; continue a pending payment with SendMessage.',\n );\n }\n if (A2A_UNSUPPORTED_METHODS.includes(method)) {\n return jsonRpcError(\n id,\n A2A_ERROR_UNSUPPORTED_OPERATION,\n `A2A method \"${method}\" is not supported by this deployment.`,\n );\n }\n if (method !== A2A_METHOD_SEND_MESSAGE) {\n return jsonRpcError(id, JSONRPC_METHOD_NOT_FOUND, `Unknown method \"${method}\".`);\n }\n\n const resumed = await resumePayment(this.context, this.pendingPayments, id, params);\n if (resumed !== undefined) return resumed;\n\n let invocation: ReturnType<typeof parseInvocation>;\n try {\n invocation = parseInvocation(params);\n } catch (err) {\n const error = toCommerceError(err);\n const a2aErrorCode = error.details?.['a2aErrorCode'];\n const code =\n typeof a2aErrorCode === 'number'\n ? a2aErrorCode\n : error.code === 'PROTOCOL_UNSUPPORTED'\n ? A2A_ERROR_UNSUPPORTED_OPERATION\n : JSONRPC_INVALID_PARAMS;\n // CommerceError messages are written for a client; nothing else is\n // relayed\n return jsonRpcError(id, code, error.message);\n }\n\n return this.execute(id, invocation, x402Extension);\n }\n\n // One accepted invocation, one `pipeline.execute()`\n private async execute(\n id: JsonRpcId,\n invocation: A2aInvocation,\n x402Extension: boolean,\n ): Promise<Record<string, unknown>> {\n const context = this.context;\n if (context === undefined) {\n return jsonRpcError(id, JSONRPC_INTERNAL_ERROR, 'A2A adapter is not running.');\n }\n\n const resource = this.skillsById.get(invocation.resourceId);\n if (resource === undefined) {\n // A commerce outcome, so a failed task rather than a JSON-RPC error. It\n // reads the same whether the resource is missing or scoped to another\n // protocol, so a caller cannot probe what A2A does not expose.\n return taskResult(\n id,\n failedTask(\n new CommerceError(\n 'RESOURCE_NOT_FOUND',\n `Unknown canonical resource \"${invocation.resourceId}\".`,\n ),\n this.taskIdentity(context, context.ids.next('a2a')),\n ),\n );\n }\n\n const requestId = context.ids.next('a2a');\n const identity = this.taskIdentity(context, requestId);\n\n // Reserved-field extraction sits inside the try: a malformed\n // `_authorization` envelope becomes a failed task like any other outcome\n try {\n const { input, payment, authorization } = extractReservedInputFields(\n invocation.input,\n resource,\n requestId,\n );\n const request: CanonicalRequest = {\n requestId,\n resourceId: invocation.resourceId,\n input,\n protocol: 'a2a',\n receivedAt: context.clock.nowIso(),\n ...(payment !== undefined ? { payment } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n };\n const outcome: ExecutionOutcome = await context.pipeline.execute(request);\n if (outcome.kind !== 'payment-required') {\n return taskResult(id, completedTask(outcome, identity));\n }\n const task = paymentRequiredTask(outcome, identity);\n const envelope = outcome.requirement.challenge.envelope;\n // The extension carries x402 only; any other rail keeps the terminal task\n if (!x402Extension || outcome.requirement.provider !== 'x402' || !isRecord(envelope)) {\n return taskResult(id, task);\n }\n const network = outcome.requirement.network;\n const held = this.pendingPayments?.put(\n identity.taskId,\n {\n contextId: identity.contextId,\n resourceId: invocation.resourceId,\n input,\n ...(authorization !== undefined ? { authorization } : {}),\n ...(network !== undefined ? { network } : {}),\n },\n outcome.requirement.expiresAt,\n );\n if (held === false) {\n return taskResult(\n id,\n failedTask(\n new CommerceError(\n 'GATEWAY_BUSY',\n 'Too many unpaid purchases are waiting for payment; retry shortly.',\n ),\n identity,\n ),\n );\n }\n return taskResult(\n id,\n inputRequired(task, paymentRequiredMetadata(envelope), identity.statusMessageId),\n );\n } catch (err) {\n // A downstream failure is the caller's answer, not a broken frame.\n // `toCommerceError` replaces a non-commerce error's message, so nothing\n // internal reaches the artifact.\n const error = toCommerceError(err);\n context.logger.warn(\n { resourceId: invocation.resourceId, requestId, err: toLogInfo(error) },\n 'a2a adapter: execution failed',\n );\n return taskResult(id, failedTask(error, identity));\n }\n }\n\n private taskIdentity(context: ProtocolAdapterContext, requestId: string): TaskIdentity {\n return {\n taskId: requestId,\n contextId: context.ids.next('a2a-ctx'),\n artifactId: context.ids.next('a2a-artifact'),\n statusMessageId: context.ids.next('a2a-msg'),\n timestamp: context.clock.nowIso(),\n };\n }\n\n async health(): Promise<AdapterHealth> {\n const checkedAt = this.context?.clock.nowIso() ?? new Date().toISOString();\n if (!this.started || this.card === undefined) {\n return { status: 'fail', detail: 'A2A adapter has not been started.', checkedAt };\n }\n return { status: 'pass', detail: `${this.skillsById.size} skill(s) published.`, checkedAt };\n }\n\n async stop(): Promise<void> {\n this.started = false;\n this.card = undefined;\n this.cardBody = '';\n this.cardEtag = '';\n this.pendingPayments?.clear();\n this.pendingPayments = undefined;\n this.skillsById = new Map();\n this.context = undefined;\n }\n\n private writeJson(\n res: ServerResponse,\n status: number,\n body: unknown,\n headers: Readonly<Record<string, string>> = {},\n ): void {\n if (res.headersSent) return;\n res.writeHead(status, { 'content-type': A2A_JSON_MEDIA_TYPE, ...headers });\n res.end(JSON.stringify(body));\n }\n}\n\n// True when the response is a task whose status message lists the extension\nfunction usesX402Extension(response: Record<string, unknown>): boolean {\n const result = response['result'] as { readonly task?: A2aTask } | undefined;\n return result?.task?.status.message?.extensions?.includes(A2A_X402_EXTENSION_URI) === true;\n}\n\n// Compare entity tags weakly; `*` matches any current card\nfunction matchesEtag(header: string | undefined, etag: string): boolean {\n if (header === undefined) return false;\n return header\n .split(',')\n .map((tag) => tag.trim().replace(/^W\\//, ''))\n .some((tag) => tag === '*' || tag === etag);\n}\n\nexport function createA2aAdapter(options: A2aAdapterOptions = {}): A2aProtocolAdapter {\n return new A2aProtocolAdapter(options);\n}\n","/**\n * ACP checkout operation -> canonical request.\n *\n * Each operation maps to one configured resource and one deterministic input\n * envelope: the keys `ACP_OPERATION_INPUT_KEYS` lists, plus any key in\n * `ACP_OPERATION_OPTIONAL_INPUT_KEYS` the caller supplied.\n *\n * No payment field is synthesized. ACP `payment_data` on completion is the\n * merchant's own purchase payment and stays inside `body` as business input;\n * a `PaymentSubmission` built from it would charge a gateway payment on top.\n */\nimport type { CanonicalRequest } from '../../core';\nimport {\n ACP_OPERATION_INPUT_KEYS,\n ACP_OPERATION_OPTIONAL_INPUT_KEYS,\n ACP_SESSION_ID_INPUT_KEY,\n} from './constants';\nimport type { AcpGuardedRequest } from './request-guards';\n\nexport interface AcpCanonicalRequestOptions {\n readonly request: AcpGuardedRequest;\n readonly resourceId: string;\n readonly requestId: string;\n readonly receivedAt: string;\n /**\n * Names this checkout operation to the merchant. The adapter derives it from\n * the idempotency scope, so it is the same value on every retry - unlike\n * `requestId`, which is new each time.\n */\n readonly idempotencyKey?: string;\n}\n\nexport function toCanonicalRequest(options: AcpCanonicalRequestOptions): CanonicalRequest {\n const { request, resourceId, requestId, receivedAt, idempotencyKey } = options;\n return {\n requestId,\n resourceId,\n input: canonicalInput(request),\n protocol: 'acp',\n receivedAt,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(request.forwardedHeaders !== undefined && Object.keys(request.forwardedHeaders).length > 0\n ? { backendHeaders: request.forwardedHeaders }\n : {}),\n };\n}\n\nfunction canonicalInput(request: AcpGuardedRequest): Record<string, unknown> {\n const keys = ACP_OPERATION_INPUT_KEYS[request.route.operation];\n const optionalKeys = ACP_OPERATION_OPTIONAL_INPUT_KEYS[request.route.operation] ?? [];\n const input: Record<string, unknown> = {};\n\n if (keys.includes('path') && request.route.sessionId !== undefined) {\n input['path'] = { [ACP_SESSION_ID_INPUT_KEY]: request.route.sessionId };\n }\n if (keys.includes('body')) {\n input['body'] = request.body;\n } else if (optionalKeys.includes('body') && Object.keys(request.body).length > 0) {\n input['body'] = request.body;\n }\n return input;\n}\n","/**\n * Adapter self-description.\n *\n * `supportedSpec` is the pinned ACP snapshot, never this package's version.\n * Status is `experimental` while the adapter lacks the features in the\n * unsupported list below; an entry leaves that list only when its feature is\n * implemented.\n */\nimport type { AdapterDescriptor } from '../../core';\nimport { ACP_CHECKOUT_OPERATIONS, ACP_SPEC_VERSION } from './constants';\n\n// What this adapter implements\nconst ACP_CAPABILITIES: readonly string[] = [\n 'rest transport',\n 'well-known discovery',\n 'bearer authentication',\n 'API-Version enforcement',\n // Forwarded as received: the gateway verifies neither signature header\n 'request header forwarding to the merchant',\n 'checkout service',\n ...ACP_CHECKOUT_OPERATIONS,\n];\n\n/**\n * Major ACP features this adapter does not implement, served on\n * `/.well-known/agent-commerce` and printed by `doctor`, so no client assumes\n * full protocol support\n */\nexport const ACP_UNSUPPORTED: readonly string[] = [\n // Services this seller does not implement, named as ACP names them. The\n // discovery document advertises `checkout` alone, and these are the reason.\n 'carts service',\n 'feed service',\n 'standalone orders service',\n 'delegate_payment',\n 'delegate_authentication',\n // Bindings and delivery directions\n 'ACP MCP transport binding',\n 'webhooks',\n 'outbound merchant-to-agent delivery',\n 'ACP client role',\n // Request authentication beyond the bearer token\n 'Signature header verification',\n 'Timestamp replay-window verification',\n // Extensions, versioning and payment handlers\n 'discount extension',\n 'general ACP extension framework',\n 'multiple ACP API versions',\n 'seller-backed payment handler integration',\n];\n\nexport function buildDescriptor(implementationVersion: string): AdapterDescriptor {\n return {\n name: 'acp',\n kind: 'protocol',\n implementationVersion,\n supportedSpec: ACP_SPEC_VERSION,\n capabilities: ACP_CAPABILITIES,\n status: 'experimental',\n unsupported: ACP_UNSUPPORTED,\n };\n}\n","/**\n * The `/.well-known/acp.json` seller discovery document.\n *\n * It advertises what this adapter implements: one transport, one service, one\n * API version. Optional metadata appears only when an operator configured it;\n * currencies are never inferred from the x402 configuration, a different\n * payment domain.\n *\n * The document is public, so the bearer token, backend URLs, resource mapping\n * and idempotency database location are not even inputs to this function.\n */\nimport { joinUrl } from '../http';\nimport { ACP_SPEC_VERSION } from './constants';\n\n/** Discovery metadata an operator may configure. Absent fields are omitted, never guessed */\nexport interface AcpDiscoveryMetadata {\n readonly documentationUrl?: string;\n readonly supportedCurrencies?: readonly string[];\n readonly supportedLocales?: readonly string[];\n readonly interventionTypes?: readonly string[];\n}\n\nexport interface AcpDiscoveryOptions {\n /** Externally reachable base URL of the gateway */\n readonly publicBaseUrl: string;\n readonly mountPath: string;\n readonly metadata?: AcpDiscoveryMetadata;\n}\n\nexport function buildAcpDiscoveryDocument(options: AcpDiscoveryOptions): Record<string, unknown> {\n const metadata = options.metadata ?? {};\n return {\n protocol: {\n name: 'acp',\n version: ACP_SPEC_VERSION,\n supported_versions: [ACP_SPEC_VERSION],\n ...(metadata.documentationUrl !== undefined\n ? { documentation_url: metadata.documentationUrl }\n : {}),\n },\n api_base_url: joinUrl(options.publicBaseUrl, options.mountPath),\n // REST only: ACP's MCP transport is a fixed checkout binding, not the\n // generic MCP adapter this gateway also serves\n transports: ['rest'],\n capabilities: {\n services: ['checkout'],\n ...(metadata.interventionTypes !== undefined\n ? { intervention_types: metadata.interventionTypes }\n : {}),\n ...(metadata.supportedCurrencies !== undefined\n ? { supported_currencies: metadata.supportedCurrencies }\n : {}),\n ...(metadata.supportedLocales !== undefined\n ? { supported_locales: metadata.supportedLocales }\n : {}),\n },\n };\n}\n","/**\n * The ACP `Error` object and the one writer every ACP response goes through,\n * so no handler invents its own error shape. Every error message is written by\n * the gateway: no stack, backend body, Ajv message, token or internal path\n * reaches a client.\n */\nimport type { ServerResponse } from 'node:http';\nimport { ACP_JSON_MEDIA_TYPE } from './constants';\n\n/** The three categories the pinned snapshot allows */\nexport type AcpErrorType = 'invalid_request' | 'processing_error' | 'service_unavailable';\n\nexport interface AcpError {\n readonly type: AcpErrorType;\n readonly code: string;\n readonly message: string;\n /** RFC 9535 JSONPath into the caller's document, never into ours */\n readonly param?: string;\n /** Only on version errors, per the snapshot */\n readonly supported_versions?: readonly string[];\n}\n\n/** An ACP error plus the status it is served with */\nexport interface AcpFailure {\n readonly status: number;\n readonly error: AcpError;\n /** Seconds for `Retry-After`, where the failure invites a retry */\n readonly retryAfterSeconds?: number;\n}\n\nexport function acpFailure(\n status: number,\n type: AcpErrorType,\n code: string,\n message: string,\n extra: { readonly param?: string; readonly supportedVersions?: readonly string[] } = {},\n): AcpFailure {\n return {\n status,\n error: {\n type,\n code,\n message,\n ...(extra.param !== undefined ? { param: extra.param } : {}),\n ...(extra.supportedVersions !== undefined\n ? { supported_versions: extra.supportedVersions }\n : {}),\n },\n };\n}\n\n/**\n * Response headers the adapter may set. Merchant backend headers are never\n * proxied: a backend's `Set-Cookie` or tracing header belongs to the\n * merchant's domain, not to the ACP client. `Retry-After` is rebuilt from a\n * parsed and capped number, not copied.\n */\nexport type AcpResponseHeaders = Readonly<Record<string, string>>;\n\nexport function writeAcpJson(\n res: ServerResponse,\n status: number,\n body: unknown,\n headers: AcpResponseHeaders = {},\n): void {\n if (res.headersSent) return;\n res.writeHead(status, { 'content-type': ACP_JSON_MEDIA_TYPE, ...headers });\n res.end(JSON.stringify(body));\n}\n\nexport function writeAcpFailure(\n res: ServerResponse,\n failure: AcpFailure,\n headers: AcpResponseHeaders = {},\n): void {\n writeAcpJson(res, failure.status, failure.error, headers);\n}\n","/**\n * Operation keys and request fingerprints for ACP idempotency.\n *\n * The fingerprint covers the parsed JSON value, not the raw bytes, so a retry\n * through another serializer (other key order, `1.0` for `1`, whitespace) is\n * a retry, not a 422 conflict. Array order, `null` versus an absent property,\n * and type still count: `1` and `\"1\"` are different requests.\n */\nimport { createHash } from 'node:crypto';\n\n/**\n * The name the merchant sees for one checkout operation, hashed from the same\n * scope that claims the key locally (deployment, endpoint, caller's key), so\n * it stays the same across client and network retries, a gateway restart and\n * a credential rotation.\n *\n * The caller's key alone does not name an operation: ACP scopes it per\n * endpoint, so one client may send `Idempotency-Key: 1` to both create and\n * complete. Two clients that pick the same key share a derived key, as they\n * share a claim row; ACP makes key uniqueness the client's responsibility.\n */\nexport function operationKey(scope: {\n readonly deployment: string;\n readonly endpoint: string;\n readonly key: string;\n}): string {\n return sha256(`acp-operation:${scope.deployment}:${scope.endpoint}:${scope.key}`);\n}\n\n/** SHA-256 over the canonical form of a parsed JSON document */\nexport function requestFingerprint(body: unknown): string {\n return sha256(canonicalize(body));\n}\n\n/**\n * Deterministic JSON canonicalization in the spirit of RFC 8785, limited to\n * what `JSON.parse` produces. Not the `canonicalize` package: that is an\n * optional peer (AP2), and this module is in the peer-free main entry.\n *\n * Object keys are sorted by UTF-16 code unit. Numbers go through\n * `JSON.stringify`, which writes each in its shortest round-trip form, so\n * `1.0` becomes `1` and `1e2` becomes `100`.\n */\nfunction canonicalize(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return `[${value.map(canonicalize).join(',')}]`;\n if (typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n // JSON.parse never yields `undefined`, but an object literal could;\n // dropping such keys keeps them equal to absent ones\n .filter(([, entry]) => entry !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalize(entry)}`).join(',')}}`;\n }\n // Strings, numbers and booleans, whose encodings keep the types distinct\n return JSON.stringify(value) ?? 'null';\n}\n\nfunction sha256(value: string): string {\n return createHash('sha256').update(value, 'utf8').digest('hex');\n}\n","/**\n * Durable ACP checkout idempotency, in its own database file: it is protocol\n * replay semantics for a checkout, unrelated to the payment replay defense in\n * the receipt store, with its own lifetime and retention.\n *\n * A key is claimed atomically before the side effect starts, so a second\n * request with the same key finds the claim instead of starting a second\n * checkout.\n *\n * A merchant call over HTTP and a SQLite commit are not one transaction. By\n * default, an attempt with an uncertain merchant outcome is marked\n * `unresolved` so a retry cannot repeat the operation. A row still\n * `in_flight` when the store opens is also marked unresolved: the earlier\n * process may have crashed before recording the outcome. With\n * `releaseOrphans`, the store frees these rows for a merchant configured to\n * deduplicate by the derived key. This assumes one gateway process per file.\n *\n * Only `completed` rows expire. Deleting an unresolved one would hand the next\n * retry a clean key; clearing it is an operator's decision, taken against the\n * merchant's own records. The merchant should still be idempotent on\n * destructive operations: this store does not make its API exactly-once.\n */\nimport type { Database } from 'better-sqlite3';\nimport { type Logger, NOOP_LOGGER } from '../../../core';\nimport { openSqliteDatabase } from '../../../storage/sqlite';\n\n// v2 keys rows by the deployment's public base URL; v1 keyed them by a\n// bearer-token digest (see `migrate`)\nconst SCHEMA_VERSION = 2;\n\n/** Longest `Idempotency-Key` ACP allows */\nexport const ACP_MAX_IDEMPOTENCY_KEY_LENGTH = 255;\n\n/** Scope of one claim: which deployment, which endpoint, which key */\nexport interface AcpIdempotencyScope {\n /**\n * The gateway's public base URL, not a credential: a rotated token must not\n * give a retry a fresh key and re-run an operation whose outcome may be\n * unknown. The URL survives rotation and still separates two gateways in\n * front of one merchant. It is not secret and is stored as-is, so an\n * operator can see which deployment wrote an unresolved row.\n */\n readonly deployment: string;\n /** The concrete endpoint path, so one key may be reused across operations */\n readonly endpoint: string;\n readonly key: string;\n}\n\n/** A response worth replaying: status plus the ACP document that was sent */\nexport interface AcpStoredResponse {\n readonly status: number;\n readonly body: unknown;\n}\n\nexport type AcpIdempotencyClaim =\n /** The caller owns the key and must now do the work */\n | { readonly kind: 'reserved' }\n /** Same scope, same body, still running elsewhere */\n | { readonly kind: 'in-flight' }\n /** Same scope, same body, and an earlier attempt's outcome was never learned */\n | { readonly kind: 'unresolved' }\n /** Same scope, different body: the key was reused for another request */\n | { readonly kind: 'conflict' }\n /** Same scope, same body, already answered */\n | ({ readonly kind: 'replay' } & AcpStoredResponse);\n\nexport interface AcpIdempotencyStore {\n /** Atomically claim `scope`, or report what already holds it */\n claim(scope: AcpIdempotencyScope, fingerprint: string): AcpIdempotencyClaim;\n /** Store the answer, making later retries a replay */\n complete(scope: AcpIdempotencyScope, response: AcpStoredResponse): void;\n /**\n * Keep the claim with no answer: the merchant may have acted. Later retries\n * are refused, neither replayed nor re-run.\n */\n markUnresolved(scope: AcpIdempotencyScope): void;\n /**\n * Drop the claim so a retry can run. The caller must establish that no\n * merchant call ran or that the merchant deduplicates by the derived key.\n */\n release(scope: AcpIdempotencyScope): void;\n close(): void;\n}\n\nexport interface AcpIdempotencyStoreOptions {\n /** File path, or ':memory:' for tests */\n readonly path: string;\n /** Never below 24 hours; config enforces the floor */\n readonly retentionHours: number;\n /**\n * Free claims left in flight by an earlier process. Enable only when the\n * merchant deduplicates by the derived key.\n */\n readonly releaseOrphans?: boolean;\n readonly logger?: Logger;\n /** Injectable for tests that need to move time */\n readonly now?: () => number;\n}\n\ninterface ClaimRow {\n state: string;\n fingerprint: string;\n status: number | null;\n body_json: string | null;\n}\n\nexport function createAcpIdempotencyStore(\n options: AcpIdempotencyStoreOptions,\n): AcpIdempotencyStore {\n const logger = options.logger ?? NOOP_LOGGER;\n const now = options.now ?? (() => Date.now());\n const retentionMs = options.retentionHours * 60 * 60 * 1000;\n\n const db: Database = openSqliteDatabase({\n path: options.path,\n label: 'ACP idempotency database',\n logger,\n });\n migrate(db, logger);\n resolveOrphanedClaims(db, logger, options.releaseOrphans === true);\n\n const selectStmt = db.prepare<[string, string, string], ClaimRow>(\n `SELECT state, fingerprint, status, body_json FROM acp_idempotency\n WHERE deployment = ? AND endpoint = ? AND idempotency_key = ?`,\n );\n const insertStmt = db.prepare(\n `INSERT INTO acp_idempotency\n (deployment, endpoint, idempotency_key, fingerprint, state, created_at, expires_at)\n VALUES (@deployment, @endpoint, @idempotency_key, @fingerprint, 'in_flight', @created_at, @expires_at)`,\n );\n const completeStmt = db.prepare(\n `UPDATE acp_idempotency SET state = 'completed', status = @status, body_json = @body_json\n WHERE deployment = @deployment AND endpoint = @endpoint AND idempotency_key = @idempotency_key`,\n );\n const deleteStmt = db.prepare(\n `DELETE FROM acp_idempotency\n WHERE deployment = ? AND endpoint = ? AND idempotency_key = ?`,\n );\n const unresolvedStmt = db.prepare(\n `UPDATE acp_idempotency SET state = 'unresolved'\n WHERE deployment = @deployment AND endpoint = @endpoint AND idempotency_key = @idempotency_key`,\n );\n // Completed rows only: to the next retry, a deleted unresolved row would look\n // like an operation that never happened\n const expireStmt = db.prepare(\n \"DELETE FROM acp_idempotency WHERE expires_at <= ? AND state = 'completed'\",\n );\n\n // Expired rows are swept lazily inside the claim transaction, with no\n // background worker\n const claimTx = db.transaction(\n (scope: AcpIdempotencyScope, fingerprint: string): AcpIdempotencyClaim => {\n const at = now();\n expireStmt.run(new Date(at).toISOString());\n\n const existing = selectStmt.get(scope.deployment, scope.endpoint, scope.key);\n if (existing === undefined) {\n insertStmt.run({\n deployment: scope.deployment,\n endpoint: scope.endpoint,\n idempotency_key: scope.key,\n fingerprint,\n created_at: new Date(at).toISOString(),\n expires_at: new Date(at + retentionMs).toISOString(),\n });\n return { kind: 'reserved' };\n }\n\n // Fingerprint first: a key reused for a different body conflicts whether\n // or not the first request has finished, and \"in flight\" would invite a\n // retry that can only conflict\n if (existing.fingerprint !== fingerprint) return { kind: 'conflict' };\n if (existing.state === 'unresolved') return { kind: 'unresolved' };\n if (existing.state !== 'completed') return { kind: 'in-flight' };\n return {\n kind: 'replay',\n status: existing.status ?? 500,\n body: existing.body_json === null ? null : JSON.parse(existing.body_json),\n };\n },\n );\n\n let closed = false;\n return {\n claim(scope, fingerprint) {\n return claimTx(scope, fingerprint);\n },\n complete(scope, response) {\n completeStmt.run({\n deployment: scope.deployment,\n endpoint: scope.endpoint,\n idempotency_key: scope.key,\n status: response.status,\n body_json: JSON.stringify(response.body ?? null),\n });\n },\n markUnresolved(scope) {\n unresolvedStmt.run({\n deployment: scope.deployment,\n endpoint: scope.endpoint,\n idempotency_key: scope.key,\n });\n },\n release(scope) {\n deleteStmt.run(scope.deployment, scope.endpoint, scope.key);\n },\n close() {\n if (closed) return;\n closed = true;\n db.close();\n },\n };\n}\n\n// Runs when the store opens, before this process claims anything, so an\n// `in_flight` row outlived the process that claimed it and would otherwise\n// answer \"retry later\" forever\nfunction resolveOrphanedClaims(db: Database, logger: Logger, release: boolean): void {\n if (release) {\n const { changes } = db.prepare(\"DELETE FROM acp_idempotency WHERE state = 'in_flight'\").run();\n if (changes > 0) {\n logger.warn(\n { released: changes },\n 'acp idempotency: freed claims left in flight by an earlier process; merchant deduplication is enabled',\n );\n }\n return;\n }\n const { changes } = db\n .prepare(\"UPDATE acp_idempotency SET state = 'unresolved' WHERE state = 'in_flight'\")\n .run();\n if (changes > 0) {\n logger.warn(\n { unresolved: changes },\n 'acp idempotency: marked claims left in flight by an earlier process as unresolved; ' +\n 'reconcile these operations against the merchant before trusting a retry',\n );\n }\n}\n\n// `PRAGMA user_version` marks the schema, so reopening a current file is a no-op\nfunction migrate(db: Database, logger: Logger): void {\n const current = db.pragma('user_version', { simple: true }) as number;\n if (current >= SCHEMA_VERSION) return;\n\n const apply = db.transaction(() => {\n if (current === 1) {\n // v1 keyed rows by a one-way digest of the bearer token, which cannot be\n // mapped to a deployment. The table is rebuilt empty, since nothing would\n // ever match those rows again, and the number of open claims dropped is\n // logged.\n const carried = db\n .prepare(\"SELECT COUNT(*) AS count FROM acp_idempotency WHERE state != 'completed'\")\n .get() as { count: number };\n if (carried.count > 0) {\n logger.warn(\n { unresolved: carried.count },\n 'acp idempotency: schema v1 -> v2 discards claims keyed by the old bearer-token digest; ' +\n 'reconcile these operations against the merchant before trusting a retry',\n );\n }\n db.exec('DROP TABLE acp_idempotency');\n }\n\n db.exec(`\n CREATE TABLE IF NOT EXISTS acp_idempotency (\n deployment TEXT NOT NULL,\n endpoint TEXT NOT NULL,\n idempotency_key TEXT NOT NULL,\n fingerprint TEXT NOT NULL,\n state TEXT NOT NULL,\n status INTEGER,\n body_json TEXT,\n created_at TEXT NOT NULL,\n expires_at TEXT NOT NULL,\n PRIMARY KEY (deployment, endpoint, idempotency_key)\n );\n CREATE INDEX IF NOT EXISTS idx_acp_idempotency_expires_at\n ON acp_idempotency(expires_at);\n `);\n db.pragma(`user_version = ${SCHEMA_VERSION}`);\n });\n apply();\n}\n","/**\n * The five stable checkout routes, matched against the adapter's mount.\n *\n * The route table is closed: anything else under the mount is a 404, so a\n * client cannot discover an unimplemented ACP service by probing paths.\n */\nimport type { AcpCheckoutOperation } from './constants';\n\n// Longest raw path segment accepted before decoding, which also bounds\n// `checkout_session_id`\nconst MAX_SEGMENT_LENGTH = 512;\n\nconst COLLECTION = 'checkout_sessions';\n\nexport interface AcpRouteMatch {\n readonly operation: AcpCheckoutOperation;\n /**\n * The concrete endpoint path, rebuilt from the matched segments rather than\n * taken from the raw URL: it scopes idempotency keys, so it must be one\n * canonical string per endpoint and never carry a query string or an\n * alternative encoding of the same path\n */\n readonly path: string;\n /** Absent only for `createCheckoutSession` */\n readonly sessionId?: string;\n /** POST routes carry an ACP request document; the GET route carries none */\n readonly acceptsBody: boolean;\n}\n\nexport type AcpRouteResult =\n | { readonly kind: 'match'; readonly route: AcpRouteMatch }\n | { readonly kind: 'not-found' }\n | { readonly kind: 'method-not-allowed'; readonly allow: readonly string[] };\n\n/**\n * Matches `method` + `url` against the checkout routes below `mountPath`.\n *\n * The URL arrives raw from Node, so it still carries any query string and may\n * be percent-encoded; both are handled here rather than by every caller.\n */\nexport function matchAcpRoute(\n method: string | undefined,\n url: string | undefined,\n mountPath: string,\n): AcpRouteResult {\n const segments = routeSegments(url, mountPath);\n if (segments === undefined || segments[0] !== COLLECTION) return { kind: 'not-found' };\n\n const verb = (method ?? '').toUpperCase();\n\n // POST /checkout_sessions\n if (segments.length === 1) {\n if (verb !== 'POST') return { kind: 'method-not-allowed', allow: ['POST'] };\n return {\n kind: 'match',\n route: {\n operation: 'createCheckoutSession',\n path: endpointPath(mountPath, segments),\n acceptsBody: true,\n },\n };\n }\n\n const sessionId = segments[1];\n if (sessionId === undefined || !isSessionId(sessionId)) return { kind: 'not-found' };\n\n // GET|POST /checkout_sessions/{id}\n if (segments.length === 2) {\n if (verb === 'GET') {\n return {\n kind: 'match',\n route: {\n operation: 'getCheckoutSession',\n path: endpointPath(mountPath, segments),\n sessionId,\n acceptsBody: false,\n },\n };\n }\n if (verb === 'POST') {\n return {\n kind: 'match',\n route: {\n operation: 'updateCheckoutSession',\n path: endpointPath(mountPath, segments),\n sessionId,\n acceptsBody: true,\n },\n };\n }\n return { kind: 'method-not-allowed', allow: ['GET', 'POST'] };\n }\n\n // POST /checkout_sessions/{id}/{complete|cancel}\n if (segments.length === 3) {\n const operation =\n segments[2] === 'complete'\n ? 'completeCheckoutSession'\n : segments[2] === 'cancel'\n ? 'cancelCheckoutSession'\n : undefined;\n if (operation === undefined) return { kind: 'not-found' };\n if (verb !== 'POST') return { kind: 'method-not-allowed', allow: ['POST'] };\n return {\n kind: 'match',\n route: { operation, path: endpointPath(mountPath, segments), sessionId, acceptsBody: true },\n };\n }\n\n return { kind: 'not-found' };\n}\n\n// Accept decoded merchant ids such as `gid://shop/Checkout/1`. Reject empty\n// ids and ASCII control characters.\nfunction isSessionId(value: string): boolean {\n if (value.length === 0) return false;\n for (const char of value) {\n const code = char.charCodeAt(0);\n if (code < 0x20 || code === 0x7f) return false;\n }\n return true;\n}\n\n// Re-encode each segment so `/` inside a session id cannot become a route\n// separator or a distinct idempotency scope\nfunction endpointPath(mountPath: string, segments: readonly string[]): string {\n return `${mountPath.replace(/\\/+$/, '')}/${segments.map(encodeURIComponent).join('/')}`;\n}\n\n/**\n * Path segments below the mount, or `undefined` when the URL is not under it.\n *\n * A percent-encoded separator (`%2F`) is decoded per segment *after* the split,\n * so an id can never smuggle in an extra path segment.\n */\nfunction routeSegments(url: string | undefined, mountPath: string): readonly string[] | undefined {\n if (url === undefined) return undefined;\n const path = url.split('?')[0]?.split('#')[0] ?? '';\n const base = mountPath.replace(/\\/+$/, '');\n if (path !== base && !path.startsWith(`${base}/`)) return undefined;\n\n const rest = path.slice(base.length);\n const segments: string[] = [];\n for (const raw of rest.split('/')) {\n if (raw.length === 0) continue;\n if (raw.length > MAX_SEGMENT_LENGTH) return undefined;\n try {\n segments.push(decodeURIComponent(raw));\n } catch {\n // A malformed escape is not a route this adapter serves\n return undefined;\n }\n }\n return segments;\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://example.com/schemas/agentic-checkout/bundle.schema.json\",\n \"title\": \"Agentic Checkout — Schema Bundle\",\n \"$defs\": {\n \"VariantOption\": {\n \"description\": \"Represents a single variant option for a product (e.g., size, color, material)\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Variant attribute name (e.g., 'Size', 'Color')\"\n },\n \"value\": {\n \"type\": \"string\",\n \"description\": \"Variant attribute value (e.g., 'Large', 'Blue')\"\n }\n },\n \"required\": [\n \"name\",\n \"value\"\n ],\n \"example\": {\n \"name\": \"Color\",\n \"value\": \"Midnight Blue\"\n }\n },\n \"WeightInfo\": {\n \"description\": \"Product weight with unit of measurement\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"value\": {\n \"type\": \"number\",\n \"description\": \"Numeric weight value\"\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\n \"g\",\n \"kg\",\n \"oz\",\n \"lb\"\n ],\n \"description\": \"Unit of measurement for weight\"\n }\n },\n \"required\": [\n \"value\",\n \"unit\"\n ],\n \"example\": {\n \"value\": 250,\n \"unit\": \"g\"\n }\n },\n \"DimensionsInfo\": {\n \"description\": \"Physical dimensions of a product with unit of measurement\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"length\": {\n \"type\": \"number\",\n \"description\": \"Length dimension\"\n },\n \"width\": {\n \"type\": \"number\",\n \"description\": \"Width dimension\"\n },\n \"height\": {\n \"type\": \"number\",\n \"description\": \"Height dimension\"\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\n \"cm\",\n \"in\"\n ],\n \"description\": \"Unit of measurement for dimensions\"\n }\n },\n \"required\": [\n \"length\",\n \"width\",\n \"height\",\n \"unit\"\n ],\n \"example\": {\n \"length\": 15.5,\n \"width\": 10.2,\n \"height\": 5.8,\n \"unit\": \"cm\"\n }\n },\n \"DiscountDetail\": {\n \"description\": \"Information about a discount applied to the checkout or a specific item\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"code\": {\n \"type\": \"string\",\n \"description\": \"Discount code if applicable\"\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"percentage\",\n \"fixed\",\n \"bogo\",\n \"volume\"\n ],\n \"description\": \"Type of discount\"\n },\n \"amount\": {\n \"type\": \"integer\",\n \"description\": \"Discount amount in minor currency units (e.g. 100 cents for $1.00 or 100 for ¥100)\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Human-readable discount description\"\n },\n \"source\": {\n \"type\": \"string\",\n \"enum\": [\n \"coupon\",\n \"automatic\",\n \"loyalty\"\n ],\n \"description\": \"Source of the discount\"\n }\n },\n \"required\": [\n \"type\",\n \"amount\"\n ],\n \"example\": {\n \"code\": \"SAVE20\",\n \"type\": \"percentage\",\n \"amount\": 1600,\n \"description\": \"20% off your order\",\n \"source\": \"coupon\"\n }\n },\n \"Address\": {\n \"description\": \"Physical address for shipping, billing, or pickup locations\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Recipient name for this address\"\n },\n \"line_one\": {\n \"type\": \"string\",\n \"description\": \"Primary street address line\"\n },\n \"line_two\": {\n \"type\": \"string\",\n \"description\": \"Secondary address line (apartment, suite, etc.)\"\n },\n \"city\": {\n \"type\": \"string\",\n \"description\": \"City name\"\n },\n \"state\": {\n \"type\": \"string\",\n \"description\": \"State or province code\"\n },\n \"country\": {\n \"type\": \"string\",\n \"description\": \"ISO 3166-1 alpha-2 country code\"\n },\n \"postal_code\": {\n \"type\": \"string\",\n \"description\": \"Postal or ZIP code\"\n },\n \"company\": {\n \"type\": \"string\",\n \"description\": \"Postal or ZIP code\"\n }\n },\n \"required\": [\n \"name\",\n \"line_one\",\n \"city\",\n \"state\",\n \"country\",\n \"postal_code\"\n ],\n \"example\": {\n \"name\": \"Jane Doe\",\n \"line_one\": \"123 Main Street\",\n \"line_two\": \"Apt 4B\",\n \"city\": \"New York\",\n \"state\": \"NY\",\n \"country\": \"US\",\n \"postal_code\": \"10001\"\n }\n },\n \"AffiliateAttributionSource\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Context about where the attribution originated.\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"url\",\n \"platform\",\n \"unknown\"\n ],\n \"description\": \"The type of attribution source.\"\n },\n \"url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"Canonical content URL when type is 'url'.\"\n }\n },\n \"required\": [\n \"type\"\n ],\n \"example\": {\n \"type\": \"url\",\n \"url\": \"https://example.com/product-review\"\n }\n },\n \"AffiliateAttributionMetadata\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"oneOf\": [\n {\n \"type\": \"string\",\n \"description\": \"String metadata value\"\n },\n {\n \"type\": \"number\",\n \"description\": \"Numeric metadata value\"\n },\n {\n \"type\": \"boolean\",\n \"description\": \"Boolean metadata value\"\n }\n ]\n },\n \"description\": \"Flat key/value map for additional non-sensitive context. Keys must be strings; values must be strings, numbers, or booleans. Arrays and nested objects are NOT permitted.\",\n \"example\": {\n \"campaign_type\": \"influencer\",\n \"commission_rate\": 0.15,\n \"is_verified\": true\n }\n },\n \"AffiliateAttribution\": {\n \"type\": \"object\",\n \"description\": \"Optional affiliate attribution data for crediting third-party publishers. Write-only: not returned in responses. Forward compatibility: Servers SHOULD ignore unknown fields to support future extensions (per RFC §8.2).\",\n \"properties\": {\n \"provider\": {\n \"type\": \"string\",\n \"description\": \"Identifier for the attribution provider / affiliate network namespace (e.g., 'impact.com').\"\n },\n \"token\": {\n \"type\": \"string\",\n \"description\": \"Opaque provider-issued token for fraud-resistant validation. Treat as secret.\"\n },\n \"publisher_id\": {\n \"type\": \"string\",\n \"description\": \"Provider-scoped affiliate/publisher identifier. Required if token is omitted.\"\n },\n \"campaign_id\": {\n \"type\": \"string\",\n \"description\": \"Provider-scoped campaign identifier.\"\n },\n \"creative_id\": {\n \"type\": \"string\",\n \"description\": \"Provider-scoped creative identifier.\"\n },\n \"sub_id\": {\n \"type\": \"string\",\n \"description\": \"Provider-scoped sub-tracking identifier.\"\n },\n \"source\": {\n \"$ref\": \"#/$defs/AffiliateAttributionSource\"\n },\n \"issued_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC3339 timestamp when the attribution token was issued.\"\n },\n \"expires_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC3339 timestamp when the attribution token expires.\"\n },\n \"metadata\": {\n \"$ref\": \"#/$defs/AffiliateAttributionMetadata\"\n },\n \"touchpoint\": {\n \"type\": \"string\",\n \"enum\": [\n \"first\",\n \"last\"\n ],\n \"description\": \"Attribution touchpoint type. Use 'first' when capturing at session creation, 'last' when capturing at completion. Enables multi-touch attribution models.\"\n }\n },\n \"required\": [\n \"provider\"\n ],\n \"anyOf\": [\n {\n \"required\": [\n \"token\"\n ]\n },\n {\n \"required\": [\n \"publisher_id\"\n ]\n }\n ],\n \"example\": {\n \"provider\": \"impact.com\",\n \"token\": \"atp_01J8Z3WXYZ9ABC\",\n \"publisher_id\": \"pub_123\",\n \"campaign_id\": \"camp_summer2026\",\n \"touchpoint\": \"first\",\n \"source\": {\n \"type\": \"url\",\n \"url\": \"https://example.com/product-review\"\n },\n \"issued_at\": \"2026-02-11T10:00:00Z\",\n \"expires_at\": \"2026-02-11T11:00:00Z\"\n }\n },\n \"FulfillmentDetails\": {\n \"description\": \"Details about how items will be fulfilled (shipping, pickup, or delivery information)\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Full name for fulfillment contact\"\n },\n \"phone_number\": {\n \"type\": \"string\",\n \"description\": \"Contact phone number. E.164 format recommended (e.g., +15551234567) for global interoperability and SMS/delivery carrier systems.\"\n },\n \"email\": {\n \"type\": \"string\",\n \"format\": \"email\",\n \"description\": \"Contact email address\"\n },\n \"address\": {\n \"$ref\": \"#/$defs/Address\",\n \"description\": \"Fulfillment address\"\n }\n },\n \"example\": {\n \"name\": \"John Smith\",\n \"phone_number\": \"15551234567\",\n \"email\": \"john.smith@example.com\",\n \"address\": {\n \"name\": \"John Smith\",\n \"line_one\": \"555 Golden Gate Avenue\",\n \"line_two\": \"Apt 401\",\n \"city\": \"San Francisco\",\n \"state\": \"CA\",\n \"country\": \"US\",\n \"postal_code\": \"94102\"\n }\n }\n },\n \"CompanyInfo\": {\n \"description\": \"Information about a company or organization associated with the buyer\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Company or organization name\"\n },\n \"tax_id\": {\n \"type\": \"string\",\n \"description\": \"Business tax identification number\"\n },\n \"department\": {\n \"type\": \"string\",\n \"description\": \"Department within the organization\"\n },\n \"cost_center\": {\n \"type\": \"string\",\n \"description\": \"Cost center code for internal accounting\"\n }\n },\n \"required\": [\n \"name\"\n ],\n \"example\": {\n \"name\": \"Acme Corporation\",\n \"tax_id\": \"12-3456789\",\n \"department\": \"Marketing\",\n \"cost_center\": \"CC-2001\"\n }\n },\n \"LoyaltyInfo\": {\n \"description\": \"Loyalty program information including membership details and rewards balance\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"tier\": {\n \"type\": \"string\",\n \"description\": \"Loyalty program tier level\"\n },\n \"points_balance\": {\n \"type\": \"integer\",\n \"description\": \"Current loyalty points balance\"\n },\n \"member_since\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the customer joined the loyalty program\"\n }\n },\n \"example\": {\n \"tier\": \"Gold\",\n \"points_balance\": 5000,\n \"member_since\": \"2024-01-15T09:00:00Z\"\n }\n },\n \"TaxExemption\": {\n \"description\": \"Tax exemption information including exemption type and applicable regions\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"certificate_id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for the tax exemption certificate\"\n },\n \"certificate_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"resale\",\n \"exempt_organization\",\n \"government\"\n ],\n \"description\": \"Type of tax exemption certificate\"\n },\n \"exempt_regions\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Region code where tax exemption applies (e.g., state abbreviation)\"\n },\n \"description\": \"List of regions where the exemption applies (e.g., state codes)\"\n },\n \"expires_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the exemption certificate expires\"\n }\n },\n \"required\": [\n \"certificate_id\",\n \"certificate_type\"\n ],\n \"example\": {\n \"certificate_id\": \"cert_12345\",\n \"certificate_type\": \"resale\",\n \"exempt_regions\": [\n \"CA\",\n \"NY\",\n \"TX\"\n ],\n \"expires_at\": \"2027-12-31T23:59:59Z\"\n }\n },\n \"Buyer\": {\n \"description\": \"Information about the buyer including contact details, company info, and loyalty status\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"first_name\": {\n \"type\": \"string\",\n \"description\": \"Buyer's first name\"\n },\n \"last_name\": {\n \"type\": \"string\",\n \"description\": \"Buyer's last name\"\n },\n \"full_name\": {\n \"type\": \"string\",\n \"description\": \"Buyer's full name\"\n },\n \"email\": {\n \"type\": \"string\",\n \"format\": \"email\",\n \"description\": \"Buyer's email address\"\n },\n \"phone_number\": {\n \"type\": \"string\",\n \"description\": \"Buyer's phone number\"\n },\n \"customer_id\": {\n \"type\": \"string\",\n \"description\": \"Merchant's internal customer identifier\"\n },\n \"account_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"guest\",\n \"registered\",\n \"business\"\n ],\n \"description\": \"Type of buyer account\"\n },\n \"authentication_status\": {\n \"type\": \"string\",\n \"enum\": [\n \"authenticated\",\n \"guest\",\n \"requires_signin\"\n ],\n \"description\": \"Buyer's authentication status\"\n },\n \"company\": {\n \"$ref\": \"#/$defs/CompanyInfo\",\n \"description\": \"Company information for business buyers\"\n },\n \"loyalty\": {\n \"$ref\": \"#/$defs/LoyaltyInfo\",\n \"description\": \"Loyalty program information\"\n },\n \"tax_exemption\": {\n \"$ref\": \"#/$defs/TaxExemption\",\n \"description\": \"Tax exemption details\"\n }\n },\n \"required\": [\n \"email\"\n ],\n \"example\": {\n \"first_name\": \"Sarah\",\n \"last_name\": \"Johnson\",\n \"full_name\": \"Sarah Johnson\",\n \"email\": \"sarah.johnson@example.com\",\n \"phone_number\": \"+1-415-555-0123\",\n \"customer_id\": \"cust_abc123\",\n \"account_type\": \"registered\",\n \"authentication_status\": \"authenticated\"\n }\n },\n \"InterventionCapabilities\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Intervention capabilities. Context-specific fields: display_context, redirect_context, max_redirects, max_interaction_depth (requests only). required, enforcement (responses only). supported field contains intersection in responses.\",\n \"properties\": {\n \"supported\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\n \"3ds\",\n \"biometric\",\n \"address_verification\"\n ]\n },\n \"description\": \"Intervention types supported. Agent request: Interventions the agent can handle. Seller response: Intersection of supported interventions.\"\n },\n \"required\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\n \"3ds\",\n \"biometric\"\n ]\n },\n \"description\": \"Intervention methods required for this session (seller only).\"\n },\n \"enforcement\": {\n \"type\": \"string\",\n \"enum\": [\n \"always\",\n \"conditional\",\n \"optional\"\n ],\n \"description\": \"When required interventions are enforced (seller only).\"\n },\n \"display_context\": {\n \"type\": \"string\",\n \"enum\": [\n \"native\",\n \"webview\",\n \"modal\",\n \"redirect\"\n ],\n \"description\": \"How the Agent presents interventions (agent only).\"\n },\n \"redirect_context\": {\n \"type\": \"string\",\n \"enum\": [\n \"in_app\",\n \"external_browser\",\n \"none\"\n ],\n \"description\": \"How the Agent handles redirects (agent only).\"\n },\n \"max_redirects\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Maximum number of redirects the Agent can handle (agent only).\"\n },\n \"max_interaction_depth\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Maximum depth of nested interactions the Agent can handle (agent only).\"\n }\n },\n \"example\": {\n \"supported\": [\n \"3ds\",\n \"address_verification\"\n ],\n \"display_context\": \"native\",\n \"redirect_context\": \"in_app\",\n \"max_redirects\": 3,\n \"max_interaction_depth\": 2\n }\n },\n \"Capabilities\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Capabilities object used in requests and responses. Context determines the party: requests are from Agents, responses are from Sellers. Seller responses contain the intersection of supported interventions.\",\n \"properties\": {\n \"payment\": {\n \"$ref\": \"#/$defs/Payment\"\n },\n \"interventions\": {\n \"$ref\": \"#/$defs/InterventionCapabilities\"\n },\n \"extensions\": {\n \"oneOf\": [\n {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Extension identifier string\"\n },\n \"uniqueItems\": true,\n \"description\": \"Extensions the agent understands (request). Simple identifiers like 'discount'.\"\n },\n {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/ExtensionDeclaration\"\n },\n \"uniqueItems\": true,\n \"description\": \"Active extensions for this session (response). Objects with name, extends, schema, spec.\"\n }\n ],\n \"description\": \"Extensions supported by the party. Requests: array of extension identifiers. Responses: array of extension declaration objects.\"\n }\n },\n \"example\": {\n \"interventions\": {\n \"supported\": [\n \"3ds\"\n ],\n \"display_context\": \"native\"\n },\n \"extensions\": [\n \"discount\",\n \"affiliate_attribution\"\n ]\n }\n },\n \"ExtensionDeclaration\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Extension declaration in capabilities.extensions (response). Describes an active extension and which schema fields it adds.\",\n \"required\": [\n \"name\"\n ],\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z][a-z0-9_-]*(@\\\\d{4}-\\\\d{2}-\\\\d{2})?$|^[a-z][a-z0-9]*(?:\\\\.[a-z][a-z0-9_-]*)+(@\\\\d{4}-\\\\d{2}-\\\\d{2})?$\",\n \"description\": \"Unique identifier for the extension.\"\n },\n \"extends\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\$\\\\.[A-Za-z][A-Za-z0-9]*(\\\\.[A-Za-z][A-Za-z0-9_]*)*$\",\n \"description\": \"JSONPath expression identifying a schema field added by this extension\"\n },\n \"uniqueItems\": true,\n \"description\": \"JSONPath expressions identifying the schema fields added by this extension. Format: $.<SchemaName>.<fieldName> (e.g., $.CheckoutSession.discounts).\"\n },\n \"schema\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the extension's JSON Schema definition.\"\n },\n \"spec\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the extension's specification document.\"\n }\n },\n \"example\": {\n \"name\": \"discount\",\n \"extends\": [\n \"$.CheckoutSession.discounts\",\n \"$.CheckoutSessionCreateRequest.coupons\"\n ],\n \"schema\": \"https://example.com/schemas/extensions/discount.schema.json\",\n \"spec\": \"https://example.com/specs/extensions/discount\"\n }\n },\n \"PaymentMethodObject\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Payment method with additional constraints (e.g., card brands, PSP routing)\",\n \"properties\": {\n \"method\": {\n \"type\": \"string\",\n \"description\": \"The payment method identifier\"\n },\n \"brands\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\n \"visa\",\n \"mastercard\",\n \"amex\",\n \"discover\",\n \"diners\",\n \"jcb\",\n \"unionpay\",\n \"eftpos\",\n \"interac\"\n ]\n },\n \"description\": \"Specific card brands/networks accepted\"\n },\n \"funding_types\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\n \"credit\",\n \"debit\",\n \"prepaid\"\n ]\n },\n \"description\": \"For card methods, funding types accepted\"\n },\n \"providers\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Payment service provider identifier\"\n },\n \"description\": \"Optional PSP routing information\"\n }\n },\n \"required\": [\n \"method\"\n ],\n \"example\": {\n \"method\": \"card\",\n \"brands\": [\n \"visa\",\n \"mastercard\"\n ],\n \"providers\": [\n \"stripe\",\n \"adyen\"\n ]\n }\n },\n \"Item\": {\n \"description\": \"A purchasable item with variant options (e.g., size, color) and quantity\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for the item\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Display name of the item\"\n },\n \"unit_amount\": {\n \"type\": \"integer\",\n \"description\": \"Price per unit in minor currency units (e.g. 100 cents for $1.00 or 100 for ¥100)\"\n }\n },\n \"required\": [\n \"id\"\n ],\n \"example\": {\n \"id\": \"item_123\",\n \"name\": \"Wireless Headphones\",\n \"unit_amount\": 7999\n }\n },\n \"Disclosure\": {\n \"description\": \"Legal disclosure or terms that must be acknowledged by the buyer\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"disclaimer\"\n ],\n \"description\": \"Type of disclosure\"\n },\n \"content_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"plain\",\n \"markdown\"\n ],\n \"description\": \"Format of the disclosure content. When set to 'markdown', content MUST conform to CommonMark (https://spec.commonmark.org/0.31.2/). Raw HTML elements MUST NOT be included. When set to 'plain', content is plain text with no formatting.\"\n },\n \"content\": {\n \"type\": \"string\",\n \"description\": \"The disclosure text content. When content_type is 'markdown', this MUST be valid CommonMark with no raw HTML. Agents MUST render using a CommonMark-compliant parser with raw HTML output disabled or sanitized.\"\n }\n },\n \"required\": [\n \"type\",\n \"content_type\",\n \"content\"\n ],\n \"example\": {\n \"type\": \"disclaimer\",\n \"content_type\": \"plain\",\n \"content\": \"This product contains small parts and is not suitable for children under 3 years.\"\n }\n },\n \"CustomAttribute\": {\n \"description\": \"Custom key-value attribute for merchant-specific metadata on line items\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"display_name\": {\n \"type\": \"string\",\n \"description\": \"Human-readable label for the attribute\"\n },\n \"value\": {\n \"type\": \"string\",\n \"description\": \"Attribute value\"\n }\n },\n \"required\": [\n \"display_name\",\n \"value\"\n ],\n \"example\": {\n \"display_name\": \"Engraving\",\n \"value\": \"Happy Birthday!\"\n }\n },\n \"MarketplaceSellerDetails\": {\n \"description\": \"Information about a third-party seller in a marketplace model\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Name of the marketplace seller or vendor\"\n }\n },\n \"required\": [\n \"name\"\n ],\n \"example\": {\n \"name\": \"TechGear Store\"\n }\n },\n \"PaymentHandler\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Payment handler configuration and capabilities\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Seller-defined handler identifier\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Handler name in reverse-DNS format (e.g., dev.acp.tokenized.card)\"\n },\n \"display_name\": {\n \"type\": \"string\",\n \"description\": \"Human-readable name for UI (e.g., Credit Card). Use when showing payment options to the buyer.\"\n },\n \"version\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{4}-\\\\d{2}-\\\\d{2}$\",\n \"description\": \"Handler version in YYYY-MM-DD format\"\n },\n \"spec\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to handler specification\"\n },\n \"requires_delegate_payment\": {\n \"type\": \"boolean\",\n \"description\": \"Whether this handler requires using delegate_payment API\"\n },\n \"requires_pci_compliance\": {\n \"type\": \"boolean\",\n \"description\": \"Whether this handler routes PCI DSS sensitive data\"\n },\n \"psp\": {\n \"type\": \"string\",\n \"description\": \"Payment Service Provider identifier\"\n },\n \"config_schema\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to JSON Schema for handler configuration\"\n },\n \"instrument_schemas\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to a JSON Schema defining accepted payment instrument format\"\n },\n \"description\": \"URLs to JSON Schemas for payment instruments\"\n },\n \"config\": {\n \"type\": \"object\",\n \"description\": \"Handler-specific configuration\"\n },\n \"display_order\": {\n \"type\": \"integer\",\n \"description\": \"Optional merchant-suggested display order (lower = higher preference). Suggestive only; platform/agent MAY reorder.\"\n }\n },\n \"required\": [\n \"id\",\n \"name\",\n \"version\",\n \"spec\",\n \"requires_delegate_payment\",\n \"requires_pci_compliance\",\n \"psp\",\n \"config_schema\",\n \"instrument_schemas\",\n \"config\"\n ],\n \"example\": {\n \"id\": \"handler_stripe_01\",\n \"name\": \"Stripe\",\n \"type\": \"direct\",\n \"instrument_schemas\": [\n \"https://example.com/schemas/payment/card.json\"\n ]\n }\n },\n \"Payment\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Payment configuration with handlers\",\n \"properties\": {\n \"handlers\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/PaymentHandler\"\n },\n \"description\": \"Available payment handlers\"\n }\n },\n \"required\": [\n \"handlers\"\n ],\n \"example\": {\n \"handlers\": []\n }\n },\n \"LineItem\": {\n \"description\": \"A line item in the checkout representing a product with pricing, discounts, and fulfillment details\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for the line item\"\n },\n \"item\": {\n \"$ref\": \"#/$defs/Item\",\n \"description\": \"Reference to the item being purchased\"\n },\n \"quantity\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Number of units for this line item\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Display name of the line item\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Detailed description of the line item\"\n },\n \"images\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"Image URL for the product\"\n },\n \"description\": \"Array of image URLs for this line item\"\n },\n \"unit_amount\": {\n \"type\": \"integer\",\n \"description\": \"The unit price of the line item in the smallest currency unit (e.g., cents for USD)\"\n },\n \"disclosures\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Disclosure\"\n },\n \"description\": \"Legal disclosures or disclaimers for this item\"\n },\n \"custom_attributes\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/CustomAttribute\"\n },\n \"description\": \"Custom attributes specific to this line item\"\n },\n \"marketplace_seller_details\": {\n \"$ref\": \"#/$defs/MarketplaceSellerDetails\",\n \"description\": \"Seller details for marketplace items\"\n },\n \"product_id\": {\n \"type\": \"string\",\n \"description\": \"Merchant's product identifier\"\n },\n \"sku\": {\n \"type\": \"string\",\n \"description\": \"Stock keeping unit identifier\"\n },\n \"variant_id\": {\n \"type\": \"string\",\n \"description\": \"Product variant identifier\"\n },\n \"category\": {\n \"type\": \"string\",\n \"description\": \"Product category\"\n },\n \"tags\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Product tag or category\"\n },\n \"description\": \"Product tags or labels\"\n },\n \"weight\": {\n \"$ref\": \"#/$defs/WeightInfo\",\n \"description\": \"Weight information for the item\"\n },\n \"dimensions\": {\n \"$ref\": \"#/$defs/DimensionsInfo\",\n \"description\": \"Dimensions for the item\"\n },\n \"availability_status\": {\n \"type\": \"string\",\n \"enum\": [\n \"in_stock\",\n \"low_stock\",\n \"out_of_stock\",\n \"backorder\",\n \"pre_order\"\n ],\n \"description\": \"Current availability status of the item\"\n },\n \"available_quantity\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Quantity currently available for purchase\"\n },\n \"max_quantity_per_order\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Maximum quantity allowed per order\"\n },\n \"fulfillable_on\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when item becomes available for fulfillment\"\n },\n \"variant_options\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/VariantOption\"\n },\n \"description\": \"Selected product variant options (e.g., size, color)\"\n },\n \"discount_details\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/DiscountDetail\"\n },\n \"description\": \"Line-item level discount details\"\n },\n \"tax_exempt\": {\n \"type\": \"boolean\",\n \"description\": \"Whether this line item is tax exempt\"\n },\n \"tax_exemption_reason\": {\n \"type\": \"string\",\n \"description\": \"Reason for tax exemption if applicable\"\n },\n \"parent_id\": {\n \"type\": \"string\",\n \"description\": \"Reference to parent line item for bundled products\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Line-item level totals breakdown including base_amount, discount, subtotal, tax, and total\"\n }\n },\n \"required\": [\n \"id\",\n \"item\",\n \"quantity\",\n \"totals\"\n ],\n \"example\": {\n \"id\": \"item_001\",\n \"product_id\": \"prod_tshirt_blue_m\",\n \"name\": \"Organic Cotton T-Shirt\",\n \"quantity\": 2,\n \"base_amount\": 2900,\n \"discount\": 0,\n \"subtotal\": 5800,\n \"tax\": 464,\n \"total\": 6264,\n \"currency\": \"usd\",\n \"image_url\": \"https://example.com/images/tshirt-blue.jpg\"\n }\n },\n \"TaxBreakdownItem\": {\n \"description\": \"Breakdown of tax amounts by type, jurisdiction, or rate\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"jurisdiction\": {\n \"type\": \"string\",\n \"description\": \"Tax jurisdiction name (e.g., 'California State Tax', 'City of San Francisco')\"\n },\n \"rate\": {\n \"type\": \"number\",\n \"description\": \"Tax rate as a decimal (e.g., 0.0875 for 8.75%)\"\n },\n \"amount\": {\n \"type\": \"integer\",\n \"description\": \"Tax amount in minor currency units (e.g. 100 cents for $1.00 or 100 for ¥100)\"\n }\n },\n \"required\": [\n \"jurisdiction\",\n \"rate\",\n \"amount\"\n ],\n \"example\": {\n \"name\": \"State Sales Tax\",\n \"amount\": 464,\n \"rate\": 0.08\n }\n },\n \"Total\": {\n \"description\": \"Total amounts for the checkout including subtotal, discounts, tax, shipping, and final total\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"items_base_amount\",\n \"items_discount\",\n \"subtotal\",\n \"discount\",\n \"fulfillment\",\n \"tax\",\n \"fee\",\n \"gift_wrap\",\n \"tip\",\n \"store_credit\",\n \"total\",\n \"amount_refunded\"\n ],\n \"description\": \"Type of total line item\"\n },\n \"display_text\": {\n \"type\": \"string\",\n \"description\": \"Localized display text for this total\"\n },\n \"amount\": {\n \"type\": \"integer\",\n \"description\": \"Amount in minor currency units (e.g. 100 cents for $1.00 or 100 for ¥100)\"\n },\n \"presentment_amount\": {\n \"type\": \"integer\",\n \"description\": \"Amount in presentment currency minor units if different from settlement currency\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Additional descriptive text for this total\"\n },\n \"breakdown\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/TaxBreakdownItem\"\n },\n \"description\": \"Detailed breakdown for tax totals\"\n }\n },\n \"required\": [\n \"type\",\n \"display_text\",\n \"amount\"\n ],\n \"example\": {\n \"currency\": \"usd\",\n \"subtotal\": 5800,\n \"discount\": 0,\n \"tax\": 464,\n \"shipping\": 500,\n \"total\": 6764\n }\n },\n \"FulfillmentOptionPickup\": {\n \"description\": \"In-store or curbside pickup fulfillment option with pickup location details\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"pickup\",\n \"description\": \"Fulfillment type discriminator\"\n },\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for this fulfillment option\"\n },\n \"title\": {\n \"type\": \"string\",\n \"description\": \"Display title for this pickup option\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Additional details about this pickup option\"\n },\n \"location\": {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Location name\"\n },\n \"address\": {\n \"$ref\": \"#/$defs/Address\",\n \"description\": \"Pickup address\"\n },\n \"phone\": {\n \"type\": \"string\",\n \"description\": \"Location phone number\"\n },\n \"instructions\": {\n \"type\": \"string\",\n \"description\": \"Special pickup instructions\"\n }\n },\n \"required\": [\n \"name\",\n \"address\"\n ],\n \"description\": \"Pickup location details\"\n },\n \"pickup_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"in_store\",\n \"curbside\",\n \"locker\"\n ],\n \"description\": \"Type of pickup method\"\n },\n \"ready_by\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when order will be ready for pickup\"\n },\n \"pickup_by\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp by which order must be picked up\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Cost breakdown for this fulfillment option\"\n }\n },\n \"required\": [\n \"type\",\n \"id\",\n \"title\",\n \"location\",\n \"totals\"\n ],\n \"example\": {\n \"id\": \"pickup_01\",\n \"type\": \"pickup\",\n \"name\": \"Store Pickup\",\n \"cost\": 0,\n \"currency\": \"usd\",\n \"address\": {\n \"name\": \"Downtown Store\",\n \"line_one\": \"123 Main St\",\n \"city\": \"San Francisco\",\n \"state\": \"CA\",\n \"country\": \"US\",\n \"postal_code\": \"94102\"\n }\n }\n },\n \"FulfillmentOptionLocalDelivery\": {\n \"description\": \"Local delivery fulfillment option with delivery address and scheduling details\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"local_delivery\",\n \"description\": \"Fulfillment type discriminator\"\n },\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for this fulfillment option\"\n },\n \"title\": {\n \"type\": \"string\",\n \"description\": \"Display title for this local delivery option\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Additional details about this delivery option\"\n },\n \"delivery_window\": {\n \"type\": \"object\",\n \"properties\": {\n \"start\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp for delivery window start\"\n },\n \"end\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp for delivery window end\"\n }\n },\n \"required\": [\n \"start\",\n \"end\"\n ],\n \"description\": \"Expected delivery time window\"\n },\n \"service_area\": {\n \"type\": \"object\",\n \"properties\": {\n \"radius_miles\": {\n \"type\": \"number\",\n \"description\": \"Delivery radius in miles\"\n },\n \"center_postal_code\": {\n \"type\": \"string\",\n \"description\": \"Center point postal code for delivery radius\"\n }\n },\n \"description\": \"Geographic service area for local delivery\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Cost breakdown for this fulfillment option\"\n }\n },\n \"required\": [\n \"type\",\n \"id\",\n \"title\",\n \"totals\"\n ],\n \"example\": {\n \"id\": \"delivery_01\",\n \"type\": \"local_delivery\",\n \"name\": \"Same Day Delivery\",\n \"cost\": 999,\n \"currency\": \"usd\",\n \"address\": {\n \"name\": \"Jane Doe\",\n \"line_one\": \"456 Oak Ave\",\n \"city\": \"San Francisco\",\n \"state\": \"CA\",\n \"country\": \"US\",\n \"postal_code\": \"94103\"\n }\n }\n },\n \"FulfillmentOptionShipping\": {\n \"description\": \"Shipping fulfillment option with carrier, service level, and delivery estimates\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"shipping\",\n \"description\": \"Fulfillment type discriminator\"\n },\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for this fulfillment option\"\n },\n \"title\": {\n \"type\": \"string\",\n \"description\": \"Display title for this shipping option (e.g., 'Standard Shipping', 'Express')\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Additional details about this shipping option\"\n },\n \"carrier\": {\n \"type\": \"string\",\n \"description\": \"Shipping carrier name (e.g., 'USPS', 'FedEx')\"\n },\n \"earliest_delivery_time\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp for earliest expected delivery\"\n },\n \"latest_delivery_time\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp for latest expected delivery\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Cost breakdown for this fulfillment option\"\n }\n },\n \"required\": [\n \"type\",\n \"id\",\n \"title\",\n \"totals\"\n ],\n \"example\": {\n \"id\": \"ship_01\",\n \"type\": \"shipping\",\n \"name\": \"Standard Shipping\",\n \"cost\": 500,\n \"currency\": \"usd\",\n \"carrier\": \"USPS\",\n \"service_level\": \"ground\"\n }\n },\n \"FulfillmentOptionDigital\": {\n \"description\": \"Digital delivery fulfillment option for downloadable or streaming content\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"digital\",\n \"description\": \"Fulfillment type discriminator\"\n },\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for this fulfillment option\"\n },\n \"title\": {\n \"type\": \"string\",\n \"description\": \"Display title for this digital delivery option\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Additional details about digital delivery method\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Cost breakdown for this fulfillment option\"\n }\n },\n \"required\": [\n \"type\",\n \"id\",\n \"title\",\n \"totals\"\n ],\n \"example\": {\n \"id\": \"digital_01\",\n \"type\": \"digital\",\n \"name\": \"Instant Download\",\n \"cost\": 0,\n \"currency\": \"usd\"\n }\n },\n \"SelectedFulfillmentOption\": {\n \"description\": \"Fulfillment option selected by the buyer for specific line items\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"shipping\",\n \"digital\",\n \"pickup\",\n \"local_delivery\"\n ],\n \"description\": \"Type of fulfillment option selected\"\n },\n \"option_id\": {\n \"type\": \"string\",\n \"description\": \"ID of the selected fulfillment option\"\n },\n \"item_ids\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Line item identifier\"\n },\n \"description\": \"List of line item IDs associated with this fulfillment option\"\n }\n },\n \"required\": [\n \"type\",\n \"option_id\",\n \"item_ids\"\n ],\n \"example\": {\n \"id\": \"ship_01\",\n \"type\": \"shipping\",\n \"item_ids\": [\n \"item_001\",\n \"item_002\"\n ]\n }\n },\n \"GiftWrap\": {\n \"description\": \"Gift wrapping option with associated cost and customization details\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"enabled\": {\n \"type\": \"boolean\",\n \"description\": \"Whether gift wrapping is enabled for this order\"\n },\n \"style\": {\n \"type\": \"string\",\n \"enum\": [\n \"birthday\",\n \"holiday\",\n \"elegant\"\n ],\n \"description\": \"Gift wrap style selected\"\n },\n \"charge\": {\n \"type\": \"integer\",\n \"description\": \"Additional charge for gift wrapping in minor currency units (e.g. 100 cents for $1.00 or 100 for ¥100)\"\n }\n },\n \"required\": [\n \"enabled\"\n ],\n \"example\": {\n \"available\": true,\n \"cost\": 500,\n \"currency\": \"usd\",\n \"message\": \"Happy Birthday!\"\n }\n },\n \"SplitPayment\": {\n \"description\": \"Split payment configuration allowing payment across multiple methods or parties\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\",\n \"description\": \"Payment amount in minor currency units (e.g. 100 cents for $1.00 or 100 for ¥100) for this split\"\n }\n },\n \"required\": [\n \"amount\"\n ],\n \"example\": {\n \"enabled\": true,\n \"methods\": [\n \"card\",\n \"paypal\"\n ]\n }\n },\n \"FulfillmentGroup\": {\n \"description\": \"Group of line items that share the same fulfillment method and destination\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for this fulfillment group\"\n },\n \"item_ids\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Line item identifier in this fulfillment group\"\n },\n \"description\": \"List of line item IDs in this fulfillment group\"\n },\n \"destination_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"shipping\",\n \"pickup\",\n \"local_delivery\",\n \"digital\"\n ],\n \"description\": \"Type of fulfillment for this group\"\n },\n \"fulfillment_details\": {\n \"$ref\": \"#/$defs/FulfillmentDetails\",\n \"description\": \"Fulfillment contact and address details\"\n },\n \"location_id\": {\n \"type\": \"string\",\n \"description\": \"Location identifier for pickup or local delivery\"\n },\n \"instructions\": {\n \"type\": \"string\",\n \"description\": \"Special fulfillment instructions\"\n }\n },\n \"required\": [\n \"id\",\n \"item_ids\",\n \"destination_type\"\n ],\n \"example\": {\n \"id\": \"fg_01\",\n \"fulfillment_option_id\": \"ship_01\",\n \"item_ids\": [\n \"item_001\",\n \"item_002\"\n ]\n }\n },\n \"EstimatedDelivery\": {\n \"description\": \"Estimated delivery date range for a fulfillment option\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"earliest\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp for earliest expected delivery\"\n },\n \"latest\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp for latest expected delivery\"\n }\n },\n \"required\": [\n \"earliest\",\n \"latest\"\n ],\n \"example\": {\n \"earliest\": \"2026-02-15\",\n \"latest\": \"2026-02-20\"\n }\n },\n \"OrderConfirmation\": {\n \"description\": \"Order confirmation details including order number and tracking information\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"confirmation_number\": {\n \"type\": \"string\",\n \"description\": \"Order confirmation number\"\n },\n \"confirmation_email_sent\": {\n \"type\": \"boolean\",\n \"description\": \"Whether a confirmation email has been sent\"\n },\n \"receipt_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the order receipt\"\n },\n \"invoice_number\": {\n \"type\": \"string\",\n \"description\": \"Invoice number if generated\"\n },\n \"order_notes\": {\n \"type\": \"string\",\n \"description\": \"Echo of order_notes attached to the order.\"\n }\n },\n \"example\": {\n \"order_id\": \"ord_abc123\",\n \"order_number\": \"12345\",\n \"confirmation_url\": \"https://example.com/orders/ord_abc123\"\n }\n },\n \"SupportInfo\": {\n \"description\": \"Customer support contact information including email, phone, and URL\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"email\": {\n \"type\": \"string\",\n \"format\": \"email\",\n \"description\": \"Support contact email\"\n },\n \"phone\": {\n \"type\": \"string\",\n \"description\": \"Support contact phone number\"\n },\n \"hours\": {\n \"type\": \"string\",\n \"description\": \"Support hours of operation\"\n },\n \"help_center_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to merchant's help center\"\n }\n },\n \"example\": {\n \"email\": \"support@example.com\",\n \"phone\": \"+1-800-555-0123\",\n \"url\": \"https://example.com/support\"\n }\n },\n \"MessageInfo\": {\n \"description\": \"Informational message to display to the buyer during checkout\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"info\",\n \"description\": \"Message type discriminator\"\n },\n \"severity\": {\n \"type\": \"string\",\n \"enum\": [\n \"info\",\n \"low\",\n \"medium\",\n \"high\",\n \"critical\"\n ],\n \"description\": \"Severity level of this informational message\"\n },\n \"resolution\": {\n \"type\": \"string\",\n \"enum\": [\n \"recoverable\",\n \"requires_buyer_input\",\n \"requires_buyer_review\"\n ],\n \"description\": \"Who resolves this message. 'recoverable': agent can fix via API. 'requires_buyer_input': buyer must provide info. 'requires_buyer_review': buyer must authorize.\"\n },\n \"param\": {\n \"type\": \"string\",\n \"description\": \"RFC 9535 JSONPath\"\n },\n \"content_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"plain\",\n \"markdown\"\n ],\n \"description\": \"Format of the message content. When set to 'markdown', content MUST conform to CommonMark (https://spec.commonmark.org/0.31.2/). Raw HTML elements MUST NOT be included. When set to 'plain', content is plain text with no formatting.\"\n },\n \"content\": {\n \"type\": \"string\",\n \"description\": \"Informational message text. When content_type is 'markdown', this MUST be valid CommonMark with no raw HTML. Agents MUST render using a CommonMark-compliant parser with raw HTML output disabled or sanitized.\"\n }\n },\n \"required\": [\n \"type\",\n \"content_type\",\n \"content\"\n ],\n \"example\": {\n \"id\": \"msg_info_01\",\n \"message\": \"Free shipping on orders over $50\",\n \"display_context\": \"banner\"\n }\n },\n \"MessageWarning\": {\n \"description\": \"Warning message to display to the buyer during checkout (non-blocking)\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"warning\",\n \"description\": \"Message type discriminator\"\n },\n \"code\": {\n \"type\": \"string\",\n \"enum\": [\n \"low_stock\",\n \"high_demand\",\n \"shipping_delay\",\n \"price_change\",\n \"expiring_promotion\",\n \"limited_availability\",\n \"discount_code_expired\",\n \"discount_code_invalid\",\n \"discount_code_already_applied\",\n \"discount_code_combination_disallowed\",\n \"discount_code_minimum_not_met\",\n \"discount_code_user_not_logged_in\",\n \"discount_code_user_ineligible\",\n \"discount_code_usage_limit_reached\"\n ],\n \"description\": \"Warning code indicating the type of warning\"\n },\n \"severity\": {\n \"type\": \"string\",\n \"enum\": [\n \"info\",\n \"low\",\n \"medium\",\n \"high\",\n \"critical\"\n ],\n \"description\": \"Severity level of this warning\"\n },\n \"resolution\": {\n \"type\": \"string\",\n \"enum\": [\n \"recoverable\",\n \"requires_buyer_input\",\n \"requires_buyer_review\"\n ],\n \"description\": \"Who resolves this message. 'recoverable': agent can fix via API. 'requires_buyer_input': buyer must provide info. 'requires_buyer_review': buyer must authorize.\"\n },\n \"param\": {\n \"type\": \"string\",\n \"description\": \"RFC 9535 JSONPath\"\n },\n \"content_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"plain\",\n \"markdown\"\n ],\n \"description\": \"Format of the warning message content. When set to 'markdown', content MUST conform to CommonMark (https://spec.commonmark.org/0.31.2/). Raw HTML elements MUST NOT be included. When set to 'plain', content is plain text with no formatting.\"\n },\n \"content\": {\n \"type\": \"string\",\n \"description\": \"Warning message text. When content_type is 'markdown', this MUST be valid CommonMark with no raw HTML. Agents MUST render using a CommonMark-compliant parser with raw HTML output disabled or sanitized.\"\n }\n },\n \"required\": [\n \"type\",\n \"code\",\n \"content_type\",\n \"content\"\n ],\n \"example\": {\n \"id\": \"msg_warn_01\",\n \"message\": \"Only 2 items left in stock\",\n \"code\": \"low_stock\",\n \"param\": \"$.items[0]\"\n }\n },\n \"MessageError\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Business-logic error within a valid CheckoutSession response. Used in messages[] on 2xx responses when the session is valid but has actionable issues (e.g. status \\\"not_ready_for_payment\\\"). The agent can respond by asking the buyer for corrections or trying alternatives. Use MessageError—not Error—when you can return a valid CheckoutSession and the problem is conversational (e.g. invalid email → code \\\"invalid\\\" and param \\\"$.buyer.email\\\"; out of stock → code \\\"out_of_stock\\\" and param \\\"$.items[0]\\\").\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"error\",\n \"description\": \"Message type discriminator\"\n },\n \"code\": {\n \"type\": \"string\",\n \"enum\": [\n \"missing\",\n \"invalid\",\n \"out_of_stock\",\n \"payment_declined\",\n \"requires_sign_in\",\n \"requires_3ds\",\n \"low_stock\",\n \"quantity_exceeded\",\n \"coupon_invalid\",\n \"coupon_expired\",\n \"minimum_not_met\",\n \"maximum_exceeded\",\n \"region_restricted\",\n \"age_verification_required\",\n \"approval_required\",\n \"unsupported\",\n \"not_found\",\n \"conflict\",\n \"rate_limited\",\n \"expired\",\n \"intervention_required\"\n ],\n \"description\": \"Error code indicating the type of error\"\n },\n \"severity\": {\n \"type\": \"string\",\n \"enum\": [\n \"info\",\n \"low\",\n \"medium\",\n \"high\",\n \"critical\"\n ],\n \"description\": \"Severity level of this error\"\n },\n \"resolution\": {\n \"type\": \"string\",\n \"enum\": [\n \"recoverable\",\n \"requires_buyer_input\",\n \"requires_buyer_review\"\n ],\n \"description\": \"Who resolves this message. 'recoverable': agent can fix via API. 'requires_buyer_input': buyer must provide info. 'requires_buyer_review': buyer must authorize.\"\n },\n \"param\": {\n \"type\": \"string\",\n \"description\": \"RFC 9535 JSONPath\"\n },\n \"content_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"plain\",\n \"markdown\"\n ],\n \"description\": \"Format of the error message content. When set to 'markdown', content MUST conform to CommonMark (https://spec.commonmark.org/0.31.2/). Raw HTML elements MUST NOT be included. When set to 'plain', content is plain text with no formatting.\"\n },\n \"content\": {\n \"type\": \"string\",\n \"description\": \"Error message text. When content_type is 'markdown', this MUST be valid CommonMark with no raw HTML. Agents MUST render using a CommonMark-compliant parser with raw HTML output disabled or sanitized.\"\n }\n },\n \"required\": [\n \"type\",\n \"code\",\n \"content_type\",\n \"content\"\n ],\n \"example\": {\n \"id\": \"msg_err_01\",\n \"message\": \"Invalid email address format\",\n \"code\": \"invalid\",\n \"param\": \"$.buyer.email\"\n }\n },\n \"Link\": {\n \"description\": \"Hyperlink with URL, display text, and optional action semantics\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"terms_of_use\",\n \"privacy_policy\",\n \"return_policy\",\n \"shipping_policy\",\n \"contact_us\",\n \"about_us\",\n \"faq\",\n \"support\"\n ],\n \"description\": \"Type of link\"\n },\n \"title\": {\n \"type\": \"string\",\n \"description\": \"Display text for the link\"\n },\n \"url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL destination\"\n }\n },\n \"required\": [\n \"type\",\n \"url\"\n ],\n \"example\": {\n \"url\": \"https://example.com/terms\",\n \"text\": \"Terms of Service\",\n \"action\": \"view\"\n }\n },\n \"PaymentData\": {\n \"description\": \"Payment instrument data collected from the buyer (e.g., card details, wallet tokens)\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"handler_id\": {\n \"type\": \"string\",\n \"description\": \"ID of the payment handler to use\"\n },\n \"instrument\": {\n \"type\": \"object\",\n \"description\": \"Payment instrument details\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"description\": \"Instrument type (e.g., card, wallet_token)\"\n },\n \"credential\": {\n \"type\": \"object\",\n \"description\": \"Payment credential\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"description\": \"Credential type (e.g., spt, wallet_token)\"\n },\n \"token\": {\n \"type\": \"string\",\n \"description\": \"Credential token value\"\n }\n },\n \"required\": [\n \"type\",\n \"token\"\n ]\n }\n },\n \"required\": [\n \"type\",\n \"credential\"\n ]\n },\n \"billing_address\": {\n \"$ref\": \"#/$defs/Address\",\n \"description\": \"Billing address for the payment\"\n },\n \"purchase_order_number\": {\n \"type\": \"string\",\n \"description\": \"Purchase order number\"\n },\n \"payment_terms\": {\n \"type\": \"string\",\n \"enum\": [\n \"immediate\",\n \"net_15\",\n \"net_30\",\n \"net_60\",\n \"net_90\"\n ],\n \"description\": \"Payment terms for B2B transactions\"\n },\n \"due_date\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when payment is due\"\n },\n \"approval_required\": {\n \"type\": \"boolean\",\n \"description\": \"Whether this payment requires approval\"\n }\n },\n \"anyOf\": [\n {\n \"required\": [\n \"handler_id\",\n \"instrument\"\n ]\n },\n {\n \"required\": [\n \"purchase_order_number\"\n ]\n }\n ],\n \"example\": {\n \"type\": \"vault_token\",\n \"token\": \"vt_01J8Z3WXYZ9ABC123\"\n }\n },\n \"ProtocolVersion\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Protocol metadata included in checkout responses. Indicates the ACP version.\",\n \"properties\": {\n \"version\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{4}-\\\\d{2}-\\\\d{2}$\",\n \"example\": \"2026-01-27\",\n \"description\": \"ACP protocol version in YYYY-MM-DD format.\"\n }\n },\n \"required\": [\n \"version\"\n ],\n \"example\": {\n \"version\": \"2026-04-17\"\n }\n },\n \"DiscountAllocation\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Breakdown of how a discount amount was allocated to a specific target.\",\n \"required\": [\n \"path\",\n \"amount\"\n ],\n \"properties\": {\n \"path\": {\n \"type\": \"string\",\n \"description\": \"JSONPath to the allocation target (e.g., '$.line_items[0]', '$.totals.shipping').\"\n },\n \"amount\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Amount allocated to this target in minor (cents) currency units.\"\n }\n },\n \"example\": {\n \"target\": \"line_item\",\n \"target_id\": \"item_001\",\n \"amount\": 500\n }\n },\n \"Coupon\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Coupon details describing the discount terms.\",\n \"required\": [\n \"id\",\n \"name\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for the coupon.\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Human-readable coupon name (e.g., 'Summer Sale 20% Off').\"\n },\n \"percent_off\": {\n \"type\": \"number\",\n \"minimum\": 0,\n \"maximum\": 100,\n \"description\": \"Percentage discount (0-100). Mutually exclusive with amount_off.\"\n },\n \"amount_off\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Fixed discount amount in minor currency units. Mutually exclusive with percent_off.\"\n },\n \"currency\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z]{3}$\",\n \"description\": \"ISO 4217 currency code for amount_off. Required if amount_off is set.\"\n },\n \"duration\": {\n \"type\": \"string\",\n \"enum\": [\n \"once\",\n \"repeating\",\n \"forever\"\n ],\n \"description\": \"How long the discount applies. 'once' = single use, 'repeating' = multiple billing periods, 'forever' = indefinitely.\"\n },\n \"duration_in_months\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Number of months the coupon applies if duration is 'repeating'.\"\n },\n \"max_redemptions\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Maximum number of times this coupon can be redeemed across all customers.\"\n },\n \"times_redeemed\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Number of times this coupon has been redeemed.\"\n },\n \"metadata\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"type\": \"string\",\n \"description\": \"Metadata value\"\n },\n \"description\": \"Arbitrary key-value metadata attached to the coupon.\"\n }\n },\n \"example\": {\n \"code\": \"SAVE20\",\n \"metadata\": {}\n }\n },\n \"AppliedDiscount\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"A discount that was successfully applied to the checkout session.\",\n \"required\": [\n \"id\",\n \"coupon\",\n \"amount\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for this applied discount instance.\"\n },\n \"code\": {\n \"type\": \"string\",\n \"description\": \"The discount code entered by the user. Omitted for automatic discounts.\"\n },\n \"coupon\": {\n \"$ref\": \"#/$defs/Coupon\",\n \"description\": \"Details about the underlying coupon/promotion.\"\n },\n \"amount\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Total discount amount in minor (cents) currency units.\"\n },\n \"automatic\": {\n \"type\": \"boolean\",\n \"default\": false,\n \"description\": \"True if applied automatically by merchant rules (no code required).\"\n },\n \"start\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the discount became active.\"\n },\n \"end\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the discount expires.\"\n },\n \"method\": {\n \"type\": \"string\",\n \"enum\": [\n \"each\",\n \"across\"\n ],\n \"description\": \"Allocation method. 'each' = applied independently per item. 'across' = split proportionally by value.\"\n },\n \"priority\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Stacking order for discount calculation. Lower numbers applied first (1 = first).\"\n },\n \"allocations\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/DiscountAllocation\"\n },\n \"description\": \"Breakdown of where this discount was allocated. Sum of allocation amounts equals total amount.\"\n }\n },\n \"example\": {\n \"code\": \"SAVE20\",\n \"amount\": 1000,\n \"allocations\": []\n }\n },\n \"DiscountsRequest\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Discount codes input for checkout create/update requests.\",\n \"properties\": {\n \"codes\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Discount code to apply\"\n },\n \"description\": \"Discount codes to apply. Case-insensitive. Replaces previously submitted codes. Send empty array to clear.\"\n }\n },\n \"example\": {\n \"codes\": [\n \"SAVE20\",\n \"FREESHIP\"\n ]\n }\n },\n \"DiscountsResponse\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Discount codes input and applied discounts output in checkout responses.\",\n \"properties\": {\n \"codes\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Discount code submitted\"\n },\n \"description\": \"Echo of submitted discount codes.\"\n },\n \"applied\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/AppliedDiscount\"\n },\n \"description\": \"Discounts successfully applied (code-based and automatic).\"\n },\n \"rejected\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/RejectedDiscount\"\n },\n \"description\": \"Discount codes that could not be applied, with reasons.\"\n }\n },\n \"example\": {\n \"codes\": [\n \"SAVE20\"\n ],\n \"applied\": [],\n \"rejected\": []\n }\n },\n \"RejectedDiscount\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"A discount code that could not be applied, with the reason.\",\n \"required\": [\n \"code\",\n \"reason\"\n ],\n \"properties\": {\n \"code\": {\n \"type\": \"string\",\n \"description\": \"The discount code that was rejected.\"\n },\n \"reason\": {\n \"$ref\": \"#/$defs/DiscountErrorCode\",\n \"description\": \"Error code indicating why the discount was rejected.\"\n },\n \"message\": {\n \"type\": \"string\",\n \"description\": \"Human-readable explanation of why the code was rejected.\"\n }\n },\n \"example\": {\n \"code\": \"EXPIRED10\",\n \"reason\": \"discount_code_expired\"\n }\n },\n \"DiscountErrorCode\": {\n \"type\": \"string\",\n \"enum\": [\n \"discount_code_expired\",\n \"discount_code_invalid\",\n \"discount_code_already_applied\",\n \"discount_code_combination_disallowed\",\n \"discount_code_minimum_not_met\",\n \"discount_code_user_not_logged_in\",\n \"discount_code_user_ineligible\",\n \"discount_code_usage_limit_reached\"\n ],\n \"description\": \"Error codes for rejected discount codes, used in messages[].code.\",\n \"example\": \"discount_code_expired\"\n },\n \"PaymentResponse\": {\n \"description\": \"Payment configuration returned by the seller including accepted methods and handlers\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"provider\": {\n \"type\": \"string\",\n \"description\": \"Payment provider identifier\"\n },\n \"instruments\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"description\": \"Payment instrument schema reference\"\n },\n \"description\": \"Available payment instruments\"\n },\n \"handlers\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"description\": \"Payment handler configuration\"\n },\n \"description\": \"Available payment handlers\"\n }\n },\n \"example\": {\n \"instruments\": [],\n \"handlers\": []\n }\n },\n \"RiskSignals\": {\n \"description\": \"Risk and fraud detection signals for the checkout session\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"ip_address\": {\n \"type\": \"string\",\n \"description\": \"IP address of the buyer\"\n },\n \"user_agent\": {\n \"type\": \"string\",\n \"description\": \"User agent string of the buyer's browser\"\n },\n \"accept_language\": {\n \"type\": \"string\",\n \"description\": \"Accept-Language header from the buyer's browser\"\n },\n \"session_id\": {\n \"type\": \"string\",\n \"description\": \"Session identifier for the buyer\"\n },\n \"device_fingerprint\": {\n \"type\": \"string\",\n \"description\": \"Device fingerprint for fraud detection\"\n }\n },\n \"example\": {\n \"ip_country\": \"US\",\n \"device_fingerprint\": \"fp_abc123\"\n }\n },\n \"Order\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Order returned after checkout completion. Contains order details and optional rich post-purchase tracking.\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"order\",\n \"description\": \"Discriminator field for webhook payloads. Always 'order' when present.\"\n },\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for the order\"\n },\n \"checkout_session_id\": {\n \"type\": \"string\",\n \"description\": \"ID of the checkout session that created this order\"\n },\n \"order_number\": {\n \"type\": \"string\",\n \"description\": \"Human-readable order number for customer reference\"\n },\n \"client_reference_id\": {\n \"type\": \"string\",\n \"description\": \"Reference from the client (agent/platform) stored on the order for reconciliation (e.g. platform transaction id, PO number, ERP id).\"\n },\n \"permalink_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"Permanent URL where the customer can view order details\"\n },\n \"status\": {\n \"type\": \"string\",\n \"description\": \"Order-level status. Implementations MUST accept unrecognized values gracefully. Defined values: 'created', 'confirmed', 'manual_review', 'processing', 'shipped', 'completed', 'canceled'. 'completed' means all items have been delivered/received regardless of fulfillment method. Distinct from LineItem.status 'fulfilled', which indicates the seller has dispatched the item.\"\n },\n \"estimated_delivery\": {\n \"$ref\": \"#/$defs/EstimatedDelivery\",\n \"description\": \"Estimated delivery time range\"\n },\n \"confirmation\": {\n \"$ref\": \"#/$defs/OrderConfirmation\",\n \"description\": \"Order confirmation details\"\n },\n \"support\": {\n \"$ref\": \"#/$defs/SupportInfo\",\n \"description\": \"Customer support contact information\"\n },\n \"line_items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/OrderLineItem\"\n },\n \"description\": \"What was ordered, with per-item fulfillment tracking\"\n },\n \"fulfillments\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Fulfillment\"\n },\n \"description\": \"How items are being delivered (shipping, pickup, digital)\"\n },\n \"adjustments\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Adjustment\"\n },\n \"description\": \"Post-order changes: refunds, credits, returns, disputes\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Order-level totals using the same Total schema as checkout. The 'total' entry is always the original charged amount. 'amount_refunded' tracks cumulative refunds.\"\n }\n },\n \"required\": [\n \"id\",\n \"checkout_session_id\",\n \"permalink_url\"\n ],\n \"example\": {\n \"id\": \"ord_abc123\",\n \"order_number\": \"12345\",\n \"status\": \"confirmed\",\n \"currency\": \"usd\",\n \"total\": 6764,\n \"line_items\": [],\n \"created_at\": \"2026-02-13T10:30:00Z\"\n }\n },\n \"OrderLineItem\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Per-line-item tracking of what was ordered and fulfillment progress.\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Line item identifier, used for references in fulfillments and adjustments\"\n },\n \"title\": {\n \"type\": \"string\",\n \"description\": \"Product name\"\n },\n \"product_id\": {\n \"type\": \"string\",\n \"description\": \"Catalog product ID\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Product description\"\n },\n \"image_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"Product image URL\"\n },\n \"url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"Product page URL\"\n },\n \"quantity\": {\n \"$ref\": \"#/$defs/OrderLineItemQuantity\"\n },\n \"unit_price\": {\n \"type\": \"integer\",\n \"description\": \"Price per unit in minor currency units (cents)\"\n },\n \"subtotal\": {\n \"type\": \"integer\",\n \"description\": \"Line total in minor currency units\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Optional line-item level totals breakdown using the same Total schema as checkout. Merchants who can provide richer breakdowns MAY use this alongside or instead of unit_price/subtotal.\"\n },\n \"status\": {\n \"type\": \"string\",\n \"description\": \"Derived from quantity fields. Implementations MUST accept unrecognized values gracefully. Defined values: 'processing', 'partial', 'fulfilled', 'removed'. Rules: 'removed' if current==0, 'fulfilled' if fulfilled==current, 'partial' if 0<fulfilled<current, 'processing' otherwise.\"\n }\n },\n \"required\": [\n \"id\",\n \"title\",\n \"quantity\"\n ],\n \"example\": {\n \"id\": \"oli_001\",\n \"title\": \"Running Shoes\",\n \"status\": \"fulfilled\",\n \"quantity\": {\n \"ordered\": 2,\n \"current\": 2,\n \"fulfilled\": 2\n }\n }\n },\n \"OrderLineItemQuantity\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Quantity tracking for an order line item. Uses a 3-field model: ordered (original), current (active after cancellations/returns), fulfilled (completed).\",\n \"properties\": {\n \"ordered\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Quantity originally ordered by the customer\"\n },\n \"current\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Current active quantity on the order. May be less than ordered due to cancellations or returns. A value of 0 means the line item has been fully removed.\"\n },\n \"fulfilled\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"default\": 0,\n \"description\": \"Quantity that has been fulfilled (shipped, picked up, or digitally delivered). Applies to all fulfillment types, not just shipping.\"\n }\n },\n \"required\": [\n \"ordered\",\n \"current\"\n ],\n \"example\": {\n \"ordered\": 3,\n \"current\": 3,\n \"fulfilled\": 2\n }\n },\n \"LineItemReference\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Reference to a line item with quantity, used in fulfillments and adjustments\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Line item ID reference\"\n },\n \"quantity\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Quantity in this fulfillment or adjustment\"\n }\n },\n \"required\": [\n \"id\",\n \"quantity\"\n ],\n \"example\": {\n \"line_item_id\": \"item_001\",\n \"quantity\": 1\n }\n },\n \"Fulfillment\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"A fulfillment represents how items are delivered to the buyer (shipping, pickup, digital).\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Fulfillment identifier\"\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"shipping\",\n \"pickup\",\n \"digital\"\n ],\n \"description\": \"Fulfillment method type\"\n },\n \"status\": {\n \"type\": \"string\",\n \"description\": \"Current fulfillment status. Implementations MUST accept unrecognized values gracefully. Defined values: 'pending', 'processing', 'shipped', 'in_transit', 'out_for_delivery', 'ready_for_pickup', 'delivered', 'failed', 'canceled'. Not all statuses apply to all types.\"\n },\n \"line_items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/LineItemReference\"\n },\n \"description\": \"Which line items and quantities are in this fulfillment\"\n },\n \"carrier\": {\n \"type\": \"string\",\n \"description\": \"Carrier name (e.g., 'FedEx', 'UPS', 'USPS'). Applies to type: shipping.\"\n },\n \"tracking_number\": {\n \"type\": \"string\",\n \"description\": \"Carrier tracking number. Applies to type: shipping.\"\n },\n \"tracking_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to track this shipment. Applies to type: shipping.\"\n },\n \"destination\": {\n \"$ref\": \"#/$defs/Address\"\n },\n \"estimated_delivery\": {\n \"$ref\": \"#/$defs/EstimatedDelivery\"\n },\n \"digital_delivery\": {\n \"type\": \"object\",\n \"description\": \"Digital delivery details. Applies to type: digital.\",\n \"properties\": {\n \"access_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to access digital content (download link, streaming page, etc.)\"\n },\n \"license_key\": {\n \"type\": \"string\",\n \"description\": \"License or activation key\"\n },\n \"expires_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"When access expires (RFC 3339 timestamp)\"\n }\n }\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Human-readable description (e.g., 'Backordered - ships Feb 15')\"\n },\n \"events\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/FulfillmentEvent\"\n },\n \"description\": \"Append-only event log tracking fulfillment progress\"\n }\n },\n \"required\": [\n \"id\",\n \"type\"\n ],\n \"example\": {\n \"id\": \"ful_001\",\n \"type\": \"shipping\",\n \"status\": \"shipped\",\n \"line_items\": [],\n \"tracking_number\": \"1Z999AA10123456784\",\n \"carrier\": \"UPS\"\n }\n },\n \"FulfillmentEvent\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"A point-in-time event in the fulfillment lifecycle.\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Event identifier\"\n },\n \"type\": {\n \"type\": \"string\",\n \"description\": \"Event type. Implementations MUST accept unrecognized values gracefully. Defined values: 'processing', 'shipped', 'in_transit', 'out_for_delivery', 'ready_for_pickup', 'delivered', 'failed_attempt', 'returned_to_sender', 'canceled', 'undeliverable'. 'out_for_delivery' and 'ready_for_pickup' are ACP extensions for richer agent experiences.\"\n },\n \"occurred_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when this event occurred\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Human-readable description (e.g., 'Left at front door')\"\n },\n \"location\": {\n \"type\": \"string\",\n \"description\": \"Location where this event occurred (e.g., 'Memphis, TN')\"\n }\n },\n \"required\": [\n \"id\",\n \"type\",\n \"occurred_at\"\n ],\n \"example\": {\n \"status\": \"shipped\",\n \"timestamp\": \"2026-02-13T14:00:00Z\",\n \"location\": \"San Francisco, CA\"\n }\n },\n \"Adjustment\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"A post-order change such as refund, credit, return, or dispute.\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Adjustment identifier\"\n },\n \"type\": {\n \"type\": \"string\",\n \"description\": \"Type of adjustment. Implementations MUST accept unrecognized values gracefully. Defined values: 'refund', 'credit', 'return', 'exchange', 'price_adjustment', 'cancellation', 'dispute'. Use 'refund' for both full and partial refunds (distinguish by amount). 'credit' replaces 'store_credit'. 'dispute' covers chargebacks.\"\n },\n \"occurred_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when this adjustment occurred\"\n },\n \"status\": {\n \"type\": \"string\",\n \"description\": \"Adjustment status. Implementations MUST accept unrecognized values gracefully. Defined values: 'pending', 'completed', 'failed'.\"\n },\n \"line_items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/LineItemReference\"\n },\n \"description\": \"Which line items and quantities are affected\"\n },\n \"amount\": {\n \"type\": \"integer\",\n \"description\": \"Total amount credited to the buyer in minor currency units, inclusive of any applicable tax\"\n },\n \"currency\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z]{3}$\",\n \"description\": \"ISO 4217 currency code\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Human-readable reason (e.g., 'Defective item')\"\n },\n \"reason\": {\n \"type\": \"string\",\n \"description\": \"Structured reason code\"\n }\n },\n \"required\": [\n \"id\",\n \"type\",\n \"occurred_at\",\n \"status\"\n ],\n \"example\": {\n \"id\": \"adj_001\",\n \"type\": \"refund\",\n \"amount\": 1000,\n \"currency\": \"usd\",\n \"reason\": \"Customer request\",\n \"created_at\": \"2026-02-14T10:00:00Z\"\n }\n },\n \"AuthenticationMetadata\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"description\": \"Seller-provided authentication metadata for 3DS flows.\",\n \"required\": [\n \"acquirer_details\",\n \"directory_server\"\n ],\n \"properties\": {\n \"acquirer_details\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Details about the acquirer used for this 3DS Authentication. This object MUST be present.\",\n \"properties\": {\n \"acquirer_bin\": {\n \"type\": \"string\",\n \"maxLength\": 11,\n \"description\": \"The Acquirer BIN (directory-server specific).\"\n },\n \"acquirer_country\": {\n \"type\": \"string\",\n \"minLength\": 2,\n \"maxLength\": 2,\n \"description\": \"Two-letter ISO 3166-1 alpha-2 country code.\"\n },\n \"acquirer_merchant_id\": {\n \"type\": \"string\",\n \"maxLength\": 35,\n \"description\": \"The Merchant ID assigned by the acquirer.\"\n },\n \"merchant_name\": {\n \"type\": \"string\",\n \"maxLength\": 40,\n \"description\": \"Merchant name assigned by the acquirer.\"\n },\n \"requestor_id\": {\n \"type\": \"string\",\n \"maxLength\": 35,\n \"description\": \"Requestor ID (if required by the directory server).\"\n }\n },\n \"required\": [\n \"acquirer_bin\",\n \"acquirer_country\",\n \"acquirer_merchant_id\",\n \"merchant_name\"\n ]\n },\n \"directory_server\": {\n \"type\": \"string\",\n \"enum\": [\n \"american_express\",\n \"mastercard\",\n \"visa\"\n ],\n \"description\": \"The 3DS directory server used for this Authentication.\"\n },\n \"flow_preference\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Contains additional details on the seller's preference for the 3DS authentication flow. Sellers MAY request a preference, but issuers ultimately decide the actual flow.\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"challenge\",\n \"frictionless\"\n ],\n \"description\": \"Type of flow requested for this 3DS Authentication. 'challenge' requests a challenge flow; 'frictionless' requests a frictionless flow.\"\n },\n \"challenge\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Details about the requested challenge flow.\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"mandated\",\n \"preferred\"\n ],\n \"description\": \"Subtype of challenge preference.\"\n }\n }\n },\n \"frictionless\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Details about the requested frictionless flow.\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"low_risk\"\n ],\n \"description\": \"Subtype of frictionless preference.\"\n }\n }\n }\n },\n \"required\": [\n \"type\"\n ]\n }\n },\n \"example\": {\n \"three_ds_version\": \"2.1.0\",\n \"merchant_name\": \"Example Store\"\n }\n },\n \"AuthenticationResult\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Agent-provided authentication results returned to the seller for card-based 3D Secure.\",\n \"properties\": {\n \"outcome\": {\n \"type\": \"string\",\n \"description\": \"The outcome of this 3DS Authentication.\",\n \"enum\": [\n \"abandoned\",\n \"attempt_acknowledged\",\n \"authenticated\",\n \"canceled\",\n \"denied\",\n \"informational\",\n \"internal_error\",\n \"not_supported\",\n \"processing_error\",\n \"rejected\"\n ],\n \"example\": \"authenticated\"\n },\n \"outcome_details\": {\n \"type\": \"object\",\n \"description\": \"Detailed authentication data. This field is required when the outcome is 'authenticated', 'informational', or 'attempt_acknowledged'.\",\n \"additionalProperties\": false,\n \"properties\": {\n \"three_ds_cryptogram\": {\n \"type\": \"string\",\n \"description\": \"The 3DS cryptogram (authentication value / AAV/CAVV/AEVV). This value is 20 bytes, base64-encoded into a 28-character string.\",\n \"example\": \"AbCdEfGhIjKlMnOpQrStUvWxY0=\"\n },\n \"electronic_commerce_indicator\": {\n \"type\": \"string\",\n \"description\": \"Electronic Commerce Indicator (ECI) returned by the 3D Secure provider. Indicates the degree/type of authentication performed.\",\n \"enum\": [\n \"01\",\n \"02\",\n \"05\",\n \"06\",\n \"07\"\n ],\n \"example\": \"05\"\n },\n \"transaction_id\": {\n \"type\": \"string\",\n \"description\": \"Transaction identifier returned by the 3DS system:\\n- For 3DS1: the XID\\n- For 3DS2: the Directory Server Transaction ID (dsTransID)\",\n \"example\": \"dsTransId_abc123\"\n },\n \"version\": {\n \"type\": \"string\",\n \"description\": \"The 3D Secure version used for this authentication (for example '1.0.2' or '2.2.0').\",\n \"example\": \"2.2.0\"\n }\n },\n \"required\": [\n \"three_ds_cryptogram\",\n \"electronic_commerce_indicator\",\n \"transaction_id\",\n \"version\"\n ]\n }\n },\n \"required\": [\n \"outcome\"\n ],\n \"allOf\": [\n {\n \"if\": {\n \"properties\": {\n \"outcome\": {\n \"enum\": [\n \"authenticated\",\n \"informational\",\n \"attempt_acknowledged\"\n ]\n }\n }\n },\n \"then\": {\n \"required\": [\n \"outcome_details\"\n ]\n }\n }\n ],\n \"example\": {\n \"status\": \"authenticated\",\n \"transaction_id\": \"3ds_abc123\",\n \"eci\": \"05\"\n }\n },\n \"MarketingConsentOption\": {\n \"description\": \"Seller-declared marketing consent option that specifies an available channel for which the seller must obtain the buyer's consent before sending marketing content\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"channel\": {\n \"type\": \"string\",\n \"description\": \"Channel for marketing consent.\",\n \"examples\": [\"email\", \"sms\", \"whatsapp\"]\n },\n \"display_text\": {\n \"type\": \"string\",\n \"description\": \"What the buyer is consenting to receive, e.g., 'promotional emails, product launches, and exclusive offers'. Agents MAY use this to compose their own consent prompt.\"\n },\n \"privacy_policy_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the seller's privacy policy governing use of the buyer's contact information for marketing.\"\n },\n \"is_subscribed\": {\n \"type\": \"boolean\",\n \"description\": \"Whether the buyer is currently subscribed to marketing via this channel. When true, agents SHOULD render the consent checkbox as pre-checked. Defaults to false if omitted.\"\n }\n },\n \"required\": [\n \"channel\",\n \"display_text\",\n \"privacy_policy_url\"\n ],\n \"example\": {\n \"channel\": \"email\",\n \"display_text\": \"Promotional emails, product launches, and exclusive offers\",\n \"privacy_policy_url\": \"https://www.example.com/privacy\",\n \"is_subscribed\": false\n }\n },\n \"MarketingConsent\": {\n \"description\": \"Buyer's marketing consent decision for a specific channel submitted at checkout completion\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"channel\": {\n \"type\": \"string\",\n \"description\": \"Channel matching the consent option channel.\",\n \"examples\": [\"email\", \"sms\", \"whatsapp\"]\n },\n \"opted_in\": {\n \"type\": \"boolean\",\n \"description\": \"Whether the buyer consented to receive marketing via this channel.\"\n }\n },\n \"required\": [\n \"channel\",\n \"opted_in\"\n ],\n \"example\": {\n \"channel\": \"email\",\n \"opted_in\": true\n }\n },\n \"CheckoutSessionBase\": {\n \"description\": \"Base checkout session model containing common fields for all checkout session states\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for the checkout session\"\n },\n \"protocol\": {\n \"$ref\": \"#/$defs/ProtocolVersion\",\n \"description\": \"Protocol version metadata\"\n },\n \"capabilities\": {\n \"$ref\": \"#/$defs/Capabilities\",\n \"description\": \"Negotiated capabilities between agent and seller\"\n },\n \"buyer\": {\n \"$ref\": \"#/$defs/Buyer\",\n \"description\": \"Buyer information\"\n },\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\n \"incomplete\",\n \"not_ready_for_payment\",\n \"requires_escalation\",\n \"authentication_required\",\n \"ready_for_payment\",\n \"pending_approval\",\n \"complete_in_progress\",\n \"completed\",\n \"canceled\",\n \"in_progress\",\n \"expired\"\n ],\n \"description\": \"Current status of the checkout session\"\n },\n \"currency\": {\n \"type\": \"string\",\n \"description\": \"ISO 4217 settlement currency code\"\n },\n \"presentment_currency\": {\n \"type\": \"string\",\n \"description\": \"ISO 4217 presentment currency code if different from settlement currency\"\n },\n \"exchange_rate\": {\n \"type\": \"number\",\n \"description\": \"Exchange rate from presentment to settlement currency\"\n },\n \"exchange_rate_timestamp\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when exchange rate was determined\"\n },\n \"locale\": {\n \"type\": \"string\",\n \"description\": \"Locale code (e.g., 'en-US') for localizing content\"\n },\n \"timezone\": {\n \"type\": \"string\",\n \"description\": \"IANA timezone identifier (e.g., 'America/New_York')\"\n },\n \"line_items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/LineItem\"\n },\n \"description\": \"Line items in the checkout session\"\n },\n \"fulfillment_details\": {\n \"$ref\": \"#/$defs/FulfillmentDetails\",\n \"description\": \"Fulfillment contact and address details\"\n },\n \"fulfillment_options\": {\n \"type\": \"array\",\n \"items\": {\n \"oneOf\": [\n {\n \"$ref\": \"#/$defs/FulfillmentOptionShipping\"\n },\n {\n \"$ref\": \"#/$defs/FulfillmentOptionDigital\"\n },\n {\n \"$ref\": \"#/$defs/FulfillmentOptionPickup\"\n },\n {\n \"$ref\": \"#/$defs/FulfillmentOptionLocalDelivery\"\n }\n ]\n },\n \"description\": \"Available fulfillment options\"\n },\n \"selected_fulfillment_options\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/SelectedFulfillmentOption\"\n },\n \"description\": \"Currently selected fulfillment options\"\n },\n \"fulfillment_groups\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/FulfillmentGroup\"\n },\n \"description\": \"Optional grouping of line items by fulfillment method\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Cart-level totals breakdown\"\n },\n \"messages\": {\n \"type\": \"array\",\n \"items\": {\n \"oneOf\": [\n {\n \"$ref\": \"#/$defs/MessageInfo\"\n },\n {\n \"$ref\": \"#/$defs/MessageWarning\"\n },\n {\n \"$ref\": \"#/$defs/MessageError\"\n }\n ]\n },\n \"description\": \"Messages to communicate with the buyer (info, warnings, errors)\"\n },\n \"links\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Link\"\n },\n \"description\": \"Relevant links (terms, policies, support)\"\n },\n \"authentication_metadata\": {\n \"$ref\": \"#/$defs/AuthenticationMetadata\",\n \"description\": \"Authentication metadata for payment interventions (e.g., 3DS)\"\n },\n \"created_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the session was created\"\n },\n \"updated_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp of last update\"\n },\n \"expires_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the session expires\"\n },\n \"continue_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to continue or resume the checkout session\"\n },\n \"metadata\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"description\": \"Arbitrary metadata for merchant use\"\n },\n \"quote_id\": {\n \"type\": \"string\",\n \"description\": \"Quote identifier if this session is based on a quote\"\n },\n \"quote_expires_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the quote expires\"\n },\n \"discounts\": {\n \"$ref\": \"#/$defs/DiscountsResponse\",\n \"description\": \"Discount extension: submitted codes and applied discounts. Present when the 'discount' extension is active.\"\n },\n \"marketing_consent_options\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/MarketingConsentOption\"\n },\n \"description\": \"Marketing consent options the seller offers. When present, the agent SHOULD display these to the buyer before checkout completion. Agents MAY selectively surface a subset of options; options not surfaced MUST be omitted from marketing_consents in the complete request. When absent, the agent MUST NOT surface any marketing consent UI. An empty array is equivalent to absent.\"\n },\n \"order\": {\n \"$ref\": \"#/$defs/Order\"\n }\n },\n \"required\": [\n \"id\",\n \"status\",\n \"currency\",\n \"line_items\",\n \"totals\",\n \"fulfillment_options\",\n \"messages\",\n \"links\",\n \"capabilities\"\n ],\n \"example\": {\n \"id\": \"cs_abc123\",\n \"status\": \"ready_for_payment\",\n \"currency\": \"usd\",\n \"line_items\": [],\n \"totals\": {\n \"currency\": \"usd\",\n \"subtotal\": 5800,\n \"total\": 6764\n },\n \"fulfillment_options\": [],\n \"messages\": [],\n \"links\": [],\n \"capabilities\": {}\n }\n },\n \"CheckoutSession\": {\n \"description\": \"Checkout session response model\",\n \"allOf\": [\n {\n \"$ref\": \"#/$defs/CheckoutSessionBase\"\n }\n ],\n \"example\": {\n \"id\": \"cs_abc123\",\n \"status\": \"ready_for_payment\",\n \"currency\": \"usd\",\n \"line_items\": [],\n \"totals\": {\n \"currency\": \"usd\",\n \"subtotal\": 5800,\n \"total\": 6764\n },\n \"fulfillment_options\": [],\n \"messages\": [],\n \"links\": [],\n \"capabilities\": {}\n }\n },\n \"CheckoutSessionWithOrder\": {\n \"description\": \"Checkout session response after completion, includes the created order\",\n \"allOf\": [\n {\n \"$ref\": \"#/$defs/CheckoutSessionBase\"\n },\n {\n \"description\": \"Order extension for completed checkout sessions\",\n \"type\": \"object\",\n \"properties\": {\n \"order\": {\n \"$ref\": \"#/$defs/Order\",\n \"description\": \"Order created when checkout is completed\"\n }\n },\n \"required\": [\n \"order\"\n ]\n }\n ],\n \"example\": {\n \"id\": \"cs_abc123\",\n \"status\": \"completed\",\n \"currency\": \"usd\",\n \"line_items\": [],\n \"totals\": {\n \"currency\": \"usd\",\n \"subtotal\": 5800,\n \"total\": 6764\n },\n \"fulfillment_options\": [],\n \"messages\": [],\n \"links\": [],\n \"capabilities\": {},\n \"order\": {\n \"id\": \"ord_abc123\",\n \"order_number\": \"12345\",\n \"status\": \"confirmed\",\n \"currency\": \"usd\",\n \"total\": 6764,\n \"line_items\": [],\n \"created_at\": \"2026-02-13T10:30:00Z\"\n }\n }\n },\n \"CheckoutSessionCreateRequest\": {\n \"description\": \"Request to create a new checkout session\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"buyer\": {\n \"$ref\": \"#/$defs/Buyer\",\n \"description\": \"Buyer information\"\n },\n \"line_items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Item\"\n },\n \"minItems\": 1,\n \"description\": \"Items to add to the checkout session\"\n },\n \"currency\": {\n \"type\": \"string\",\n \"description\": \"ISO 4217 currency code\"\n },\n \"fulfillment_details\": {\n \"$ref\": \"#/$defs/FulfillmentDetails\",\n \"description\": \"Fulfillment contact and address details\"\n },\n \"capabilities\": {\n \"$ref\": \"#/$defs/Capabilities\",\n \"description\": \"Agent capabilities and supported features\"\n },\n \"fulfillment_groups\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/FulfillmentGroup\"\n },\n \"description\": \"Grouping of items by fulfillment method\"\n },\n \"affiliate_attribution\": {\n \"$ref\": \"#/$defs/AffiliateAttribution\",\n \"description\": \"Affiliate attribution data for first-touch tracking\"\n },\n \"coupons\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Coupon code to apply\"\n },\n \"description\": \"DEPRECATED: Use discounts.codes instead. Discount codes to apply.\"\n },\n \"discounts\": {\n \"$ref\": \"#/$defs/DiscountsRequest\",\n \"description\": \"Discount codes to apply to the checkout session.\"\n },\n \"locale\": {\n \"type\": \"string\",\n \"description\": \"Locale code for localizing content (e.g., 'en-US')\"\n },\n \"timezone\": {\n \"type\": \"string\",\n \"description\": \"IANA timezone identifier (e.g., 'America/New_York')\"\n },\n \"quote_id\": {\n \"type\": \"string\",\n \"description\": \"Quote identifier if this session is based on a quote\"\n },\n \"metadata\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"description\": \"Arbitrary metadata for merchant use\"\n },\n \"order_notes\": {\n \"type\": \"string\",\n \"maxLength\": 5000,\n \"description\": \"Optional customer/order notes (e.g., delivery instructions, gift message).\"\n }\n },\n \"required\": [\n \"line_items\",\n \"currency\",\n \"capabilities\"\n ],\n \"example\": {\n \"items\": [\n {\n \"product_id\": \"prod_tshirt_blue_m\",\n \"quantity\": 2\n }\n ],\n \"currency\": \"usd\",\n \"capabilities\": {}\n }\n },\n \"CheckoutSessionUpdateRequest\": {\n \"description\": \"Request to update an existing checkout session\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"buyer\": {\n \"$ref\": \"#/$defs/Buyer\",\n \"description\": \"Updated buyer information\"\n },\n \"line_items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Item\"\n },\n \"description\": \"Items to update in the checkout session\"\n },\n \"fulfillment_details\": {\n \"$ref\": \"#/$defs/FulfillmentDetails\",\n \"description\": \"Updated fulfillment contact and address\"\n },\n \"fulfillment_groups\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/FulfillmentGroup\"\n },\n \"description\": \"Updated fulfillment groupings\"\n },\n \"selected_fulfillment_options\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/SelectedFulfillmentOption\"\n },\n \"description\": \"Fulfillment option selected by the buyer\"\n },\n \"coupons\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Coupon code to apply\"\n },\n \"description\": \"DEPRECATED: Use discounts.codes instead. Discount codes to apply.\"\n },\n \"discounts\": {\n \"$ref\": \"#/$defs/DiscountsRequest\",\n \"description\": \"Discount codes to apply. Replaces previously submitted codes.\"\n },\n \"order_notes\": {\n \"type\": \"string\",\n \"maxLength\": 5000,\n \"description\": \"Optional customer/order notes.\"\n }\n },\n \"example\": {\n \"buyer\": {\n \"email\": \"customer@example.com\"\n }\n }\n },\n \"CheckoutSessionCompleteRequest\": {\n \"description\": \"Request to complete a checkout session and create an order\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"buyer\": {\n \"$ref\": \"#/$defs/Buyer\",\n \"description\": \"Final buyer information\"\n },\n \"payment_data\": {\n \"$ref\": \"#/$defs/PaymentData\",\n \"description\": \"Payment method and details\"\n },\n \"authentication_result\": {\n \"$ref\": \"#/$defs/AuthenticationResult\",\n \"description\": \"Authentication result for 3DS flows\"\n },\n \"affiliate_attribution\": {\n \"$ref\": \"#/$defs/AffiliateAttribution\",\n \"description\": \"Affiliate attribution data for last-touch tracking\"\n },\n \"risk_signals\": {\n \"$ref\": \"#/$defs/RiskSignals\",\n \"description\": \"Risk and fraud signals\"\n },\n \"marketing_consents\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/MarketingConsent\"\n },\n \"description\": \"Buyer's marketing consent decisions. Agents SHOULD include an entry for each consent option surfaced to the buyer. Options not surfaced MUST be omitted — omission preserves existing subscription state. Sellers SHOULD ignore entries in marketing_consents that do not correspond to a channel in marketing_consent_options.\"\n },\n \"order_notes\": {\n \"type\": \"string\",\n \"maxLength\": 5000,\n \"description\": \"Optional customer/order notes (delivery instructions, gift message).\"\n }\n },\n \"required\": [\n \"payment_data\"\n ],\n \"example\": {\n \"payment_data\": {\n \"type\": \"vault_token\",\n \"token\": \"vt_01J8Z3WXYZ9ABC123\"\n }\n }\n },\n \"IntentTrace\": {\n \"description\": \"Structured reason for why a buyer action was taken, used for analytics and debugging\",\n \"type\": \"object\",\n \"properties\": {\n \"reason_code\": {\n \"type\": \"string\",\n \"description\": \"Reason for abandonment. This enum is extensible: servers SHOULD accept unrecognized values and treat them as 'other' (see RFC Section 7.2). Validators SHOULD be configured for lenient enum handling.\",\n \"enum\": [\n \"price_sensitivity\",\n \"shipping_cost\",\n \"shipping_speed\",\n \"product_fit\",\n \"trust_security\",\n \"returns_policy\",\n \"payment_options\",\n \"comparison\",\n \"timing_deferred\",\n \"other\"\n ]\n },\n \"trace_summary\": {\n \"type\": \"string\",\n \"maxLength\": 500,\n \"description\": \"A generated summary of the specific objection or negotiation gap.\"\n },\n \"metadata\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"type\": [\n \"string\",\n \"number\",\n \"boolean\"\n ],\n \"description\": \"Metadata value\"\n },\n \"description\": \"Additional structured metadata about the intent\"\n }\n },\n \"required\": [\n \"reason_code\"\n ],\n \"example\": {\n \"reason_code\": \"buyer_initiated\",\n \"description\": \"Customer requested to complete checkout\",\n \"metadata\": {}\n }\n },\n \"CancelSessionRequest\": {\n \"description\": \"Request to cancel a checkout session\",\n \"type\": \"object\",\n \"properties\": {\n \"intent_trace\": {\n \"$ref\": \"#/$defs/IntentTrace\"\n }\n },\n \"example\": {\n \"intent_trace\": {\n \"reason_code\": \"buyer_cancelled\",\n \"description\": \"Customer decided not to purchase\"\n }\n }\n },\n \"DiscoveryResponse\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Well-known discovery document served at /.well-known/acp.json. Describes the seller's capabilities. This is stable, deterministic information that does not vary per session. Session-specific capabilities (payment methods, payment handlers) are negotiated inline via the capabilities object on POST /checkout_sessions.\",\n \"properties\": {\n \"protocol\": {\n \"$ref\": \"#/$defs/DiscoveryProtocol\"\n },\n \"api_base_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"Base URL for the ACP REST API. Agents append resource paths to this URL (e.g., {api_base_url}/checkout_sessions).\"\n },\n \"transports\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\"rest\", \"mcp\"]\n },\n \"uniqueItems\": true,\n \"description\": \"Transport bindings supported by this seller. \\\"rest\\\" indicates the REST API at api_base_url. \\\"mcp\\\" indicates a Model Context Protocol server is available (see SEP #135). New values are introduced in new API versions; agents MAY treat this enum as exhaustive for a given version.\"\n },\n \"capabilities\": {\n \"$ref\": \"#/$defs/DiscoveryCapabilities\"\n }\n },\n \"required\": [\"protocol\", \"api_base_url\", \"transports\", \"capabilities\"],\n \"example\": {\n \"protocol\": {\n \"name\": \"acp\",\n \"version\": \"2026-04-17\",\n \"supported_versions\": [\"2025-09-29\", \"2026-01-30\", \"2026-04-17\"]\n },\n \"api_base_url\": \"https://acp.stripe.com/api\",\n \"transports\": [\"rest\"],\n \"capabilities\": {\n \"services\": [\"checkout\"]\n }\n }\n },\n \"DiscoveryCapabilities\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Seller capabilities advertised in the well-known discovery document. Contains feature declarations that are stable across sessions.\",\n \"properties\": {\n \"services\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\"checkout\", \"orders\", \"delegate_payment\", \"carts\"]\n },\n \"uniqueItems\": true,\n \"description\": \"Services available from this seller. Indicates which ACP operations are implemented. This enum is closed per API version; new values are introduced in new API versions. Agents MAY treat the set as exhaustive for a given version.\"\n },\n \"extensions\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/DiscoveryExtension\"\n },\n \"description\": \"Extensions the seller supports. Whether a specific extension is active for a given session is determined during checkout session creation.\"\n },\n \"intervention_types\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\"3ds\", \"biometric\", \"address_verification\"]\n },\n \"uniqueItems\": true,\n \"description\": \"Intervention types the seller supports. Actual availability for a specific session is negotiated via the capabilities object on POST /checkout_sessions. This enum is closed per API version; new values are introduced in new API versions. Agents MAY treat the set as exhaustive for a given version.\"\n },\n \"supported_currencies\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z]{3}$\",\n \"description\": \"ISO 4217 currency code in lowercase (e.g., \\\"usd\\\", \\\"eur\\\")\"\n },\n \"uniqueItems\": true,\n \"description\": \"ISO 4217 currency codes supported by the seller.\"\n },\n \"supported_locales\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"BCP 47 locale tag (e.g., \\\"en-US\\\", \\\"fr-FR\\\")\"\n },\n \"uniqueItems\": true,\n \"description\": \"BCP 47 locale tags supported by the seller for localized responses.\"\n }\n },\n \"required\": [\"services\"],\n \"example\": {\n \"services\": [\"checkout\", \"orders\", \"delegate_payment\", \"carts\"],\n \"extensions\": [{ \"name\": \"discount\", \"spec\": \"https://agenticcommerce.dev/specs/discount\", \"schema\": \"https://agenticcommerce.dev/schemas/discount.json\" }],\n \"intervention_types\": [\"3ds\"],\n \"supported_currencies\": [\"usd\", \"eur\"],\n \"supported_locales\": [\"en-US\"]\n }\n },\n \"DiscoveryProtocol\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Protocol identification and version information.\",\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"const\": \"acp\",\n \"description\": \"Protocol identifier. Always \\\"acp\\\".\"\n },\n \"version\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{4}-\\\\d{2}-\\\\d{2}$\",\n \"description\": \"The current (latest) API version supported by the seller, in YYYY-MM-DD format.\"\n },\n \"supported_versions\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{4}-\\\\d{2}-\\\\d{2}$\",\n \"description\": \"API version in YYYY-MM-DD format\"\n },\n \"uniqueItems\": true,\n \"description\": \"All API versions the seller currently supports, in chronological order (oldest first). Agents SHOULD use the API-Version header to request a specific version. The last element is always the latest supported version.\"\n },\n \"documentation_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the seller's ACP documentation.\"\n }\n },\n \"required\": [\"name\", \"version\", \"supported_versions\"],\n \"example\": {\n \"name\": \"acp\",\n \"version\": \"2026-04-17\",\n \"supported_versions\": [\"2025-09-29\", \"2026-01-30\", \"2026-04-17\"],\n \"documentation_url\": \"https://agenticcommerce.dev\"\n }\n },\n \"DiscoveryExtension\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"High-level extension declaration in the discovery document. Identifies the extension and provides a spec URL, but does not include session-level details like schema or extends fields.\",\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Extension identifier (e.g., \\\"discount\\\", \\\"fulfillment\\\").\"\n },\n \"spec\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the extension's specification document.\"\n },\n \"schema\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the extension's JSON Schema definition for programmatic validation.\"\n }\n },\n \"required\": [\"name\"],\n \"example\": {\n \"name\": \"discount\",\n \"spec\": \"https://agenticcommerce.dev/specs/discount\",\n \"schema\": \"https://agenticcommerce.dev/schemas/discount.json\"\n }\n },\n \"Error\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Protocol-level error returned in 4xx/5xx responses when the server cannot return a valid CheckoutSession at all (e.g. malformed request or unexpected failure). Use Error—not MessageError—when there is no valid session state to return. type semantics: invalid_request — malformed request, missing required fields, invalid JSON, or idempotency violations (codes: idempotency_key_required, idempotency_in_flight, idempotency_conflict); processing_error — unexpected server-side failure; service_unavailable — temporary unavailability.\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"invalid_request\",\n \"processing_error\",\n \"service_unavailable\"\n ],\n \"description\": \"Error type indicating the category of protocol-level error\"\n },\n \"code\": {\n \"type\": \"string\",\n \"description\": \"Implementation-defined error code\"\n },\n \"message\": {\n \"type\": \"string\",\n \"description\": \"Human-readable error message\"\n },\n \"param\": {\n \"type\": \"string\",\n \"description\": \"RFC 9535 JSONPath (optional)\"\n },\n \"supported_versions\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{4}-\\\\d{2}-\\\\d{2}$\",\n \"description\": \"Supported API version in YYYY-MM-DD format\"\n },\n \"description\": \"List of API versions supported by the server, ordered by preference (newest first). Only included in version-related errors.\"\n }\n },\n \"required\": [\n \"type\",\n \"code\",\n \"message\"\n ],\n \"example\": {\n \"type\": \"invalid_request\",\n \"code\": \"invalid_email\",\n \"message\": \"The email address format is invalid\",\n \"param\": \"$.buyer.email\"\n }\n }\n }\n}\n","/**\n * Wire validation against the vendored ACP checkout schema.\n *\n * ACP documents need far more of JSON Schema than the subset\n * `src/core/execution` validates canonical input with, so the pinned official\n * schema is compiled with Ajv rather than restated by hand.\n *\n * The schema is imported, not read from disk: bundling collapses `src/**` into\n * a few files under `dist/`, where a relative `readFileSync` resolves from the\n * wrong depth.\n */\n\nimport type { ErrorObject, ValidateFunction } from 'ajv';\nimport Ajv2020 from 'ajv/dist/2020.js';\nimport addFormats from 'ajv-formats';\nimport { CommerceError } from '../../core';\n// The snapshot directory is part of the path on purpose: a new ACP version is\n// a new import beside this one, never an edit to the vendored file\nimport schemaDocument from './spec/2026-04-17/schema.agentic_checkout.json' with { type: 'json' };\n\n/**\n * A validation failure, reduced to what may safely cross the adapter\n * boundary. Ajv messages and schema paths describe *our* compiled schema and\n * never reach a client; the adapter turns this into an ACP `Error`.\n */\nexport interface AcpValidationFailure {\n /** The JSON Schema keyword that failed: spec vocabulary, not an Ajv internal */\n readonly code: string;\n /** `$.buyer.email`-style pointer to the offending value. Omitted at the document root */\n readonly path?: string;\n}\n\n/**\n * The released `$defs` this adapter validates against, keyed by the role it\n * uses them in. Values are the exact snapshot names; all are compiled on first\n * use, which the adapter's start-up discovery check triggers, so a typo fails\n * the adapter at start rather than on a checkout request.\n */\nexport const ACP_DEFINITIONS = {\n createRequest: 'CheckoutSessionCreateRequest',\n updateRequest: 'CheckoutSessionUpdateRequest',\n completeRequest: 'CheckoutSessionCompleteRequest',\n cancelRequest: 'CancelSessionRequest',\n checkoutSession: 'CheckoutSession',\n checkoutSessionWithOrder: 'CheckoutSessionWithOrder',\n discoveryResponse: 'DiscoveryResponse',\n error: 'Error',\n} as const;\n\nexport type AcpDefinition = keyof typeof ACP_DEFINITIONS;\n\nlet validators: ReadonlyMap<AcpDefinition, ValidateFunction> | undefined;\n\n// Compiled once per process, on first use rather than at import, so a gateway\n// with ACP disabled never pays for it\nfunction acpValidators(): ReadonlyMap<AcpDefinition, ValidateFunction> {\n if (validators !== undefined) return validators;\n\n const ajv = new Ajv2020({\n // The vendored document is the released spec; unknown annotations in it\n // are no reason to refuse to start\n strict: false,\n // Only one failure leaves the adapter, and collecting every error in a\n // deeply nested cart is work a caller could request repeatedly\n allErrors: false,\n });\n addFormats(ajv);\n\n const document = relaxExtensibleEnums(structuredClone(schemaDocument)) as Record<string, unknown>;\n openCapabilityValues(document);\n const schemaId = typeof document['$id'] === 'string' ? document['$id'] : '';\n ajv.addSchema(document as Parameters<typeof ajv.addSchema>[0]);\n\n const compiled = new Map<AcpDefinition, ValidateFunction>();\n for (const [name, definition] of Object.entries(ACP_DEFINITIONS)) {\n const validate = ajv.getSchema(`${schemaId}#/$defs/${definition}`);\n if (validate === undefined) {\n throw new CommerceError(\n 'PROTOCOL_UNSUPPORTED',\n `The vendored ACP schema has no definition \"${definition}\" - the pinned snapshot and this adapter disagree`,\n { details: { definition } },\n );\n }\n compiled.set(name as AcpDefinition, validate);\n }\n\n validators = compiled;\n return compiled;\n}\n\n/**\n * Drops the `enum` constraint from the fields whose description says the enum\n * is extensible (\"servers SHOULD accept unrecognized values and treat them as\n * 'other'\"). Enums ACP calls closed per API version stay closed; this only\n * avoids refusing, say, a cancel over a reason code the buyer's agent knows\n * and this snapshot does not.\n */\nfunction relaxExtensibleEnums(node: unknown): unknown {\n if (Array.isArray(node)) {\n for (const entry of node) relaxExtensibleEnums(entry);\n return node;\n }\n if (node === null || typeof node !== 'object') return node;\n\n const record = node as Record<string, unknown>;\n const description = record['description'];\n if (\n Array.isArray(record['enum']) &&\n typeof description === 'string' &&\n /enum is extensible/i.test(description)\n ) {\n delete record['enum'];\n }\n for (const value of Object.values(record)) relaxExtensibleEnums(value);\n return node;\n}\n\n/**\n * Allow unknown intervention values in negotiated `supported` and `required`\n * lists, as ACP requires. The snapshot schema closes these enums; other\n * fields remain strict.\n */\nfunction openCapabilityValues(document: Record<string, unknown>): void {\n const defs = document['$defs'] as Record<string, { properties?: Record<string, unknown> }>;\n const properties = defs['InterventionCapabilities']?.properties ?? {};\n for (const list of ['supported', 'required']) {\n const items = (properties[list] as { items?: Record<string, unknown> } | undefined)?.items;\n if (items !== undefined) delete items['enum'];\n }\n}\n\n/**\n * Validates one ACP document against a released definition: `undefined` when\n * it conforms, otherwise the first failure. Inbound, a failure is a 400 and no\n * pipeline call; outbound, the merchant's body is not ACP and is not forwarded.\n */\nexport function validateAcpDocument(\n definition: AcpDefinition,\n value: unknown,\n): AcpValidationFailure | undefined {\n const validate = acpValidators().get(definition);\n /* c8 ignore next -- unreachable: every AcpDefinition is compiled above */\n if (validate === undefined) return { code: 'unknown_definition' };\n\n if (validate(value)) return undefined;\n const error = validate.errors?.[0];\n if (error === undefined) return { code: 'invalid' };\n\n const path = failurePath(error);\n return { code: error.keyword, ...(path !== undefined ? { path } : {}) };\n}\n\n/**\n * Ajv's JSON Pointer, rewritten in the `$.a.b[0]` form ACP errors use in `param`.\n * `required` and `additionalProperties` failures point at the parent object,\n * so the offending key is appended: `$.buyer.email` rather than `$.buyer`.\n */\nfunction failurePath(error: ErrorObject): string | undefined {\n const segments = error.instancePath\n .split('/')\n .filter((segment) => segment.length > 0)\n .map((segment) => segment.replaceAll('~1', '/').replaceAll('~0', '~'));\n\n const params = error.params as { missingProperty?: unknown; additionalProperty?: unknown };\n const key = params.missingProperty ?? params.additionalProperty;\n if (typeof key === 'string') segments.push(key);\n\n if (segments.length === 0) return undefined;\n return segments.reduce(\n (path, segment) => (/^\\d+$/.test(segment) ? `${path}[${segment}]` : `${path}.${segment}`),\n '$',\n );\n}\n","/**\n * Everything that must hold before an ACP request reaches the pipeline, in a\n * fixed order that fails closed at the first step that does not hold: route ->\n * bearer auth -> API-Version -> Idempotency-Key -> body size -> content type\n * -> JSON -> ACP request schema. A request failing any step never reaches the\n * pipeline.\n */\nimport type { IncomingMessage } from 'node:http';\nimport { readCappedBody } from '../http';\nimport {\n ACP_API_VERSION,\n ACP_API_VERSION_HEADER,\n ACP_FORWARDED_HEADERS,\n ACP_IDEMPOTENCY_KEY_HEADER,\n ACP_MAX_FORWARDED_HEADER_LENGTH,\n ACP_MAX_REQUEST_ID_LENGTH,\n ACP_REQUEST_ID_HEADER,\n} from './constants';\nimport { type AcpFailure, type AcpResponseHeaders, acpFailure } from './errors';\nimport { ACP_MAX_IDEMPOTENCY_KEY_LENGTH } from './idempotency/store';\nimport { type AcpRouteMatch, matchAcpRoute } from './router';\nimport { type AcpDefinition, validateAcpDocument } from './validation';\n\n// A second line behind the gateway mount's cap, bounding what this adapter\n// buffers if it is mounted without that guard\nconst ACP_MAX_REQUEST_BODY_BYTES = 256 * 1024;\n\n// Which released request definition each operation's body is validated against\nconst REQUEST_DEFINITIONS: Readonly<Record<AcpRouteMatch['operation'], AcpDefinition | undefined>> =\n {\n createCheckoutSession: 'createRequest',\n updateCheckoutSession: 'updateRequest',\n completeCheckoutSession: 'completeRequest',\n cancelCheckoutSession: 'cancelRequest',\n getCheckoutSession: undefined,\n };\n\nexport interface AcpGuardedRequest {\n readonly route: AcpRouteMatch;\n /** Validated ACP request document. `{}` for a body-less route */\n readonly body: Record<string, unknown>;\n /** The caller's `Request-Id`, bounded and filtered, when it sent a usable one */\n readonly requestId?: string;\n /** Present on every body-bearing route, where ACP makes it mandatory */\n readonly idempotencyKey?: string;\n /**\n * Usable caller headers for the merchant. `Signature` and `Timestamp` pass\n * through unverified. The gateway re-serializes JSON, so raw-byte signatures\n * will not survive; canonical JSON signatures may.\n */\n readonly forwardedHeaders?: Readonly<Record<string, string>>;\n}\n\nexport type AcpGuardResult =\n | { readonly ok: true; readonly value: AcpGuardedRequest }\n | ({ readonly ok: false; readonly headers: AcpResponseHeaders } & AcpFailure);\n\nexport interface AcpGuardOptions {\n readonly mountPath: string;\n /** `createBearerCheck` over the configured token */\n readonly isAuthorized: (authorizationHeader: string | undefined) => boolean;\n readonly maxBodyBytes?: number;\n}\n\n/**\n * The correlation headers a checkout response echoes: a filtered `Request-Id`,\n * and on a POST an `Idempotency-Key` that passes its own syntax check. Read\n * from the raw request, so a refusal before or outside the guard can echo them.\n */\nexport function acpEchoHeaders(req: IncomingMessage): AcpResponseHeaders {\n const echo: Record<string, string> = {};\n const presentedRequestId = normalizeRequestId(header(req, ACP_REQUEST_ID_HEADER));\n if (presentedRequestId !== undefined) echo[ACP_REQUEST_ID_HEADER] = presentedRequestId;\n const presentedKey = header(req, ACP_IDEMPOTENCY_KEY_HEADER)?.trim();\n if (req.method === 'POST' && presentedKey !== undefined && isUsableIdempotencyKey(presentedKey)) {\n echo[ACP_IDEMPOTENCY_KEY_HEADER] = presentedKey;\n }\n return echo;\n}\n\nexport async function guardAcpRequest(\n req: IncomingMessage,\n options: AcpGuardOptions,\n): Promise<AcpGuardResult> {\n const echo = acpEchoHeaders(req);\n const failed = (failure: AcpFailure, extra: AcpResponseHeaders = {}): AcpGuardResult => ({\n ok: false,\n ...failure,\n headers: { ...echo, ...extra },\n });\n\n const matched = matchAcpRoute(req.method, req.url, options.mountPath);\n if (matched.kind === 'not-found') {\n return failed(acpFailure(404, 'invalid_request', 'not_found', 'Unknown ACP route.'));\n }\n if (matched.kind === 'method-not-allowed') {\n return failed(\n acpFailure(\n 405,\n 'invalid_request',\n 'method_not_allowed',\n `This ACP route accepts ${matched.allow.join(', ')}.`,\n ),\n { allow: matched.allow.join(', ') },\n );\n }\n const route = matched.route;\n\n // Before any body is read, so an unauthenticated caller cannot make this\n // adapter buffer or parse. Only the bearer token authenticates: a\n // `Signature` header is not verified and never stands in for it.\n if (!options.isAuthorized(header(req, 'authorization'))) {\n return failed(\n acpFailure(\n 401,\n 'invalid_request',\n 'unauthorized',\n 'A valid \"Authorization: Bearer <token>\" header is required.',\n ),\n // RFC 9110 requires a challenge on every 401\n { 'www-authenticate': 'Bearer' },\n );\n }\n\n const version = header(req, ACP_API_VERSION_HEADER);\n if (version === undefined || version.trim().length === 0) {\n return failed(\n acpFailure(\n 400,\n 'invalid_request',\n 'missing_api_version',\n `The ${ACP_API_VERSION_HEADER} header is required.`,\n { supportedVersions: [ACP_API_VERSION] },\n ),\n );\n }\n if (version.trim() !== ACP_API_VERSION) {\n // Never mapped to the pinned version: \"latest\", an older snapshot and a\n // typo get the same answer\n return failed(\n acpFailure(\n 400,\n 'invalid_request',\n 'unsupported_api_version',\n 'The requested API version is not supported.',\n { supportedVersions: [ACP_API_VERSION] },\n ),\n );\n }\n\n // Checked before the body is read: a POST without a usable key can never be\n // executed, so reading its body would be wasted work\n let idempotencyKey: string | undefined;\n if (route.acceptsBody) {\n const presentedKey = header(req, ACP_IDEMPOTENCY_KEY_HEADER)?.trim();\n if (presentedKey === undefined || presentedKey.length === 0) {\n return failed(\n acpFailure(\n 400,\n 'invalid_request',\n 'idempotency_key_required',\n `The ${ACP_IDEMPOTENCY_KEY_HEADER} header is required on this ACP operation.`,\n ),\n );\n }\n // Bounded and printable ASCII like Request-Id: the key is echoed in a\n // response header, where a CRLF would split the response\n if (!isUsableIdempotencyKey(presentedKey)) {\n return failed(\n acpFailure(\n 400,\n 'invalid_request',\n 'idempotency_key_invalid',\n `The ${ACP_IDEMPOTENCY_KEY_HEADER} header must be 1-${ACP_MAX_IDEMPOTENCY_KEY_LENGTH} printable ASCII characters.`,\n ),\n );\n }\n idempotencyKey = presentedKey;\n }\n\n const read = await readCappedBody(req, options.maxBodyBytes ?? ACP_MAX_REQUEST_BODY_BYTES);\n if (read.kind === 'too-large') {\n return failed(\n acpFailure(\n 413,\n 'invalid_request',\n 'request_body_too_large',\n 'The request body is too large.',\n ),\n );\n }\n if (read.kind === 'unreadable') {\n return failed(\n acpFailure(\n 400,\n 'invalid_request',\n 'invalid_request_body',\n 'Could not read the request body.',\n ),\n );\n }\n\n const raw = read.text;\n const contentTypeFailure = checkContentType(header(req, 'content-type'), raw, route);\n if (contentTypeFailure !== undefined) return failed(contentTypeFailure);\n\n const definition = REQUEST_DEFINITIONS[route.operation];\n if (definition === undefined) {\n // GET carries no document; a body on it is ignored, not validated\n return ok(route, {}, req, idempotencyKey);\n }\n\n let body: unknown;\n if (raw.trim().length === 0) {\n // An absent body is an empty document, which the schema accepts (cancel)\n // or rejects (create) on its own terms\n body = {};\n } else {\n try {\n body = JSON.parse(raw);\n } catch {\n return failed(\n acpFailure(400, 'invalid_request', 'invalid_json', 'The request body is not valid JSON.'),\n );\n }\n }\n\n const failure = validateAcpDocument(definition, body);\n if (failure !== undefined) {\n // Only the pointer into the caller's document travels, not the Ajv message\n return failed(\n acpFailure(400, 'invalid_request', 'invalid_request_body', 'The request body is invalid.', {\n ...(failure.path !== undefined ? { param: failure.path } : {}),\n }),\n );\n }\n\n return ok(route, body as Record<string, unknown>, req, idempotencyKey);\n}\n\nfunction checkContentType(\n contentType: string | undefined,\n raw: string,\n route: AcpRouteMatch,\n): AcpFailure | undefined {\n if (!route.acceptsBody) return undefined;\n if (contentType === undefined) {\n // A POST with no body at all (a bare cancel) needs no content type\n return raw.trim().length === 0\n ? undefined\n : acpFailure(\n 415,\n 'invalid_request',\n 'unsupported_media_type',\n 'ACP request bodies must be sent as \"application/json\".',\n );\n }\n const mediaType = contentType.split(';')[0]?.trim().toLowerCase();\n if (mediaType === 'application/json' || mediaType?.endsWith('+json')) return undefined;\n return acpFailure(\n 415,\n 'invalid_request',\n 'unsupported_media_type',\n 'ACP request bodies must be sent as \"application/json\".',\n );\n}\n\nfunction ok(\n route: AcpRouteMatch,\n body: Record<string, unknown>,\n req: IncomingMessage,\n idempotencyKey: string | undefined,\n): AcpGuardResult {\n const requestId = normalizeRequestId(header(req, ACP_REQUEST_ID_HEADER));\n return {\n ok: true,\n value: {\n route,\n body,\n ...(requestId !== undefined ? { requestId } : {}),\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n forwardedHeaders: forwardedHeaders(req, requestId),\n },\n };\n}\n\n// Forward only bounded, printable caller headers. Request-Id is filtered\n// for echoing; API-Version has already passed validation.\nfunction forwardedHeaders(\n req: IncomingMessage,\n requestId: string | undefined,\n): Readonly<Record<string, string>> {\n const forwarded: Record<string, string> = {};\n for (const name of ACP_FORWARDED_HEADERS) {\n const value = name === ACP_REQUEST_ID_HEADER ? requestId : header(req, name)?.trim();\n if (\n value !== undefined &&\n value.length > 0 &&\n value.length <= ACP_MAX_FORWARDED_HEADER_LENGTH &&\n isVisibleAscii(value)\n ) {\n forwarded[name] = value;\n }\n }\n return forwarded;\n}\n\nfunction isUsableIdempotencyKey(value: string): boolean {\n return (\n value.length > 0 && value.length <= ACP_MAX_IDEMPOTENCY_KEY_LENGTH && isVisibleAscii(value)\n );\n}\n\n/**\n * The caller's correlation id, echoed back but never used as the gateway's own\n * request id. It is caller-controlled text bound for a response header, so it\n * is truncated and dropped unless it is printable ASCII.\n */\nfunction normalizeRequestId(value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n const trimmed = value.trim().slice(0, ACP_MAX_REQUEST_ID_LENGTH);\n if (trimmed.length === 0) return undefined;\n if (!isVisibleAscii(trimmed)) return undefined;\n return trimmed;\n}\n\nfunction isVisibleAscii(value: string): boolean {\n return !/[^\\x20-\\x7e]/.test(value);\n}\n\nfunction header(req: IncomingMessage, name: string): string | undefined {\n const value = req.headers[name];\n return Array.isArray(value) ? value[0] : value;\n}\n","/**\n * Execution outcome -> ACP response, under two rules. A successful answer must\n * be a document the pinned snapshot accepts, on the status ACP fixes for the\n * route, because a merchant backend is not automatically ACP-conformant. A\n * failure uses ACP's error shape. Only selected fields of a valid merchant\n * ACP error and a capped `Retry-After` delay can cross this boundary; internal\n * details stay in logs.\n */\nimport type { CommerceError, DeliveredOutcome } from '../../core';\nimport { BackendErrorResponse } from '../../core/execution/backend-http';\nimport { isRecord } from '../../core/is-record';\nimport {\n ACP_MERCHANT_RETRY_AFTER_DEFAULT_SECONDS,\n ACP_MERCHANT_RETRY_AFTER_MAX_SECONDS,\n type AcpCheckoutOperation,\n} from './constants';\nimport { type AcpErrorType, type AcpFailure, acpFailure } from './errors';\nimport { type AcpDefinition, validateAcpDocument } from './validation';\n\n/** One ACP answer, as a value: it may have to be stored before it is written */\nexport interface AcpResponse {\n readonly status: number;\n readonly body: unknown;\n /** True when this answer came from the idempotency store rather than work done now */\n readonly replayed?: boolean;\n /**\n * Seconds for `Retry-After`, set only where a retry is the right move. Not\n * derived from the status: two of the 409s this adapter returns must not\n * invite a retry.\n */\n readonly retryAfterSeconds?: number;\n}\n\n/**\n * The status each route answers on success, fixed by ACP. A merchant backend\n * that succeeded with a different one has not implemented the operation ACP\n * describes, so its answer is refused rather than quietly renumbered.\n */\nexport const ACP_SUCCESS_STATUS: Readonly<Record<AcpCheckoutOperation, number>> = {\n createCheckoutSession: 201,\n updateCheckoutSession: 200,\n getCheckoutSession: 200,\n completeCheckoutSession: 200,\n cancelCheckoutSession: 200,\n};\n\n/**\n * A mapped response, plus what the operator needs in the log to understand a\n * refusal. `logDetail` is kept apart from `response` so it never reaches the\n * client.\n */\nexport interface AcpMappedResponse {\n readonly response: AcpResponse;\n readonly logDetail?: Readonly<Record<string, unknown>>;\n}\n\nconst PROCESSING_ERROR = acpFailure(\n 500,\n 'processing_error',\n 'processing_error',\n 'The server could not process this checkout operation.',\n);\n\nexport function toAcpResponse(\n operation: AcpCheckoutOperation,\n outcome: DeliveredOutcome,\n): AcpMappedResponse {\n const expected = ACP_SUCCESS_STATUS[operation];\n if (outcome.backendStatus !== expected) {\n return {\n response: asResponse(PROCESSING_ERROR),\n logDetail: {\n reason: 'unexpected-backend-status',\n operation,\n backendStatus: outcome.backendStatus,\n expected,\n },\n };\n }\n\n const definition = responseDefinition(operation, outcome.body);\n const failure = validateAcpDocument(definition, outcome.body);\n if (failure !== undefined) {\n // Not ACP, so not forwarded, and the caller learns nothing of its shape:\n // the pointer is into the merchant's document, ours to fix, not theirs\n return {\n response: asResponse(PROCESSING_ERROR),\n logDetail: {\n reason: 'backend-response-not-acp',\n operation,\n definition,\n path: failure.path ?? '$',\n keyword: failure.code,\n },\n };\n }\n\n const htmlPath = rawHtmlPath(outcome.body, '$');\n if (htmlPath !== undefined) {\n // Reject detected HTML markup before forwarding merchant markdown\n return {\n response: asResponse(PROCESSING_ERROR),\n logDetail: { reason: 'backend-markdown-has-raw-html', operation, path: htmlPath },\n };\n }\n\n return { response: { status: expected, body: outcome.body } };\n}\n\n// Detect common HTML markup: tags, comments, processing instructions,\n// declarations and CDATA. Autolinks such as <https://x> do not match.\nconst RAW_HTML = /<\\/?[A-Za-z][A-Za-z0-9-]*(?=[\\s/>]|$)|<!--|<\\?|<![A-Za-z]|<!\\[CDATA\\[/;\n\n// Ignore backtick-delimited code spans when checking for HTML markup\nconst CODE_SPAN = /(`+)[\\s\\S]*?\\1/g;\n\n// Path to the first markdown `content` with detected HTML markup\nfunction rawHtmlPath(node: unknown, path: string): string | undefined {\n if (Array.isArray(node)) {\n for (const [index, item] of node.entries()) {\n const found = rawHtmlPath(item, `${path}[${index}]`);\n if (found !== undefined) return found;\n }\n return undefined;\n }\n if (!isRecord(node)) return undefined;\n const content = node['content'];\n if (\n node['content_type'] === 'markdown' &&\n typeof content === 'string' &&\n RAW_HTML.test(content.replace(CODE_SPAN, ''))\n ) {\n return `${path}.content`;\n }\n for (const [key, value] of Object.entries(node)) {\n const found = rawHtmlPath(value, `${path}.${key}`);\n if (found !== undefined) return found;\n }\n return undefined;\n}\n\n/**\n * Completion is the one route with two shapes, chosen by the session's own\n * `status`. A completed session must carry its order\n * (`CheckoutSessionWithOrder`, where `Order` requires an id), but a completion\n * that ends in a declined payment or an out-of-stock item answers 200 with an\n * ordinary session and no order, as the snapshot's own examples show.\n */\nfunction responseDefinition(operation: AcpCheckoutOperation, body: unknown): AcpDefinition {\n if (operation !== 'completeCheckoutSession') return 'checkoutSession';\n const status = (body as { status?: unknown } | null)?.status;\n return status === 'completed' ? 'checkoutSessionWithOrder' : 'checkoutSession';\n}\n\n/**\n * Map pipeline failures to ACP errors. For relayed merchant statuses, a\n * valid ACP error can contribute its type, safe code and optional param. The\n * merchant's message and remaining body fields stay out of the response.\n */\nexport function mapCommerceErrorToAcp(\n error: CommerceError,\n operation: AcpCheckoutOperation,\n): AcpFailure {\n switch (error.code) {\n case 'INPUT_INVALID':\n // The ACP schema accepted the document, so the resource's own input\n // schema rejected it: reported without naming its internal fields\n return acpFailure(\n 400,\n 'invalid_request',\n 'invalid_request_body',\n 'The request could not be accepted for this checkout operation.',\n );\n case 'BACKEND_TIMEOUT':\n return acpFailure(\n 504,\n 'service_unavailable',\n 'service_unavailable',\n 'The merchant did not respond in time.',\n );\n case 'GATEWAY_BUSY':\n return acpFailure(\n 503,\n 'service_unavailable',\n 'service_unavailable',\n 'The gateway is busy; retry shortly.',\n );\n case 'BACKEND_ERROR':\n return fromBackendStatus(error, operation);\n default:\n // RESOURCE_NOT_FOUND means the mapping points at a resource that is gone;\n // a PAYMENT_* code means a checkout resource was configured as paid.\n // Both are broken deployments, not something the caller did.\n return PROCESSING_ERROR;\n }\n}\n\n/**\n * Relay compatible merchant statuses and map merchant 429/503 to ACP 503.\n * Merchant 401/403 maps to 502 so it does not suggest the agent's bearer\n * token failed.\n */\nfunction fromBackendStatus(error: CommerceError, operation: AcpCheckoutOperation): AcpFailure {\n const failure = statusFailure(error, operation);\n return failure.status < 500 ? withMerchantError(failure, error) : failure;\n}\n\n/** True for merchant 429, which the adapter treats as unprocessed */\nexport function isMerchantRateLimit(error: CommerceError): boolean {\n return error.code === 'BACKEND_ERROR' && error.details?.['status'] === 429;\n}\n\n// Parse whole seconds, cap the delay, and use the default for other forms\nfunction merchantRetryAfterSeconds(error: CommerceError): number {\n const value =\n error.cause instanceof BackendErrorResponse ? error.cause.headers['retry-after'] : undefined;\n if (value === undefined || !/^\\d{1,9}$/.test(value.trim())) {\n return ACP_MERCHANT_RETRY_AFTER_DEFAULT_SECONDS;\n }\n return Math.min(Math.max(Number(value), 1), ACP_MERCHANT_RETRY_AFTER_MAX_SECONDS);\n}\n\n// Limit merchant codes to snake_case and params to short printable text\n// beginning with `$`. The `idempotency_` codes describe the caller's own key\n// and only the gateway issues them.\nconst MERCHANT_CODE = /^(?!idempotency_)[a-z][a-z0-9_]{0,63}$/;\nconst MERCHANT_PARAM = /^\\$[\\x20-\\x7e]{0,255}$/;\n\n/**\n * Keep the type and safe code from a valid merchant ACP error on a relayed\n * status. Include a safe param when present; retain the gateway's message.\n */\nfunction withMerchantError(failure: AcpFailure, error: CommerceError): AcpFailure {\n const body = error.cause instanceof BackendErrorResponse ? error.cause.body : undefined;\n if (!isRecord(body) || validateAcpDocument('error', body) !== undefined) return failure;\n const { type, code, param } = body;\n if (typeof code !== 'string' || !MERCHANT_CODE.test(code)) return failure;\n const relayParam = typeof param === 'string' && MERCHANT_PARAM.test(param) ? param : undefined;\n return acpFailure(\n failure.status,\n type as AcpErrorType,\n code,\n failure.error.message,\n relayParam !== undefined ? { param: relayParam } : {},\n );\n}\n\nfunction statusFailure(error: CommerceError, operation: AcpCheckoutOperation): AcpFailure {\n const merchantStatus = error.details?.['status'];\n const status = typeof merchantStatus === 'number' ? merchantStatus : 0;\n switch (status) {\n case 404:\n return acpFailure(\n 404,\n 'invalid_request',\n 'checkout_session_not_found',\n 'No such checkout session.',\n );\n case 405:\n return operation === 'cancelCheckoutSession'\n ? acpFailure(\n 405,\n 'invalid_request',\n 'checkout_session_not_cancelable',\n 'This checkout session can no longer be canceled.',\n )\n : acpFailure(\n 405,\n 'invalid_request',\n 'method_not_allowed',\n 'The merchant does not allow this operation on this checkout session.',\n );\n case 400:\n case 422:\n // Relayed on the merchant's own status: the snapshot's 3DS refusal is a\n // 400, and its only 422 is the idempotency conflict\n return acpFailure(\n status,\n 'invalid_request',\n 'invalid_request_body',\n 'The merchant rejected this checkout request.',\n );\n case 409:\n return acpFailure(\n 409,\n 'invalid_request',\n 'checkout_session_conflict',\n 'This checkout session is in a state that does not allow this operation.',\n );\n case 429:\n case 503:\n return {\n ...acpFailure(\n 503,\n 'service_unavailable',\n 'service_unavailable',\n 'The merchant is temporarily unavailable.',\n ),\n retryAfterSeconds: merchantRetryAfterSeconds(error),\n };\n default:\n return acpFailure(\n 502,\n 'processing_error',\n 'processing_error',\n 'The merchant could not process this checkout operation.',\n );\n }\n}\n\nexport function asResponse(failure: AcpFailure): AcpResponse {\n return {\n status: failure.status,\n body: failure.error,\n ...(failure.retryAfterSeconds !== undefined\n ? { retryAfterSeconds: failure.retryAfterSeconds }\n : {}),\n };\n}\n","/**\n * ACP (Agentic Commerce Protocol) adapter, experimental.\n *\n * Serves two paths: the configured mount (`/acp`), where the five stable\n * checkout routes live, and the specification-fixed `/.well-known/acp.json`,\n * declared through `additionalHttpRoutes` so the gateway needs no ACP-specific\n * routing.\n *\n * A request that passes every protocol guard runs its mapped resource through\n * the pipeline, under an idempotency claim when it carries a key. This file\n * never calls a merchant backend and never inspects a payment object.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport {\n type AdapterDescriptor,\n type AdapterHealth,\n type AdapterHttpRoute,\n CommerceError,\n type CommerceResource,\n type DeliveredOutcome,\n type HttpProtocolAdapter,\n type ProtocolAdapterContext,\n toCommerceError,\n} from '../../core';\nimport { toLogInfo } from '../../core/errors';\nimport { PACKAGE_VERSION } from '../../version';\nimport { createBearerCheck } from '../http';\nimport { toCanonicalRequest } from './checkout-mapping';\nimport {\n ACP_CHECKOUT_OPERATIONS,\n ACP_IDEMPOTENCY_KEY_HEADER,\n ACP_IDEMPOTENT_REPLAYED_HEADER,\n ACP_IN_FLIGHT_RETRY_AFTER_SECONDS,\n ACP_REQUEST_ID_HEADER,\n ACP_WELL_KNOWN_PATH,\n type AcpCheckoutOperation,\n} from './constants';\nimport { buildDescriptor } from './descriptor';\nimport { type AcpDiscoveryMetadata, buildAcpDiscoveryDocument } from './discovery';\nimport {\n type AcpFailure,\n type AcpResponseHeaders,\n acpFailure,\n writeAcpFailure,\n writeAcpJson,\n} from './errors';\nimport { operationKey, requestFingerprint } from './idempotency/fingerprint';\nimport {\n type AcpIdempotencyScope,\n type AcpIdempotencyStore,\n createAcpIdempotencyStore,\n} from './idempotency/store';\nimport { type AcpGuardedRequest, acpEchoHeaders, guardAcpRequest } from './request-guards';\nimport {\n type AcpResponse,\n asResponse,\n isMerchantRateLimit,\n mapCommerceErrorToAcp,\n toAcpResponse,\n} from './response-mapping';\nimport { validateAcpDocument } from './validation';\n\n// Discovery is fixed for the life of the process, so edge caches may keep it\nconst DISCOVERY_CACHE_CONTROL = 'public, max-age=3600';\n\n/**\n * Whether this attempt could have changed anything at the merchant. `no` must\n * be proven, because only `no` frees an idempotency key for a retry; `unknown`\n * and `yes` are treated alike and differ only in the log.\n */\ntype MerchantReach = 'no' | 'unknown' | 'yes';\n\ninterface AcpCheckoutAttempt {\n readonly response: AcpResponse;\n readonly reached: MerchantReach;\n}\n\n/**\n * The codes the pipeline raises strictly before it calls the merchant. An\n * allowlist, so a new code counts as ambiguous rather than freeing a key.\n * `STORAGE_ERROR` is absent: the pipeline raises it only when reserving a\n * payment attempt, which a free checkout resource never does, so on this route\n * it can only be unexpected and counts as ambiguous.\n */\nconst PRE_BACKEND_ERROR_CODES: ReadonlySet<string> = new Set([\n 'CONFIG_INVALID',\n 'RESOURCE_NOT_FOUND',\n 'INPUT_INVALID',\n 'PROTOCOL_UNSUPPORTED',\n 'GATEWAY_BUSY',\n 'PAYMENT_REQUIRED',\n 'PAYMENT_INVALID',\n 'PAYMENT_REPLAYED',\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'PAYMENT_SETTLEMENT_FAILED',\n 'AUTHORIZATION_REQUIRED',\n 'AUTHORIZATION_INVALID',\n 'AUTHORIZATION_REPLAYED',\n 'AUTHORIZATION_PROVIDER_UNAVAILABLE',\n]);\n\n// Treat merchant 429 as unprocessed and release the key. A 503 may follow\n// partial work, so its outcome stays unknown.\nfunction reachedFor(error: CommerceError): MerchantReach {\n return PRE_BACKEND_ERROR_CODES.has(error.code) || isMerchantRateLimit(error) ? 'no' : 'unknown';\n}\n\nfunction notReached(failure: AcpFailure): AcpCheckoutAttempt {\n return { response: asResponse(failure), reached: 'no' };\n}\n\nexport interface AcpAdapterOptions {\n readonly mountPath: string;\n /** The configured bearer token. Never logged, never echoed, never published */\n readonly token: string;\n /** Which canonical resource implements each ACP checkout operation */\n readonly operations: Readonly<Record<AcpCheckoutOperation, string>>;\n /** Where checkout idempotency records live, and how long they are kept */\n readonly idempotency: {\n readonly path: string;\n readonly retentionHours: number;\n /**\n * Declare that the merchant deduplicates by the derived `Idempotency-Key`.\n * Allows a fresh retry after a 5xx. Defaults to false.\n */\n readonly merchantIdempotent?: boolean;\n };\n readonly discovery?: AcpDiscoveryMetadata;\n}\n\nexport class AcpProtocolAdapter implements HttpProtocolAdapter {\n readonly name = 'acp' as const;\n readonly mountPath: string;\n readonly descriptor: AdapterDescriptor;\n readonly additionalHttpRoutes: readonly AdapterHttpRoute[];\n\n private readonly isAuthorized: (authorizationHeader: string | undefined) => boolean;\n private readonly operations: Readonly<Record<AcpCheckoutOperation, string>>;\n private readonly idempotencyOptions: AcpAdapterOptions['idempotency'];\n /**\n * The deployment an idempotency claim is scoped to, `context.publicBaseUrl`.\n * Not readonly because it is known only once the adapter starts.\n */\n private deployment: string | undefined;\n private readonly discoveryMetadata: AcpDiscoveryMetadata | undefined;\n private idempotency: AcpIdempotencyStore | undefined;\n private resources: ReadonlyMap<AcpCheckoutOperation, CommerceResource> = new Map();\n\n private context: ProtocolAdapterContext | undefined;\n private started = false;\n // Built once at start: the document is fixed by config, and a per-request\n // build would be work an unauthenticated GET could trigger at will\n private discovery: Record<string, unknown> | undefined;\n\n constructor(options: AcpAdapterOptions) {\n this.mountPath = options.mountPath;\n this.isAuthorized = createBearerCheck(options.token);\n this.operations = options.operations;\n this.idempotencyOptions = options.idempotency;\n this.discoveryMetadata = options.discovery;\n this.descriptor = buildDescriptor(PACKAGE_VERSION);\n this.additionalHttpRoutes = [\n {\n method: 'GET',\n path: ACP_WELL_KNOWN_PATH,\n handleHttp: (req, res) => this.handleDiscovery(req, res),\n },\n ];\n }\n\n async start(context: ProtocolAdapterContext): Promise<void> {\n this.context = context;\n this.started = false;\n\n const document = buildAcpDiscoveryDocument({\n publicBaseUrl: context.publicBaseUrl,\n mountPath: this.mountPath,\n ...(this.discoveryMetadata !== undefined ? { metadata: this.discoveryMetadata } : {}),\n });\n // Configured metadata is free text (a currency that is not ISO 4217, an\n // intervention type ACP does not define), so the document is validated\n // against the pinned snapshot before it is published. A failure stops only\n // this adapter.\n const invalid = validateAcpDocument('discoveryResponse', document);\n if (invalid !== undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `ACP discovery document does not conform to the ${this.descriptor.supportedSpec} snapshot at \"${invalid.path ?? '$'}\" (${invalid.code}) - check protocols.acp.discovery`,\n { details: { path: invalid.path ?? '$', code: invalid.code } },\n );\n }\n\n // Config already refuses a mapping to a resource that is not acp-exposed;\n // the adapter checks again, as MCP and A2A do\n const exposed = new Map(\n context.resources.listExposedVia('acp').map((resource) => [resource.id, resource]),\n );\n const resolved = new Map<AcpCheckoutOperation, CommerceResource>();\n for (const operation of ACP_CHECKOUT_OPERATIONS) {\n const resourceId = this.operations[operation];\n const resource = exposed.get(resourceId);\n if (resource === undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `ACP operation \"${operation}\" is mapped to resource \"${resourceId}\", which is not exposed via acp`,\n { details: { operation, resourceId } },\n );\n }\n resolved.set(operation, resource);\n }\n this.resources = resolved;\n\n this.deployment = context.publicBaseUrl;\n this.idempotency = createAcpIdempotencyStore({\n path: this.idempotencyOptions.path,\n retentionHours: this.idempotencyOptions.retentionHours,\n releaseOrphans: this.idempotencyOptions.merchantIdempotent === true,\n logger: context.logger,\n });\n\n this.discovery = document;\n this.started = true;\n context.logger.info(\n {\n mountPath: this.mountPath,\n discoveryPath: ACP_WELL_KNOWN_PATH,\n idempotencyRetentionHours: this.idempotencyOptions.retentionHours,\n },\n 'acp adapter started',\n );\n }\n\n /** `GET /.well-known/acp.json`: public, unauthenticated, cacheable */\n async handleDiscovery(req: IncomingMessage, res: ServerResponse): Promise<void> {\n try {\n if (!this.started || this.discovery === undefined) {\n writeAcpFailure(\n res,\n acpFailure(\n 503,\n 'service_unavailable',\n 'service_unavailable',\n 'The ACP adapter is not running.',\n ),\n );\n return;\n }\n if (req.method !== 'GET') {\n writeAcpFailure(\n res,\n acpFailure(\n 405,\n 'invalid_request',\n 'method_not_allowed',\n 'The ACP discovery document is read-only.',\n ),\n { allow: 'GET' },\n );\n return;\n }\n writeAcpJson(res, 200, this.discovery, { 'cache-control': DISCOVERY_CACHE_CONTROL });\n } catch (err) {\n this.fail(res, err, 'acp adapter: discovery request failed');\n }\n }\n\n /** `<mountPath>/checkout_sessions...`: the five stable checkout routes */\n async handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void> {\n try {\n if (!this.started) {\n // Reachable during shutdown, which stops adapters before the server\n writeAcpFailure(\n res,\n acpFailure(\n 503,\n 'service_unavailable',\n 'service_unavailable',\n 'The ACP adapter is not running.',\n ),\n acpEchoHeaders(req),\n );\n return;\n }\n\n const guarded = await guardAcpRequest(req, {\n mountPath: this.mountPath,\n isAuthorized: this.isAuthorized,\n });\n if (!guarded.ok) {\n writeAcpFailure(res, guarded, guarded.headers);\n return;\n }\n\n const request = guarded.value;\n const response = await this.dispatch(request);\n writeAcpJson(res, response.status, response.body, this.responseHeaders(request, response));\n } catch (err) {\n this.fail(res, err, 'acp adapter: request handling failed', acpEchoHeaders(req));\n }\n }\n\n /**\n * One request, at most one execution. A body-bearing route claims its\n * idempotency key before the work starts, so a retry arriving meanwhile finds\n * the claim; the read-only GET carries no key.\n */\n private async dispatch(request: AcpGuardedRequest): Promise<AcpResponse> {\n const store = this.idempotency;\n const deployment = this.deployment;\n const key = request.idempotencyKey;\n if (store === undefined || deployment === undefined || key === undefined) {\n return (await this.runCheckout(request)).response;\n }\n\n const scope: AcpIdempotencyScope = { deployment, endpoint: request.route.path, key };\n const claim = store.claim(scope, requestFingerprint(request.body));\n\n switch (claim.kind) {\n case 'in-flight':\n return {\n ...asResponse(\n acpFailure(\n 409,\n 'invalid_request',\n 'idempotency_in_flight',\n 'A request with this Idempotency-Key is still being processed.',\n ),\n ),\n retryAfterSeconds: ACP_IN_FLIGHT_RETRY_AFTER_SECONDS,\n };\n case 'unresolved':\n // Neither re-run nor replayed: an earlier attempt reached the merchant\n // and its outcome is unknown (see the idempotency store)\n return asResponse(\n acpFailure(\n 409,\n 'invalid_request',\n 'idempotency_unresolved',\n 'An earlier request with this Idempotency-Key reached the merchant and its outcome is unknown. Check the operation with the merchant before retrying.',\n ),\n );\n case 'conflict':\n return asResponse(\n acpFailure(\n 422,\n 'invalid_request',\n 'idempotency_conflict',\n 'This Idempotency-Key was already used for a different request body.',\n ),\n );\n case 'replay':\n return { status: claim.status, body: claim.body, replayed: true };\n default:\n break;\n }\n\n let outcome: AcpCheckoutAttempt;\n try {\n outcome = await this.runCheckout(request, operationKey(scope));\n } catch (err) {\n // An adapter bug, not a merchant verdict; the merchant may have been\n // called, so the claim is kept\n store.markUnresolved(scope);\n throw err;\n }\n\n // A 2xx or 4xx is an outcome, even a refusal, and answers every retry\n if (outcome.response.status < 500) {\n store.complete(scope, outcome.response);\n } else if (outcome.reached === 'no' || this.idempotencyOptions.merchantIdempotent === true) {\n // Release when no call ran, the merchant returned 429, or the merchant\n // deduplicates retries by the derived key\n store.release(scope);\n } else {\n // A timeout, a merchant status ACP cannot relay or a non-ACP reply: the\n // merchant may have acted, and freeing the key could turn one checkout\n // into two orders\n store.markUnresolved(scope);\n }\n return outcome.response;\n }\n\n // One accepted request, one `pipeline.execute()`\n private async runCheckout(\n request: AcpGuardedRequest,\n idempotencyKey?: string,\n ): Promise<AcpCheckoutAttempt> {\n const context = this.context;\n const resource = this.resources.get(request.route.operation);\n if (context === undefined || resource === undefined) {\n return notReached(\n acpFailure(\n 503,\n 'service_unavailable',\n 'service_unavailable',\n 'The ACP adapter is not running.',\n ),\n );\n }\n\n const canonical = toCanonicalRequest({\n request,\n resourceId: resource.id,\n requestId: context.ids.next('acp'),\n receivedAt: context.clock.nowIso(),\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n });\n\n try {\n const outcome = await context.pipeline.execute(canonical);\n if (outcome.kind === 'payment-required') {\n // Config refuses a paid checkout resource and ACP cannot carry a\n // gateway challenge, so this is a broken deployment. Nothing about the\n // challenge is disclosed.\n context.logger.error(\n { resourceId: resource.id, requestId: canonical.requestId },\n 'acp adapter: mapped checkout resource returned payment-required - it must be priced free',\n );\n return notReached(\n acpFailure(\n 500,\n 'processing_error',\n 'processing_error',\n 'The server could not process this checkout operation.',\n ),\n );\n }\n const mapped = toAcpResponse(request.route.operation, outcome as DeliveredOutcome);\n if (mapped.logDetail !== undefined) {\n // The merchant answered, but not with ACP: the details go to the log,\n // the caller gets the refusal in `response`\n context.logger.error(\n { resourceId: resource.id, requestId: canonical.requestId, ...mapped.logDetail },\n 'acp adapter: refusing to forward a non-conformant merchant response',\n );\n }\n // Delivered, so the merchant ran the operation even if its answer is\n // refused as non-ACP; the order may exist, so the key is not freed\n return { response: mapped.response, reached: 'yes' };\n } catch (err) {\n const error = toCommerceError(err);\n context.logger.warn(\n {\n resourceId: resource.id,\n requestId: canonical.requestId,\n reached: reachedFor(error),\n err: toLogInfo(error),\n },\n 'acp adapter: checkout execution failed',\n );\n return {\n response: asResponse(mapCommerceErrorToAcp(error, request.route.operation)),\n reached: reachedFor(error),\n };\n }\n }\n\n // Protocol-owned headers only. No merchant header is proxied: `Retry-After`\n // is written from seconds the mapping parsed and capped.\n private responseHeaders(\n request: AcpGuardedRequest,\n response?: AcpResponse,\n ): Readonly<Record<string, string>> {\n const replayed = response?.replayed === true;\n return {\n ...(request.requestId !== undefined ? { [ACP_REQUEST_ID_HEADER]: request.requestId } : {}),\n ...(request.idempotencyKey !== undefined\n ? { [ACP_IDEMPOTENCY_KEY_HEADER]: request.idempotencyKey }\n : {}),\n ...(replayed ? { [ACP_IDEMPOTENT_REPLAYED_HEADER]: 'true' } : {}),\n ...(response?.retryAfterSeconds !== undefined\n ? { 'retry-after': String(response.retryAfterSeconds) }\n : {}),\n };\n }\n\n private fail(\n res: ServerResponse,\n err: unknown,\n message: string,\n headers: AcpResponseHeaders = {},\n ): void {\n // Nothing from `err` reaches the client\n this.context?.logger.error({ err: toLogInfo(err) }, message);\n writeAcpFailure(\n res,\n acpFailure(500, 'processing_error', 'internal_error', 'Internal server error.'),\n headers,\n );\n }\n\n async health(): Promise<AdapterHealth> {\n const checkedAt = this.context?.clock.nowIso() ?? new Date().toISOString();\n if (!this.started || this.discovery === undefined) {\n return { status: 'fail', detail: 'ACP adapter has not been started.', checkedAt };\n }\n return {\n status: 'pass',\n detail: `checkout service published at ${this.mountPath}.`,\n checkedAt,\n };\n }\n\n async stop(): Promise<void> {\n this.started = false;\n this.discovery = undefined;\n this.resources = new Map();\n this.idempotency?.close();\n this.idempotency = undefined;\n this.deployment = undefined;\n this.context = undefined;\n }\n}\n\nexport function createAcpAdapter(options: AcpAdapterOptions): AcpProtocolAdapter {\n return new AcpProtocolAdapter(options);\n}\n","/**\n * Defense in depth against persisting secrets. Receipt, event and payment\n * metadata must not carry secrets (docs/contracts.md, \"Store no secrets\"); at\n * the persistence boundary this module replaces secret-shaped values rather\n * than rejecting the write, because event persistence must not break a\n * commerce flow.\n */\n\n// Matches anywhere in the key (only `auth` and `proof` must be the whole key),\n// so an audit field whose name contains \"token\", \"session\", \"jwt\" or similar\n// persists as [REDACTED]\nconst SECRET_KEY_PATTERN =\n /private[-_ ]?key|secret|password|mnemonic|seed[-_ ]?phrase|api[-_ ]?key|authoriz(e|ation)|^auth$|auth[-_]?header|payment[-_ ]?proof|^proof$|x-payment|signature|signed[-_ ]?message|token|bearer|credential|cookie|session|jwt/i;\n\nconst REDACTED = '[REDACTED]';\n\n/** True if `key` looks like it names a secret value */\nexport function isSecretKey(key: string): boolean {\n return SECRET_KEY_PATTERN.test(key);\n}\n\n/**\n * Returns a copy with every value under a secret-shaped key replaced, at any\n * depth. Clean input comes back equal to itself.\n */\nexport function redact<T>(value: T): T {\n return redactValue(value) as T;\n}\n\nfunction redactValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(redactValue);\n }\n if (value !== null && typeof value === 'object') {\n const out: Record<string, unknown> = {};\n for (const [key, inner] of Object.entries(value as Record<string, unknown>)) {\n out[key] = isSecretKey(key) ? REDACTED : redactValue(inner);\n }\n return out;\n }\n return value;\n}\n","/**\n * SQLite row shapes and their mapping to and from the canonical model. Under\n * `exactOptionalPropertyTypes`, an optional field is set only when present.\n */\nimport type {\n AuthorizationRecord,\n CommerceEvent,\n CommerceEventType,\n CommerceReceipt,\n PaymentAttempt,\n PaymentResult,\n} from '../../core';\nimport { redact } from './redact';\n\nexport interface ReceiptRow {\n readonly id: string;\n readonly request_id: string;\n readonly resource_id: string;\n readonly payment_json: string | null;\n readonly delivered_at: string;\n readonly backend_status: number;\n readonly duration_ms: number | null;\n readonly protocol: string | null;\n readonly metadata_json: string | null;\n readonly authorization_json: string | null;\n}\n\nexport interface EventRow {\n readonly id: string;\n readonly type: string;\n readonly request_id: string;\n readonly resource_id: string | null;\n readonly at: string;\n readonly adapter: string | null;\n readonly payment_provider: string | null;\n readonly duration_ms: number | null;\n readonly status: string | null;\n readonly data_json: string | null;\n}\n\nexport interface PaymentAttemptRow {\n readonly id: string;\n readonly request_id: string;\n readonly resource_id: string;\n readonly provider: string;\n readonly replay_key: string;\n readonly status: string;\n readonly amount: string;\n readonly currency: string;\n readonly payer: string | null;\n readonly payee: string | null;\n readonly external_reference: string | null;\n readonly rejection_reason: string | null;\n readonly created_at: string;\n readonly updated_at: string;\n}\n\nexport function receiptToRow(receipt: CommerceReceipt): {\n id: string;\n request_id: string;\n resource_id: string;\n payment_json: string | null;\n delivered_at: string;\n backend_status: number;\n duration_ms: number | null;\n protocol: string | null;\n metadata_json: string | null;\n authorization_json: string | null;\n} {\n return {\n id: receipt.id,\n request_id: receipt.requestId,\n resource_id: receipt.resourceId,\n payment_json: receipt.payment !== undefined ? JSON.stringify(redact(receipt.payment)) : null,\n delivered_at: receipt.deliveredAt,\n backend_status: receipt.backendStatus,\n duration_ms: receipt.durationMs ?? null,\n protocol: receipt.protocol ?? null,\n metadata_json: receipt.metadata !== undefined ? JSON.stringify(redact(receipt.metadata)) : null,\n authorization_json:\n receipt.authorization !== undefined ? JSON.stringify(redact(receipt.authorization)) : null,\n };\n}\n\nexport function rowToReceipt(row: ReceiptRow): CommerceReceipt {\n const payment =\n row.payment_json !== null ? (JSON.parse(row.payment_json) as PaymentResult) : undefined;\n const metadata =\n row.metadata_json !== null\n ? (JSON.parse(row.metadata_json) as Record<string, unknown>)\n : undefined;\n // Null for a receipt written before this column existed and for a resource\n // that requires no authorization\n const authorization =\n row.authorization_json !== null\n ? (JSON.parse(row.authorization_json) as AuthorizationRecord)\n : undefined;\n return {\n id: row.id,\n requestId: row.request_id,\n resourceId: row.resource_id,\n deliveredAt: row.delivered_at,\n backendStatus: row.backend_status,\n ...(payment !== undefined ? { payment } : {}),\n ...(row.duration_ms !== null ? { durationMs: row.duration_ms } : {}),\n ...(row.protocol !== null ? { protocol: row.protocol } : {}),\n ...(metadata !== undefined ? { metadata } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n };\n}\n\nexport function eventToRow(event: CommerceEvent): {\n id: string;\n type: string;\n request_id: string;\n resource_id: string | null;\n at: string;\n adapter: string | null;\n payment_provider: string | null;\n duration_ms: number | null;\n status: string | null;\n data_json: string | null;\n} {\n return {\n id: event.id,\n type: event.type,\n request_id: event.requestId,\n resource_id: event.resourceId ?? null,\n at: event.at,\n adapter: event.adapter ?? null,\n payment_provider: event.paymentProvider ?? null,\n duration_ms: event.durationMs ?? null,\n status: event.status ?? null,\n data_json: event.data !== undefined ? JSON.stringify(redact(event.data)) : null,\n };\n}\n\nexport function rowToEvent(row: EventRow): CommerceEvent {\n const data =\n row.data_json !== null ? (JSON.parse(row.data_json) as Record<string, unknown>) : undefined;\n return {\n id: row.id,\n type: row.type as CommerceEventType,\n requestId: row.request_id,\n at: row.at,\n ...(row.resource_id !== null ? { resourceId: row.resource_id } : {}),\n ...(row.adapter !== null ? { adapter: row.adapter } : {}),\n ...(row.payment_provider !== null ? { paymentProvider: row.payment_provider } : {}),\n ...(row.duration_ms !== null ? { durationMs: row.duration_ms } : {}),\n ...(row.status !== null ? { status: row.status as 'ok' | 'error' } : {}),\n ...(data !== undefined ? { data } : {}),\n };\n}\n\nexport function rowToPaymentAttempt(row: PaymentAttemptRow): PaymentAttempt {\n return {\n id: row.id,\n requestId: row.request_id,\n resourceId: row.resource_id,\n provider: row.provider,\n replayKey: row.replay_key,\n status: row.status as PaymentAttempt['status'],\n amount: row.amount,\n currency: row.currency,\n ...(row.payer !== null ? { payer: row.payer } : {}),\n ...(row.payee !== null ? { payee: row.payee } : {}),\n ...(row.external_reference !== null ? { externalReference: row.external_reference } : {}),\n ...(row.rejection_reason !== null ? { rejectionReason: row.rejection_reason } : {}),\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n","/**\n * Receipt-store schema migrations. `PRAGMA user_version` records the applied\n * version, so a restart against an existing file keeps its data.\n */\nimport type Database from 'better-sqlite3';\n\ninterface Migration {\n readonly version: number;\n up(db: Database.Database): void;\n}\n\nconst MIGRATIONS: readonly Migration[] = [\n {\n version: 1,\n up(db) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS receipts (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n request_id TEXT NOT NULL,\n resource_id TEXT NOT NULL,\n payment_json TEXT,\n delivered_at TEXT NOT NULL,\n backend_status INTEGER NOT NULL,\n duration_ms INTEGER,\n protocol TEXT,\n metadata_json TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_receipts_request_id ON receipts(request_id);\n CREATE INDEX IF NOT EXISTS idx_receipts_delivered_at ON receipts(delivered_at);\n\n CREATE TABLE IF NOT EXISTS events (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n type TEXT NOT NULL,\n request_id TEXT NOT NULL,\n resource_id TEXT,\n at TEXT NOT NULL,\n adapter TEXT,\n payment_provider TEXT,\n duration_ms INTEGER,\n status TEXT,\n data_json TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_events_request_id ON events(request_id);\n CREATE INDEX IF NOT EXISTS idx_events_at ON events(at);\n\n CREATE TABLE IF NOT EXISTS payment_attempts (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n request_id TEXT NOT NULL,\n resource_id TEXT NOT NULL,\n provider TEXT NOT NULL,\n replay_key TEXT NOT NULL UNIQUE,\n status TEXT NOT NULL,\n amount TEXT NOT NULL,\n currency TEXT NOT NULL,\n payer TEXT,\n payee TEXT,\n external_reference TEXT,\n rejection_reason TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_payment_attempts_request_id ON payment_attempts(request_id);\n CREATE INDEX IF NOT EXISTS idx_payment_attempts_created_at ON payment_attempts(created_at);\n `);\n },\n },\n {\n version: 2,\n up(db) {\n // Not folded into v1: an existing database keeps its rows, and a receipt\n // written before this column has no authorization to record\n db.exec(`ALTER TABLE receipts ADD COLUMN authorization_json TEXT;`);\n },\n },\n {\n version: 3,\n up(db) {\n // Archive rejected attempts before reclaim overwrites them. replay_key\n // is not unique here: one authorization can be rejected and reclaimed\n // repeatedly.\n db.exec(`\n CREATE TABLE IF NOT EXISTS payment_attempt_history (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL,\n request_id TEXT NOT NULL,\n resource_id TEXT NOT NULL,\n provider TEXT NOT NULL,\n replay_key TEXT NOT NULL,\n status TEXT NOT NULL,\n amount TEXT NOT NULL,\n currency TEXT NOT NULL,\n payer TEXT,\n payee TEXT,\n external_reference TEXT,\n rejection_reason TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n superseded_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_replay_key ON payment_attempt_history(replay_key);\n CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_request_id ON payment_attempt_history(request_id);\n `);\n },\n },\n];\n\n/** Target schema version: the version of the last migration */\nexport const SCHEMA_VERSION = MIGRATIONS.at(-1)?.version ?? 0;\n\n/**\n * Brings `db` up to {@link SCHEMA_VERSION}, one transaction per migration.\n * On an already-migrated file it only reads `PRAGMA user_version`.\n */\nexport function migrate(db: Database.Database): void {\n const current = db.pragma('user_version', { simple: true }) as number;\n for (const migration of MIGRATIONS) {\n if (migration.version <= current) continue;\n const apply = db.transaction(() => {\n migration.up(db);\n db.pragma(`user_version = ${migration.version}`);\n });\n apply();\n }\n}\n","/**\n * SQLite implementation of the frozen ReceiptStore interface: a thin layer\n * over statements prepared once at open, with no ORM\n */\nimport { randomUUID } from 'node:crypto';\nimport { accessSync, constants as fsConstants } from 'node:fs';\nimport {\n type AdapterDescriptor,\n type AdapterHealth,\n type Clock,\n CommerceError,\n type CommerceEvent,\n type CommerceReceipt,\n type IdGenerator,\n type ListOptions,\n type Logger,\n NOOP_LOGGER,\n type PaymentAttempt,\n type PaymentAttemptReservation,\n type PaymentAttemptUpdate,\n type ReceiptStore,\n systemClock,\n toCommerceError,\n} from '../../core';\nimport { PACKAGE_VERSION } from '../../version';\nimport { openSqliteDatabase } from '../sqlite';\nimport {\n type EventRow,\n eventToRow,\n type PaymentAttemptRow,\n type ReceiptRow,\n receiptToRow,\n rowToEvent,\n rowToPaymentAttempt,\n rowToReceipt,\n} from './rows';\nimport { migrate, SCHEMA_VERSION } from './schema';\n\nconst DEFAULT_LIST_LIMIT = 50;\n/**\n * Ceiling on every list query, enforced in the store so every caller is\n * covered, not only the HTTP route. SQLite reads a negative `LIMIT` as no\n * limit, so `{ limit: -1 }` would otherwise return the whole table.\n */\nconst MAX_LIST_LIMIT = 500;\n\n// Clamps to a whole number in [1, MAX_LIST_LIMIT]. An absent or non-finite\n// limit (NaN, Infinity) takes the default, whether or not the caller filtered\n// it first.\nfunction clampListLimit(limit: number | undefined): number {\n const base = limit !== undefined && Number.isFinite(limit) ? limit : DEFAULT_LIST_LIMIT;\n return Math.min(Math.max(Math.trunc(base), 1), MAX_LIST_LIMIT);\n}\n\nexport interface SqliteReceiptStoreOptions {\n /** File path, or ':memory:' for tests. Parent directory is created if missing */\n readonly path: string;\n readonly logger?: Logger;\n readonly clock?: Clock;\n readonly ids?: IdGenerator;\n}\n\nconst defaultIds: IdGenerator = {\n next: (prefix) => (prefix !== undefined ? `${prefix}_${randomUUID()}` : randomUUID()),\n};\n\nfunction isUniqueConstraintOn(err: unknown, column: string): boolean {\n return (\n err instanceof Error &&\n 'code' in err &&\n (err as { code?: unknown }).code === 'SQLITE_CONSTRAINT_UNIQUE' &&\n err.message.includes(column)\n );\n}\n\nexport function createSqliteReceiptStore(options: SqliteReceiptStoreOptions): ReceiptStore {\n const logger = options.logger ?? NOOP_LOGGER;\n const clock = options.clock ?? systemClock;\n const ids = options.ids ?? defaultIds;\n const path = options.path;\n const isFileBacked = path !== ':memory:';\n\n // Shared with the ACP idempotency and AP2 replay stores, so the permission\n // hardening has one definition\n const db = openSqliteDatabase({ path, label: 'Receipt database', logger });\n migrate(db);\n\n const insertReceiptStmt = db.prepare(\n `INSERT INTO receipts (id, request_id, resource_id, payment_json, delivered_at, backend_status, duration_ms, protocol, metadata_json, authorization_json)\n VALUES (@id, @request_id, @resource_id, @payment_json, @delivered_at, @backend_status, @duration_ms, @protocol, @metadata_json, @authorization_json)`,\n );\n const getReceiptStmt = db.prepare<[string], ReceiptRow>('SELECT * FROM receipts WHERE id = ?');\n const listReceiptsStmt = db.prepare<[number], ReceiptRow>(\n 'SELECT * FROM receipts ORDER BY delivered_at DESC, seq DESC LIMIT ?',\n );\n const listReceiptsByRequestStmt = db.prepare<[string, number], ReceiptRow>(\n 'SELECT * FROM receipts WHERE request_id = ? ORDER BY delivered_at DESC, seq DESC LIMIT ?',\n );\n const countReceiptsStmt = db.prepare<[], { count: number }>(\n 'SELECT COUNT(*) AS count FROM receipts',\n );\n // backend_status is NOT NULL, so NOT BETWEEN cannot skip a row. 0 (no status\n // known) and every non-2xx status count as undelivered, the same rule as the\n // dashboard's deliveryResult() in ReceiptList.tsx.\n const countUndeliveredReceiptsStmt = db.prepare<[], { count: number }>(\n 'SELECT COUNT(*) AS count FROM receipts WHERE backend_status NOT BETWEEN 200 AND 299',\n );\n\n const insertEventStmt = db.prepare(\n `INSERT INTO events (id, type, request_id, resource_id, at, adapter, payment_provider, duration_ms, status, data_json)\n VALUES (@id, @type, @request_id, @resource_id, @at, @adapter, @payment_provider, @duration_ms, @status, @data_json)`,\n );\n const listEventsStmt = db.prepare<[number], EventRow>(\n 'SELECT * FROM events ORDER BY at DESC, seq DESC LIMIT ?',\n );\n const listEventsByRequestStmt = db.prepare<[string, number], EventRow>(\n 'SELECT * FROM events WHERE request_id = ? ORDER BY at DESC, seq DESC LIMIT ?',\n );\n\n const insertPaymentAttemptStmt = db.prepare<Record<string, unknown>, PaymentAttemptRow>(\n `INSERT INTO payment_attempts (id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at)\n VALUES (@id, @request_id, @resource_id, @provider, @replay_key, @status, @amount, @currency, @payer, @payee, @external_reference, @rejection_reason, @created_at, @updated_at)\n RETURNING *`,\n );\n // Keeps the rejected row a reclaim is about to overwrite\n const archiveRejectedAttemptStmt = db.prepare(\n `INSERT INTO payment_attempt_history (id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at, superseded_at)\n SELECT id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at, @created_at\n FROM payment_attempts\n WHERE replay_key = @replay_key AND provider = @provider AND status = 'rejected'`,\n );\n const reclaimPaymentAttemptStmt = db.prepare<Record<string, unknown>, PaymentAttemptRow>(\n `UPDATE payment_attempts SET id = @id, request_id = @request_id, resource_id = @resource_id,\n status = 'reserved', amount = @amount, currency = @currency,\n payer = @payer, payee = @payee, external_reference = NULL, rejection_reason = NULL,\n created_at = @created_at, updated_at = @updated_at\n WHERE replay_key = @replay_key AND provider = @provider AND status = 'rejected'\n RETURNING *`,\n );\n // COALESCE: an omitted field (bound as NULL by updatePaymentAttempt) keeps\n // its stored value. A status-only update must not erase external_reference,\n // which holds the tx hash of a settlement-uncertain attempt: the record that\n // the buyer's funds may have moved. Clearing a value would need an explicit\n // sentinel, not `undefined`.\n const updatePaymentAttemptStmt = db.prepare(\n `UPDATE payment_attempts SET status = @status,\n external_reference = COALESCE(@external_reference, external_reference),\n rejection_reason = COALESCE(@rejection_reason, rejection_reason),\n updated_at = @updated_at\n WHERE replay_key = @replay_key`,\n );\n const listPaymentAttemptsStmt = db.prepare<[number], PaymentAttemptRow>(\n 'SELECT * FROM payment_attempts ORDER BY created_at DESC, seq DESC LIMIT ?',\n );\n const listPaymentAttemptsByRequestStmt = db.prepare<[string, number], PaymentAttemptRow>(\n 'SELECT * FROM payment_attempts WHERE request_id = ? ORDER BY created_at DESC, seq DESC LIMIT ?',\n );\n const paymentAttemptStatusStmt = db.prepare<[string], Pick<PaymentAttemptRow, 'status'>>(\n 'SELECT status FROM payment_attempts WHERE replay_key = ?',\n );\n // IMMEDIATE takes the write lock before the read, so of two retries on one\n // file only one archives and reclaims. The other finds no rejected row, and\n // its insert hits the unique replay key.\n const reclaimRejectedAttempt = db.transaction(\n (params: Record<string, unknown>): PaymentAttemptRow | undefined => {\n archiveRejectedAttemptStmt.run(params);\n return reclaimPaymentAttemptStmt.get(params);\n },\n );\n\n let closed = false;\n\n const descriptor: AdapterDescriptor = {\n name: 'sqlite-receipt-store',\n kind: 'storage',\n implementationVersion: PACKAGE_VERSION,\n supportedSpec: `sqlite-schema-v${SCHEMA_VERSION}`,\n capabilities: ['receipts', 'events', 'payment-attempts'],\n status: 'stable',\n };\n\n const store: ReceiptStore = {\n async init(): Promise<void> {\n // Migration already ran synchronously at construction. This check keeps\n // init() a real, idempotent gate for callers that await it first.\n const version = db.pragma('user_version', { simple: true }) as number;\n if (version !== SCHEMA_VERSION) {\n throw new CommerceError(\n 'STORAGE_ERROR',\n `Receipt store schema version mismatch (found ${version}, expected ${SCHEMA_VERSION})`,\n );\n }\n },\n\n async appendEvent(event: CommerceEvent): Promise<void> {\n try {\n insertEventStmt.run(eventToRow(event));\n } catch (err) {\n logger.warn(\n {\n err: err instanceof Error ? err.message : String(err),\n eventId: event.id,\n requestId: event.requestId,\n },\n 'receipt-store: failed to persist commerce event',\n );\n }\n },\n\n async reservePaymentAttempt(reservation: PaymentAttemptReservation): Promise<PaymentAttempt> {\n const now = clock.nowIso();\n const params = {\n id: ids.next('attempt'),\n request_id: reservation.requestId,\n resource_id: reservation.resourceId,\n provider: reservation.provider,\n replay_key: reservation.replayKey,\n amount: reservation.amount,\n currency: reservation.currency,\n payer: reservation.payer ?? null,\n payee: reservation.payee ?? null,\n created_at: now,\n updated_at: now,\n };\n let row: PaymentAttemptRow;\n try {\n // Reclaim only if the rail permits reusing an authorization whose\n // attempt was rejected. NEAR client retries reuse the access key's\n // next nonce and therefore the replay key.\n row =\n (reservation.reclaimRejected === true\n ? reclaimRejectedAttempt.immediate(params)\n : undefined) ??\n // RETURNING on a successful insert always yields the inserted row\n (insertPaymentAttemptStmt.get({\n ...params,\n status: 'reserved' satisfies PaymentAttempt['status'],\n external_reference: null,\n rejection_reason: null,\n }) as PaymentAttemptRow);\n } catch (err) {\n if (isUniqueConstraintOn(err, 'payment_attempts.replay_key')) {\n // Report the existing status so the pipeline can choose a replay response\n const existing = paymentAttemptStatusStmt.get(reservation.replayKey);\n throw new CommerceError(\n 'PAYMENT_REPLAYED',\n `Payment authorization has already been used (replayKey=${reservation.replayKey})`,\n {\n requestId: reservation.requestId,\n resourceId: reservation.resourceId,\n ...(existing !== undefined ? { details: { attemptStatus: existing.status } } : {}),\n },\n );\n }\n throw toCommerceError(err, 'STORAGE_ERROR', 'Failed to reserve payment attempt');\n }\n return rowToPaymentAttempt(row);\n },\n\n async updatePaymentAttempt(update: PaymentAttemptUpdate): Promise<void> {\n try {\n const result = updatePaymentAttemptStmt.run({\n replay_key: update.replayKey,\n status: update.status,\n external_reference: update.externalReference ?? null,\n rejection_reason: update.rejectionReason ?? null,\n updated_at: clock.nowIso(),\n });\n if (result.changes === 0) {\n throw new CommerceError(\n 'STORAGE_ERROR',\n `No payment attempt found for replayKey=${update.replayKey}`,\n );\n }\n } catch (err) {\n throw toCommerceError(err, 'STORAGE_ERROR', 'Failed to update payment attempt');\n }\n },\n\n async saveReceipt(receipt: CommerceReceipt): Promise<void> {\n try {\n insertReceiptStmt.run(receiptToRow(receipt));\n } catch (err) {\n throw toCommerceError(err, 'STORAGE_ERROR', 'Failed to save receipt');\n }\n },\n\n async getReceipt(id: string): Promise<CommerceReceipt | undefined> {\n const row = getReceiptStmt.get(id);\n return row !== undefined ? rowToReceipt(row) : undefined;\n },\n\n async listReceipts(listOptions: ListOptions = {}): Promise<readonly CommerceReceipt[]> {\n const limit = clampListLimit(listOptions.limit);\n const rows =\n listOptions.requestId !== undefined\n ? listReceiptsByRequestStmt.all(listOptions.requestId, limit)\n : listReceiptsStmt.all(limit);\n return rows.map(rowToReceipt);\n },\n\n // Exact total, not bounded by the listReceipts clamp (see ReceiptStore.countReceipts)\n async countReceipts(): Promise<number> {\n return countReceiptsStmt.get()?.count ?? 0;\n },\n\n // Exact count of non-2xx receipts (see ReceiptStore.countUndeliveredReceipts)\n async countUndeliveredReceipts(): Promise<number> {\n return countUndeliveredReceiptsStmt.get()?.count ?? 0;\n },\n\n async listEvents(listOptions: ListOptions = {}): Promise<readonly CommerceEvent[]> {\n const limit = clampListLimit(listOptions.limit);\n const rows =\n listOptions.requestId !== undefined\n ? listEventsByRequestStmt.all(listOptions.requestId, limit)\n : listEventsStmt.all(limit);\n return rows.map(rowToEvent);\n },\n\n async listPaymentAttempts(listOptions: ListOptions = {}): Promise<readonly PaymentAttempt[]> {\n const limit = clampListLimit(listOptions.limit);\n const rows =\n listOptions.requestId !== undefined\n ? listPaymentAttemptsByRequestStmt.all(listOptions.requestId, limit)\n : listPaymentAttemptsStmt.all(limit);\n return rows.map(rowToPaymentAttempt);\n },\n\n descriptor,\n\n async health(): Promise<AdapterHealth> {\n // `detail` comes from a fixed vocabulary, never from a caught error: an\n // accessSync error carries an absolute host path, e.g. \"EACCES:\n // permission denied, access '/workspace/data/receipts.sqlite'\". The raw\n // message goes to the logger at warn.\n const startedAt = clock.monotonicMs();\n if (closed) {\n return { status: 'fail', detail: 'store-unavailable', checkedAt: clock.nowIso() };\n }\n if (isFileBacked) {\n try {\n accessSync(path, fsConstants.W_OK);\n } catch (err) {\n logger.warn(\n { err: err instanceof Error ? err.message : String(err) },\n 'receipt-store: health check failed (store not writable)',\n );\n return {\n status: 'fail',\n detail: 'store-unwritable',\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n }\n try {\n const version = db.pragma('user_version', { simple: true }) as number;\n if (version !== SCHEMA_VERSION) {\n logger.warn(\n { found: version, expected: SCHEMA_VERSION },\n 'receipt-store: health check failed (schema version mismatch)',\n );\n return {\n status: 'fail',\n detail: 'store-schema-mismatch',\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n return {\n status: 'pass',\n detail: `sqlite schema v${SCHEMA_VERSION} writable`,\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n } catch (err) {\n logger.warn(\n { err: err instanceof Error ? err.message : String(err) },\n 'receipt-store: health check failed (store unavailable)',\n );\n return {\n status: 'fail',\n detail: 'store-unavailable',\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n },\n\n async close(): Promise<void> {\n if (!closed) {\n closed = true;\n db.close();\n }\n },\n };\n\n return store;\n}\n"]}
|