@devlab.group/agent-commerce 1.4.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +168 -183
  2. package/dist/ap2.d.ts +21 -24
  3. package/dist/ap2.js +68 -82
  4. package/dist/ap2.js.map +1 -1
  5. package/dist/authorization-BpbWGGrf.d.ts +115 -0
  6. package/dist/{chunk-NWIQLJNU.js → chunk-74BSEXB5.js} +37 -34
  7. package/dist/chunk-74BSEXB5.js.map +1 -0
  8. package/dist/chunk-AFI2CEZS.js +10 -0
  9. package/dist/chunk-AFI2CEZS.js.map +1 -0
  10. package/dist/chunk-ATTWSFQP.js +680 -0
  11. package/dist/chunk-ATTWSFQP.js.map +1 -0
  12. package/dist/{chunk-ZEGFLRGV.js → chunk-IVJC5YLE.js} +63 -26
  13. package/dist/chunk-IVJC5YLE.js.map +1 -0
  14. package/dist/{chunk-GF6KHHKL.js → chunk-RAJGPGJG.js} +5 -8
  15. package/dist/chunk-RAJGPGJG.js.map +1 -0
  16. package/dist/chunk-V2V2E7HX.js +27 -0
  17. package/dist/chunk-V2V2E7HX.js.map +1 -0
  18. package/dist/cli/index.js +812 -573
  19. package/dist/cli/index.js.map +1 -1
  20. package/dist/constants-Bkq04FRZ.d.ts +48 -0
  21. package/dist/guardrails-71XwtXlT.d.ts +31 -0
  22. package/dist/index.d.ts +245 -265
  23. package/dist/index.js +1222 -626
  24. package/dist/index.js.map +1 -1
  25. package/dist/mcp.d.ts +6 -59
  26. package/dist/mcp.js +64 -53
  27. package/dist/mcp.js.map +1 -1
  28. package/dist/mpp.d.ts +50 -0
  29. package/dist/mpp.js +353 -0
  30. package/dist/mpp.js.map +1 -0
  31. package/dist/protocol-adapter-DTkrXTev.d.ts +238 -0
  32. package/dist/runtime-CiYbgGpi.d.ts +303 -0
  33. package/dist/{types-CJtwLu1c.d.ts → types-O6lg3Q5V.d.ts} +17 -23
  34. package/dist/x402.d.ts +43 -75
  35. package/dist/x402.js +13 -693
  36. package/dist/x402.js.map +1 -1
  37. package/package.json +13 -2
  38. package/dist/authorization-CPDcpJVa.d.ts +0 -123
  39. package/dist/chunk-GF6KHHKL.js.map +0 -1
  40. package/dist/chunk-NWIQLJNU.js.map +0 -1
  41. package/dist/chunk-ZEGFLRGV.js.map +0 -1
  42. package/dist/guardrails-Dmwi63KB.d.ts +0 -38
  43. package/dist/protocol-adapter-Bebmggf_.d.ts +0 -273
  44. package/dist/runtime-CKq3d_3K.d.ts +0 -340
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/config/env.ts","../src/config/filename.ts","../src/core/execution/backend-http.ts","../src/core/execution/event-bus.ts","../src/core/execution/validation.ts","../src/core/execution/pipeline.ts","../src/core/execution/registry.ts","../src/protocols/acp/constants.ts","../src/config/schema.ts","../src/config/load.ts","../src/gateway/ids.ts","../src/gateway/logger.ts","../src/gateway/access-control.ts","../src/gateway/adapters.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/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/auth.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","isPlainObject","durationMs","url","validators","describeError","fs","parseYaml","header","createHash","timingSafeEqual","sha256","SCHEMA_VERSION","migrate","randomUUID","fsConstants"],"mappings":";;;;;;;;;;;;;;;;AAoCA,IAAM,mBAAA,GAAsB,6CAAA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,SACpC;AAAA,MACF,SAAS,GAAA,EAAK;AACZ,QAAA,MAAA,CAAO,IAAA;AAAA,UACL,EAAE,KAAK,GAAA,YAAe,KAAA,GAAQ,IAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAA,EAAE;AAAA,UACxD;AAAA,SACF;AACA,QAAA,OAAO;AAAA,UACL,MAAA,EAAQ,MAAA;AAAA,UACR,MAAA,EAAQ,mBAAA;AAAA,UACR,SAAA,EAAW,MAAM,MAAA,EAAO;AAAA,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 an arbitrary parsed-YAML value.\n *\n * Only string leaves are touched; numbers/booleans/null pass through untouched\n * (the caller coerces the *resulting* string back into a number/boolean where\n * the schema expects one). An unresolved placeholder fails config loading\n * immediately — startup must never proceed with an unresolved secret. That\n * includes one left behind by a *nested* placeholder such as `${A:-${B}}`,\n * which is rejected rather than silently passed through. There is no\n * escape syntax for a literal `${NAME}`; nothing in this config format needs\n * one, and adding it would mean two ways to write every value.\n *\n * `${VAR}` (no default) requires `VAR` to be present in `env` (any value,\n * including an empty string, counts as present).\n * `${VAR:-default}` falls back to `default` when `VAR` is absent OR empty,\n * matching common shell semantics.\n *\n * Anything else brace-shaped is refused: `${VAR-x}`, `${VAR:=x}`, `${VAR:?x}`\n * are valid *shell* and would otherwise load as literal strings. That is\n * harmless where a downstream check rejects the literal, and quietly wrong for\n * a free-string field — `adminToken: ${ADMIN_TOKEN-fallback}` would run the\n * gateway with that literal as the ledger credential while the operator\n * believed an env secret gated it. A bare `$VAR` is deliberately left alone: it\n * is not brace-shaped, and refusing it would reject values that legitimately\n * contain a dollar sign.\n *\n * Every rule above is decided from the **template**, before substitution.\n * Deciding afterwards is how `${A:-${B}}` used to corrupt a value on the one\n * branch its guard did not cover, and how a resolved secret containing a\n * `${…}`-shaped fragment used to get quoted back in the error text.\n *\n * The resolved *value* of a variable is never included in any error message —\n * only the variable *name* and the config path are.\n */\nimport { CommerceError } from '../core/index.js';\n\nconst PLACEHOLDER_PATTERN = /\\$\\{([A-Za-z_][A-Za-z0-9_]*)(:-([^}]*))?\\}/g;\n\n/** An innermost brace token: `${` … `}` with no braces between. */\nconst BRACE_TOKEN = /\\$\\{[^{}]*\\}/g;\n\n/** The same grammar as PLACEHOLDER_PATTERN, 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 (isPlainObject(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 honour, before any substitution runs.\n *\n * `${A:-${B}}` is the case that motivated this. `[^}]*` cannot span the inner\n * `}`, so the match consumes `${A:-${B` and leaves a stray `}` behind. When `A`\n * is unset the leftover `${B}` was visible afterwards and got caught; when `A`\n * is *set* — the normal case, and the whole reason someone writes a default —\n * substitution succeeded and the stray `}` was appended to the resolved value\n * with nothing to notice it. For `adminToken` that means the gateway compares\n * against a credential the operator does not hold, with no diagnostic.\n *\n * Deciding from the template covers both branches with one rule, and means no\n * error message is ever derived from a resolved value.\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 BRACE_TOKEN.lastIndex = 0;\n for (const [token] of value.matchAll(BRACE_TOKEN)) {\n if (SUPPORTED_TOKEN.test(token)) continue;\n // The token itself, never the surrounding value: this runs pre-substitution,\n // so it cannot contain a resolved 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 recognised; 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\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","/**\n * The default configuration filename, in one place.\n *\n * Deliberately its own module with **no imports**: `src/cli` reaches the rest\n * of `src/config` only through a dynamic import (see\n * `src/cli/lib/config-client.ts`), so that a broken config module cannot take\n * down commands that never read configuration. A leaf file holding a single\n * string has no module graph to break, so the CLI can import it directly\n * without reopening that seam — and `init`'s default output path, `--config`'s\n * help text and the loader's own lookup cannot drift apart, which is what\n * three separate copies of this string invited.\n */\nexport const DEFAULT_CONFIG_FILENAME = 'config.yaml';\n","/**\n * The only outbound HTTP path to a merchant backend.\n *\n * - Uses global `fetch` and always applies a bound timeout via `AbortSignal.timeout`.\n * - `redirect: 'manual'` - a 3xx response is treated as a `BACKEND_ERROR`, never\n * followed (SSRF hardening).\n * - `{param}` segments in `handler.url` are filled from validated input and\n * URL-encoded; whatever remains goes to the query string (GET/DELETE) or a\n * JSON body (POST/PUT/PATCH). `handler.inputBindings` replaces that\n * leftover rule with one that names each group explicitly - see\n * `buildBackendRequestParts`.\n */\nimport {\n type BackendHandler,\n type BackendMethod,\n DEFAULT_BACKEND_TIMEOUT_MS,\n} from '../domain/resource.js';\nimport { CommerceError } from '../errors/index.js';\nimport type { BackendExecutor, BackendRequest, BackendResponse } from '../interfaces/backend.js';\nimport { type Logger, NOOP_LOGGER } from '../interfaces/logger.js';\n\nconst MAX_BODY_SNIPPET_LENGTH = 512;\n/**\n * How a merchant recognises a repeat of an operation it may already have\n * performed. The de-facto standard name, and the one ACP already mandates\n * inbound, so a merchant speaking ACP needs no second convention.\n */\nconst IDEMPOTENCY_KEY_HEADER = 'idempotency-key';\n/**\n * The one canonical `{param}` grammar. Extraction, substitution, the config\n * gate and `doctor`'s probe all go through it.\n *\n * `-` and `.` are admitted: `/report/{report-id}` is ordinary\n * REST, and under the previous `[a-zA-Z0-9_]+` class it matched *nothing*. It\n * was therefore invisible to the config gate, survived substitution as a\n * literal, and a paid resource settled the buyer's payment before sending\n * `/report/%7Breport-id%7D` to a backend that 404s - the earlier money bug,\n * reachable again through the character class rather than through the check.\n */\nconst PATH_PARAM_PATTERN = /\\{([a-zA-Z0-9_.-]+)\\}/g;\n/** A hostile or broken backend can otherwise materialise an arbitrarily\n * large response in memory - AbortSignal.timeout bounds it by *time*, not\n * bytes. 1 MB is generous for a JSON API response. */\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 /** A non-2xx backend body is logged here (debug), never shipped to the client. */\n readonly logger?: Logger;\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 = isPlainObject(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\n // the same call pre-payment through validateBackendRequestShape(); this is\n // defence in depth for a caller that bypasses it, not the normal path.\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 // Belt-and-braces beyond the per-parameter check above: whatever the\n // templated path resolved to must still live under the template's own\n // literal (pre-`{param}`) prefix. Templating something other than a path\n // segment (e.g. the host) is not a documented usage; if the literal\n // prefix does not even parse as a URL, skip this extra check rather than\n // fail a request the per-parameter check already covers.\n const literalPrefix = handler.url.split('{')[0] ?? handler.url;\n try {\n const literalPrefixPathname = new URL(literalPrefix).pathname;\n if (!target.pathname.startsWith(literalPrefixPathname)) {\n throw new CommerceError(\n 'INPUT_INVALID',\n 'Path parameters resolved outside the configured backend path',\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n },\n );\n }\n } catch (error) {\n if (error instanceof CommerceError) throw error;\n }\n\n const headers: Record<string, string> = { ...(handler.headers ?? {}) };\n // Overrides a configured header of the same name rather than deferring to\n // it, unlike content-type below. A *static* idempotency key is never a\n // deliberate setting: every request after the first would look like a\n // retry of the first, and an idempotent merchant would replay one answer\n // forever. Only the per-operation value is usable.\n if (request.idempotencyKey !== undefined) {\n deleteHeader(headers, IDEMPOTENCY_KEY_HEADER);\n headers[IDEMPOTENCY_KEY_HEADER] = request.idempotencyKey;\n }\n let body: string | undefined;\n\n //.set() REPLACES an existing param, so without this check a caller\n // input key with the same name as an operator-baked-in query param\n // (?apikey=SECRET in handler.url) silently overwrites it.\n // Shared with validateBackendRequestShape() - that copy runs\n // *before* payment, this one is defence in depth.\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 stays authoritative: a backend wanting\n // `application/vnd.x+json` says so in config and we do not override it.\n if (!hasHeader(headers, 'content-type')) {\n headers['content-type'] = 'application/json';\n }\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 = headersToRecord(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 =\n error instanceof Error && error.message.startsWith('response-body-too-large');\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 backend status is ours to state; the backend's own response body\n // is not - a merchant backend in verbose/dev-error mode routinely\n // emits stack traces, hostnames or SQL fragments, and this gateway is\n // not the one who gets to decide those are safe to forward to whoever\n // called the (possibly free, possibly unauthenticated) resource. Log\n // it for the operator; never put it in a client-visible field.\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 });\n }\n\n return {\n status: response.status,\n headers: responseHeaders,\n body: parsedBody,\n durationMs,\n };\n }\n}\n\n/**\n * The traversal and query-collision checks below must run before payment,\n * not only inside `call()` - pipeline step 6, which is *after*\n * verify -> reserve -> settle.\n * Both throw INPUT_INVALID, which schema validation (step 2) cannot catch\n * (it validates against `resource.inputSchema`, which knows nothing about\n * the URL template a bad value would collide with). Concretely: a paid,\n * path-templated resource called with `{ city: \"\" }` would settle the buyer's\n * payment on-chain and then never call the backend - payment without\n * delivery, no refund, no release of the reserved authorisation. Both\n * checks are pure functions of `(handler.url, input)` with no I/O, so the\n * pipeline calls this immediately after schema validation, *before* price\n * resolution - before any payment provider is even selected. `call()` keeps\n * its own copy as defence in depth (it is a public class; the pipeline is\n * not the only possible caller).\n */\n/**\n * `{param}` names in a `backend.url` template, in declaration order.\n * Exported so `src/config`'s `normaliseResource` can\n * cross-check every template parameter against the resource's input schema\n * at config load - the same regex, not a second copy that could silently\n * drift out of sync with what this file actually treats as a path\n * parameter.\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 * Widening the grammar fixes the *common* spelling; it cannot fix every one.\n * `{report id}`, `{a/b}`, `{}` and an unbalanced `{` still match nothing, and\n * \"matches nothing\" is precisely the silent-literal shape that costs a buyer\n * money on a paid resource. So the rule is inverted: rather than enumerating\n * what is illegal, anything brace-shaped that is *not* a recognised parameter\n * is refused at config load. Exported so `src/config` applies it - the\n * grammar and its residue must never live in two files.\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\nexport function validateBackendRequestShape(\n handler: BackendHandler,\n input: unknown,\n context: ShapeContext,\n): void {\n const inputRecord = isPlainObject(input) ? input : {};\n\n // Every shape error - missing or invalid path parameter, a bound group that\n // is not an object - throws INPUT_INVALID from here, before payment.\n const parts = buildBackendRequestParts(handler, inputRecord, context);\n\n let target: URL;\n try {\n target = new URL(parts.url);\n } catch {\n return; // call() surfaces the real 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` - the single place either mode is decided, so\n * `call()` and the pre-payment `validateBackendRequestShape()` can never\n * disagree about what request the input describes.\n *\n * Throws only `CommerceError('INPUT_INVALID')`, which is what makes it safe to\n * run before pricing.\n */\nfunction 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 at all rather than `null`: a request\n // body the operation does not require is simply not there. A body the\n // operation *does* require is caught one step earlier, by `required` in the\n // resource's input schema - also before payment.\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 (!isPlainObject(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\nfunction 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\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n// encodeURIComponent does not escape \".\" - a raw \"..\"/\".\" path-parameter\n// value survives it and new URL() then normalises the segment away, letting\n// a caller step outside the template's own directory (bounded traversal:\n// slashes ARE escaped, so only removing segments, never adding them). Reject\n// these exact values at substitution time instead of shipping them.\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 `key in remaining`: `in` also matches inherited\n // Object.prototype names (\"constructor\", \"toString\", …), which a\n // config-authored template naming a path param after one of them would\n // otherwise silently resolve to the wrong (inherited) value.\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 // Tempting to shrug this off as a config/schema mismatch rather than bad\n // caller input. But a paid, `{param}`-templated resource whose input can\n // never supply it would reach settle() on every call - the buyer pays, the\n // backend is never called, no refund. `normaliseResource` (src/config) is\n // the root-cause fix, rejecting the shape at config load; throwing here\n // stops a hand-built `CommerceResource` from reintroducing the money bug\n // by skipping config validation.\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\nfunction 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\nfunction hasHeader(headers: Record<string, string>, name: string): boolean {\n const target = name.toLowerCase();\n return Object.keys(headers).some((key) => key.toLowerCase() === target);\n}\n\n// Header names are case-insensitive, so replacing one means removing whatever\n// casing it was configured under first; plain assignment would leave both\nfunction deleteHeader(headers: Record<string, string>, name: string): void {\n const target = name.toLowerCase();\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() === target) delete headers[key];\n }\n}\n\nfunction headersToRecord(headers: Headers): Record<string, string> {\n const record: Record<string, string> = {};\n headers.forEach((value, key) => {\n record[key] = value;\n });\n return record;\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 throw new Error(`response-body-too-large:${maxBytes}`);\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 * Fan-out `EventSink`: persists every event to the receipt store and notifies\n * in-process subscribers (the gateway's SSE feed). Never throws to the caller —\n * a store or subscriber failure is caught and logged.\n */\nimport type { CommerceEvent, EventSink } from '../domain/event.js';\nimport type { Logger } from '../interfaces/logger.js';\nimport type { Clock, IdGenerator } from '../interfaces/runtime.js';\nimport type { ReceiptStore } from '../interfaces/store.js';\n\nexport interface CreateEventBusOptions {\n readonly store: ReceiptStore;\n readonly logger: Logger;\n /** Reserved for callers that want the bus to mint ids/timestamps itself. */\n readonly ids?: IdGenerator;\n readonly clock?: Clock;\n}\n\nexport interface EventBus extends EventSink {\n /** Subscribe to every emitted event. Returns an unsubscribe function. */\n subscribe(fn: (event: CommerceEvent) => void): () => void;\n}\n\nexport function createEventBus(options: CreateEventBusOptions): EventBus {\n const subscribers = new Set<(event: CommerceEvent) => void>();\n\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 for (const subscriber of subscribers) {\n try {\n subscriber(event);\n } catch (error) {\n options.logger.error(\n { err: describeError(error), eventType: event.type, requestId: event.requestId },\n 'Event subscriber threw',\n );\n }\n }\n },\n\n subscribe(fn: (event: CommerceEvent) => void): () => void {\n subscribers.add(fn);\n return () => {\n subscribers.delete(fn);\n };\n },\n };\n}\n\nfunction describeError(error: unknown): { message: string; name?: string } {\n if (error instanceof Error) {\n return { message: error.message, name: error.name };\n }\n return { message: String(error) };\n}\n","/**\n * A small, honest JSON Schema validator for resource input.\n *\n * Supported subset (draft-2020-12 vocabulary, structural only):\n * - `type`: \"object\" | \"string\" | \"number\" | \"integer\" | \"boolean\" | \"array\" | \"null\",\n * or an array of any of those (draft-2020-12 union form, e.g. `[\"object\",\"null\"]`)\n * - `properties` (object schemas, validated recursively)\n * - `required` (string[])\n * - `additionalProperties` (boolean, or a schema applied to extra properties)\n * - `enum` (array of allowed literal values, deep-equality compared)\n * - `items` (single schema applied to every array element — no tuple form)\n *\n * Explicitly NOT supported and silently ignored (never enforced):\n * `minLength`, `maxLength`, `pattern`, `format`, `minimum`, `maximum`,\n * `exclusiveMinimum/Maximum`, `multipleOf`, `oneOf`, `anyOf`, `allOf`, `not`,\n * `$ref`, `const`, `patternProperties`, `minItems`, `maxItems`, `uniqueItems`,\n * tuple-style `items` arrays. An unrecognised `type` value is not enforced\n * either. This is a deliberate, documented limitation of this release — do\n * not assume any of the above is validated.\n */\nimport type { JsonSchema } from '../domain/common.js';\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/** Compile a resource `inputSchema` into 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 isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction matchesType(type: string, value: unknown): boolean {\n switch (type) {\n case 'object':\n return isPlainObject(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\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== typeof b) return false;\n if (a === null || b === null) return false;\n if (typeof a !== 'object') return false;\n try {\n return JSON.stringify(a) === JSON.stringify(b);\n } catch {\n return false;\n }\n}\n\nfunction own(obj: Record<string, unknown>, key: string): unknown {\n return Object.hasOwn(obj, key) ? obj[key] : undefined;\n}\n\n/**\n * `type` may be a single string or (draft-2020-12) an array of strings,\n * e.g. `[\"object\", \"null\"]`. Only recognised when every entry is a string —\n * same conservative \"skip rather than guess\" rule the single-string form\n * already followed for an unrecognised type name.\n */\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 * A bare `type === 'object'` string comparison is not enough: `type:\n * [\"object\", \"null\"]` — valid JSON Schema — would never route into\n * `validateObject`, so neither `required` nor `additionalProperties` would be\n * enforced on it, while `defaultClosedObjectSchema` (src/config) stamps\n * `additionalProperties: false` on it believing it closed. Also treats a node\n * with `properties`/`required` and no `type`\n * at all as an object schema, the same shape config's own stamping already\n * recognises via a bare `properties` check — a schema author relying on\n * `type` being implied by `properties` should not be silently unenforced.\n *\n * **exported**, and now the only definition of \"this node is\n * an object schema\" in the codebase. `src/config`'s `defaultClosedObjectSchema`\n * carried its own — `declaresObjectType || properties` — one keyword short of\n * this one, so a schema declaring only `required` was stamped by neither:\n * config left it open and this validator then enforced nothing on it, quietly\n * forwarding every unknown caller key to the merchant's backend while\n * docs/security.md promised \"closed by default at every level\". These two\n * definitions have been aligned once already; keeping them as two definitions\n * is what let them drift again.\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 recognisedTypes = types?.filter((entry) => SUPPORTED_TYPES.has(entry));\n\n if (\n types !== undefined &&\n recognisedTypes !== undefined &&\n recognisedTypes.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) && isPlainObject(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 = isPlainObject(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 schema\n // requiring \"toString\"/\"constructor\"/\"valueOf\"/\"hasOwnProperty\"/\n // \"__proto__\" could never actually enforce it — those names are always\n // present via inheritance, so `!(key in value)` is always false. This is\n // the same bug class every other lookup in this file already\n // guards against by using own().\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 // Object.hasOwn, not `properties[key]`: a plain-object lookup for\n // \"__proto__\"/\"constructor\"/\"toString\"/\"valueOf\"/\"hasOwnProperty\" resolves\n // to an inherited Object.prototype member instead of undefined, so those\n // keys would otherwise silently skip the additionalProperties check below.\n const propSchemaRaw = own(properties, key);\n if (propSchemaRaw !== undefined) {\n if (isPlainObject(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 (isPlainObject(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 (isPlainObject(itemsRaw)) {\n value.forEach((item, index) => {\n errors.push(...validateNode(itemsRaw, item, `${path}[${index}]`));\n });\n }\n return errors;\n}\n","/**\n * The single execution path every protocol adapter converges on.\n *\n * Order is a security boundary — do not reorder:\n * 1. resolve resource RESOURCE_NOT_FOUND\n * 2. strip reserved input fields, validate input INPUT_INVALID\n * 3. resolve price\n * 4. free -> straight to backend\n * 5. paid -> pick provider -> createRequirement -> (challenge | verify ->\n * authorize/reserve -> reserve replay key -> settle -> consume/release the\n * authorization), fail closed at every step\n * 6. call backend BACKEND_TIMEOUT / BACKEND_ERROR\n * 7. persist receipt, emit events, return outcome\n */\n\nimport type {\n AuthorizationProvider,\n AuthorizationRecord,\n AuthorizationVerification,\n} from '../domain/authorization.js';\nimport type { AuthorizationMethodName, PaymentMethodName } from '../domain/common.js';\nimport type { CommerceEvent, EventSink } from '../domain/event.js';\nimport type { PaymentProvider, PaymentRequirement, PaymentResult } from '../domain/payment.js';\nimport type { CommerceReceipt } from '../domain/receipt.js';\nimport type { CanonicalRequest, ExecutionOutcome, ExecutionPipeline } from '../domain/request.js';\nimport type { CommerceResource, ResourceRegistry } from '../domain/resource.js';\nimport { RESERVED_INPUT_FIELDS } from '../domain/wire.js';\nimport { CommerceError, isCommerceError, toCommerceError } from '../errors/index.js';\nimport type { BackendExecutor, BackendResponse } from '../interfaces/backend.js';\nimport type { Logger } from '../interfaces/logger.js';\nimport type { Clock, IdGenerator } from '../interfaces/runtime.js';\nimport type { ReceiptStore } from '../interfaces/store.js';\nimport { validateBackendRequestShape } from './backend-http.js';\nimport { compileJsonSchema, type Validator } from './validation.js';\n\nexport interface CreateExecutionPipelineOptions {\n readonly resources: ResourceRegistry;\n readonly paymentProviders: readonly PaymentProvider[];\n /** Empty by default, so a deployment configuring none is unchanged */\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` is the only way it ends, so no path can leave one open.\n */\ninterface AuthorizationHold {\n readonly record: AuthorizationRecord;\n finalize(action: 'consume' | 'release' | 'markUncertain'): Promise<void>;\n}\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 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 /**\n * Verify and reserve what the resource requires, or undefined if it requires\n * none. Runs after payment verification, which has no side effect: a bad\n * payment proof must not burn a reservation.\n */\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 // Any failure leaves the row reserved, which is still unspendable.\n // Not worth replacing the outcome the caller is about to see.\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 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, same message as a genuine miss: `expose` is an admin scoping\n // decision enforced on the one execution path every adapter shares — a\n // caller on a protocol the resource isn't exposed via must not be able to\n // distinguish \"doesn't exist\" from \"exists but not for you\".\n if (!resource || !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 // validate the backend request shape (path-traversal, query-param\n // collision) here — before price resolution, so a resource that fails\n // this check never reaches payment. Both checks are pure functions of\n // (handler.url, input); doing them at pipeline step 6 (inside the actual\n // backend call) meant a bad value like `{ city: \"\" }` against a paid,\n // path-templated resource settled the buyer's payment and then never\n // called the backend at all — payment without delivery. call() keeps its\n // own copy of these checks as defence in depth.\n validateBackendRequestShape(resource.handler, validInput, {\n requestId: request.requestId,\n resourceId: resource.id,\n });\n\n // 3. resolve price\n if (resource.pricing.type === 'dynamic') {\n // Config validation rejects this before the gateway starts; this is defence-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 requiring one on a free resource\n // means nothing would ever read the proof. Config refuses it at load; the\n // execution path must not be the one that serves it unchecked.\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\n if (resource.pricing.type === 'fixed') {\n const pricing = resource.pricing;\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 });\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 verification = await provider.verify({\n requestId: request.requestId,\n resource,\n requirement,\n submission: payment,\n });\n } catch (error) {\n // Any typed CommerceError the provider throws is rethrown as-is (a\n // provider can legitimately fail with STORAGE_ERROR, etc. — flattening\n // every code to PAYMENT_INVALID would hide the real cause and the\n // real, possibly-retryable HTTP status). Only a genuinely untyped\n // throw is mapped, with a fixed client-facing message — never the\n // raw error's own 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 });\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 },\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 authorization = hold?.record;\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 });\n } catch (error) {\n // The store contract only promises PAYMENT_REPLAYED for an actual\n // duplicate replayKey (already a CommerceError with that code, so\n // isCommerceError below preserves it as-is). Anything else — a disk-\n // full error, a dropped connection — is a storage failure, not a\n // replay, and must not be mislabelled as one: telling a buyer\n // \"duplicate payment\" for a transient outage is actively false, and\n // poisons any alerting keyed on replay counts.\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 mapped;\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 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 // A verdict arrives as a *returned* PaymentResult, settled or\n // rejected. A throw means no verdict was obtained, and no throw on\n // this rail can say whether the transfer happened: a facilitator can\n // accept a settlement, broadcast it, then lose the response to a\n // timeout, a reset or a proxy 502. \"No transaction hash\" is not\n // evidence of \"no transfer\", only evidence that we never heard one.\n // So every throw out of settle() is uncertain: the attempt is\n // recorded unresolved and the authorization hold is kept, because a\n // released mandate is spendable again with a fresh payment\n // authorization against a charge that may already have landed. Only\n // a returned `rejected` below - the facilitator's own statement that\n // nothing moved - releases it. The resource is not delivered either\n // way: only what gets *recorded* changes, never the fail-closed\n // outcome.\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 merchant's record now tells the truth (above); the buyer must\n // too - they are the party whose funds may have moved, and the\n // client-visible error is their only way to find out. Code stays\n // PAYMENT_SETTLEMENT_FAILED, not the retryable\n // PAYMENT_PROVIDER_UNAVAILABLE: a retry would reuse the\n // already-reserved replay key, and paying again is the one thing an\n // unresolved settlement must never invite. The correlation id is the\n // envelope's requestId; the transaction hash, when there is one, is\n // safe to disclose, being the buyer's own payment and public\n // on-chain the moment it lands. Nothing else from the underlying\n // error travels.\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 },\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 }),\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 throw new CommerceError(\n 'PAYMENT_SETTLEMENT_FAILED',\n settlement.rejectionReason ?? 'Settlement was rejected',\n {\n requestId: request.requestId,\n resourceId: resource.id,\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 paymentResult = settlement;\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 });\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 (paymentResult !== undefined) {\n // Settlement already succeeded (verify -> reserve -> settle all\n // completed) before the backend call failed, so the\n // uncertain-settlement rule (\"the merchant's record now tells the\n // truth; the buyer must too\") applies to this far more common\n // *certain*-loss branch as well, not only to the uncertain-RPC-timeout\n // one 100 lines above. A backend 500 is more likely than an RPC\n // confirmation timeout, so disclosing strictly *less* here than there\n // would be backwards. The tx hash is\n // safe to disclose: it is the buyer's own payment, public\n // on-chain the moment it lands.\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 },\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 // 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 HTTP status the backend actually returned, when known (backend-http.ts\n * attaches it as `details.status` for a non-2xx response). 0 means \"no\n * response was received at all\" (timeout/transport failure) — distinct from\n * any real HTTP status. */\nfunction backendErrorStatus(error: CommerceError): number {\n const status = error.details?.['status'];\n return typeof status === 'number' ? status : 0;\n}\n\n// The broadcast transaction hash a provider attached to a settlement throw,\n// when it knows one. Absent far more often than not: the response that would\n// have carried it is usually the thing that went missing\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/**\n * The provider for each method a resource requires, in the resource's order.\n *\n * Config refuses an unconfigured method at load. Missing it here would mean\n * serving the resource with no authorization at all, so it is checked again.\n */\nfunction 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\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\nconst RESERVED_INPUT_KEYS = new Set([...RESERVED_INPUT_FIELDS, '__proto__']);\n\nfunction stripReservedFields(input: unknown): unknown {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) return input;\n const record = input as Record<string, unknown>;\n // Object.hasOwn: `in` would also match inherited names and strip things\n // that were never actually present on this input.\n const hasReserved = [...RESERVED_INPUT_KEYS].some((key) => Object.hasOwn(record, key));\n if (!hasReserved) return input;\n const rest: Record<string, unknown> = {};\n for (const key of Object.keys(record)) {\n // \"__proto__\" is dropped, not just excluded from the reserved-field\n // check: `rest[key] = record[key]` for key === \"__proto__\" would invoke\n // the inherited setter and reassign rest's own prototype instead of\n // creating a data property (belt-and-braces — validation.ts's\n // Object.hasOwn fix is the primary control).\n if (!RESERVED_INPUT_KEYS.has(key)) rest[key] = record[key];\n }\n return rest;\n}\n\nfunction describeError(error: unknown): { message: string; name?: string } {\n if (error instanceof Error) return { message: error.message, name: error.name };\n return { message: String(error) };\n}\n","/**\n * In-memory implementation of the frozen `ResourceRegistry` interface.\n */\nimport type { ProtocolName } from '../domain/common.js';\nimport type { CommerceResource, ResourceRegistry } from '../domain/resource.js';\nimport { CommerceError } from '../errors/index.js';\n\nexport class 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 * 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 * Cancel is deliberately absent a body: the pinned schema does not require\n * one, and inventing one would make every cancel resource declare a property\n * ACP may never fill.\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/** 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 * `config.yaml` schema, validation and normalisation into the\n * canonical `GatewayConfig` (docs/contracts.md).\n *\n * Two-phase validation:\n * 1. Zod validates *shape* (types, required fields, unknown-key rejection).\n * Numeric/boolean leaves accept either their native type or a string\n * (env substitution always produces a string), and are left as-is here -\n * Zod's typed transforms have surprising inference interactions with\n * `.strict()` objects, so numeric/boolean coercion is done explicitly,\n * in plain TypeScript, in the normalisation pass below.\n * 2. A manual business-rule pass validates cross-references that need a\n * specific, actionable message (duplicate ids, disabled protocols/payment\n * methods, dynamic pricing, destination-address plausibility) and\n * performs the numeric/boolean coercion.\n *\n * Env substitution (`${VAR}` / `${VAR:-default}`) runs over the raw parsed\n * value *before* either phase, so numeric/boolean fields can be templated too.\n * One exception, deliberate: `checkVersion` runs **before** substitution, so\n * `version:` cannot itself be templated. It is the compatibility gate that\n * decides whether this parser understands the document at all; resolving\n * environment variables to find out which schema version to expect would be\n * backwards. The order is intended; `version:` is the one exception to the\n * substitution rule, which this sentence exists to record.\n */\n\nimport { type ZodError, type ZodIssue, type ZodTypeAny, 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.js';\nimport type {\n Ap2AuthorizationConfig,\n Ap2Mode,\n Ap2TrustedIssuer,\n} from '../authorization/ap2/types.js';\nimport {\n extractPathParameterNames,\n findUnparsedBraceToken,\n isObjectSchemaNode,\n} from '../core/execution/index.js';\nimport {\n type AuthorizationMethodName,\n CommerceError,\n type CommerceResource,\n PROTOCOL_NAMES,\n type Pricing,\n RESERVED_INPUT_FIELDS,\n} from '../core/index.js';\nimport { resolveX402Deployment, type X402FacilitatorConfig } from '../payments/x402/guardrails.js';\nimport {\n ACP_CHECKOUT_OPERATIONS,\n ACP_OPERATION_INPUT_KEYS,\n ACP_WELL_KNOWN_PATH,\n type AcpCheckoutOperation,\n} from '../protocols/acp/constants.js';\nimport { substituteEnv } from './env.js';\n\nconst SUPPORTED_CONFIG_VERSION = 1;\n\n/** `0x` + 40 hex chars. Checksum-insensitive: casing is not enforced. */\nconst ADDRESS_PATTERN = /^0x[0-9a-fA-F]{40}$/;\nconst ZERO_ADDRESS_PATTERN = /^0x0{40}$/i;\n\n/**\n * A resource `id` doubles as its MCP tool name (protocol-mcp registers one\n * tool per resource, named by id). Value verified against the regex actually\n * shipped in the installed `@modelcontextprotocol/sdk@1.30.0`\n * (`shared/toolNameValidation.js`, SEP-986 \"Specify Format for Tool Names\") -\n * not duplicated as an SDK dependency, since config stays protocol-agnostic.\n */\nconst MCP_TOOL_NAME_PATTERN = /^[A-Za-z0-9._-]{1,128}$/;\n\n// ---------------------------------------------------------------------------\n// Zod schema for the *shape* of the raw (post-substitution) document.\n// ---------------------------------------------------------------------------\n\n/** Accepts a real number or a (post env-substitution) numeric string. */\nconst NumberOrString = z.union([z.number(), z.string()]);\n/** Accepts a real boolean or a (post env-substitution) \"true\"/\"false\" string. */\nconst BooleanOrString = z.union([z.boolean(), z.string()]);\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, /api/events, /api/events/stream. No token -> those routes 404. */\n adminToken: z.string().min(1).optional(),\n /** Browser origins allowed to read the dashboard-facing routes. Empty by default: closed. */\n // Entries are matched literally against the browser's\n // `Origin` header, so `\"*\"` and a trailing slash match nothing at all -\n // fail-closed (a lockout, not a bypass), but silently, and a lockout with\n // no explanation is the kind of thing an operator \"fixes\" by disabling the\n // check. Reject those two shapes with a pointer instead.\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/**\n * Every path the gateway registers itself (`src/gateway/routes.ts`), plus the\n * fixed discovery paths adapters own. An adapter mount that equals one of\n * these makes Fastify's `.all()` a duplicate of the registered route; one that\n * is a path-prefix of them swallows their 404s through the mount's\n * `${mountPath}/*` wildcard.\n */\nconst RESERVED_GATEWAY_PATHS = [\n '/health',\n '/ready',\n '/.well-known/agent-commerce',\n // Fixed by the A2A specification, so it is the adapter's to serve and never\n // a configurable mount's to claim.\n '/.well-known/agent-card.json',\n // Likewise 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 '/api/events/stream',\n] as const;\n\n/**\n * `mountPath` reaches Fastify as a route pattern, and a bad one throws inside\n * route registration - deferred to `server.ready()`, so `createGateway` fails\n * wholesale with an opaque `FST_ERR_*` instead of the adapter alone degrading.\n * Catching the shape here turns that into a CONFIG_INVALID naming the value.\n * Fastify pattern syntax (`:param`, `*`) is rejected rather than supported:\n * the mount registers its own wildcard, so a pattern here has no meaning.\n */\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 in this release - `none` is not offered. */\nconst AcpAuthSchema = z.object({ type: z.literal('bearer'), token: z.string().min(1) }).strict();\n\nconst AcpIdempotencySchema = z\n .object({ path: z.string().min(1), retentionHours: NumberOrString.optional() })\n .strict();\n\n/**\n * Operation ids are validated against `ACP_CHECKOUT_OPERATIONS` in the business\n * pass rather than spelled out again here: one list of the five names, and a\n * missing or misspelled key gets a message naming the operation.\n */\nconst AcpCheckoutSchema = z.object({ operations: z.record(z.string().min(1)) }).strict();\n\n/** Optional discovery metadata. Omitted when not configured - never guessed. */\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 block: A2A is off unless an operator asks for it, and an\n // existing config predating the adapter stays valid.\n a2a: z\n .object({\n enabled: BooleanOrString,\n mountPath: MountPathSchema.optional(),\n })\n .strict()\n .optional(),\n // Likewise optional and off by default. The sub-blocks are optional here\n // and required by the business pass only when ACP is enabled, so a\n // disabled placeholder block stays writable and an enabled one gets a\n // message naming the piece it is missing.\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\n/** Applied when `protocols.a2a` is absent or names no mount. */\nconst DEFAULT_A2A_MOUNT_PATH = '/a2a';\n\n/** Applied when `protocols.acp` is absent or names no mount. */\nconst DEFAULT_ACP_MOUNT_PATH = '/acp';\n\n/**\n * Idempotency records must outlive the window in which a client may retry, and\n * ACP fixes that window at 24 hours. A shorter retention would let a replayed\n * key past an expired record and run a checkout side effect twice, so it is\n * both the default and the floor.\n */\nconst ACP_RETENTION_HOURS = 24;\n\nconst BackendMethodSchema = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);\n\n/**\n * Names the top-level input properties carrying each part of the backend\n * request. Strict: a typo like `bodyy` must fail at load, not silently mean\n * \"no body binding\" and ship a request missing its payload.\n */\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\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 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/**\n * Facilitator credentials, kept generic on purpose: x402 facilitators are not\n * a single-vendor category, and an auth block shaped around one provider's\n * credentials would make the abstraction a fiction. A facilitator needing\n * per-request signed credentials is refused rather than sent nothing.\n */\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; a static header cannot express it.\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\nconst 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 means \"this facilitator takes no credential\" - an explicit\n // statement, normalised to `{ type: 'none' }` below. On a mainnet that\n // combination is refused outright, so the default can never quietly\n // become an unauthenticated production facilitator.\n auth: FacilitatorAuthSchema.optional(),\n })\n .strict(),\n]);\n\nconst X402Schema = z\n .object({\n enabled: BooleanOrString,\n network: z.string().min(1),\n rpcUrl: z.string().min(1),\n asset: z.string().min(1),\n assetName: z.string().min(1),\n assetVersion: z.string().min(1),\n assetDecimals: NumberOrString,\n payTo: z.string().min(1),\n maxTimeoutSeconds: NumberOrString,\n facilitator: FacilitatorSchema,\n /** Real funds. Never defaulted - see src/payments/x402/guardrails.ts. */\n allowMainnet: BooleanOrString.optional(),\n /** Accepts a mainnet facilitator that takes no credential. Never defaulted. */\n allowUnauthenticatedFacilitator: BooleanOrString.optional(),\n })\n .strict();\n\nconst PaymentsSchema = z\n .object({\n x402: X402Schema.optional(),\n })\n .strict();\n\n/**\n * A public verification key, given inline.\n *\n * Inline only: there is no `jwksUri`, no `jku`, no discovery URL. AP2 still\n * has an open standardisation question around secure key distribution, and\n * inventing dynamic trust here would mean fetching keys from a location a\n * mandate can influence. The JWK's own members are checked against\n * `AP2_JWK_MEMBERS` in the business pass, which stops `x5u` reintroducing the\n * same fetch one level down.\n */\nconst Ap2KeySchema = z\n .object({\n kid: z.string().min(1),\n jwk: z.record(z.string(), z.unknown()),\n })\n .strict();\n\nconst Ap2IssuerSchema = z\n .object({\n issuer: z.string().min(1),\n /**\n * Required, not defaulted. Without it, a mandate minted for another\n * merchant would verify here, and there is no value worth guessing for\n * something that decides that.\n */\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 replay: z\n .object({ path: z.string().min(1) })\n .strict()\n .optional(),\n })\n .strict();\n\n/**\n * Optional block, off by default. A config predating AP2 stays valid, and the\n * sub-blocks are optional here so a disabled placeholder is writable; the\n * business pass requires each of them only once AP2 is enabled, and names the\n * missing piece.\n */\nconst AuthorizationSchema = z.object({ ap2: Ap2Schema.optional() }).strict();\n\nconst 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\ntype RawConfig = z.infer<typeof RawConfigSchema>;\ntype RawResourceEntry = z.infer<typeof ResourceEntrySchema>;\n\n// ---------------------------------------------------------------------------\n// Public shape (docs/contracts.md - exact).\n// ---------------------------------------------------------------------------\n\n/** Optional ACP discovery metadata. Absent fields are omitted from the document. */\nexport interface AcpDiscoveryConfig {\n readonly documentationUrl?: string;\n readonly supportedCurrencies?: readonly string[];\n readonly supportedLocales?: readonly string[];\n readonly interventionTypes?: readonly string[];\n}\n\n/**\n * Discriminated on `enabled` so an enabled ACP config carries everything the\n * adapter needs, with no optional-field assertions at the mount point: a\n * half-configured checkout lifecycle is rejected at load instead.\n */\nexport type AcpProtocolConfig =\n | { readonly enabled: false; readonly mountPath: string }\n | {\n readonly enabled: true;\n readonly mountPath: string;\n readonly auth: { readonly type: 'bearer'; readonly token: string };\n readonly idempotency: { readonly path: string; readonly retentionHours: number };\n readonly checkout: {\n readonly operations: Readonly<Record<AcpCheckoutOperation, string>>;\n };\n readonly discovery?: AcpDiscoveryConfig;\n };\n\nexport interface GatewayConfig {\n readonly version: 1;\n readonly merchant: { readonly id: string; readonly name: string; readonly publicBaseUrl: string };\n readonly server: {\n readonly port: number;\n readonly host: string;\n readonly adminToken?: string;\n readonly allowedOrigins: readonly string[];\n };\n readonly storage: { readonly receipts: { readonly driver: 'sqlite'; readonly path: string } };\n readonly protocols: {\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: AcpProtocolConfig;\n };\n /** Canonical resources, already normalised. */\n readonly resources: readonly CommerceResource[];\n readonly payments: {\n readonly x402?: {\n readonly enabled: boolean;\n readonly network: string;\n readonly rpcUrl: string;\n readonly asset: string;\n readonly assetName: string;\n readonly assetVersion: string;\n readonly assetDecimals: number;\n readonly payTo: string;\n readonly maxTimeoutSeconds: number;\n readonly facilitator: X402FacilitatorConfig;\n readonly allowMainnet?: boolean;\n readonly allowUnauthenticatedFacilitator?: boolean;\n };\n };\n /**\n * Absent when no `authorization:` block is configured, which is how every\n * config written before AP2 existed reads.\n */\n readonly authorization?: { readonly ap2: Ap2AuthorizationConfig };\n}\n\n// ---------------------------------------------------------------------------\n// Entry point\n// ---------------------------------------------------------------------------\n\nexport function parseConfig(raw: unknown, env: NodeJS.ProcessEnv): GatewayConfig {\n if (typeof raw !== 'object' || raw === null || Array.isArray(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 as Record<string, unknown>);\n\n const substituted = substituteEnv(raw, env);\n const parsed = parseWithZod(RawConfigSchema, substituted);\n return normalise(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 rawVersion = raw['version'];\n const version = typeof rawVersion === 'string' ? Number(rawVersion) : rawVersion;\n if (version !== SUPPORTED_CONFIG_VERSION) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Unsupported config version \"${String(rawVersion)}\": this gateway only supports version ${SUPPORTED_CONFIG_VERSION}`,\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\n// ---------------------------------------------------------------------------\n// Numeric / boolean coercion (explicit, not via Zod - see file header).\n// ---------------------------------------------------------------------------\n\nfunction toNumber(\n value: number | string,\n path: string,\n bounds: { min?: number; max?: number } = {},\n): number {\n // `Number('')` is 0 - finite, integral, and inside\n // `server.port`'s deliberate `min: 0` (\"let the OS pick\"). So `port: ${PORT:-}`\n // or an exported-but-empty PORT validated PASS and the gateway bound a random\n // port, after which `doctor` derived `http://127.0.0.1:0`, failed to connect,\n // and reported the gateway unreachable while it was serving. `Number` also\n // accepts `\"0x50\"` (80) and `\"1e3\"` (1000) for fields that are decimal\n // integers everywhere they are documented. Require plain digits instead.\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\nfunction 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\n// ---------------------------------------------------------------------------\n// Business-rule validation + normalisation into the canonical shape.\n// ---------------------------------------------------------------------------\n\nconst SUPPORTED_PROTOCOLS: ReadonlySet<string> = new Set(PROTOCOL_NAMES);\nconst SUPPORTED_PAYMENT_METHODS = new Set(['x402']);\nconst SUPPORTED_AUTHORIZATION_METHODS: ReadonlySet<string> = new Set(['ap2']);\n\nfunction normalise(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: normaliseAcp(raw.protocols.acp),\n };\n validateMountPaths(protocols);\n\n const x402Raw = raw.payments.x402;\n const facilitator: X402FacilitatorConfig | undefined =\n x402Raw === undefined\n ? undefined\n : x402Raw.facilitator.mode === 'local'\n ? { mode: 'local', signerPrivateKey: x402Raw.facilitator.signerPrivateKey }\n : {\n mode: 'remote',\n url: x402Raw.facilitator.url,\n auth: x402Raw.facilitator.auth ?? { type: 'none' },\n };\n const x402 =\n x402Raw && facilitator\n ? {\n enabled: toBoolean(x402Raw.enabled, 'payments.x402.enabled'),\n network: x402Raw.network,\n rpcUrl: x402Raw.rpcUrl,\n asset: x402Raw.asset,\n assetName: x402Raw.assetName,\n assetVersion: x402Raw.assetVersion,\n assetDecimals: toNumber(x402Raw.assetDecimals, 'payments.x402.assetDecimals', {\n min: 0,\n max: 36,\n }),\n payTo: x402Raw.payTo,\n maxTimeoutSeconds: toNumber(\n x402Raw.maxTimeoutSeconds,\n 'payments.x402.maxTimeoutSeconds',\n {\n min: 1,\n },\n ),\n facilitator,\n ...(x402Raw.allowMainnet !== undefined\n ? { allowMainnet: toBoolean(x402Raw.allowMainnet, 'payments.x402.allowMainnet') }\n : {}),\n ...(x402Raw.allowUnauthenticatedFacilitator !== undefined\n ? {\n allowUnauthenticatedFacilitator: toBoolean(\n x402Raw.allowUnauthenticatedFacilitator,\n 'payments.x402.allowUnauthenticatedFacilitator',\n ),\n }\n : {}),\n }\n : undefined;\n\n if (x402) {\n validateAddress('payments.x402.payTo', x402.payTo);\n validateAddress('payments.x402.asset', x402.asset);\n // The same call the provider makes at construction, run here so\n // `agent-commerce validate` reports an unsafe deployment where an operator\n // expects to hear about it, rather than at first boot.\n resolveX402Deployment({\n network: x402.network,\n payTo: x402.payTo,\n asset: x402.asset,\n assetName: x402.assetName,\n assetVersion: x402.assetVersion,\n facilitator: x402.facilitator,\n ...(x402.allowMainnet !== undefined ? { allowMainnet: x402.allowMainnet } : {}),\n ...(x402.allowUnauthenticatedFacilitator !== undefined\n ? { allowUnauthenticatedFacilitator: x402.allowUnauthenticatedFacilitator }\n : {}),\n });\n }\n\n const ap2 = normaliseAp2(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 normaliseResource(id, entry, protocols, x402, ap2),\n );\n if (protocols.acp.enabled) validateAcpCheckoutMapping(protocols.acp, resources);\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 // min 0, not 1: port 0 is the standard \"let the OS pick a free port\"\n // convention, useful for tests and ephemeral dev/demo 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 ...(x402 !== undefined ? { x402 } : {}),\n },\n ...(ap2 !== undefined ? { authorization: { ap2 } } : {}),\n };\n}\n\ninterface NormalisedProtocols {\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: AcpProtocolConfig;\n}\n\n/**\n * Two enabled mounts may not overlap: each registers a `${mountPath}/*`\n * wildcard, so a shared prefix means one adapter silently answers for the\n * other. Disabled protocols mount nothing and are not compared.\n */\nfunction validateMountPaths(protocols: NormalisedProtocols): 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// ---------------------------------------------------------------------------\n// AP2 authorization (experimental)\n// ---------------------------------------------------------------------------\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\nfunction normaliseAp2(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 authorise a second settlement',\n );\n }\n\n const mandateIssuers = normaliseIssuers(\n raw.trust?.mandateIssuers,\n 'authorization.ap2.trust.mandateIssuers',\n );\n const checkoutIssuers = normaliseIssuers(\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 replay: { path: raw.replay.path },\n };\n}\n\n/**\n * Both issuer lists are required and non-empty when AP2 is on.\n *\n * Two signatures have to be checked: the issuer's over the Checkout Mandate,\n * and the merchant's over the checkout JWT it binds. An empty list would make\n * every mandate fail verification, which reads as a broken deployment rather\n * than as the misconfiguration it is.\n */\nfunction normaliseIssuers(\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/**\n * Checks a configured verification key against the one shape this release\n * accepts: a public P-256 key, nothing else.\n *\n * Every member is checked here rather than passed through to the JOSE library\n * at first purchase, so a key that is wrong is wrong at deploy time. The\n * alternative is learning about it from a buyer whose valid mandate was\n * refused.\n */\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` is the private scalar; naming it is worth the extra branch, because\n // an operator who pasted a full key pair into the gateway has put signing\n // material where only verification material belongs, and needs to know\n // that rather than read \"unsupported member\".\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 normalised: Record<string, string> = {};\n for (const member of AP2_JWK_MEMBERS) {\n if (jwk[member] !== undefined) normalised[member] = value(member);\n }\n return normalised;\n}\n\n/**\n * The AP2 replay store gets its own SQLite file.\n *\n * Reserved mandates, payment attempts and ACP idempotency records have\n * different schemas and different retention rules. Pointing two of them at one\n * file gives either a migration conflict at startup or a shared write lock on\n * the settlement path.\n */\nfunction validateReplayStoreIsolated(\n replayPath: string,\n receiptsPath: string,\n acp: AcpProtocolConfig,\n): void {\n // Every `:memory:` handle is its own private database, so two of them are\n // not the collision the literal comparison would call them.\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/**\n * Resolves a resource's `authorization.required` list against the configured\n * provider.\n *\n * A requirement that cannot be enforced is worse than none, because the\n * resource looks protected in config and settles unprotected in production.\n * Everything that would produce that gap is refused here.\n */\nfunction normaliseResourceAuthorization(\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, so there has to be one. It\n // also never unlocks a resource by itself, which makes requiring one on a\n // free resource a statement the pipeline has no way to act on.\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\n// ---------------------------------------------------------------------------\n// ACP (experimental)\n// ---------------------------------------------------------------------------\n\ntype RawAcp = NonNullable<RawConfig['protocols']['acp']>;\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\nfunction normaliseAcp(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 },\n checkout: { operations: normaliseAcpOperations(raw.checkout) },\n // Built key by key rather than passed through: absent metadata must stay\n // absent from the discovery document, not appear there as `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/**\n * All five operations, each on its own resource.\n *\n * Partial mappings are refused because ACP discovery advertises `checkout` as\n * one service: a seller announcing it must be able to serve the whole\n * lifecycle. One resource serving two operations is refused because the\n * operations differ in method, canonical input and success status - a resource\n * that satisfies both is a resource that implements neither faithfully.\n */\nfunction normaliseAcpOperations(\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\nfunction 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 its own purchase payment (`payment_data` on\n // completion). Charging an Agent Commerce payment to *invoke* the operation\n // would stack a second, unrelated payment layer on one call, and ACP has no\n // wire representation for our payment-required outcome to negotiate it.\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/**\n * The adapter sends a fixed canonical envelope per operation, so a resource\n * whose input schema forbids a key ACP always sends - or demands one ACP never\n * sends - can only ever fail at request time with INPUT_INVALID. Cheaper to\n * say so at load.\n */\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 properties = schema['properties'];\n\n if (schema['additionalProperties'] === false && isPlainObject(properties)) {\n for (const key of keys) {\n if (!Object.hasOwn(properties, key)) {\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 always sends for this operation`,\n { resourceId: resource.id },\n );\n }\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 never supplies (it sends: ${keys.join(', ')})`,\n { resourceId: resource.id },\n );\n }\n }\n }\n}\n\ninterface NormalisedX402 {\n readonly enabled: boolean;\n readonly assetDecimals: number;\n}\n\nfunction normaliseResource(\n id: string,\n entry: RawResourceEntry,\n protocols: NormalisedProtocols,\n x402: NormalisedX402 | 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 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 if (entry.pricing.type === 'fixed') {\n validatePricingAmount(id, entry.pricing.amount, x402);\n }\n\n const paymentMethods = entry.payments ?? [];\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: x402.`,\n { details: { path: `resources.${id}.payments`, resourceId: id, method } },\n );\n }\n if (method === 'x402' && (!x402 || !x402.enabled)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" names payment method \"x402\" which is not configured or not enabled under payments.x402`,\n { details: { path: `resources.${id}.payments`, resourceId: id, method } },\n );\n }\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 = normaliseResourceAuthorization(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/**\n * `{param}` templates (e.g. `.../weather/{city}`) parse fine as a URL - the\n * WHATWG parser just percent-encodes the braces - so this only rejects\n * genuinely malformed strings and non-http(s) schemes, not templating.\n */\n/**\n * Permissive-by-default is the wrong default for a value forwarded to\n * someone else's API: an object schema that\n * omits `additionalProperties` defaults, per JSON Schema itself, to\n * \"anything goes\" - so default it to `false` here instead, unless the\n * operator set it explicitly (including explicitly to `true`, which is\n * respected).\n *\n * An earlier fix only stamped the ROOT schema, so\n * `filter: { type: object }` *looked* closed (the top level really was)\n * while every key one level down under `properties.filter` still passed\n * verbatim - `core`'s validator (execution/validation.ts) only enforces\n * `additionalProperties` where the schema states it explicitly, at every\n * level independently. Recurse into `properties` and `items` the same way\n * `validateResourceSchemaKeywords` below already does, so \"closed\" actually\n * means closed at every depth, not just the one an operator happened to\n * write `additionalProperties: false` on.\n *\n * `type` can be an array (`[\"object\",\"null\"]`, valid JSON\n * Schema) - a bare `=== 'object'` string comparison missed it, so a schema\n * in that shape got stamped as open. `declaresObjectType` below is the same\n * check `core`'s validator now makes (`execution/validation.ts`'s\n * `isObjectSchemaNode`) so the two stay in agreement.\n */\nfunction defaultClosedObjectSchema(schema: Record<string, unknown>): Record<string, unknown> {\n // imported, never re-implemented. The local predicate this\n // replaces recognised `type`/`properties` but not `required`, while core's\n // validator recognised `properties`/`required` - so `input: { required: [q] }`\n // was an object to the validator and not to the stamper, and every unknown\n // key sailed through to the merchant backend. One definition, one drift.\n const isObjectSchema = isObjectSchemaNode(schema);\n const result: Record<string, unknown> = { ...schema };\n\n if (isObjectSchema) {\n const properties = schema['properties'];\n if (isPlainObject(properties)) {\n result['properties'] = Object.fromEntries(\n Object.entries(properties).map(([key, sub]) => [\n key,\n isPlainObject(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 (isPlainObject(items)) {\n result['items'] = defaultClosedObjectSchema(items);\n }\n\n // The third place this stamper drifted from the validator, after `required`\n // and tuple `items`. `additionalProperties: {schema}` is the idiomatic\n // \"map of typed objects\" shape, and core's validator applies that subschema\n // recursively at unbounded depth - so without this branch, every node under\n // it stayed open and unknown keys reached the merchant backend. Recursion\n // here is not conditional on `isObjectSchema`: the validator applies the\n // subschema wherever it finds one.\n const additional = schema['additionalProperties'];\n if (isPlainObject(additional)) {\n result['additionalProperties'] = defaultClosedObjectSchema(additional);\n }\n\n return result;\n}\n\n/**\n * A resource that declares no `input:` at all got\n * `inputSchema: undefined`, and `compileJsonSchema(undefined)` is an\n * always-valid validator - every caller key was forwarded to the merchant\n * backend verbatim. The decision: default \"declared nothing\" to \"accepts\n * nothing\" (an empty closed object) rather than rejecting the config at load\n * time - a no-argument resource that omits `input:` is a legitimate shape,\n * and rejecting it would break every existing config that uses it.\n */\nconst EMPTY_CLOSED_OBJECT_SCHEMA: Record<string, unknown> = {\n type: 'object',\n properties: {},\n additionalProperties: false,\n};\n\n/**\n * `src/core`'s validator only enforces the subset documented in\n * `execution/validation.ts` (type/properties/required/additionalProperties/\n * enum/items) - everything else (`pattern`, `minLength`, `format`, `oneOf`,\n * …) is silently ignored at runtime. An operator who writes `pattern` and\n * never sees it enforced has no way to know that from the config alone, so\n * warn at load time instead of letting them find out the hard way.\n */\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\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** `type` explicitly set to something that rules out \"object\" (a bare\n * value, or an array not containing \"object\"). `undefined` - no `type` at\n * all - is deliberately NOT treated as excluding: core's validator treats\n * `properties`/`required` with no `type` as an object schema, so that shape\n * is fine, not another instance of this bug. */\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, both warning (existing, unenforced\n * keywords) and rejecting (a node whose declared `type`\n * cannot structurally be an object, yet which still carries `properties` or\n * `required`). The `properties`/`required`-with-no-`type` shape is not\n * this function's problem any more, since the\n * validator now treats that shape as an object; what's still a trap is a\n * `type` that actively rules \"object\" out while `properties`/`required`\n * imply it was meant to be one, e.g. a copy-pasted sibling schema whose\n * `type` was never updated. Rejecting (not just warning) here is the\n * decision - a warning is exactly what let this bug class ship silently in\n * the first place (`validate`/`doctor` both said PASS).\n */\nfunction 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 // eslint-disable-next-line no-console\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 // the other half. Closing a `required`-only node is\n // correct JSON Schema and quietly unsatisfiable: `required: [\"q\"]` demands a\n // property that `properties` never declares, so the stamped\n // `additionalProperties: false` rejects `q` as an unknown key - the schema\n // can never be satisfied by any input at all. Fail-closed, so no money is at\n // risk, but every call would 400 with a config that loaded cleanly. Say so\n // at load instead. Only when the node really will be closed: an explicit\n // `additionalProperties` 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 = isPlainObject(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 (isPlainObject(properties)) {\n for (const [key, sub] of Object.entries(properties)) {\n if (isPlainObject(sub)) validateResourceSchemaKeywords(id, `${path}.properties.${key}`, sub);\n }\n }\n const additional = schema['additionalProperties'];\n if (isPlainObject(additional)) {\n validateResourceSchemaKeywords(id, `${path}.additionalProperties`, additional);\n }\n const items = schema['items'];\n if (isPlainObject(items)) {\n validateResourceSchemaKeywords(id, `${path}.items`, items);\n } else if (Array.isArray(items)) {\n // tuple-form `items` (an array of per-position\n // schemas) is valid JSON Schema, but `core`'s validator only supports\n // the single-schema form applied to every element - a tuple silently\n // enforces nothing, invisibly rather than wrongly, so warn the same way\n // an unsupported keyword does.\n // eslint-disable-next-line no-console\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\n/**\n * `amount: z.string().min(1)` alone let \"0,01\", \"$0.01\", \"1e-2\", \"-1\" and an\n * over-precise \"0.0000001\" all pass config + `doctor`, then throw on every\n * purchase. A plain\n * positive decimal only - no currency symbol, no thousands separator, no\n * exponent notation.\n */\nconst PRICING_AMOUNT_PATTERN = /^\\d+(?:\\.\\d+)?$/;\nconst ZERO_AMOUNT_PATTERN = /^0(?:\\.0+)?$/;\n\nfunction validatePricingAmount(id: string, amount: string, x402: NormalisedX402 | 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 settles a zero-value transfer, which is\n // nonsense - if something is free, it should say so.\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 (x402 !== undefined) {\n const fractionalDigits = amount.includes('.') ? (amount.split('.')[1]?.length ?? 0) : 0;\n if (fractionalDigits > x402.assetDecimals) {\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 (${x402.assetDecimals} decimals)`,\n { details: { path, resourceId: id } },\n );\n }\n }\n}\n\n/**\n * `backend.inputBindings` names top-level input properties; this is the gate\n * that makes those names mean something at load time rather than at the first\n * paid call. Input schemas are closed by default at every depth\n * (`defaultClosedObjectSchema`), so a binding naming a property the schema\n * never declares can never be satisfied - the group would be silently empty\n * on every request, which on a paid resource is payment for a request the\n * backend receives incomplete.\n *\n * Returns the schema node `{param}` declarations must be found in: the path\n * group in explicit mode, the whole input in legacy mode.\n */\nfunction 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 = isPlainObject(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 legitimately be any JSON value; only the two groups the\n // executor iterates as key/value pairs have to be objects.\n const declared = properties[property];\n if (location !== 'body' && isPlainObject(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: isPlainObject(group) ? group : undefined,\n where: `input.properties.${bindings.path}`,\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\n/**\n * The root-cause half. `validateBackendRequestShape`\n * (src/core) rejects a missing path parameter at request time - after\n * schema validation but, without this check, on every single call, because\n * a schema that never declares `{city}` can never satisfy it. A paid\n * resource in that shape settles the buyer's payment and then always fails\n * to reach the backend: no refund, replay key burned, on every call, not an\n * unlucky one. Every `{param}` in `backend.url` must be BOTH declared in\n * `properties` AND listed in `required` - an optional value hits the exact\n * same \"caller structurally cannot supply it on every call that omits it\"\n * problem as an undeclared one, just less often. This is the config-load\n * gate `agent-commerce validate`/`doctor` catch it at; the runtime\n * `INPUT_INVALID` in `validateBackendRequestShape` is defence in depth for\n * a hand-built `CommerceResource` this check never saw.\n */\nfunction validatePathParametersDeclared(\n id: string,\n url: string,\n input: Record<string, unknown> | undefined,\n where: string,\n): void {\n // Before anything else: a brace token the canonical grammar does not\n // recognise is neither extracted here nor substituted at request time, so it\n // would travel to the backend as a percent-encoded literal. On a paid\n // resource that is payment-without-delivery on every single call. Refuse it\n // at load rather than letting \"matches nothing\" mean \"nothing to check\".\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 be sent to the backend literally, so a paid resource would settle payment and then never reach the backend`,\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 // Every defence around `{param}` guards the *path* position, and in the host\n // position all of them fail open at once: `new URL('http://{host}/api')`\n // parses (the hostname is literally `{host}`) so the URL check passes; the\n // runtime containment check is skipped because its literal prefix\n // (`http://`) does not itself parse as a URL; and `encodeURIComponent` does\n // not escape dots, so a hostname survives it whole. Caller input then chooses\n // which host the gateway calls - the metadata service, an internal address,\n // anything. `http://{region}.api.internal/...` is an ordinary-looking\n // multi-tenant template, so this is refused here rather than warned about.\n //\n // The rule: everything before the first `{` must already be a complete\n // authority - a parseable origin followed by the path's leading `/`.\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 at all - the parameter starts before the authority is done.\n }\n if (origin === undefined || !prefix.startsWith(`${origin}/`)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has a backend.url parameter before the end of the host (\"${url}\"). 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 = isPlainObject(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 settle payment (if priced) and then fail to reach the backend`,\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 caller that omits it hits the same unservable-request problem as an undeclared parameter`,\n { details: { path, resourceId: id, param } },\n );\n }\n }\n}\n\nfunction validateBackendUrl(id: string, url: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has an invalid backend.url \"${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\nfunction validateAddress(path: string, value: string): void {\n if (!ADDRESS_PATTERN.test(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 (ZERO_ADDRESS_PATTERN.test(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","/**\n * Locates and parses `config.yaml`, then hands the raw value to\n * `parseConfig`. Never trusts raw YAML before Zod 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/index.js';\nimport { DEFAULT_CONFIG_FILENAME } from './filename.js';\nimport { type GatewayConfig, parseConfig } from './schema.js';\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 // Retained for programmatic callers. Nothing in the CLI prints a\n // `cause`, and nothing should start: this is the object whose\n // `.message` carries the source excerpt (see below).\n cause: error,\n },\n );\n }\n\n return parseConfig(raw, env);\n}\n\n/**\n * A YAML failure described from the error's *structured* fields only.\n *\n * Deliberately not `error.message`: the `yaml` package builds that message\n * with a **code frame excerpt of the source line**, so a syntax error next to\n * an inline secret would reproduce it verbatim into `validate`/`doctor` output — including `doctor --json`, the output most\n * likely to be pasted into an issue or captured by CI:\n *\n * … is not valid YAML: Nested mappings are not allowed … at line 2, column 15:\n *\n * adminToken: super-secret-token-value\n * ^\n *\n * `server.adminToken` and `payments.x402.facilitator.signerPrivateKey` are\n * both legal as inline literals, so this was a real sink rather than a\n * hypothetical one — and it contradicted `validate`'s own promise never to\n * print a resolved value: it never printed a resolved `${ENV}`, only an\n * inlined one. `code` and `linePos` locate the fault exactly as well and\n * cannot contain file content.\n */\n/**\n * Plain-English phrasing for the codes an operator actually hits, so replacing\n * the excerpt does not also cost the diagnostic its readability. These are\n * fixed strings chosen here — they can never contain file content, which is\n * the entire property that matters. Anything unlisted degrades to the bare\n * code, which is still precise.\n */\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\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","/** Default `IdGenerator` used when the caller does not inject one. */\nimport { randomUUID } from 'node:crypto';\nimport type { IdGenerator } from '../core/index.js';\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 with redaction. Never log secrets: the credential and\n * proof headers (`authorization`, `payment-signature`, `agent-authorization`),\n * private keys, seeds, mnemonics, signatures.\n *\n * Two independent things are built here, deliberately not the same pino\n * instance (Fastify's `loggerInstance` option forces its generic `Logger`\n * type into `FastifyInstance`, which then conflicts with our own `Logger`\n * shape under `exactOptionalPropertyTypes`):\n * - `fastifyLoggerOptions()` — a plain options object handed to Fastify's\n * `logger` option, so Fastify builds its own internally-typed pino\n * instance (still redacted, still pino-pretty in development) for HTTP\n * access logs.\n * - `createGatewayLogger()` — a standalone pino instance wrapped to the\n * `src/core` `Logger` shape, injected into the\n * execution pipeline and protocol adapters.\n * Both share the same redaction paths and level/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/index.js';\n\n/**\n * Absolute path to pino-pretty, or `undefined` when it is not installed.\n *\n * pino-pretty is a **devDependency**: it is a developer-experience nicety and\n * making every consumer of the published package install it (and its\n * transitive tree) to get log lines would be the wrong trade. But the pretty\n * default keys off `NODE_ENV`, which is unset in a normal consumer process —\n * so \"development\" was inferred and `pino()` threw\n * `unable to determine transport target for \"pino-pretty\"`, taking down\n * `createGateway()` for anyone importing the library. The clean-consumer test\n * caught it; nothing in the repo could, because here it is always installed.\n *\n * Resolving it ourselves answers the only question that matters — *is it\n * actually there* — and passing the resolved absolute path (rather than the\n * bare name) removes the second failure mode, where pino resolves transport\n * targets from a different directory than we do.\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// pino/fast-redact paths below are single-level wildcards: '*.privateKey'\n// matches privateKey one level deep (e.g. `wallet.privateKey`), not at\n// arbitrary nesting (`a.b.privateKey` is not covered). Nothing leaks today\n// because every call site funnels through describeError(), which extracts\n// only {message, name} before logging — never a raw caught object — but that\n// is a property of current call sites, not of this redact config. Do not log\n// a raw object that might carry a secret at depth > 1 without either\n// extending these paths or hand-picking safe fields first.\nconst SECRET_FIELD_NAMES = [\n 'privateKey',\n 'signerPrivateKey',\n 'signature',\n 'seed',\n 'mnemonic',\n 'secret',\n 'apiKey',\n 'adminToken',\n 'token',\n] as const;\n\n/**\n * The bare top-level form was missing — `'*.privateKey'`\n * matches `{ wallet: { privateKey } }` but not `{ privateKey }`, so a\n * `logger.error({ privateKey })` would have printed it. Both forms are\n * generated now. The depth limit is real and unchanged: fast-redact wildcards\n * are single-level, so a secret at depth ≥ 2 is still not covered, and the\n * documentation says so rather than promising \"any field\".\n */\n/**\n * Request headers carrying a credential or a proof, read from the wire\n * constants rather than written out again here.\n *\n * A hardcoded copy is how this drifted before: `x-payment` became\n * `payment-signature` for x402 v2, and a literal list would still be redacting\n * a header no client sends. `agent-authorization` carries an AP2 mandate and\n * belongs here for the same reason a payment proof does.\n */\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 // Never spawn a pino-pretty worker thread in tests: many short-lived\n // Fastify/pino instances are created per test run, and pretty-printing is a\n // pure developer-experience nicety, not a functional requirement there.\n const wantPretty = options.prettyPrint ?? (nodeEnv !== 'production' && nodeEnv !== 'test');\n // Asked for *and* available. An explicit `prettyPrint: true` cannot conjure\n // an uninstalled module, so it degrades to JSON rather than throwing —\n // pretty-printing is cosmetic, and losing colour beats losing the gateway.\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 * Strips the query string from a request URL before it reaches a log line\n * or an echoed-back response body. The admin token is header-only, with no\n * `?adminToken=` exception for the SSE route (see access-control.ts's doc\n * comment), so this is not the only thing keeping it out of logs — but any\n * query parameter, on any route, could carry something sensitive, and a\n * blanket redaction costs nothing to keep. Single source of truth: every place that puts a\n * request URL in front of a log or a client must call this, not re-derive\n * its own redaction — two redactors drift (Fastify's\n * default 404 handler built its own message string from the raw URL,\n * bypassing the `req` serializer below entirely; see server.ts's\n * `setNotFoundHandler`, which uses this same function).\n */\nexport function 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/** Overrides (not extends) Fastify's default `req` serializer — see sanitizeUrl. */\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/** Plain options object 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 * Fastify's own default 404 handler (four-oh-four.js's `basic404` ->\n * log-controller.js's `routeNotFound`) builds its log line by interpolating\n * `request.raw.url` into a template string — bypassing the `req` serializer\n * above entirely, since it's a plain string, not a structured log call.\n * Registering a `setNotFoundHandler` replaces Fastify's internal one outright\n * (it is only ever invoked when none is set), so this is the only fix point.\n * Exported (not inlined in server.ts) so production and tests share the exact\n * same handler — a second, test-only reimplementation is exactly the kind of\n * thing that quietly drifts from what actually 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 * `onRequest` hooks doing two separate jobs:\n * - `buildAccessControlHook` (global, registered once): DNS-rebinding Host\n * defence + allowlisted CORS for browser traffic. Neither is path-keyed,\n * so this stays a single hook on the whole server.\n * - `buildOperatorTokenHook` (per-route, registered on each of the three\n * ledger routes individually): the `server.adminToken` gate.\n *\n * Why per-route and not the global hook: a global gate has only\n * `request.url`'s path to match against a literal string set. Fastify's\n * router (find-my-way) percent-*decodes* before matching, so such a gate\n * compares the *raw, still-encoded* string. `/api/%72eceipts` is \"not an\n * operator path\" to the gate and *is* `/api/receipts` to the router — a full\n * bypass with no precondition beyond network reach. A per-route hook removes\n * the whole bug class rather than guarding one instance of it: Fastify only invokes it\n * once routing has already matched this exact route, so there is no path\n * string left to attack — nothing here compares against `request.url` at\n * all.\n */\nimport { createHash, timingSafeEqual } from 'node:crypto';\nimport type { FastifyReply, FastifyRequest } from 'fastify';\n\nconst CORS_METHODS = 'GET,POST,DELETE,OPTIONS';\nconst CORS_HEADERS = 'content-type,payment-signature,x-request-id,authorization';\n/**\n * Without this a browser client can read neither the challenge nor the\n * settlement result: cross-origin JS only sees the CORS-safelisted response\n * headers unless they are named here.\n */\nconst CORS_EXPOSED_HEADERS = 'payment-required,payment-response,x-request-id';\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 // Compare case-insensitively (matches the Host check below) — an\n // operator's mis-cased allowedOrigins entry should not lock out the real\n // dashboard behind a generic 403 with no hint why. The *response* header\n // still echoes the browser's own Origin verbatim (not the lowercased\n // form): CORS requires a byte-for-byte match against what the browser\n // sent, and browsers always send Origin already lowercased in practice, so\n // this loses nothing while fixing the config-typo case.\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 validation (DNS-rebinding defence) — every request, browser or not.\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 that carry an Origin (browser traffic). A\n // request with no Origin (the normal case for agents/MCP clients) gets no\n // CORS header at all.\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 // Preflight: never carries credentials, so it must not hit a\n // downstream per-route token gate — the browser only sends the real\n // request afterward.\n reply.status(204).send();\n }\n }\n };\n}\n\n/**\n * Per-route token gate — register via `{ onRequest: buildOperatorTokenHook(...) }`\n * on each ledger route's own definition, not the global hook. Closed by\n * default: no token configured => 404 (fail closed, indistinguishable from\n * \"route doesn't exist\"). Token configured but missing/wrong => 401.\n *\n * Header-only, with no exception for the SSE route. `EventSource` cannot send\n * headers, which makes a `?adminToken=` query parameter tempting; the\n * dashboard uses its authenticated polling fallback instead — see\n * SECURITY.md. A token in a query string leaks through Referer, browser\n * history and proxy logs.\n */\nexport function buildOperatorTokenHook(\n adminToken: string | undefined,\n): (request: FastifyRequest, reply: FastifyReply) => Promise<void> {\n // async, matching buildAccessControlHook's convention: a plain 2-arg\n // function that returns `void` (not a Promise) is ambiguous to Fastify's\n // hook runner, which otherwise waits on a 3rd `done` callback that never\n // comes.\n return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n if (!adminToken) {\n reply.status(404).send();\n return;\n }\n if (!isValidAdminToken(request.headers.authorization, adminToken)) {\n reply\n .status(401)\n .send({ status: 'error', code: 'UNAUTHORIZED', message: 'Admin token required' });\n }\n };\n}\n\n/** `new URL()` handles port-stripping and IPv6 bracket notation; no need to hand-roll it. */\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 aliases are always trusted regardless of configured publicBaseUrl:\n// a DNS-rebinding attacker's page sends its OWN hostname as Host, never the\n// literal string \"localhost\"/\"127.0.0.1\"/\"::1\" — so allowing these can never\n// reintroduce the attack this check exists to stop, and it keeps local\n// dev/test setups (where the bind host and the configured publicBaseUrl\n// legitimately differ, e.g. 127.0.0.1 vs. localhost) working without\n// requiring them to match exactly.\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\nfunction isValidAdminToken(authHeader: string | undefined, adminToken: string): boolean {\n const provided = authHeader?.startsWith('Bearer ')\n ? authHeader.slice('Bearer '.length)\n : undefined;\n if (provided === undefined) return false;\n // Hash both sides first: timingSafeEqual throws on unequal-length buffers,\n // and a thrown-vs-not branch is itself a timing/type oracle on the token's\n // length. SHA-256 digests are always 32 bytes, so the comparison is\n // constant-shape regardless of what the caller sent.\n return timingSafeEqual(hashToken(provided), hashToken(adminToken));\n}\n\nfunction hashToken(value: string): Buffer {\n return createHash('sha256').update(value, 'utf8').digest();\n}\n","/**\n * Adapter isolation: a failing adapter must not\n * prevent the server from starting or other adapters from working.\n *\n * `HttpProtocolAdapter`s are mounted at `adapter.mountPath` inside an\n * encapsulated Fastify plugin that never lets Fastify consume the request\n * body — the adapter's own transport (MCP's Streamable HTTP) reads\n * `request.raw` itself, so we register a wildcard content-type parser that\n * is a deliberate no-op, then hand the adapter the raw Node req/res and\n * `reply.hijack()` so Fastify does not also try to send a response.\n *\n * Fastify enforces `bodyLimit` *inside* the content-type parser — a\n * parser that never touches the payload never enforces it, so this mount had\n * no body cap at all, and the SDK's Streamable HTTP transport buffers the\n * whole request into memory with no cap of its own (unauthenticated, no\n * handshake needed). MOUNT_BODY_LIMIT_BYTES is enforced by tallying bytes on\n * the underlying *socket* (not the request stream) as they arrive and\n * destroying the connection past the cap: `Content-Length` alone is\n * insufficient (chunked encoding has none), and observing the socket's own\n * 'data' event doesn't compete with however the adapter reads the body —\n * Node's HTTP module already keeps the socket flowing internally to feed its\n * parser, so an extra listener is pure fan-out, never a second consumer. It\n * can only ever say \"stop\", never corrupt or steal a byte the 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/index.js';\n\n/**\n * A separate, larger (1 MB) cap for this mount is tempting — MCP tool\n * payloads can legitimately carry more data than a REST-style invoke body.\n * It matches `server.ts`'s route `bodyLimit` (256 KB) anyway: the adapter\n * closes the batch-fan-out half (bounded concurrency, stop-on-disconnect),\n * but the SDK transport still parses the whole array before adapter code\n * ever runs, so\n * this cap is the only lever left on the first-request parse-time memory\n * spike, and a smaller cap admits proportionally fewer batch entries. One\n * documented number is also simpler to state correctly than \"two caps,\n * enforced two different ways\" — which is how `/mcp` ended up with no cap\n * at all in the first place (see docs/security.md). `server.ts` imports\n * this rather than defining its own, so there is exactly one number, not\n * two that happen to currently agree.\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 // Before anything starts: two adapters claiming the same path is a\n // composition-root bug, not a runtime condition. Fastify would only notice\n // it inside deferred route registration and fail `server.ready()` with an\n // opaque 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 // Pre-scope the logger so every adapter's own log calls carry\n // `adapter: <name>` automatically — the adapter never has to remember to\n // add it itself.\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 = describeError(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 *cross-adapter* claims conflict. An adapter serving a fixed route under\n * its own mount is fine — Fastify prefers a static route over a wildcard — and\n * 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 * The body limit and the per-tool-call semaphore\n * (`protocol-mcp`'s MAX_CONCURRENT_TOOL_CALLS) both bound *what happens\n * after* a request is parsed — neither sees the SDK's own JSON.parse of the\n * request body, which was measured spiking one 256 KB batch\n * request's heap by ~106 MB (26 -> 132 MB) before GC reclaims it. Not a\n * leak, but unbounded concurrency times an unbounded spike is unbounded\n * memory: a 20-concurrent-batches probe (262 KB each) is\n * the only concurrency level this has actually been measured safe at (peak\n * RSS 368 MB, fully reclaimed) — so 20 is the cap, not a rounder guess.\n * compose sets no memory limit, so this is the only thing standing between\n * \"~40 connections\" and a multi-gigabyte spike.\n */\nexport const MOUNT_MAX_CONCURRENT_REQUESTS = 20;\n/** Short and blunt on purpose: this is a parse-time spike that clears in\n * well under a second once GC runs, not an outage a client should back off\n * from for long. */\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 for the whole adapter, mount and fixed routes alike: the cap\n // bounds what this adapter can be made to parse concurrently, and a second\n // door into the same adapter would be a way around it.\n let inFlight = 0;\n\n void server.register(async (instance) => {\n // Fastify pre-registers exact-match parsers for application/json and\n // text/plain that run BEFORE the '*' fallback (checked in getParser()).\n // MCP clients send application/json, so without an exact no-op here\n // Fastify's built-in JSON parser drains request.raw before the adapter's\n // own transport ever reads it -> the adapter sees 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 // Reject before the SDK ever sees the body — the whole point is to\n // never let a request past this line start the parse that spikes\n // memory. No body-limit enforcement needed either: nothing here has\n // read a byte of it yet.\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: describeError(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, even on a throw above — a stranded count would\n // shrink the effective cap by one forever and eventually 503 every\n // request on this mount permanently, which is worse than the\n // problem this exists to solve.\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 socket.destroy() gives the client ECONNRESET\n // with nothing naming the cap — right for an attacker, wrong for a\n // legitimate client the first time a tool payload crosses the limit.\n // Attempt a 413 with a JSON-RPC error body first, then destroy once it\n // has actually flushed. If the adapter already started writing its own\n // response, headersSent is true and there is nothing left to say —\n // just destroy. Never read the rest of the oversized body to be polite\n // about it; that defeats the point of the cap.\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 // `.end()`'s callback fires once the write is handed to the OS,\n // not once the peer has actually received it, so even a\n // best-effort destroy afterward can occasionally race a\n // still-in-flight response and truncate it (the client sees a\n // bare ECONNRESET instead of the 413 body). That is an accepted\n // trade — see \"attempt\" in the comment above — over leaving the\n // read side open, which would undo the whole point of this cap\n // (an attacker's still-arriving bytes must not keep flowing to\n // whatever is reading `req`).\n res.end(body, () => socket.destroy());\n return;\n } catch {\n // Fall through to a bare destroy below — e.g. the socket was\n // already gone by the time we tried to write.\n }\n }\n socket.destroy();\n }\n };\n const stop = (): void => {\n if (stopped) return;\n stopped = true;\n // A keep-alive connection carries many requests, and this function adds\n // a 'close' listener per request. Removing only the 'data' listener here\n // would leave the 'close' one to pile up, one per request, until the\n // connection finally closed (MaxListenersExceeded at request 11). Remove\n // both.\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: describeError(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: describeError(error) }, 'Protocol adapter failed to stop cleanly');\n }\n }\n}\n\nfunction describeError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Public (secret-free) projection of a `CommerceResource`.\n *\n * `handler.headers` may carry resolved backend secrets (e.g. an\n * `Authorization` value built from `${API_KEY}`) — never expose it on a\n * public discovery surface (`GET /api/resources`, `.well-known`).\n */\nimport type { CommerceResource } from '../core/index.js';\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` readiness computation: 503 unless the store, every configured\n * protocol adapter, every payment provider AND every authorization provider\n * are healthy. `status: 'warn'` is treated as still-serving (degraded); only\n * `status: 'fail'` blocks readiness — applied uniformly to all four kinds of\n * dependency.\n *\n * Payment providers are consulted here alongside the store and protocol\n * adapters: without that, a gateway whose x402 RPC is unreachable reports\n * `ready: true` and goes on serving 402 challenges it cannot honour. `fail`, not `warn`, blocks readiness for a provider — same\n * threshold as the store and adapters, not a special case: a broken payment\n * provider is not \"degraded but serving\", it is a broken core promise for\n * every resource that requires payment, exactly like a store that cannot\n * record or a required adapter that cannot route.\n *\n * The raw `detail` a store/adapter/provider health() implementation\n * returns (or a raw thrown Error's message) is exactly the kind of internal\n * detail exists to keep off a client-visible field — and this is an\n * unauthenticated route. The client only ever sees one of a small fixed\n * vocabulary; the raw detail is logged for the operator.\n *\n * `/ready` is itself unauthenticated, with no cache and no rate\n * limit, and `checkReadiness` calls every dependency's `health()` fresh on\n * every request — on a commercial RPC provider that is a live, billed\n * upstream call an attacker spends for free (measured: 20 requests -> 60\n * upstream JSON-RPC calls). `createReadinessProbe` memoises the result for\n * READINESS_TTL_MS and collapses concurrent callers onto one in-flight\n * evaluation, so a burst of N requests produces at most one real check.\n */\nimport type {\n AdapterHealth,\n AuthorizationProvider,\n Clock,\n Logger,\n PaymentProvider,\n ReceiptStore,\n} from '../core/index.js';\nimport { type AdapterRuntime, getAdapterHealth } from './adapters.js';\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\nconst STORE_DETAIL: Readonly<Record<AdapterHealth['status'], string | undefined>> = {\n pass: undefined,\n warn: 'store-degraded',\n fail: 'store-unwritable',\n};\n\nconst ADAPTER_DETAIL: Readonly<Record<AdapterHealth['status'], string | undefined>> = {\n pass: undefined,\n warn: 'adapter-degraded',\n fail: 'adapter-unreachable',\n};\n\nconst PAYMENT_PROVIDER_DETAIL: Readonly<Record<AdapterHealth['status'], string | undefined>> = {\n pass: undefined,\n warn: 'payment-provider-degraded',\n fail: 'payment-provider-unreachable',\n};\n\nconst AUTHORIZATION_PROVIDER_DETAIL: Readonly<Record<AdapterHealth['status'], string | undefined>> =\n {\n pass: undefined,\n warn: 'authorization-provider-degraded',\n fail: 'authorization-provider-unreachable',\n };\n\n/**\n * One probe for both provider kinds. A provider whose `health()` throws told us\n * nothing, so it counts as failing rather than as absent, and only the fixed\n * vocabulary above reaches the client.\n */\nasync function probeProvider(\n provider: { readonly name: string; health(): Promise<AdapterHealth> },\n kind: string,\n details: Readonly<Record<AdapterHealth['status'], string | undefined>>,\n options: Pick<CheckReadinessOptions, 'clock' | 'logger'>,\n): Promise<ReadinessCheck> {\n let health: AdapterHealth;\n try {\n health = await provider.health();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n options.logger.error({ err: message, provider: provider.name }, `${kind} health() threw`);\n health = { status: 'fail', checkedAt: options.clock.nowIso() };\n }\n if (health.detail !== undefined) {\n options.logger.debug(\n { provider: provider.name, detail: health.detail },\n `${kind} health detail (not sent to the client)`,\n );\n }\n const detail = details[health.status];\n return {\n name: provider.name,\n status: health.status,\n ...(detail !== undefined ? { detail } : {}),\n };\n}\n\nexport async function checkReadiness(options: CheckReadinessOptions): Promise<ReadinessResult> {\n let storeHealth: AdapterHealth;\n let storeThrew = false;\n try {\n storeHealth = await options.store.health();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n options.logger.error({ err: message }, 'store.health() threw');\n storeHealth = { status: 'fail', checkedAt: options.clock.nowIso() };\n storeThrew = true;\n }\n if (storeHealth.detail !== undefined) {\n options.logger.debug(\n { detail: storeHealth.detail },\n 'store health detail (not sent to the client)',\n );\n }\n\n const adapterChecks = await Promise.all(\n options.adapterRuntimes.map(async (runtime): Promise<ReadinessCheck> => {\n const health = await getAdapterHealth(runtime, options.clock);\n if (health.detail !== undefined) {\n options.logger.debug(\n { adapter: runtime.adapter.name, detail: health.detail },\n 'adapter health detail (not sent to the client)',\n );\n }\n const detail = ADAPTER_DETAIL[health.status];\n return {\n name: runtime.adapter.name,\n status: health.status,\n ...(detail !== undefined ? { detail } : {}),\n };\n }),\n );\n\n const paymentProviderChecks = await Promise.all(\n options.paymentProviders.map((provider) =>\n probeProvider(provider, 'payment provider', PAYMENT_PROVIDER_DETAIL, options),\n ),\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 honour\n const authorizationProviderChecks = await Promise.all(\n options.authorizationProviders.map((provider) =>\n probeProvider(provider, 'authorization provider', AUTHORIZATION_PROVIDER_DETAIL, options),\n ),\n );\n\n const storeReady = storeHealth.status !== 'fail';\n const adaptersReady = adapterChecks.every((check) => check.status !== 'fail');\n const paymentProvidersReady = paymentProviderChecks.every((check) => check.status !== 'fail');\n const authorizationProvidersReady = authorizationProviderChecks.every(\n (check) => check.status !== 'fail',\n );\n const storeDetail = storeThrew ? 'store-unreachable' : STORE_DETAIL[storeHealth.status];\n\n return {\n ready: storeReady && adaptersReady && paymentProvidersReady && authorizationProvidersReady,\n store: {\n name: 'store',\n status: storeHealth.status,\n ...(storeDetail !== undefined ? { detail: storeDetail } : {}),\n },\n adapters: adapterChecks,\n paymentProviders: paymentProviderChecks,\n authorizationProviders: authorizationProviderChecks,\n };\n}\n\n/** A readiness probe does not need sub-second freshness: a real outage is\n * still caught within one TTL window, and this is short enough that a burst\n * of requests during a genuine state change (e.g. right after startup) isn't\n * stuck looking at a stale answer for long. */\nexport const READINESS_TTL_MS = 2_000;\n\nexport interface ReadinessProbe {\n check(): Promise<ReadinessResult>;\n}\n\nexport function createReadinessProbe(\n options: CheckReadinessOptions,\n ttlMs: number = READINESS_TTL_MS,\n): ReadinessProbe {\n let cached: { readonly result: ReadinessResult; readonly at: number } | undefined;\n let inFlight: Promise<ReadinessResult> | undefined;\n\n return {\n async check(): Promise<ReadinessResult> {\n const now = options.clock.monotonicMs();\n if (cached && now - cached.at < ttlMs) return cached.result;\n if (inFlight) return inFlight;\n\n inFlight = checkReadiness(options)\n .then((result) => {\n cached = { result, at: options.clock.monotonicMs() };\n return result;\n })\n .finally(() => {\n inFlight = undefined;\n });\n return inFlight;\n },\n };\n}\n","/**\n * `GET /.well-known/agent-commerce` — merchant + every adapter/provider/store\n * `AdapterDescriptor`, protocol/spec versions. This route is unauthenticated\n * by design, so nothing here may be a credential.\n *\n * The x402 settlement destination (`payTo`), `network` and `asset` ARE\n * public information — a payer needs them (plus scheme/amount, which travel\n * in the challenge's `accepts` array) to construct a payment, and `payTo` is\n * visible on-chain the moment any transfer lands. `rpcUrl` is different and\n * is deliberately NOT published here: every commercial EVM RPC\n * provider embeds an API key in the URL itself (Alchemy's `/v2/<KEY>`,\n * Infura's `/v3/<KEY>`, QuickNode's per-endpoint token) — on any non-local\n * deployment, echoing it back on an open route hands out a live credential\n * to anyone who asks. The facilitator URL is withheld for the same reason,\n * and the facilitator private key never appears at all. `doctor`'s\n * live/local cross-check (src/cli) only reads `asset`/`network`/`payTo` from\n * this document, so dropping `rpcUrl` does not affect it.\n *\n * `WellKnownDocument` is also exported via the package's\n * `./well-known.js` subpath (non-frozen — see docs/contracts.md's change\n * log) so `demo/dashboard`'s hand-maintained mirror of this shape\n * (`types.ts`) can assert assignability against the real type instead of\n * silently drifting — which is exactly how it twice shipped `rpcUrl` as\n * non-optional after this file stopped sending it. Consuming this as\n * `import type` only is what keeps the dashboard's browser bundle free of\n * Fastify/pino/better-sqlite3: a type-only import is erased entirely by any\n * TypeScript-aware bundler (esbuild, swc, tsc), independent of whatever\n * runtime code this file also happens to export — the same property\n * `src/core`'s `./execution` subpath already relies on.\n */\n\nimport type { GatewayConfig } from '../config/index.js';\nimport type {\n AdapterDescriptor,\n AdapterHealth,\n AuthorizationProvider,\n Clock,\n PaymentProvider,\n ReceiptStore,\n} from '../core/index.js';\nimport {\n type DeploymentMode,\n requireNetworkProfile,\n resolveDeploymentMode,\n} from '../payments/x402/networks.js';\nimport { PACKAGE_VERSION } from '../version.js';\nimport { type AdapterRuntime, getAdapterHealth } from './adapters.js';\n\n/**\n * The spec version is deliberately NOT derived from `PACKAGE_VERSION`. It\n * names the wire contract a client negotiates against, which changes only\n * when that contract does — a patch release of this package speaks the same\n * spec, and announcing a new one on every version bump would tell every\n * client the protocol moved when it did not.\n */\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 a resource requires authorization. Listed separately from\n * `paymentProviders` because an authorization method is not a payment rail\n * 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 readonly assetName: string;\n readonly assetVersion: string;\n readonly assetDecimals: number;\n readonly payTo: string;\n readonly maxTimeoutSeconds: number;\n readonly facilitator: { readonly mode: 'local' | 'remote' };\n /** What this deployment actually is. */\n readonly mode: DeploymentMode;\n };\n };\n}\n\nexport interface BuildWellKnownOptions {\n readonly config: GatewayConfig;\n readonly paymentProviders: readonly PaymentProvider[];\n readonly authorizationProviders: readonly AuthorizationProvider[];\n readonly store: ReceiptStore;\n readonly adapterRuntimes: readonly AdapterRuntime[];\n readonly clock: Clock;\n}\n\n/**\n * Strips a health result down to what an anonymous caller may see.\n *\n * `/ready` already codifies this rule and maps `detail` to a fixed vocabulary,\n * because the raw string is exactly the internal detail an unauthenticated\n * route must not carry — `getAdapterHealth` puts `describeError()` there for a\n * thrown `health()`, and a start failure puts the raw throw message, routinely\n * a module path or an internal hostname. This route is the same trust level and\n * was returning it verbatim. `createGateway` is public API and accepts\n * arbitrary adapters, so \"our own adapters say nothing sensitive\" is not a\n * property this code can rely on.\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\nexport async function buildWellKnownDocument(\n options: BuildWellKnownOptions,\n): Promise<WellKnownDocument> {\n const adapters = await Promise.all(\n options.adapterRuntimes.map(async (runtime) => {\n const health = await getAdapterHealth(runtime, options.clock);\n return { ...runtime.adapter.descriptor, health: publicHealth(health) };\n }),\n );\n\n const x402 = options.config.payments.x402;\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 assetName: x402.assetName,\n assetVersion: x402.assetVersion,\n assetDecimals: x402.assetDecimals,\n payTo: x402.payTo,\n maxTimeoutSeconds: x402.maxTimeoutSeconds,\n // Never the signerPrivateKey, and never the facilitator URL:\n // a facilitator endpoint is a per-deployment operational detail\n // that can carry a tenant path or an API key, exactly like\n // `rpcUrl` above. Only whether it is local or remote is public.\n facilitator: { mode: x402.facilitator.mode },\n // Chain id 84532 is shared between the local dev chain and\n // public Base Sepolia, so the network id alone cannot say which\n // one a client is talking to. This can.\n mode: resolveDeploymentMode(\n requireNetworkProfile(x402.network, 'payments.x402.network'),\n x402.facilitator.mode,\n ),\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 type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';\nimport type { GatewayConfig } from '../config/index.js';\nimport type { EventBus } from '../core/execution/index.js';\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 PaymentProvider,\n parseAuthorizationHeader,\n type ReceiptStore,\n type ResourceRegistry,\n toCommerceError,\n toErrorEnvelope,\n toPaymentRequiredEnvelope,\n} from '../core/index.js';\nimport { buildOperatorTokenHook } from './access-control.js';\nimport type { AdapterRuntime } from './adapters.js';\nimport { toPublicResource } from './public-resource.js';\nimport { createReadinessProbe } from './readiness.js';\nimport { buildWellKnownDocument } from './well-known.js';\n\nconst SSE_HEARTBEAT_MS = 15_000;\nconst MAX_SSE_SUBSCRIBERS = 32;\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 eventBus: EventBus;\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 // memoised + single-flight — see readiness.ts's own doc comment.\n // `options.adapterRuntimes` is mutated in place (pushed into) after\n // adapters start, so capturing the reference here is fine — the probe\n // always reads whatever it currently holds.\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 adapterRuntimes: options.adapterRuntimes,\n clock: options.clock,\n }),\n );\n\n server.get('/api/resources', async () => ({\n resources: options.resources.list().map(toPublicResource),\n }));\n\n server.post('/api/resources/:id/invoke', async (request, reply) => {\n await handleInvoke(request, reply, options);\n });\n\n // The admin-token gate is a per-route hook on each of these three\n // route definitions (not the global onRequest hook) — see\n // access-control.ts's file header for why. Fastify only invokes it once\n // routing has matched this exact route, so there is no percent-encoded\n // path string left for an attacker to disagree with the router about.\n const receiptsTokenHook = buildOperatorTokenHook(options.config.server.adminToken);\n const eventsTokenHook = buildOperatorTokenHook(options.config.server.adminToken);\n const eventsStreamTokenHook = buildOperatorTokenHook(options.config.server.adminToken);\n\n server.get('/api/receipts', { onRequest: receiptsTokenHook }, async (request, reply) => {\n try {\n const limit = parseLimit((request.query as Record<string, unknown>)['limit']);\n return { receipts: await options.store.listReceipts(limit !== undefined ? { limit } : {}) };\n } catch (error) {\n const commerceError = toCommerceError(error);\n reply.status(commerceError.httpStatus).send(toErrorEnvelope(commerceError));\n return undefined;\n }\n });\n\n server.get('/api/events', { onRequest: eventsTokenHook }, async (request, reply) => {\n try {\n const limit = parseLimit((request.query as Record<string, unknown>)['limit']);\n return { events: await options.store.listEvents(limit !== undefined ? { limit } : {}) };\n } catch (error) {\n const commerceError = toCommerceError(error);\n reply.status(commerceError.httpStatus).send(toErrorEnvelope(commerceError));\n return undefined;\n }\n });\n\n let activeSseSubscribers = 0;\n\n server.get('/api/events/stream', { onRequest: eventsStreamTokenHook }, (request, reply) => {\n // cap concurrent subscribers — the token hook above already\n // rejects an unauthenticated client before this handler runs; this cap\n // is about an *authenticated* client that never reads, which would\n // otherwise let Node buffer indefinitely, N times over.\n if (activeSseSubscribers >= MAX_SSE_SUBSCRIBERS) {\n reply.status(503).send({\n status: 'error',\n code: 'UNAVAILABLE',\n message: 'Too many event-stream subscribers',\n });\n return;\n }\n reply.raw.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n });\n // Increment only after writeHead succeeds: if it threw, cleanup() below\n // was never registered, and incrementing first would leak the slot\n // permanently (after MAX_SSE_SUBSCRIBERS such leaks, the route is dead).\n activeSseSubscribers += 1;\n reply.raw.write(': connected\\n\\n');\n\n // Backpressure: write() returning false means the socket buffer\n // is full. Drop frames — not queue them — until 'drain'; an SSE feed is\n // \"latest state\", not a guaranteed-delivery log, and queuing unboundedly\n // is the exact memory-growth problem this is meant to avoid.\n let writable = true;\n reply.raw.on('drain', () => {\n writable = true;\n });\n\n // no `event:` line — the dashboard's EventSource only listens for\n // the default `message` type, and a named event never reaches onmessage\n // (onopen still fires, so the client reports \"live\" over a frozen feed).\n // `data:` already carries `type` in the serialised payload.\n //\n // queueMicrotask decouples fan-out from the caller: EventBus#emit() is\n // awaited inside the execution pipeline, so writing synchronously here\n // would add a slow SSE reader's latency to the payment path.\n const unsubscribe = options.eventBus.subscribe((event) => {\n queueMicrotask(() => {\n if (!writable) return;\n writable = reply.raw.write(`data: ${JSON.stringify(event)}\\n\\n`);\n });\n });\n\n const heartbeat = setInterval(() => {\n if (!writable) return;\n writable = reply.raw.write(': heartbeat\\n\\n');\n }, SSE_HEARTBEAT_MS);\n heartbeat.unref();\n\n // Guards against a double-decrement if both 'close' and 'error' fire for\n // the same connection (never actually observed — 40 connect/destroy\n // cycles could not trigger it — but the guard is one line and removes\n // the question).\n let cleanedUp = false;\n const cleanup = (): void => {\n if (cleanedUp) return;\n cleanedUp = true;\n clearInterval(heartbeat);\n unsubscribe();\n activeSseSubscribers -= 1;\n };\n request.raw.on('close', cleanup);\n reply.raw.on('error', cleanup);\n\n reply.hijack();\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\n try {\n const resource = options.resources.get(resourceId);\n if (!resource || !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 const paymentHeader = request.headers[PAYMENT_HEADER];\n const paymentValue = Array.isArray(paymentHeader) ? paymentHeader[0] : paymentHeader;\n\n // The gateway does not decide which rail a resource uses — that's the\n // canonical resource's job (mirrors the protocol-side fix in the MCP\n // adapter). Derive the method from resource.paymentMethods instead of\n // hard-coding 'x402'. If a proof arrives for a resource with no payment\n // method configured, drop it rather than inventing a rail: the pipeline\n // will treat the resource as free (or reject it) on its own terms.\n const paymentMethod = resource.paymentMethods[0];\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 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 };\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.envelope !== undefined) {\n // x402 v2 clients read the challenge from this header and never look\n // at the body. The body is still sent — it is richer, and it is the\n // only channel the MCP surface has — but the header is what makes an\n // off-the-shelf client able to pay.\n reply.header(PAYMENT_REQUIRED_HEADER, encodeHeaderDocument(envelope.payment.envelope));\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 reply.status(402).send(envelope);\n return;\n }\n\n if (outcome.payment) {\n reply.header(PAYMENT_RESPONSE_HEADER, encodePaymentSummary(outcome.payment));\n }\n reply.status(outcome.backendStatus).send(outcome.body);\n } catch (error) {\n const commerceError = toCommerceError(error);\n // a backend failure after successful settlement carries the\n // settlement summary on details.payment (pipeline.ts) — set the same\n // header the success path sets, so the buyer isn't told strictly less\n // about their own payment on the error path than on the happy path.\n const settledPayment = errorPaymentSummary(commerceError);\n if (settledPayment !== undefined) {\n reply.header(PAYMENT_RESPONSE_HEADER, encodePaymentSummary(settledPayment));\n }\n reply.status(commerceError.httpStatus).send(toErrorEnvelope(commerceError));\n }\n}\n\ninterface PaymentSummary {\n readonly status: string;\n readonly provider: string;\n readonly amount: string;\n readonly currency: string;\n readonly network?: string;\n readonly externalReference?: string;\n}\n\nfunction errorPaymentSummary(\n error: ReturnType<typeof toCommerceError>,\n): PaymentSummary | undefined {\n const payment = error.details?.['payment'];\n if (typeof payment !== 'object' || payment === null) return undefined;\n const rec = payment as Record<string, unknown>;\n const { status, provider, amount, currency, network, externalReference } = rec;\n if (\n typeof status !== 'string' ||\n typeof provider !== 'string' ||\n typeof amount !== 'string' ||\n typeof currency !== 'string'\n ) {\n return undefined;\n }\n return {\n status,\n provider,\n amount,\n currency,\n ...(typeof network === 'string' ? { network } : {}),\n ...(typeof externalReference === 'string' ? { externalReference } : {}),\n };\n}\n\n/**\n * Base64 of a JSON document, the encoding every x402 v2 payment header uses.\n *\n * Hand-rolled rather than imported from the x402 SDK on purpose: this module\n * is reachable from the package's main entry point, which must import zero\n * optional peers, and it is two lines.\n */\nfunction encodeHeaderDocument(document: unknown): string {\n return Buffer.from(JSON.stringify(document), 'utf8').toString('base64');\n}\n\n/**\n * The settlement result, in the shape an x402 v2 client decodes from\n * `PAYMENT-RESPONSE` (`SettleResponse`), mapped from the canonical\n * {@link PaymentResult} the pipeline produced.\n *\n * `provider`, `amount` and `currency` are ours and are additive: a v2 client\n * reads the fields it knows and ignores the rest.\n */\nfunction encodePaymentSummary(payment: PaymentSummary): string {\n return encodeHeaderDocument({\n success: payment.status === 'settled',\n transaction: payment.externalReference ?? '',\n network: payment.network ?? '',\n status: payment.status,\n provider: payment.provider,\n amount: payment.amount,\n currency: payment.currency,\n ...(payment.externalReference !== undefined\n ? { externalReference: payment.externalReference }\n : {}),\n });\n}\n\n/** Undefined = no limit given / unparseable (caller applies its own default). A\n * parseable but non-positive value (SQLite treats a negative LIMIT as\n * unbounded) is a caller error, not silently \"no limit\". */\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","/**\n * `createGateway()` — the Fastify server. Fully usable (and tested) with\n * fakes, without `main.ts` (docs/contracts.md \"Composition root\").\n */\n\nimport Fastify, { type FastifyInstance } from 'fastify';\nimport type { GatewayConfig } from '../config/index.js';\nimport {\n createEventBus,\n createExecutionPipeline,\n createResourceRegistry,\n HttpBackendExecutor,\n} from '../core/execution/index.js';\nimport {\n type AuthorizationProvider,\n type BackendExecutor,\n type Clock,\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/index.js';\nimport { buildAccessControlHook } from './access-control.js';\nimport {\n type AdapterRuntime,\n MOUNT_BODY_LIMIT_BYTES,\n startAndMountAdapters,\n stopAdapters,\n} from './adapters.js';\nimport { createDefaultIdGenerator } from './ids.js';\nimport { buildNotFoundHandler, createGatewayLogger, fastifyLoggerOptions } from './logger.js';\nimport { registerRoutes } from './routes.js';\n\nconst REQUEST_ID_HEADER = 'x-request-id';\n// an unvalidated caller-supplied id becomes the audit trail's\n// correlation key — a caller could reuse a legitimate flow's id to conflate\n// records, or write an unbounded string into every row. A client id is only\n// accepted in this constrained form; anything else gets a gateway-minted one.\nconst CLIENT_REQUEST_ID_PATTERN = /^[A-Za-z0-9._:-]{1,64}$/;\n\nexport interface GatewayOptions {\n readonly config: GatewayConfig;\n readonly store: ReceiptStore;\n readonly paymentProviders: readonly PaymentProvider[];\n /** Absent means no resource requires authorization, which is the default */\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\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(options.config.resources);\n const eventBus = createEventBus({ store: options.store, logger });\n const pipeline = createExecutionPipeline({\n resources,\n paymentProviders: options.paymentProviders,\n authorizationProviders,\n store: options.store,\n backend,\n events: eventBus,\n logger,\n clock,\n ids,\n });\n\n const server = Fastify({\n // One number for both surfaces — see adapters.ts's doc comment\n // on MOUNT_BODY_LIMIT_BYTES for why they're enforced two different ways.\n bodyLimit: MOUNT_BODY_LIMIT_BYTES,\n genReqId: (rawReq) => {\n const header = rawReq.headers[REQUEST_ID_HEADER];\n const value = Array.isArray(header) ? header[0] : header;\n return value !== undefined && CLIENT_REQUEST_ID_PATTERN.test(value) ? value : ids.next('req');\n },\n logger: fastifyLoggerOptions({ name: `${options.config.merchant.id}-http` }),\n });\n\n // See buildNotFoundHandler's own doc comment (logger.ts) — this\n // is what leaked the SSE ?adminToken= query param at info level on any 404\n // (a typo'd route, even a trailing slash on a real one).\n server.setNotFoundHandler(buildNotFoundHandler());\n\n // Host/Origin/admin-token gate — see access-control.ts. Closed by default:\n // no allowedOrigins means no browser can read anything cross-origin, and no\n // adminToken means the ledger routes 404 rather than serving openly.\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 eventBus,\n clock,\n adapterRuntimes,\n logger,\n });\n\n const context: ProtocolAdapterContext = {\n pipeline,\n resources,\n events: eventBus,\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 * ACP checkout operation -> canonical request.\n *\n * Each operation maps to exactly one configured resource and one deterministic\n * input envelope, matching `ACP_OPERATION_INPUT_KEYS`: `path` carries\n * `checkout_session_id`, `body` carries the validated ACP document.\n *\n * What is deliberately absent: any synthesis of a payment field. ACP\n * `payment_data` on completion is the merchant's own purchase payment and\n * stays inside `body` as ordinary business input. Turning it into a\n * `PaymentSubmission` would stack a gateway payment on top of the merchant's\n * one, for a single call.\n */\nimport type { CanonicalRequest } from '../../core/index.js';\nimport { ACP_OPERATION_INPUT_KEYS } from './constants.js';\nimport type { AcpGuardedRequest } from './request-guards.js';\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 };\n}\n\nfunction canonicalInput(request: AcpGuardedRequest): Record<string, unknown> {\n const keys = ACP_OPERATION_INPUT_KEYS[request.route.operation];\n const input: Record<string, unknown> = {};\n\n if (keys.includes('path') && request.route.sessionId !== undefined) {\n input['path'] = { checkout_session_id: request.route.sessionId };\n }\n if (keys.includes('body')) {\n input['body'] = request.body;\n } else if (request.route.acceptsBody && Object.keys(request.body).length > 0) {\n // Cancel: the pinned schema requires no body, so resources are not asked to\n // declare one - but a caller that did send `intent_trace` meant it, and\n // silently dropping it would lose the only thing the request carried.\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` and stays that way until the unsupported list below\n * shrinks on purpose rather than by omission.\n */\nimport type { AdapterDescriptor } from '../../core/index.js';\nimport { ACP_CHECKOUT_OPERATIONS, ACP_SPEC_VERSION } from './constants.js';\n\n/** What this adapter actually implements. */\nexport const ACP_CAPABILITIES: readonly string[] = [\n 'rest transport',\n 'well-known discovery',\n 'bearer authentication',\n 'API-Version negotiation',\n 'checkout service',\n ...ACP_CHECKOUT_OPERATIONS,\n];\n\n/**\n * Everything an ACP client may reasonably expect and will not get here.\n * Complete on purpose: a short list reads as \"mostly compatible\", which is\n * exactly the blanket claim alpha honesty forbids. `doctor` and\n * `/.well-known/agent-commerce` surface this verbatim.\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 and versioning.\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 exactly what this adapter implements: one transport, one\n * service, one API version. Optional metadata appears only when an operator\n * configured it - in particular currencies are never inferred from the\n * gateway's x402 configuration, which is a different payment domain entirely.\n *\n * Nothing derived from a secret goes in here: the document is public and\n * unauthenticated, so bearer token, backend URLs, resource mapping ids and the\n * idempotency database location all stay out by construction - they are not\n * inputs to this function.\n */\nimport { ACP_SPEC_VERSION } from './constants.js';\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 // Only the REST binding. ACP's MCP transport is its own fixed checkout\n // binding and is not the generic MCP adapter this gateway also serves;\n // advertising it here because \"we do MCP\" would be a false claim.\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\nfunction joinUrl(baseUrl: string, mountPath: string): string {\n return `${baseUrl.replace(/\\/+$/, '')}/${mountPath.replace(/^\\/+|\\/+$/g, '')}`;\n}\n","/**\n * The ACP `Error` object, and the one writer every ACP response goes through.\n *\n * Centralised so no handler can invent its own error shape, and so the rule\n * that nothing internal reaches a client - no stack, no backend body, no Ajv\n * message, no token, no path - is enforced in one place instead of at a dozen\n * call sites.\n */\nimport type { ServerResponse } from 'node:http';\nimport { ACP_JSON_MEDIA_TYPE } from './constants.js';\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}\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 is allowed to set. Merchant backend headers are\n * never proxied - a `Set-Cookie` or a tracing header from a backend belongs to\n * the merchant's own domain, not to the ACP client.\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 * Identity and request fingerprints for ACP idempotency.\n *\n * The fingerprint is taken over the *parsed* JSON value, not the raw bytes: a\n * client that retries the same request through a different JSON serializer\n * (different key order, `1.0` where it first sent `1`, whitespace) is retrying,\n * not conflicting, and answering it with a 422 would be wrong. The distinctions\n * that do matter are kept: array order, `null` versus an absent property, and\n * type - `1` and `\"1\"` are different requests.\n */\nimport { createHash } from 'node:crypto';\n\n/**\n * The name the merchant sees for one checkout operation.\n *\n * Derived from the same scope that claims the key locally - deployment,\n * endpoint and the caller's key - so it is identical across a client retry, a\n * network retry, a gateway restart and a credential rotation.\n *\n * Hashed rather than forwarded raw because the caller's key alone does not\n * name an operation. ACP scopes it per endpoint, so one client may\n * legitimately send `Idempotency-Key: 1` to both create and complete, and a\n * merchant keying state on the raw value would read those as one operation.\n * The digest folds the whole scope into the one header ACP gives us.\n *\n * What it does *not* do is separate two clients that picked the same key.\n * They share a deployment and an endpoint, so they share a derived key, and\n * they already share a row in the local claim store for the same reason. ACP\n * makes key uniqueness the client's responsibility, and nothing here can fix\n * that for them.\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 and limited to\n * what `JSON.parse` can produce - no dependency for what is twenty lines.\n *\n * Object keys are sorted by UTF-16 code unit, exactly as `Array.prototype.sort`\n * orders them, so two orderings of the same object canonicalize identically.\n * Numbers go through `JSON.stringify`, which already normalises `1.0`, `1e2`\n * and `100` to one shortest round-trip form.\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 // `undefined` cannot come from JSON.parse, but a caller could hand us an\n // object literal; dropping those keys keeps \"absent\" and \"absent\" equal.\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. `JSON.stringify` never returns undefined\n // for these, and the types stay distinct because their encodings do.\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.\n *\n * Its own table in its own database file: this is protocol replay semantics for\n * a merchant checkout, and it has nothing to do with the x402 payment replay\n * defence in the receipt store. Sharing a table would tie two unrelated\n * lifetimes and two unrelated retention policies together.\n *\n * The reservation is what makes it safe. A key is claimed atomically *before*\n * the side effect starts, so a second request carrying the same key finds the\n * claim rather than starting a second checkout.\n *\n * What this cannot do: a merchant side effect over HTTP and a local SQLite\n * commit are not one transaction. If the process dies after the merchant\n * completed an order but before the response was stored, the row stays\n * `in_flight` and every retry of that key is refused - deliberately, because\n * re-running a completion whose remote state is unknown risks charging a\n * buyer twice. The third state, `unresolved`, is the same reasoning applied\n * to an attempt that reached the merchant and came back as a timeout, a 5xx\n * or a document we could not read. None of those say nothing happened, so\n * the claim is kept rather than freed for a retry that could order twice.\n *\n * Only a `completed` row expires. An unresolved one is the record that a\n * duplicate is possible, so a retention sweep deleting it would hand the next\n * retry a clean key and re-create the problem the state exists to prevent.\n * Clearing one is an operator's decision, taken against the merchant's own\n * records.\n *\n * Merchant-side idempotency on destructive operations is still strongly\n * recommended; this store does not make the merchant's API exactly-once.\n */\nimport type { Database } from 'better-sqlite3';\nimport { type Logger, NOOP_LOGGER } from '../../../core/index.js';\nimport { openSqliteDatabase } from '../../../storage/sqlite.js';\n\n/**\n * v2 replaced the bearer-token digest in the primary key with the deployment's\n * public base URL. See `migrate`: the upgrade discards v1 rows rather than\n * translating keys it cannot translate.\n */\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.\n *\n * Not a digest of the bearer token, which this was until a rotation turned\n * out to free every claim: a new token is a new key, so a retry finds no\n * row, reserves a fresh one, and re-runs an operation whose outcome may\n * already be unknown. A credential must not be able to do that. The base\n * URL survives rotation, is already configuration, and still separates two\n * gateways fronting the same merchant backend.\n *\n * It is not a secret and is stored as-is, so an operator reading an\n * unresolved row can see which deployment produced it.\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 and we cannot\n * say. Later retries are refused rather than replayed or re-run.\n */\n markUnresolved(scope: AcpIdempotencyScope): void;\n /**\n * Drop the claim so a clean retry can run.\n *\n * Only for an attempt that provably never reached the merchant. Calling it\n * after an ambiguous failure is what lets one operation happen twice.\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 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\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 // `state = 'completed'` is the whole point: a row holding an unknown\n // merchant outcome outlives retention, because to the next retry, deleting\n // it looks exactly like the operation never having happened\n const expireStmt = db.prepare(\n \"DELETE FROM acp_idempotency WHERE expires_at <= ? AND state = 'completed'\",\n );\n\n /**\n * Lazy cleanup, on the same connection and inside the claim transaction: a\n * background worker would be a second moving part for something a request\n * already has to touch.\n */\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 request is a conflict\n // whether or not the first one has finished. Reporting \"in flight\" there\n // would invite a retry that can only ever 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/**\n * `PRAGMA user_version` as the migration marker, so reopening an existing file\n * is a fast no-op check rather than a re-create.\n */\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 every row by a digest of the bearer token. Those keys cannot\n // be translated forward: the digest is one-way, and what it stood for\n // was the credential, not the deployment. So the table is rebuilt empty\n // - the one time orphaning a claim is right, because leaving rows that\n // nothing will ever match again is worse than saying they are gone.\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 * Bearer authentication for the ACP checkout endpoints.\n *\n * Bearer is the only scheme this release accepts (config refuses any other),\n * discovery stays public, and a `Signature` header is never allowed to stand\n * in for the token - signature verification is not implemented and not\n * advertised, so treating one as authentication would be an unauthenticated\n * checkout endpoint dressed as a secure one.\n */\nimport { createHash, timingSafeEqual } from 'node:crypto';\n\nconst BEARER_PREFIX = /^Bearer +/i;\n\n/**\n * Constant-time comparison of the presented token against the configured one.\n *\n * Both sides are hashed first: `timingSafeEqual` throws on a length mismatch,\n * and comparing raw tokens would leak the configured length through that throw\n * (and through the early return that avoiding it invites). Digests are always\n * 32 bytes, so every wrong token costs exactly the same.\n */\nexport function isAuthorizedBearer(header: string | undefined, expectedToken: string): boolean {\n if (header === undefined) return false;\n if (!BEARER_PREFIX.test(header)) return false;\n const presented = header.replace(BEARER_PREFIX, '');\n if (presented.length === 0) return false;\n return timingSafeEqual(sha256(presented), sha256(expectedToken));\n}\n\nfunction sha256(value: string): Buffer {\n return createHash('sha256').update(value, 'utf8').digest();\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.js';\n\n/** Longest accepted `checkout_session_id`. Merchant ids are short; this bounds what a caller can send. */\nconst MAX_SESSION_ID_LENGTH = 128;\n\n/** ACP session ids are opaque, but they are path segments and go into canonical input. */\nconst SESSION_ID_PATTERN = /^[A-Za-z0-9._~-]{1,128}$/;\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 || !SESSION_ID_PATTERN.test(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\nfunction endpointPath(mountPath: string, segments: readonly string[]): string {\n return `${mountPath.replace(/\\/+$/, '')}/${segments.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_SESSION_ID_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 request and response bodies are far larger than the JSON-Schema subset\n * `src/core/execution` validates canonical input with, so the pinned official\n * schema is compiled with Ajv rather than restated by hand: a hand-written\n * copy is a second definition of the protocol, and it drifts.\n *\n * The schema is *imported*, not read from disk. `dist/` collapses `src/**`\n * into two bundled files, so a relative `readFileSync` resolves from the wrong\n * depth once built - a failure this repository has shipped twice.\n */\n\nimport type { ErrorObject, ValidateFunction } from 'ajv';\nimport Ajv2020 from 'ajv/dist/2020.js';\nimport addFormats from 'ajv-formats';\nimport { CommerceError } from '../../core/index.js';\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, by the role it uses\n * them in. Keys are ours; values are the exact names in the released snapshot,\n * and a typo in one is caught at first use rather than at first 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/**\n * Compiled once for the process, on first use rather than at import: a gateway\n * with ACP disabled never pays for it, and the cost is the same either way for\n * one that has it on.\n */\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: annotations we do not know\n // are the spec's business, not a reason to refuse to start.\n strict: false,\n // One failure is all that leaves the adapter, and collecting every error\n // in a deeply nested cart is work an unauthenticated caller could ask for\n // repeatedly.\n allErrors: false,\n });\n addFormats(ajv);\n\n const document = relaxExtensibleEnums(structuredClone(schemaDocument)) as Record<string, unknown>;\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 few fields the snapshot itself marks as\n * extensible (\"servers SHOULD accept unrecognized values and treat them as\n * 'other'\", and \"validators SHOULD be configured for lenient enum handling\").\n *\n * Only fields carrying that wording are relaxed. The enums ACP calls closed\n * per API version stay closed - the point is not to be permissive, it is to\n * avoid refusing, say, a cancel because of an analytics reason code the buyer's\n * agent knows about 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 * Validates one ACP document against a released definition.\n *\n * Returns `undefined` when the value conforms, otherwise the first failure.\n * Inbound, that failure becomes a 400 and no pipeline call happens; outbound,\n * it means the merchant backend returned something that is not ACP, and the\n * body must not be 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, rendered as the `$.a.b[0]` form ACP errors use in\n * `param`. `required` and `additionalProperties` failures report the parent\n * object, so the offending key is appended - the difference between telling a\n * client `$` and telling it `$.buyer.email`.\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.\n *\n * The sequence is fixed and fails closed at the first step that does not hold:\n * route -> bearer auth -> API-Version -> content type -> body size -> JSON ->\n * ACP request schema. Nothing below this file runs for a request that fails\n * any of them, which is what makes \"no pipeline call on a guard failure\"\n * checkable rather than a claim.\n */\nimport type { IncomingMessage } from 'node:http';\nimport { isAuthorizedBearer } from './auth.js';\nimport {\n ACP_API_VERSION,\n ACP_API_VERSION_HEADER,\n ACP_IDEMPOTENCY_KEY_HEADER,\n ACP_MAX_REQUEST_ID_LENGTH,\n ACP_REQUEST_ID_HEADER,\n} from './constants.js';\nimport { type AcpFailure, acpFailure } from './errors.js';\nimport { ACP_MAX_IDEMPOTENCY_KEY_LENGTH } from './idempotency/store.js';\nimport { type AcpRouteMatch, matchAcpRoute } from './router.js';\nimport { type AcpDefinition, validateAcpDocument } from './validation.js';\n\n/**\n * A second line behind the gateway mount's own cap, so this adapter bounds\n * what it buffers even if it is ever mounted without that guard.\n */\nexport const 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: ACP makes it mandatory there. */\n readonly idempotencyKey?: string;\n}\n\nexport type AcpGuardResult =\n | { readonly ok: true; readonly value: AcpGuardedRequest }\n | ({ readonly ok: false } & AcpFailure);\n\nexport interface AcpGuardOptions {\n readonly mountPath: string;\n readonly token: string;\n readonly maxBodyBytes?: number;\n}\n\nexport async function guardAcpRequest(\n req: IncomingMessage,\n options: AcpGuardOptions,\n): Promise<AcpGuardResult> {\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 );\n }\n const route = matched.route;\n\n // Before anything reads a body: an unauthenticated caller must not be able\n // to make this adapter buffer or parse.\n if (!isAuthorizedBearer(header(req, 'authorization'), options.token)) {\n return failed(\n acpFailure(\n 401,\n 'invalid_request',\n 'unauthorized',\n 'A valid \"Authorization: Bearer <token>\" header is required.',\n ),\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 are the same answer: this deployment serves one contract.\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 // Header-level and cheap, so it runs before a byte of body is read: a POST\n // without a usable key can never be executed, and reading its body first\n // would be work an authenticated client could ask for at will.\n let idempotencyKey: string | undefined;\n if (route.acceptsBody) {\n const presented = header(req, ACP_IDEMPOTENCY_KEY_HEADER)?.trim();\n if (presented === undefined || presented.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 visible-ASCII for the same reason as Request-Id: the key is\n // echoed back in a response header, so a CRLF in it is a response-splitting\n // attempt rather than a key.\n if (presented.length > ACP_MAX_IDEMPOTENCY_KEY_LENGTH || !isVisibleAscii(presented)) {\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 = presented;\n }\n\n const read = await readBody(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 rather than 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 pinned schema then\n // accepts (cancel) 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 caller's own pointer travels; the Ajv message stays here.\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 },\n };\n}\n\nfunction failed(failure: AcpFailure): AcpGuardResult {\n return { ok: false, ...failure };\n}\n\n/**\n * The caller's correlation id, echoed back but never used as the gateway's own\n * request identity. It is attacker-controlled text on its way into a response\n * header, so it is bounded and reduced to visible ASCII - a newline in there is\n * a response-splitting attempt, not a correlation id.\n */\nexport function 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/**\n * Reads the unconsumed request stream the gateway hands over, stopping at the\n * cap rather than buffering whatever arrives.\n */\nasync function readBody(req: IncomingMessage, maxBytes: number): Promise<BodyRead> {\n const chunks: Buffer[] = [];\n let total = 0;\n try {\n for await (const chunk of req) {\n const buffer = chunk as Buffer;\n total += buffer.length;\n if (total > maxBytes) return { kind: 'too-large' };\n chunks.push(buffer);\n }\n } catch {\n return { kind: 'unreadable' };\n }\n return { kind: 'ok', text: Buffer.concat(chunks).toString('utf8') };\n}\n\n/** A result object, not a sentinel string: a body whose text *is* \"too-large\" is a body. */\ntype BodyRead =\n | { readonly kind: 'ok'; readonly text: string }\n | { readonly kind: 'too-large' }\n | { readonly kind: 'unreadable' };\n","/**\n * Execution outcome -> ACP response.\n *\n * Two rules run everything here. A successful checkout answer must be a\n * document the pinned snapshot accepts, on the status ACP fixes for that route\n * - a merchant backend is not automatically ACP-conformant, and forwarding\n * whatever it returned would publish its shape as ours. And a failure tells the\n * caller what went wrong in ACP's vocabulary and nothing else: no merchant\n * response body, no stack, no internal path, no database error.\n */\nimport type { CommerceError, DeliveredOutcome } from '../../core/index.js';\nimport type { AcpCheckoutOperation } from './constants.js';\nimport { type AcpFailure, acpFailure } from './errors.js';\nimport { type AcpDefinition, validateAcpDocument } from './validation.js';\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 to put in `Retry-After`, set only where retrying is the right\n * move. Opt-in rather than derived from the status: two of the 409s this\n * adapter returns must *not* invite a retry, so a shared status is a poor\n * proxy for advice to the caller.\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 whatever the operator needs in the log to understand\n * a refusal. `logDetail` never reaches the client - that is the whole point of\n * carrying it separately from `response`.\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 // The backend document is not ACP. It must not be forwarded, and the\n // caller learns nothing about its shape - the pointer is into the\n // *merchant's* document, which is 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 return { response: { status: expected, body: outcome.body } };\n}\n\n/**\n * Completion is the one route with two shapes.\n *\n * A completed session must carry its order - that is the `CheckoutSessionWithOrder`\n * definition, and `Order` requires an id. But a completion attempt that ends in\n * a declined payment or an out-of-stock line item legitimately answers 200 with\n * an ordinary session and no order (both are examples in the snapshot), so\n * demanding an order on every completion would refuse valid merchant answers.\n * The session's own `status` is what decides which contract applies.\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 * Every failure the pipeline can raise, in ACP's vocabulary.\n *\n * Only the error *code* and, for a backend failure, the backend's *status*\n * cross this boundary. Both are ours to state; the merchant's response body is\n * not, and the gateway already withholds it.\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 this is the *resource's* input\n // contract rejecting it: a configuration mismatch the caller cannot fix,\n // reported without naming the resource's internal field names.\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 * A merchant status worth relaying, or a 502.\n *\n * Only statuses that mean the same thing to an ACP client are passed through.\n * A merchant 401 or 403, in particular, is not: relaying it would tell the\n * agent its own bearer token failed, when what failed is the gateway's\n * credential with the backend.\n */\nfunction fromBackendStatus(error: CommerceError, operation: AcpCheckoutOperation): AcpFailure {\n const status = error.details?.['status'];\n switch (typeof status === 'number' ? status : 0) {\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 return acpFailure(\n 422,\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 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 { status: failure.status, body: failure.error };\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 * Discovery and every protocol guard that must hold before canonical execution\n * are implemented. A guarded request is not executed yet: until checkout\n * operations reach the pipeline, a fully-valid request is answered with an\n * honest \"not implemented\" rather than a fabricated session.\n *\n * This file never calls a merchant backend and never inspects a payment\n * 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/index.js';\nimport { PACKAGE_VERSION } from '../../version.js';\nimport { toCanonicalRequest } from './checkout-mapping.js';\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.js';\nimport { buildDescriptor } from './descriptor.js';\nimport { type AcpDiscoveryMetadata, buildAcpDiscoveryDocument } from './discovery.js';\nimport { type AcpFailure, acpFailure, writeAcpFailure, writeAcpJson } from './errors.js';\nimport { operationKey, requestFingerprint } from './idempotency/fingerprint.js';\nimport {\n type AcpIdempotencyScope,\n type AcpIdempotencyStore,\n createAcpIdempotencyStore,\n} from './idempotency/store.js';\nimport { type AcpGuardedRequest, guardAcpRequest } from './request-guards.js';\nimport {\n type AcpResponse,\n asResponse,\n mapCommerceErrorToAcp,\n toAcpResponse,\n} from './response-mapping.js';\nimport { validateAcpDocument } from './validation.js';\n\n/** Discovery is stable for the life of the process, so it is safe to cache at the edge. */\nconst DISCOVERY_CACHE_CONTROL = 'public, max-age=3600';\n\n/**\n * Whether this attempt could have changed anything at the merchant.\n *\n * `no` has to be a proof, never a guess: it is the only value that frees an\n * idempotency key for a retry. The caller treats `unknown` and `yes` alike,\n * and they are kept apart only so a log says which it was.\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.\n *\n * An allowlist, so a code added later is ambiguous by default rather than\n * silently freeing a key. `STORAGE_ERROR` is deliberately absent: the receipt\n * is written *after* delivery, so it means the merchant did act.\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\nfunction reachedFor(code: string): MerchantReach {\n return PRE_BACKEND_ERROR_CODES.has(code) ? '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: { readonly path: string; readonly retentionHours: number };\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 token: string;\n private readonly operations: Readonly<Record<AcpCheckoutOperation, string>>;\n private readonly idempotencyOptions: AcpAdapterOptions['idempotency'];\n /**\n * What an idempotency claim is scoped to, from `context.publicBaseUrl`.\n *\n * Not readonly because, unlike the token, it is known only once the adapter\n * starts. Worth that: scoping by the credential meant a rotation freed\n * every outstanding claim.\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 rebuilding it\n // per request would let an unauthenticated GET do work a caller controls the\n // cost of.\n private discovery: Record<string, unknown> | undefined;\n\n constructor(options: AcpAdapterOptions) {\n this.mountPath = options.mountPath;\n this.token = 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 // Validated against the pinned snapshot rather than trusted: configured\n // metadata is free text (a currency that is not ISO 4217, an intervention\n // type ACP does not define), and publishing a document that fails ACP's own\n // schema would be the blanket-compatibility claim this project refuses to\n // make. Failing here fails only this adapter - the gateway isolates it.\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 // The same defence in depth MCP and A2A apply: config already refuses a\n // mapping to a resource that is not acp-exposed, but the adapter must not\n // rely on that alone to keep a resource scoped to another protocol out of\n // an ACP checkout.\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 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 );\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 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\n const guarded = await guardAcpRequest(req, {\n mountPath: this.mountPath,\n token: this.token,\n });\n if (!guarded.ok) {\n // A guard failure never carries a Request-Id echo: the header is only\n // normalised once the request is known to be well-formed.\n writeAcpFailure(res, guarded);\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');\n }\n }\n\n /**\n * One request, at most one execution.\n *\n * A body-bearing route claims its idempotency key *before* the work starts,\n * so a retry that arrives while the first one is still running finds the\n * claim instead of starting a second checkout. A route with no key (the GET)\n * is read-only and needs none.\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 // Not \"try again\": an earlier attempt reached the merchant and nobody\n // learned its outcome. Re-running it could order twice, and replaying\n // it would invent an answer nobody gave. It may already have\n // succeeded, and only the merchant's records can say.\n return asResponse(\n acpFailure(\n 409,\n 'processing_error',\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 // A throw here is a bug in this adapter, not a merchant verdict, and it\n // says nothing about how far the request had got. The merchant may have\n // been called, so the claim is kept.\n store.markUnresolved(scope);\n throw err;\n }\n\n // A 2xx or 4xx is the answer to this request and every retry of it: the\n // merchant stated an outcome, even a refusing one, so it is cached.\n if (outcome.response.status < 500) {\n store.complete(scope, outcome.response);\n } else if (outcome.reached === 'no') {\n // Proven never to have left the gateway, so the key is freed and the\n // caller can retry cleanly once the deployment is fixed.\n store.release(scope);\n } else {\n // A timeout, a merchant 5xx, or a reply we could not read. None of them\n // say the merchant did nothing, and freeing the key here is how one\n // checkout becomes two orders.\n store.markUnresolved(scope);\n }\n return outcome.response;\n }\n\n /**\n * One accepted request, one `pipeline.execute()`.\n *\n * Nothing here prices a resource, inspects a payment proof or calls a\n * merchant backend: the adapter builds a canonical request and reads back\n * what the pipeline decided.\n */\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 // ACP has no wire representation for a gateway payment challenge, and\n // config refuses a paid checkout resource - so reaching this is a\n // broken deployment, not something the caller can act on. Nothing about\n // the 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. Everything needed to fix it\n // goes to the log; the caller gets the safe 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 // The pipeline delivered, so the merchant ran the operation - including\n // where its answer was not ACP and is being refused. The order may well\n // exist, and the key must not be freed for a retry.\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.code),\n err: error.toInfo(),\n },\n 'acp adapter: checkout execution failed',\n );\n return {\n response: asResponse(mapCommerceErrorToAcp(error, request.route.operation)),\n reached: reachedFor(error.code),\n };\n }\n }\n\n /**\n * Protocol-owned headers only. A merchant backend's own headers are never\n * proxied onto an ACP response.\n */\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(res: ServerResponse, err: unknown, message: string): void {\n // Nothing from `err` reaches the client: stack, exception name and any\n // upstream detail stay in the log.\n this.context?.logger.error({ err: toCommerceError(err).toInfo() }, message);\n writeAcpFailure(\n res,\n acpFailure(500, 'processing_error', 'internal_error', 'Internal server error.'),\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 * Defence-in-depth against accidentally persisting secrets.\n *\n * The gateway and payment providers are expected to never place secrets into\n * `CommerceReceipt.metadata`, `CommerceEvent.data` or `PaymentResult.metadata`\n * (see docs/contracts.md, \"Store NO secrets\"). This module is a second line\n * of defence at the persistence boundary: any key that *looks* like it holds\n * a private key, an auth header or a raw payment proof is stripped — never\n * persisted — rather than rejecting the whole write, so a logging bug never\n * takes down an otherwise-successful commerce flow (appendEvent especially\n * must never throw into the caller's flow).\n */\n/**\n * The bearer-token family was missing — `token`, `bearerToken`,\n * `adminToken`, `authToken`, `credential`, `cookie`, `sessionId`, `jwt` all\n * returned false. Nothing writes such a key today, which is exactly the state\n * a second line of defence is for; and this data also lands in a\n * file that is now owner-only precisely because it is worth protecting.\n */\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 * Recursively strip values whose key looks secret-shaped, returning a new\n * object. Safe to call on already-clean data (no-op in that case).\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/** True if `value` (recursively) contains any key that looks secret-shaped. */\nexport function containsSecretKey(value: unknown): boolean {\n if (Array.isArray(value)) {\n return value.some(containsSecretKey);\n }\n if (value !== null && typeof value === 'object') {\n return Object.entries(value as Record<string, unknown>).some(\n ([key, inner]) => isSecretKey(key) || containsSecretKey(inner),\n );\n }\n return false;\n}\n","/**\n * SQLite row shapes and mapping to/from the canonical domain model.\n *\n * `exactOptionalPropertyTypes` is on: optional fields are only assigned when\n * present (see docs/contracts.md, assumption 8).\n */\nimport type {\n AuthorizationRecord,\n CommerceEvent,\n CommerceEventType,\n CommerceReceipt,\n PaymentAttempt,\n PaymentResult,\n} from '../../core/index.js';\nimport { redact } from './redact.js';\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 !== undefined ? receipt.durationMs : null,\n protocol: receipt.protocol !== undefined ? 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 every receipt written before this column existed, and for every\n // resource 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 !== undefined ? event.resourceId : null,\n at: event.at,\n adapter: event.adapter !== undefined ? event.adapter : null,\n payment_provider: event.paymentProvider !== undefined ? event.paymentProvider : null,\n duration_ms: event.durationMs !== undefined ? event.durationMs : null,\n status: event.status !== undefined ? 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 * Explicit migration scheme for the receipt-store SQLite schema.\n *\n * Uses SQLite's built-in `PRAGMA user_version` as the migration marker so a\n * restart against an existing database file re-opens without re-creating or\n * losing data (required negative test: \"gateway restart with receipt storage\n * preserved\").\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 must keep its rows, and a\n // receipt written before authorization truthfully has none\n db.exec(`ALTER TABLE receipts ADD COLUMN authorization_json TEXT;`);\n },\n },\n];\n\n/** Current target schema version — the version of the last migration. */\nexport const SCHEMA_VERSION = MIGRATIONS[MIGRATIONS.length - 1]?.version ?? 0;\n\n/**\n * Bring `db` up to {@link SCHEMA_VERSION}. Idempotent: re-opening an existing,\n * already-migrated file is a fast no-op check against `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.\n *\n * Thin repository layer — no ORM. Every write goes through a prepared\n * statement; the only thing that varies between calls is parameters.\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/index.js';\nimport { PACKAGE_VERSION } from '../../version.js';\nimport { openSqliteDatabase } from '../sqlite.js';\nimport {\n type EventRow,\n eventToRow,\n type PaymentAttemptRow,\n type ReceiptRow,\n receiptToRow,\n rowToEvent,\n rowToPaymentAttempt,\n rowToReceipt,\n} from './rows.js';\nimport { migrate, SCHEMA_VERSION } from './schema.js';\n\nconst DEFAULT_LIST_LIMIT = 50;\n/**\n * Hard ceiling on every list query, applied here rather than only at the\n * gateway route, so every caller (HTTP, CLI, a future adapter) is covered.\n * SQLite treats a negative `LIMIT` as \"no limit\" —\n * confirmed `{ limit: -1 }` returns the entire table.\n */\nconst MAX_LIST_LIMIT = 500;\n\n/**\n * Clamps to a whole number in [1, MAX_LIST_LIMIT], defaulting when absent OR\n * non-finite (NaN/Infinity) — a store-level invariant that must hold\n * regardless of whether the current caller already filters those out.\n */\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 // Opening and hardening the file is shared with the ACP idempotency store -\n // see src/storage/sqlite.ts. Two copies of that logic is how one of them\n // ends up shipping a world-readable database.\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 INTEGER NOT NULL (schema.ts) so NOT BETWEEN never has\n // a NULL row to silently miss; 0 (backend never responded at all) and\n // every non-2xx status both count as undelivered, matching the dashboard's\n // deliveryResult() (ReceiptList.tsx) — the two views must not disagree\n // about what \"delivered\" means, which is the confusion.\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(\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 );\n const getPaymentAttemptByIdStmt = db.prepare<[string], PaymentAttemptRow>(\n 'SELECT * FROM payment_attempts WHERE id = ?',\n );\n // COALESCE: an omitted field (bound as NULL — see updatePaymentAttempt)\n // means \"leave the existing value alone\", not \"clear it\". Without this, a\n // second update that doesn't re-supply external_reference/rejection_reason\n // erases it — exactly the field that carries the on-chain tx hash for a\n // settlement-uncertain attempt, the one record proving the buyer's funds\n // may have moved. There is no current caller that needs to clear an\n // already-set value; if one appears, it needs an explicit sentinel rather\n // than overloading `undefined` to mean two different things again.\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\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 // Schema setup already happened synchronously above (better-sqlite3 is\n // sync). This re-check makes init() a meaningful, idempotent gate for\n // callers that treat it as the lifecycle hook that must succeed before\n // any other method is used.\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 id = ids.next('attempt');\n try {\n insertPaymentAttemptStmt.run({\n id,\n request_id: reservation.requestId,\n resource_id: reservation.resourceId,\n provider: reservation.provider,\n replay_key: reservation.replayKey,\n status: 'reserved' satisfies PaymentAttempt['status'],\n amount: reservation.amount,\n currency: reservation.currency,\n payer: reservation.payer ?? null,\n payee: reservation.payee ?? null,\n external_reference: null,\n rejection_reason: null,\n created_at: now,\n updated_at: now,\n });\n } catch (err) {\n if (isUniqueConstraintOn(err, 'payment_attempts.replay_key')) {\n throw new CommerceError(\n 'PAYMENT_REPLAYED',\n `Payment authorisation has already been used (replayKey=${reservation.replayKey})`,\n { requestId: reservation.requestId, resourceId: reservation.resourceId },\n );\n }\n throw toCommerceError(err, 'STORAGE_ERROR', 'Failed to reserve payment attempt');\n }\n const row = getPaymentAttemptByIdStmt.get(id);\n if (row === undefined) {\n throw new CommerceError(\n 'STORAGE_ERROR',\n 'Payment attempt vanished immediately after insert',\n );\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, ignoring the listReceipts clamp — see the interface doc for why this exists. */\n async countReceipts(): Promise<number> {\n return countReceiptsStmt.get()?.count ?? 0;\n },\n\n /** Exact count of non-2xx receipts — see the interface doc for why this exists. */\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 // Same discipline: a client-visible field is authored from a\n // fixed vocabulary, never inherited from a caught error's `.message`.\n // `accessSync` on a real deployment throws e.g.\n // \"EACCES: permission denied, access '/workspace/data/receipts.sqlite'\"\n // — an absolute host path that must never reach the unauthenticated\n // `/ready` response). The raw message still goes\n // to the injected logger, so nothing is lost for diagnosis.\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/core/execution/backend-http.ts","../src/core/execution/validation.ts","../src/core/execution/pipeline.ts","../src/core/execution/registry.ts","../src/core/execution/store-event-sink.ts","../src/protocols/acp/constants.ts","../src/config/schema.ts","../src/config/load.ts","../src/protocols/http.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/agent-card.ts","../src/protocols/a2a/descriptor.ts","../src/protocols/a2a/jsonrpc.ts","../src/protocols/a2a/message-mapping.ts","../src/protocols/a2a/task-mapping.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","durationMs","url","invalid","validators","fs","parseYaml","header","value","z","task","buildDescriptor","sha256","createHash","SCHEMA_VERSION","migrate","randomUUID","fsConstants"],"mappings":";;;;;;;;;;;;;;;;;;;AAqBA,IAAM,mBA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ACxC,SAAA,EAAW,MAAM,MAAA,EAAO;AAAA,UACxB,UAAA,EAAY,KAAA,CAAM,WAAA,EAAY,GAAI;AAAA,SACpC;AAAA,MACF,SAAS,GAAA,EAAK;AACZ,QAAA,MAAA,CAAO,IAAA;AAAA,UACL,EAAE,KAAK,GAAA,YAAe,KAAA,GAAQ,IAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAA,EAAE;AAAA,UACxD;AAAA,SACF;AACA,QAAA,OAAO;AAAA,UACL,MAAA,EAAQ,MAAA;AAAA,UACR,MAAA,EAAQ,mBAAA;AAAA,UACR,SAAA,EAAW,MAAM,MAAA,EAAO;AAAA,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 * 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.\n */\nimport {\n type BackendHandler,\n type BackendMethod,\n DEFAULT_BACKEND_TIMEOUT_MS,\n} 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';\n\nconst MAX_BODY_SNIPPET_LENGTH = 512;\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// 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// 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\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);\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 });\n }\n\n return {\n status: response.status,\n headers: responseHeaders,\n body: parsedBody,\n durationMs,\n };\n }\n}\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 * Runs the traversal, query-collision and header checks that `call()` repeats,\n * so the pipeline can run them after schema validation and before pricing.\n * Schema validation cannot catch these: `inputSchema` knows nothing about the\n * URL template. Found only inside `call()`, after settlement, a bad value such\n * as `{ city: \"\" }` for a paid, path-templated resource would take payment\n * without delivery. Throws INPUT_INVALID for the input, BACKEND_ERROR for an\n * illegal configured header, and does no I/O.\n */\nexport function validateBackendRequestShape(\n handler: BackendHandler,\n input: unknown,\n context: ShapeContext,\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);\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 */\nfunction 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\nfunction 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\nfunction 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.\nfunction buildHeaders(handler: BackendHandler, context: ShapeContext): Headers {\n try {\n return new Headers(handler.headers);\n } catch {\n throw invalidHeaderError(context);\n }\n}\n\nfunction setHeader(headers: Headers, name: string, value: string, context: ShapeContext): 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// `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","/**\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, createRequirement, then either return the challenge\n * or verify, reserve the authorization, reserve the replay key, settle, and\n * consume, release or mark uncertain the authorization. Fail closed at every\n * step\n * 6. call backend (BACKEND_TIMEOUT / BACKEND_ERROR)\n * 7. persist receipt, emit events, return outcome\n */\n\nimport type {\n AuthorizationProvider,\n AuthorizationRecord,\n AuthorizationVerification,\n} from '../domain/authorization';\nimport type { AuthorizationMethodName, PaymentMethodName } from '../domain/common';\nimport type { CommerceEvent, EventSink } from '../domain/event';\nimport type { PaymentProvider, PaymentRequirement, PaymentResult } from '../domain/payment';\nimport type { CommerceReceipt } from '../domain/receipt';\nimport type { CanonicalRequest, ExecutionOutcome, ExecutionPipeline } from '../domain/request';\nimport type { CommerceResource, ResourceRegistry } from '../domain/resource';\nimport { RESERVED_INPUT_FIELDS } from '../domain/wire';\nimport { CommerceError, describeError, isCommerceError, toCommerceError } from '../errors';\nimport type { BackendExecutor, BackendResponse } from '../interfaces/backend';\nimport type { Logger } from '../interfaces/logger';\nimport type { Clock, IdGenerator } from '../interfaces/runtime';\nimport type { ReceiptStore } from '../interfaces/store';\nimport { isRecord } from '../is-record';\nimport { validateBackendRequestShape } from './backend-http';\nimport { compileJsonSchema, type Validator } from './validation';\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// A reservation held across settlement, plus the summary the receipt keeps.\n// `finalize` ends it.\ninterface AuthorizationHold {\n readonly record: AuthorizationRecord;\n finalize(action: 'consume' | 'release' | 'markUncertain'): Promise<void>;\n}\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 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 // 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 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(resource.handler, validInput, {\n requestId: request.requestId,\n resourceId: resource.id,\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\n if (resource.pricing.type === 'fixed') {\n const pricing = resource.pricing;\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 });\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 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),\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 authorization = hold?.record;\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 });\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 mapped;\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 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 // A verdict arrives as a returned PaymentResult; a throw means none. A\n // facilitator can broadcast a settlement and then lose the response, so\n // a missing transaction hash is no evidence that nothing moved. Every\n // throw is recorded as settlement-uncertain and the authorization is\n // marked uncertain, not released: a released mandate could be spent\n // again against a charge that may have landed. Of the settlement\n // outcomes, only a returned result other than `settled` releases it.\n // Nothing is delivered either way.\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 buyer must learn the outcome is unknown, since their funds may\n // have moved. Not the retryable PAYMENT_PROVIDER_UNAVAILABLE: a retry\n // would hit the reserved replay key, and an unresolved settlement must\n // never invite paying again. Of the underlying error only the\n // transaction hash travels: the buyer's own payment, public on-chain\n // once it lands.\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 },\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 }),\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 throw new CommerceError(\n 'PAYMENT_SETTLEMENT_FAILED',\n settlement.rejectionReason ?? 'Settlement was rejected',\n {\n requestId: request.requestId,\n resourceId: resource.id,\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 paymentResult = settlement;\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 });\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 (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 ...(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 // 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\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// 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.\nfunction 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\n// A rejected proof leaves this request's challenge unused. Returning it lets a\n// client pay again without another round trip for a fresh one.\nfunction retryChallenge(requirement: PaymentRequirement): { details?: Record<string, unknown> } {\n const envelope = requirement.challenge.envelope;\n return envelope === undefined ? {} : { details: { challenge: envelope } };\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\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","/**\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/** 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 * `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 */\n\nimport { type ZodError, type ZodIssue, type ZodTypeAny, 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 { Ap2AuthorizationConfig, Ap2Mode, Ap2TrustedIssuer } from '../authorization/ap2/types';\nimport {\n type AuthorizationMethodName,\n CommerceError,\n type CommerceResource,\n PAYMENT_METHOD_NAMES,\n PROTOCOL_NAMES,\n type Pricing,\n RESERVED_INPUT_FIELDS,\n} from '../core';\nimport {\n extractPathParameterNames,\n findUnparsedBraceToken,\n isObjectSchemaNode,\n} from '../core/execution';\nimport { isRecord } from '../core/is-record';\nimport {\n isMppNetwork,\n MPP_DEFAULT_NETWORK,\n MPP_MIN_CHALLENGE_SECRET_LENGTH,\n MPP_NETWORKS,\n MPP_PROFILE,\n type MppNetwork,\n} from '../payments/mpp/constants';\nimport { resolveX402Deployment, type X402FacilitatorConfig } from '../payments/x402/guardrails';\nimport {\n ACP_CHECKOUT_OPERATIONS,\n ACP_OPERATION_INPUT_KEYS,\n ACP_OPERATION_OPTIONAL_INPUT_KEYS,\n ACP_WELL_KNOWN_PATH,\n type AcpCheckoutOperation,\n} from '../protocols/acp/constants';\nimport { MCP_TOOL_NAME_PATTERN } from '../protocols/mcp/constants';\nimport { substituteEnv } from './env';\n\nconst SUPPORTED_CONFIG_VERSION = 1;\n\n// `0x` + 40 hex chars. Casing (the EIP-55 checksum) is not checked\nconst ADDRESS_PATTERN = /^0x[0-9a-fA-F]{40}$/;\nconst ZERO_ADDRESS_PATTERN = /^0x0{40}$/i;\n\n// ---------------------------------------------------------------------------\n// Zod schema for the shape of the raw (post-substitution) document\n// ---------------------------------------------------------------------------\n\n// A number, or a numeric string from env substitution\nconst NumberOrString = z.union([z.number(), z.string()]);\n// A boolean, or a \"true\"/\"false\" string from env substitution\nconst BooleanOrString = z.union([z.boolean(), z.string()]);\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({ path: z.string().min(1), retentionHours: NumberOrString.optional() })\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\n// Applied when `protocols.a2a` is absent or names no mount\nconst DEFAULT_A2A_MOUNT_PATH = '/a2a';\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\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\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 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\nconst 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\nconst X402Schema = z\n .object({\n enabled: BooleanOrString,\n network: z.string().min(1),\n rpcUrl: z.string().min(1),\n asset: z.string().min(1),\n assetName: z.string().min(1),\n assetVersion: z.string().min(1),\n assetDecimals: NumberOrString,\n payTo: z.string().min(1),\n maxTimeoutSeconds: NumberOrString,\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: z.string().min(1),\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 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\nconst 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 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\nconst 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\ntype RawConfig = z.infer<typeof RawConfigSchema>;\ntype RawResourceEntry = z.infer<typeof ResourceEntrySchema>;\n\n// ---------------------------------------------------------------------------\n// Public shape (docs/contracts.md)\n// ---------------------------------------------------------------------------\n\n/** Optional ACP discovery metadata. Absent fields are omitted from the document */\nexport interface AcpDiscoveryConfig {\n readonly documentationUrl?: string;\n readonly supportedCurrencies?: readonly string[];\n readonly supportedLocales?: readonly string[];\n readonly interventionTypes?: readonly string[];\n}\n\n/**\n * Discriminated on `enabled`, so an enabled ACP config carries everything the\n * adapter needs; a half-configured checkout is rejected at load\n */\nexport type AcpProtocolConfig =\n | { readonly enabled: false; readonly mountPath: string }\n | {\n readonly enabled: true;\n readonly mountPath: string;\n readonly auth: { readonly type: 'bearer'; readonly token: string };\n readonly idempotency: { readonly path: string; readonly retentionHours: number };\n readonly checkout: {\n readonly operations: Readonly<Record<AcpCheckoutOperation, string>>;\n };\n readonly discovery?: AcpDiscoveryConfig;\n };\n\nexport interface GatewayConfig {\n readonly version: 1;\n readonly merchant: { readonly id: string; readonly name: string; readonly publicBaseUrl: string };\n readonly server: {\n readonly port: number;\n readonly host: string;\n readonly adminToken?: string;\n readonly allowedOrigins: readonly string[];\n };\n readonly storage: { readonly receipts: { readonly driver: 'sqlite'; readonly path: string } };\n readonly protocols: {\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: AcpProtocolConfig;\n };\n /** Canonical resources, already normalized */\n readonly resources: readonly CommerceResource[];\n readonly payments: {\n readonly x402?: {\n readonly enabled: boolean;\n readonly network: string;\n readonly rpcUrl: string;\n readonly asset: string;\n readonly assetName: string;\n readonly assetVersion: string;\n readonly assetDecimals: number;\n readonly payTo: string;\n readonly maxTimeoutSeconds: number;\n readonly facilitator: X402FacilitatorConfig;\n readonly allowMainnet?: boolean;\n readonly allowUnauthenticatedFacilitator?: boolean;\n };\n readonly mpp?: {\n readonly enabled: boolean;\n readonly network: MppNetwork;\n readonly rpcUrl: string;\n readonly asset: string;\n readonly assetName: string;\n readonly assetVersion: string;\n readonly recipient: string;\n readonly realm: string;\n readonly challengeSecret: string;\n readonly challengeTtlSeconds?: number;\n readonly facilitator: X402FacilitatorConfig;\n readonly allowMainnet?: boolean;\n readonly allowUnauthenticatedFacilitator?: boolean;\n };\n };\n /** Absent when no `authorization:` block is configured */\n readonly authorization?: { readonly ap2: Ap2AuthorizationConfig };\n}\n\n// ---------------------------------------------------------------------------\n// Entry point\n// ---------------------------------------------------------------------------\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\n// ---------------------------------------------------------------------------\n// Numeric and boolean coercion (plain TypeScript, not Zod; see file header)\n// ---------------------------------------------------------------------------\n\nfunction 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\nfunction 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\n// ---------------------------------------------------------------------------\n// Business rules and normalization into the canonical shape\n// ---------------------------------------------------------------------------\n\nconst SUPPORTED_PROTOCOLS: ReadonlySet<string> = new Set(PROTOCOL_NAMES);\nconst SUPPORTED_PAYMENT_METHODS: ReadonlySet<string> = new Set(PAYMENT_METHOD_NAMES);\nconst SUPPORTED_AUTHORIZATION_METHODS: ReadonlySet<string> = new Set(['ap2']);\n\nfunction 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 x402Raw = raw.payments.x402;\n const x402 =\n x402Raw !== undefined\n ? {\n enabled: toBoolean(x402Raw.enabled, 'payments.x402.enabled'),\n network: x402Raw.network,\n rpcUrl: x402Raw.rpcUrl,\n asset: x402Raw.asset,\n assetName: x402Raw.assetName,\n assetVersion: x402Raw.assetVersion,\n assetDecimals: toNumber(x402Raw.assetDecimals, 'payments.x402.assetDecimals', {\n min: 0,\n max: 36,\n }),\n payTo: x402Raw.payTo,\n maxTimeoutSeconds: toNumber(\n x402Raw.maxTimeoutSeconds,\n 'payments.x402.maxTimeoutSeconds',\n {\n min: 1,\n },\n ),\n facilitator: normalizeFacilitator(x402Raw.facilitator),\n ...(x402Raw.allowMainnet !== undefined\n ? { allowMainnet: toBoolean(x402Raw.allowMainnet, 'payments.x402.allowMainnet') }\n : {}),\n ...(x402Raw.allowUnauthenticatedFacilitator !== undefined\n ? {\n allowUnauthenticatedFacilitator: toBoolean(\n x402Raw.allowUnauthenticatedFacilitator,\n 'payments.x402.allowUnauthenticatedFacilitator',\n ),\n }\n : {}),\n }\n : undefined;\n\n if (x402) {\n validateAddress('payments.x402.payTo', x402.payTo);\n validateAddress('payments.x402.asset', x402.asset);\n // The provider makes the same call at construction; running it here lets\n // `agent-commerce validate` report an unsafe deployment before boot\n resolveX402Deployment({\n network: x402.network,\n payTo: x402.payTo,\n asset: x402.asset,\n assetName: x402.assetName,\n assetVersion: x402.assetVersion,\n facilitator: x402.facilitator,\n ...(x402.allowMainnet !== undefined ? { allowMainnet: x402.allowMainnet } : {}),\n ...(x402.allowUnauthenticatedFacilitator !== undefined\n ? { allowUnauthenticatedFacilitator: x402.allowUnauthenticatedFacilitator }\n : {}),\n });\n }\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, x402, mpp, ap2),\n );\n if (protocols.acp.enabled) validateAcpCheckoutMapping(protocols.acp, resources);\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 ...(x402 !== undefined ? { x402 } : {}),\n ...(mpp !== undefined ? { mpp } : {}),\n },\n ...(ap2 !== undefined ? { authorization: { ap2 } } : {}),\n };\n}\n\ninterface NormalizedProtocols {\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: AcpProtocolConfig;\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// ---------------------------------------------------------------------------\n// AP2 authorization (experimental)\n// ---------------------------------------------------------------------------\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\nfunction 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 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.\nfunction 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.\nfunction 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\n// ---------------------------------------------------------------------------\n// ACP (experimental)\n// ---------------------------------------------------------------------------\n\ntype RawAcp = NonNullable<RawConfig['protocols']['acp']>;\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\nfunction 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 },\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\nfunction 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`.\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 properties = schema['properties'];\n\n if (schema['additionalProperties'] === false && isRecord(properties)) {\n for (const key of [...keys, ...optionalKeys]) {\n if (!Object.hasOwn(properties, 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 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\ninterface NormalizedX402 {\n readonly enabled: boolean;\n readonly assetDecimals: number;\n}\n\nfunction normalizeFacilitator(raw: z.infer<typeof FacilitatorSchema>): 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\ntype NormalizedMpp = NonNullable<GatewayConfig['payments']['mpp']>;\n\nfunction 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 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\nfunction 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 if (entry.pricing.type === 'fixed') {\n validatePricingAmount(id, entry.pricing.amount, x402?.assetDecimals);\n }\n\n const paymentMethods = entry.payments ?? [];\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 = [...(x402?.enabled ? ['x402'] : []), ...(mpp?.enabled ? ['mpp'] : [])];\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 // 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 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/**\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 */\nfunction defaultClosedObjectSchema(schema: Record<string, unknown>): 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.\nconst 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 */\nfunction 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\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+)?$/;\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/**\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 */\nfunction 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// 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\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 */\nfunction 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\nfunction 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.\nfunction validateBackendHeaders(id: string, headers: Record<string, string> | undefined): 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\nfunction validateAddress(path: string, value: string): void {\n if (!ADDRESS_PATTERN.test(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 (ZERO_ADDRESS_PATTERN.test(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","/**\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","// HTTP helpers shared by the A2A and ACP adapters and the gateway's admin-token gate\nimport { createHash, timingSafeEqual } from 'node:crypto';\nimport type { IncomingMessage } from 'node:http';\n\nconst BEARER_PREFIX = /^Bearer +/i;\n\n/**\n * Builds a check of an `Authorization: Bearer <token>` header against a fixed\n * token. The scheme is case-insensitive (RFC 9110). Both sides are compared as\n * SHA-256 digests, because `timingSafeEqual` throws on a length mismatch and\n * would reveal the token's length; the expected digest is computed once here.\n */\nexport function createBearerCheck(expectedToken: string): (header: string | undefined) => boolean {\n const expected = sha256(expectedToken);\n return (header) => {\n if (header === undefined || !BEARER_PREFIX.test(header)) return false;\n const presented = header.replace(BEARER_PREFIX, '');\n return presented.length > 0 && timingSafeEqual(sha256(presented), expected);\n };\n}\n\nfunction sha256(value: string): Buffer {\n return createHash('sha256').update(value, 'utf8').digest();\n}\n\n/** A tagged result, so no body text can be mistaken for a failure */\nexport type BodyRead =\n | { readonly kind: 'ok'; readonly text: string }\n | { readonly kind: 'too-large' }\n | { readonly kind: 'unreadable' };\n\n/**\n * Reads the unconsumed request stream the gateway hands an adapter, stopping\n * at the cap rather than buffering whatever arrives\n */\nexport async function readCappedBody(req: IncomingMessage, maxBytes: number): Promise<BodyRead> {\n const chunks: Buffer[] = [];\n let total = 0;\n try {\n for await (const chunk of req) {\n const buffer = chunk as Buffer;\n total += buffer.length;\n if (total > maxBytes) return { kind: 'too-large' };\n chunks.push(buffer);\n }\n } catch {\n return { kind: 'unreadable' };\n }\n return { kind: 'ok', text: Buffer.concat(chunks).toString('utf8') };\n}\n\n/**\n * Joins a base URL and a mount path with exactly one slash between them and\n * none at the end. Plain concatenation can yield `https://host//a2a`, which a\n * router may treat as a different path.\n */\nexport function joinUrl(baseUrl: string, mountPath: string): string {\n return `${baseUrl.replace(/\\/+$/, '')}/${mountPath.replace(/^\\/+|\\/+$/g, '')}`;\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// `authorization` carries bearer tokens (admin, ACP) and MPP credentials; the\n// AP2 mandate travels in its own header\nconst CORS_HEADERS = [\n 'content-type',\n PAYMENT_HEADER,\n AUTHORIZATION_HEADER,\n 'x-request-id',\n 'authorization',\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 nor the\n// settlement result\nconst CORS_EXPOSED_HEADERS = 'payment-required,payment-response,www-authenticate,payment-receipt';\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 buffers the whole body with no cap of\n * its own. 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 the SDK parses a whole JSON-RPC batch before any adapter\n * code runs, and this cap is the only bound on that parse's memory 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}\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 };\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 /** Every adapter's health from the same memoized evaluation, detail included */\n adapterHealth(): Promise<readonly ProbedAdapter[]>;\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 };\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 {\n AdapterDescriptor,\n AdapterHealth,\n AuthorizationProvider,\n PaymentProvider,\n ReceiptStore,\n} from '../core';\nimport { MPP_PROFILE } from '../payments/mpp/constants';\nimport {\n type DeploymentMode,\n requireNetworkProfile,\n resolveDeploymentMode,\n} from '../payments/x402/networks';\nimport { PACKAGE_VERSION } from '../version';\nimport type { ProbedAdapter } 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 readonly assetName: string;\n readonly assetVersion: string;\n readonly assetDecimals: number;\n readonly payTo: string;\n readonly maxTimeoutSeconds: number;\n readonly facilitator: { readonly mode: 'local' | 'remote' };\n /** `local`, `testnet` or `mainnet`, from the network and facilitator together */\n readonly mode: DeploymentMode;\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 };\n };\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 memoized readiness probe, so this route shares `/ready`'s `health()` calls */\n readonly adapters: readonly ProbedAdapter[];\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\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\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 assetName: x402.assetName,\n assetVersion: x402.assetVersion,\n assetDecimals: x402.assetDecimals,\n payTo: x402.payTo,\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 // Chain id 84532 is both the local dev chain and public Base\n // Sepolia, so the network id alone cannot say which one this is\n mode: resolveDeploymentMode(\n requireNetworkProfile(x402.network, 'payments.x402.network'),\n x402.facilitator.mode,\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(\n requireNetworkProfile(mpp.network, 'payments.mpp.network'),\n mpp.facilitator.mode,\n ),\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 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 { buildOperatorTokenHook } from './access-control';\nimport type { AdapterRuntime } from './adapters';\nimport { toPublicResource } from './public-resource';\nimport { createReadinessProbe } from './readiness';\nimport { buildWellKnownDocument } from './well-known';\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 }),\n );\n\n server.get('/api/resources', async () => ({\n resources: options.resources.list().map(toPublicResource),\n }));\n\n server.post('/api/resources/:id/invoke', async (request, reply) => {\n await handleInvoke(request, reply, options);\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// `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\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 const 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 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 };\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 // x402 v2 clients read the challenge from this header and ignore the\n // body, which still carries the full envelope\n reply.header(PAYMENT_REQUIRED_HEADER, encodeHeaderDocument(envelope.payment.envelope));\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 reply.status(402).send(envelope);\n return;\n }\n\n if (outcome.payment) {\n reply.header(PAYMENT_RESPONSE_HEADER, encodePaymentSummary(outcome.payment));\n const receipt = outcome.payment.metadata?.['receipt'];\n if (outcome.payment.provider === 'mpp' && typeof receipt === 'string') {\n reply.header('payment-receipt', receipt);\n }\n }\n reply.status(outcome.backendStatus).send(outcome.body);\n } catch (error) {\n const commerceError = toCommerceError(error);\n // A backend failure after settlement carries the payment summary in\n // details.payment. Send the success path's headers so the buyer still\n // learns what they paid.\n const settledPayment = errorPaymentSummary(commerceError);\n if (settledPayment !== undefined) {\n reply.header(PAYMENT_RESPONSE_HEADER, encodePaymentSummary(settledPayment));\n if (settledPayment.provider === 'mpp' && settledPayment.receipt !== undefined) {\n reply.header('payment-receipt', settledPayment.receipt);\n }\n }\n // An MPP client pays again only from a fresh WWW-Authenticate challenge\n const challenge = commerceError.details?.['challenge'] as Record<string, unknown> | undefined;\n if (\n commerceError.code === 'PAYMENT_INVALID' &&\n typeof challenge?.['wwwAuthenticate'] === 'string'\n ) {\n reply.header('www-authenticate', challenge['wwwAuthenticate']);\n reply.header('cache-control', 'no-store');\n }\n reply.status(commerceError.httpStatus).send(toErrorEnvelope(commerceError));\n }\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\ninterface PaymentSummary {\n readonly status: string;\n readonly provider: string;\n readonly amount: string;\n readonly currency: string;\n readonly network?: string;\n readonly externalReference?: string;\n // Serialized MPP `Payment-Receipt`, when the provider issued one\n readonly receipt?: string;\n}\n\nfunction errorPaymentSummary(\n error: ReturnType<typeof toCommerceError>,\n): PaymentSummary | undefined {\n const payment = error.details?.['payment'];\n if (!isRecord(payment)) return undefined;\n const { status, provider, amount, currency, network, externalReference, receipt } = payment;\n if (\n typeof status !== 'string' ||\n typeof provider !== 'string' ||\n typeof amount !== 'string' ||\n typeof currency !== 'string'\n ) {\n return undefined;\n }\n return {\n status,\n provider,\n amount,\n currency,\n ...(typeof network === 'string' ? { network } : {}),\n ...(typeof externalReference === 'string' ? { externalReference } : {}),\n ...(typeof receipt === 'string' ? { receipt } : {}),\n };\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/**\n * The settlement result in the `SettleResponse` shape an x402 v2 client\n * decodes from `PAYMENT-RESPONSE`. `status`, `provider`, `amount`, `currency`\n * and `externalReference` are ours; a v2 client ignores fields it does not know.\n */\nfunction encodePaymentSummary(payment: PaymentSummary): string {\n return encodeHeaderDocument({\n success: payment.status === 'settled',\n transaction: payment.externalReference ?? '',\n network: payment.network ?? '',\n status: payment.status,\n provider: payment.provider,\n amount: payment.amount,\n currency: payment.currency,\n ...(payment.externalReference !== undefined\n ? { externalReference: payment.externalReference }\n : {}),\n });\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.0` 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.0';\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. A2A v1 carries the protocol version out of band,\n * so a request without it comes from an older convention and is refused as\n * unsupported.\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 * 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 */\nexport const A2A_UNSUPPORTED_METHODS: readonly string[] = [\n 'SendStreamingMessage',\n 'GetTask',\n 'ListTasks',\n 'CancelTask',\n 'SubscribeToTask',\n 'CreateTaskPushNotificationConfig',\n 'GetTaskPushNotificationConfig',\n 'ListTaskPushNotificationConfigs',\n 'DeleteTaskPushNotificationConfig',\n 'GetExtendedAgentCard',\n];\n\n/**\n * Terminal task states. Only these two are ever returned: a synchronous\n * execution is finished by the time the response is written, and no task\n * store exists for a caller to poll a non-terminal one against.\n */\nexport const A2A_TASK_STATE_COMPLETED = 'TASK_STATE_COMPLETED';\nexport const A2A_TASK_STATE_FAILED = 'TASK_STATE_FAILED';\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 * The card is a *discovery* document: it says what exists and how to reach the\n * endpoint, not how to call a skill. The invocation envelope is the adapter's\n * concern.\n */\nimport type { CommerceResource } from '../../core';\nimport { joinUrl } from '../http';\nimport { A2A_JSON_MEDIA_TYPE, A2A_PROTOCOL_BINDING, A2A_PROTOCOL_VERSION } from './constants';\nimport type { A2aAgentCard, A2aAgentSkill } from './types';\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\nfunction buildAgentSkill(resource: CommerceResource): A2aAgentSkill {\n return {\n id: resource.id,\n name: resource.name,\n description: skillDescription(resource),\n tags: skillTags(resource),\n inputModes: [A2A_JSON_MEDIA_TYPE],\n outputModes: [A2A_JSON_MEDIA_TYPE],\n };\n}\n\nexport function buildAgentCard(options: AgentCardOptions): A2aAgentCard {\n return {\n name: options.name,\n description: options.description,\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: { streaming: false, pushNotifications: false, extendedAgentCard: false },\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.0`), 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[] = ['agent-card', 'jsonrpc', 'SendMessage'];\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',\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];\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 * 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/**\n * A2A's own `UnsupportedOperationError`, for a real A2A operation this\n * deployment declines to serve (an unsupported protocol version included), as\n * distinct from `METHOD_NOT_FOUND`, which means the method does not exist\n */\nexport const A2A_ERROR_UNSUPPORTED_OPERATION = -32004;\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}\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\nexport function jsonRpcError(\n id: JsonRpcId,\n code: number,\n message: string,\n): Record<string, unknown> {\n return { jsonrpc: '2.0', id, error: { code, message } };\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 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. Guessing at intent, such as taking\n * the first of several data parts, could turn a caller's mistake into a\n * successful, possibly paid, call for something they did not ask for.\n */\nimport { z } from 'zod';\nimport { CommerceError } from '../../core';\nimport { isRecord } from '../../core/is-record';\nimport { A2A_JSON_MEDIA_TYPE } from './constants';\n\n// The only role a request message may carry. A2A v1 spells roles this way\nconst A2A_USER_ROLE = 'ROLE_USER';\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, when the request carried one */\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): CommerceError {\n return new CommerceError('PROTOCOL_UNSUPPORTED', message);\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\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('Task continuation is not supported: send a request with no taskId.');\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('File and URL parts are not supported: send a structured data part.');\n }\n if ('text' in part) {\n throw unsupported('Text parts are not supported: send a structured data part.');\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 );\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\n assertNoContinuation(params);\n\n if (message.role !== A2A_USER_ROLE) {\n throw invalid(`Unsupported message role \"${message.role}\": only ${A2A_USER_ROLE} is accepted.`);\n }\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 {\n resourceId,\n input: rawInput ?? {},\n ...(message.messageId !== undefined ? { messageId: message.messageId } : {}),\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 { A2A_JSON_MEDIA_TYPE, A2A_TASK_STATE_COMPLETED, A2A_TASK_STATE_FAILED } from './constants';\nimport type { A2aArtifact, A2aTask } from './types';\n\nexport interface TaskIdentity {\n /** Gateway request id, reused so a task correlates with receipts and events */\n readonly taskId: string;\n /** Fresh every time: nothing here can be continued, so nothing shares a context */\n readonly contextId: string;\n readonly artifactId: 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 * `TASK_STATE_FAILED`, not `TASK_STATE_INPUT_REQUIRED`: without a task store\n * the adapter cannot resume the task, so it ends it. The caller retries by\n * sending a new message carrying the proof.\n */\nexport function paymentRequiredTask(\n outcome: PaymentRequiredOutcome,\n identity: TaskIdentity,\n): A2aTask {\n return task(identity, A2A_TASK_STATE_FAILED, {\n name: outcome.resourceId,\n parts: [{ data: { ...toPaymentRequiredEnvelope(outcome) }, mediaType: A2A_JSON_MEDIA_TYPE }],\n });\n}\n\nexport function failedTask(error: CommerceError, identity: TaskIdentity): A2aTask {\n return task(identity, A2A_TASK_STATE_FAILED, {\n parts: [{ data: { ...toErrorEnvelope(error) }, mediaType: A2A_JSON_MEDIA_TYPE }],\n });\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 in scope; every other A2A method\n * is listed in `descriptor.unsupported` rather than half-served. 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 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 { 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_JSON_MEDIA_TYPE,\n A2A_METHOD_SEND_MESSAGE,\n A2A_PROTOCOL_VERSION,\n A2A_UNSUPPORTED_METHODS,\n A2A_VERSION_HEADER,\n} from './constants';\nimport { buildDescriptor } from './descriptor';\nimport {\n A2A_ERROR_UNSUPPORTED_OPERATION,\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 jsonRpcResult,\n parseJsonRpcRequest,\n} from './jsonrpc';\nimport { type A2aInvocation, parseInvocation } from './message-mapping';\nimport { completedTask, failedTask, paymentRequiredTask, type TaskIdentity } from './task-mapping';\nimport type { A2aAgentCard, A2aTask } from './types';\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\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\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.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 this.writeJson(res, 200, this.card);\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 version = req.headers[A2A_VERSION_HEADER];\n const declared = Array.isArray(version) ? version[0] : version;\n if (declared !== A2A_PROTOCOL_VERSION) {\n // Missing counts as unsupported: a client that negotiates no version\n // is speaking an older convention, and answering it as if it were v1\n // would be guessing on its behalf\n this.writeJson(\n res,\n 200,\n jsonRpcError(\n null,\n A2A_ERROR_UNSUPPORTED_OPERATION,\n `Unsupported A2A protocol version. Send the ${A2A_VERSION_HEADER} header with \"${A2A_PROTOCOL_VERSION}\".`,\n ),\n );\n return;\n }\n\n const read = await readCappedBody(req, MAX_REQUEST_BODY_BYTES);\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 this.writeJson(\n res,\n 200,\n await this.dispatch(parsed.request.id, parsed.request.method, parsed.request.params),\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 ): Promise<Record<string, unknown>> {\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 let invocation: ReturnType<typeof parseInvocation>;\n try {\n invocation = parseInvocation(params);\n } catch (err) {\n const error = toCommerceError(err);\n const code =\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);\n }\n\n // One accepted invocation, one `pipeline.execute()`\n private async execute(\n id: JsonRpcId,\n invocation: A2aInvocation,\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 this.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 return this.taskResult(\n id,\n outcome.kind === 'payment-required'\n ? paymentRequiredTask(outcome, identity)\n : completedTask(outcome, identity),\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 this.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 timestamp: context.clock.nowIso(),\n };\n }\n\n // A2A's JSON-RPC result wraps the terminal task\n private taskResult(id: JsonRpcId, task: A2aTask): Record<string, unknown> {\n return jsonRpcResult(id, { task });\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.skillsById = new Map();\n this.context = undefined;\n }\n\n private writeJson(res: ServerResponse, status: number, body: unknown): void {\n if (res.headersSent) return;\n res.writeHead(status, { 'content-type': A2A_JSON_MEDIA_TYPE });\n res.end(JSON.stringify(body));\n }\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 { ACP_OPERATION_INPUT_KEYS, ACP_OPERATION_OPTIONAL_INPUT_KEYS } 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 };\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'] = { checkout_session_id: 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 negotiation',\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}\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.\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. An\n * attempt that reached the merchant and ended in a timeout, a merchant status\n * ACP cannot relay or a non-ACP reply is marked `unresolved`: the merchant may\n * have acted, so every retry of the key is refused rather than re-run, which\n * could charge a buyer twice. A row still `in_flight` when the store opens was\n * never finalized by an earlier process, which crashed or failed to write the\n * outcome, so it is marked `unresolved` too. That assumes one gateway process\n * per database 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 clean retry can run. Only for an attempt that provably\n * never reached the merchant: after an ambiguous failure, one operation\n * could happen twice.\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 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);\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): void {\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_SESSION_ID_LENGTH = 128;\n\n// ACP session ids are opaque, but they are path segments and go into canonical input\nconst SESSION_ID_PATTERN = /^[A-Za-z0-9._~-]{1,128}$/;\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 || !SESSION_ID_PATTERN.test(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\nfunction endpointPath(mountPath: string, segments: readonly string[]): string {\n return `${mountPath.replace(/\\/+$/, '')}/${segments.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_SESSION_ID_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 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 * 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_IDEMPOTENCY_KEY_HEADER,\n ACP_MAX_REQUEST_ID_LENGTH,\n ACP_REQUEST_ID_HEADER,\n} from './constants';\nimport { type AcpFailure, 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\nexport type AcpGuardResult =\n | { readonly ok: true; readonly value: AcpGuardedRequest }\n | ({ readonly ok: false } & 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\nexport async function guardAcpRequest(\n req: IncomingMessage,\n options: AcpGuardOptions,\n): Promise<AcpGuardResult> {\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 );\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 );\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 presented = header(req, ACP_IDEMPOTENCY_KEY_HEADER)?.trim();\n if (presented === undefined || presented.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 (presented.length > ACP_MAX_IDEMPOTENCY_KEY_LENGTH || !isVisibleAscii(presented)) {\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 = presented;\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 },\n };\n}\n\nfunction failed(failure: AcpFailure): AcpGuardResult {\n return { ok: false, ...failure };\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 is described in ACP's vocabulary only: no merchant response body,\n * stack, internal path or database error.\n */\nimport type { CommerceError, DeliveredOutcome } from '../../core';\nimport type { AcpCheckoutOperation } from './constants';\nimport { 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 return { response: { status: expected, body: outcome.body } };\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 * Every failure the pipeline can raise, in ACP's vocabulary. Only the error\n * code and, for a backend failure, the backend's status cross this boundary,\n * never the merchant's response body.\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 * A merchant status worth relaying, or a 502. Only statuses that mean the same\n * to an ACP client pass through. A merchant 401 or 403 does not: it would tell\n * the agent its own bearer token failed, when the gateway's backend credential\n * did.\n */\nfunction fromBackendStatus(error: CommerceError, operation: AcpCheckoutOperation): AcpFailure {\n const status = error.details?.['status'];\n switch (typeof status === 'number' ? status : 0) {\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 return acpFailure(\n 422,\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 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 { status: failure.status, body: failure.error };\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 { type AcpFailure, acpFailure, writeAcpFailure, writeAcpJson } from './errors';\nimport { operationKey, requestFingerprint } from './idempotency/fingerprint';\nimport {\n type AcpIdempotencyScope,\n type AcpIdempotencyStore,\n createAcpIdempotencyStore,\n} from './idempotency/store';\nimport { type AcpGuardedRequest, guardAcpRequest } from './request-guards';\nimport {\n type AcpResponse,\n asResponse,\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\nfunction reachedFor(code: string): MerchantReach {\n return PRE_BACKEND_ERROR_CODES.has(code) ? '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: { readonly path: string; readonly retentionHours: number };\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 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 );\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 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\n const guarded = await guardAcpRequest(req, {\n mountPath: this.mountPath,\n isAuthorized: this.isAuthorized,\n });\n if (!guarded.ok) {\n // A guard failure echoes no Request-Id: the header is only normalized\n // once the request is known to be well formed\n writeAcpFailure(res, guarded);\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');\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 'processing_error',\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') {\n // Proven never to have left the gateway, so the key is freed for a retry\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.code),\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.code),\n };\n }\n }\n\n // Protocol-owned headers only; a merchant backend's headers are never proxied\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(res: ServerResponse, err: unknown, message: string): 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 );\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\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 // 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\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 id = ids.next('attempt');\n let row: PaymentAttemptRow;\n try {\n // RETURNING on a successful insert always yields the inserted row\n row = insertPaymentAttemptStmt.get({\n id,\n request_id: reservation.requestId,\n resource_id: reservation.resourceId,\n provider: reservation.provider,\n replay_key: reservation.replayKey,\n status: 'reserved' satisfies PaymentAttempt['status'],\n amount: reservation.amount,\n currency: reservation.currency,\n payer: reservation.payer ?? null,\n payee: reservation.payee ?? null,\n external_reference: null,\n rejection_reason: null,\n created_at: now,\n updated_at: now,\n }) as PaymentAttemptRow;\n } catch (err) {\n if (isUniqueConstraintOn(err, 'payment_attempts.replay_key')) {\n throw new CommerceError(\n 'PAYMENT_REPLAYED',\n `Payment authorization has already been used (replayKey=${reservation.replayKey})`,\n { requestId: reservation.requestId, resourceId: reservation.resourceId },\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"]}