@devlab.group/agent-commerce 1.6.0 → 1.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ap2.js +3 -3
- package/dist/{chunk-74BSEXB5.js → chunk-CBJIT7QP.js} +3 -3
- package/dist/{chunk-74BSEXB5.js.map → chunk-CBJIT7QP.js.map} +1 -1
- package/dist/{chunk-ATTWSFQP.js → chunk-JKEKKXRJ.js} +4 -4
- package/dist/{chunk-ATTWSFQP.js.map → chunk-JKEKKXRJ.js.map} +1 -1
- package/dist/{chunk-IVJC5YLE.js → chunk-N5KRK7YA.js} +3 -3
- package/dist/{chunk-IVJC5YLE.js.map → chunk-N5KRK7YA.js.map} +1 -1
- package/dist/{chunk-RAJGPGJG.js → chunk-VKDXMXHL.js} +3 -3
- package/dist/{chunk-RAJGPGJG.js.map → chunk-VKDXMXHL.js.map} +1 -1
- package/dist/cli/index.js +2 -2
- package/dist/cli/index.js.map +1 -1
- package/dist/index.js +4 -4
- package/dist/mcp.js +1 -1
- package/dist/mpp.js +3 -3
- package/dist/x402.js +4 -4
- package/package.json +7 -5
package/dist/cli/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config/filename.ts","../../src/core/domain/common.ts","../../src/core/domain/event.ts","../../src/core/domain/resource.ts","../../src/core/errors/codes.ts","../../src/core/errors/commerce-error.ts","../../src/core/errors/index.ts","../../src/core/is-record.ts","../../src/core/domain/wire.ts","../../src/core/interfaces/logger.ts","../../src/core/interfaces/protocol-adapter.ts","../../src/core/interfaces/runtime.ts","../../src/core/public-types.ts","../../src/core/index.ts","../../src/authorization/ap2/constants.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/core/execution/index.ts","../../src/payments/mpp/constants.ts","../../src/payments/x402/networks.ts","../../src/protocols/acp/constants.ts","../../src/config/env.ts","../../src/payments/x402/local-chain/accounts.ts","../../src/payments/x402/dev-key-guard.ts","../../src/payments/x402/guardrails.ts","../../src/protocols/mcp/constants.ts","../../src/config/schema.ts","../../src/config/load.ts","../../src/config/index.ts","../../src/cli/program.ts","../../src/cli/commands/demo.ts","../../src/cli/commands/doctor.ts","../../src/authorization/ap2/descriptor.ts","../../src/protocols/a2a/constants.ts","../../src/protocols/a2a/descriptor.ts","../../src/protocols/acp/descriptor.ts","../../src/storage/receipts/store.ts","../../src/version.ts","../../src/storage/sqlite.ts","../../src/storage/receipts/redact.ts","../../src/storage/receipts/rows.ts","../../src/storage/receipts/schema.ts","../../src/cli/lib/config-client.ts","../../src/cli/lib/http.ts","../../src/cli/lib/init-config.ts","../../src/payments/x402/local-chain/manifest.ts","../../src/cli/lib/manifest-env.ts","../../src/cli/lib/mask.ts","../../package.json","../../src/cli/lib/versions.ts","../../src/cli/commands/import-openapi.ts","../../src/openapi/discover.ts","../../src/openapi/refs.ts","../../src/openapi/draft.ts","../../src/openapi/request.ts","../../src/openapi/schema.ts","../../src/openapi/load.ts","../../src/cli/commands/init.ts","../../src/cli/commands/validate.ts","../../src/cli/commands/version.ts","../../src/cli/lib/io.ts","../../src/cli/index.ts"],"names":["init_constants","path","text","fs","parseYaml","fsConstants","accessSync","z","existsSync","sameAddress","dirname","loadConfig","typeList","open","isDeepStrictEqual","required","invalid","extname","resolve","writeFile","mkdirSync"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IASa,uBAAA;AATb,IAAA,aAAA,GAAA,KAAA,CAAA;AAAA,EAAA,wBAAA,GAAA;AASO,IAAM,uBAAA,GAA0B,aAAA;AAAA,EAAA;AAAA,CAAA,CAAA;;;ACTvC,IAaM,kBAAA,EAWO,gBAeP,wBAAA,EAGO,oBAAA;AA1Cb,IAAA,WAAA,GAAA,KAAA,CAAA;AAAA,EAAA,2BAAA,GAAA;AAaA,IAAM,kBAAA,GAAiD;AAAA,MACrD,IAAA,EA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AA,MAAM,GAAA;AAAA,EACR;AACF;AAEA,KAAK,IAAA,EAAK","file":"index.js","sourcesContent":["/**\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","// Shared primitive aliases for the canonical domain model. FROZEN CONTRACT\n\n/**\n * A JSON Schema document (in practice a draft 2020-12 subset). Deliberately\n * loose: adapters translate it to their own schema representation. Never treat\n * it as trusted input without validation.\n */\nexport type JsonSchema = Record<string, unknown>;\n\n/** Protocol surfaces a resource can be exposed through */\nexport type ProtocolName = 'http' | 'mcp' | 'a2a' | 'acp';\n\n// A Record over the union fails to compile when a name is missing or extra\nconst PROTOCOL_NAME_KEYS: Record<ProtocolName, true> = {\n http: true,\n mcp: true,\n a2a: true,\n acp: true,\n};\n\n/**\n * The same names as a value, for code that checks one at runtime: config\n * validation and the OpenAPI importer's `--expose`\n */\nexport const PROTOCOL_NAMES: readonly ProtocolName[] = Object.keys(\n PROTOCOL_NAME_KEYS,\n) as ProtocolName[];\n\n/**\n * Payment rails a resource can accept.\n *\n * A resource's list is an ordered candidate list, not a buyer-selected menu.\n * The pipeline uses the first method with an enabled provider, and a\n * rejection ends the request instead of trying another rail. Config requires at\n * least one named rail to be enabled and permits others that are not.\n */\nexport type PaymentMethodName = 'x402' | 'mpp';\n\n// Checked for completeness the same way as PROTOCOL_NAME_KEYS\nconst PAYMENT_METHOD_NAME_KEYS: Record<PaymentMethodName, true> = { x402: true, mpp: true };\n\n/** The same names as a value, for config validation */\nexport const PAYMENT_METHOD_NAMES: readonly PaymentMethodName[] = Object.keys(\n PAYMENT_METHOD_NAME_KEYS,\n) as PaymentMethodName[];\n\n/**\n * Authorization methods a resource can require. Neither a transport nor a\n * payment rail: it proves the purchase was approved, and sits beside the\n * payment rather than replacing it.\n */\nexport type AuthorizationMethodName = 'ap2';\n\n/** ISO-8601 timestamp string, always UTC with millisecond precision */\nexport type IsoTimestamp = string;\n\n/**\n * A decimal amount as a string in the currency's display unit (for example\n * \"0.01\" USDC), never a float and never base units. Payment providers convert\n * it to on-chain base units.\n */\nexport type DecimalAmount = string;\n\n/** Health of an individual adapter or subsystem */\nexport interface AdapterHealth {\n readonly status: 'pass' | 'warn' | 'fail';\n readonly detail?: string;\n readonly checkedAt: IsoTimestamp;\n readonly durationMs?: number;\n}\n\n/** Describes an adapter's supported surface for diagnostics */\nexport interface AdapterDescriptor {\n readonly name: string;\n readonly kind: 'protocol' | 'payment' | 'storage' | 'authorization';\n /** Version of this adapter implementation, independent of the spec */\n readonly implementationVersion: string;\n /** Exact pinned specification revision this adapter targets */\n readonly supportedSpec: string;\n readonly capabilities: readonly string[];\n readonly status: 'stable' | 'experimental' | 'planned';\n /** Capabilities explicitly not implemented, printed by `doctor` */\n readonly unsupported?: readonly string[];\n}\n","/**\n * Canonical commerce events. FROZEN CONTRACT. Every event in one flow shares\n * one `requestId`, which correlates logs, payment attempts, backend calls and\n * receipts.\n */\nimport type { IsoTimestamp } from './common';\n\nexport const COMMERCE_EVENT_TYPES = [\n 'resource.discovered',\n 'resource.requested',\n 'payment.required',\n 'payment.rejected',\n 'payment.verified',\n 'payment.settled',\n // The same two types for every authorization method, so an audit-trail\n // reader never has to know what AP2 is\n 'authorization.verified',\n 'authorization.rejected',\n 'backend.called',\n 'backend.failed',\n 'resource.delivered',\n] as const;\n\nexport type CommerceEventType = (typeof COMMERCE_EVENT_TYPES)[number];\n\nexport interface CommerceEvent {\n readonly id: string;\n readonly type: CommerceEventType;\n readonly requestId: string;\n readonly resourceId?: string;\n readonly at: IsoTimestamp;\n /** Protocol adapter that originated the request, e.g. 'mcp' or 'http' */\n readonly adapter?: string;\n readonly paymentProvider?: string;\n readonly durationMs?: number;\n readonly status?: 'ok' | 'error';\n /** Non-secret, structured detail. Must never contain keys, headers or proofs */\n readonly data?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Sink for canonical events. `emit` must not throw: a sink failure must never\n * fail an otherwise successful commerce flow.\n */\nexport interface EventSink {\n emit(event: CommerceEvent): Promise<void>;\n}\n","// Canonical resource model. FROZEN CONTRACT\nimport type {\n AuthorizationMethodName,\n DecimalAmount,\n JsonSchema,\n PaymentMethodName,\n ProtocolName,\n} from './common';\n\n/** HTTP methods a backend handler may use */\nexport type BackendMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * How the gateway calls the merchant's existing backend.\n *\n * Backend URLs come from operator configuration only, never from users or\n * agents (docs/security.md, SSRF). Secret header values belong in `${ENV_VAR}`\n * placeholders resolved by the config loader, not in plaintext configuration.\n */\nexport interface BackendHandler {\n readonly type: 'http';\n readonly method: BackendMethod;\n readonly url: string;\n readonly headers?: Readonly<Record<string, string>>;\n /** Hard upper bound on the backend call. Defaults to `DEFAULT_BACKEND_TIMEOUT_MS` */\n readonly timeoutMs?: number;\n /**\n * Names the top-level input properties carrying each part of the request.\n *\n * When absent, `{param}` values come from top-level input and everything left\n * over becomes the query string (GET/DELETE) or the whole JSON body\n * (POST/PUT/PATCH). That cannot express an operation with path, query and\n * body at once, such as `POST /users/{userId}/orders?notify=true`.\n *\n * When present, each group comes from its named property, and top-level input\n * that no binding names is not forwarded.\n */\n readonly inputBindings?: {\n readonly path?: string;\n readonly query?: string;\n readonly body?: string;\n };\n}\n\n/** Default backend timeout when a resource does not specify one */\nexport const DEFAULT_BACKEND_TIMEOUT_MS = 10_000;\n\n/**\n * Canonical pricing. `dynamic` exists in the type for forward compatibility;\n * config validation rejects it and the pipeline refuses it as defense in depth.\n */\nexport type Pricing =\n | { readonly type: 'free' }\n | {\n readonly type: 'fixed';\n readonly amount: DecimalAmount;\n readonly currency: string;\n }\n | {\n readonly type: 'dynamic';\n readonly resolver: string;\n };\n\n/**\n * A merchant capability exposed to agents. Protocol adapters map it outward and\n * never define their own parallel notion of a resource.\n */\nexport interface CommerceResource {\n readonly id: string;\n readonly name: string;\n readonly description?: string;\n readonly inputSchema?: JsonSchema;\n readonly outputSchema?: JsonSchema;\n readonly handler: BackendHandler;\n readonly pricing: Pricing;\n readonly exposedVia: readonly ProtocolName[];\n readonly paymentMethods: readonly PaymentMethodName[];\n /**\n * Authorization the buyer must present in addition to payment. Opt-in per\n * resource. It sits beside `paymentMethods`, not inside it, because an\n * authorization method is not a payment rail and must never be selectable as\n * one.\n */\n readonly authorization?: {\n readonly required: readonly AuthorizationMethodName[];\n };\n}\n\n/** Read-only view of every configured resource */\nexport interface ResourceRegistry {\n get(id: string): CommerceResource | undefined;\n list(): readonly CommerceResource[];\n /** Resources exposed through a given protocol surface */\n listExposedVia(protocol: ProtocolName): readonly CommerceResource[];\n has(id: string): boolean;\n}\n","/**\n * Typed domain error codes. FROZEN CONTRACT. Protocol adapters map them into\n * their own response format. Never throw a bare string or untyped Error across\n * an area boundary.\n */\nexport const COMMERCE_ERROR_CODES = [\n 'CONFIG_INVALID',\n 'RESOURCE_NOT_FOUND',\n 'INPUT_INVALID',\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 'BACKEND_TIMEOUT',\n 'BACKEND_ERROR',\n 'PROTOCOL_UNSUPPORTED',\n 'GATEWAY_BUSY',\n 'STORAGE_ERROR',\n 'INTERNAL_ERROR',\n] as const;\n\nexport type CommerceErrorCode = (typeof COMMERCE_ERROR_CODES)[number];\n\n/**\n * Canonical HTTP status for each error code. Every payment failure maps to a\n * 4xx or 5xx status, never to a delivery.\n */\nexport const COMMERCE_ERROR_HTTP_STATUS: Readonly<Record<CommerceErrorCode, number>> = {\n CONFIG_INVALID: 500,\n RESOURCE_NOT_FOUND: 404,\n INPUT_INVALID: 400,\n PAYMENT_REQUIRED: 402,\n PAYMENT_INVALID: 402,\n PAYMENT_REPLAYED: 409,\n PAYMENT_PROVIDER_UNAVAILABLE: 503,\n PAYMENT_SETTLEMENT_FAILED: 502,\n // 403, not 402: a 402 tells a client to pay and retry, which cannot fix a\n // missing or rejected mandate, and a client that auto-pays on 402 would be\n // charged for a request that was never going to be delivered\n AUTHORIZATION_REQUIRED: 403,\n AUTHORIZATION_INVALID: 403,\n AUTHORIZATION_REPLAYED: 409,\n AUTHORIZATION_PROVIDER_UNAVAILABLE: 503,\n BACKEND_TIMEOUT: 504,\n BACKEND_ERROR: 502,\n PROTOCOL_UNSUPPORTED: 501,\n GATEWAY_BUSY: 503,\n STORAGE_ERROR: 500,\n INTERNAL_ERROR: 500,\n};\n\n/** Codes for which a client may reasonably retry the same request */\nexport const RETRYABLE_ERROR_CODES: ReadonlySet<CommerceErrorCode> = new Set([\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n // The verifier or replay store was unreachable, so the mandate got no\n // verdict. The same proof can verify once the outage clears.\n 'AUTHORIZATION_PROVIDER_UNAVAILABLE',\n 'BACKEND_TIMEOUT',\n // Load shedding is transient: the caller should back off and try again.\n // Clients act on this flag, and leaving it out would make a momentary\n // throttle look like a permanent failure.\n 'GATEWAY_BUSY',\n]);\n","// The single error type crossing area boundaries. FROZEN CONTRACT\nimport { COMMERCE_ERROR_HTTP_STATUS, type CommerceErrorCode, RETRYABLE_ERROR_CODES } from './codes';\n\nexport interface CommerceErrorOptions {\n /** Structured, non-secret detail safe to return to a client */\n readonly details?: Readonly<Record<string, unknown>>;\n readonly cause?: unknown;\n readonly requestId?: string;\n readonly resourceId?: string;\n /** Override the default HTTP status for this code */\n readonly httpStatus?: number;\n}\n\n/** Serializable wire form of a CommerceError */\nexport interface CommerceErrorInfo {\n readonly code: CommerceErrorCode;\n readonly message: string;\n readonly httpStatus: number;\n readonly retryable: boolean;\n readonly requestId?: string;\n readonly resourceId?: string;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\nexport class CommerceError extends Error {\n readonly code: CommerceErrorCode;\n readonly httpStatus: number;\n readonly retryable: boolean;\n readonly details?: Readonly<Record<string, unknown>>;\n readonly requestId?: string;\n readonly resourceId?: string;\n\n constructor(code: CommerceErrorCode, message: string, options: CommerceErrorOptions = {}) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = 'CommerceError';\n this.code = code;\n this.httpStatus = options.httpStatus ?? COMMERCE_ERROR_HTTP_STATUS[code];\n this.retryable = RETRYABLE_ERROR_CODES.has(code);\n if (options.details !== undefined) this.details = options.details;\n if (options.requestId !== undefined) this.requestId = options.requestId;\n if (options.resourceId !== undefined) this.resourceId = options.resourceId;\n Error.captureStackTrace?.(this, CommerceError);\n }\n\n /** Non-secret, client-safe representation. `cause` is never included */\n toInfo(): CommerceErrorInfo {\n return {\n code: this.code,\n message: this.message,\n httpStatus: this.httpStatus,\n retryable: this.retryable,\n ...(this.requestId !== undefined ? { requestId: this.requestId } : {}),\n ...(this.resourceId !== undefined ? { resourceId: this.resourceId } : {}),\n ...(this.details !== undefined ? { details: this.details } : {}),\n };\n }\n}\n\nexport function isCommerceError(value: unknown): value is CommerceError {\n return value instanceof CommerceError;\n}\n\n/**\n * Passes an existing CommerceError through. Other thrown values become a\n * CommerceError with a caller-chosen message, for example\n * `toCommerceError(err, 'BACKEND_ERROR', 'Backend call failed')`.\n *\n * Arbitrary Error messages may contain internal URLs, hostnames or file paths.\n * The original value remains on `cause` for internal logging; `toInfo()` and\n * `toErrorEnvelope()` do not serialize it.\n */\nexport function toCommerceError(\n value: unknown,\n fallbackCode: CommerceErrorCode = 'INTERNAL_ERROR',\n fallbackMessage = 'Unexpected internal error',\n): CommerceError {\n if (isCommerceError(value)) return value;\n return new CommerceError(fallbackCode, fallbackMessage, { cause: value });\n}\n\n/** A thrown value reduced to its message and name, for a log line */\nexport function 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/**\n * `Name: message` for a log line, with every URL cut to its scheme and host,\n * because a backend or RPC URL can carry a credential in its userinfo, path or\n * query\n */\nexport function redactedErrorText(value: unknown): string {\n const text = value instanceof Error ? `${value.name}: ${value.message}` : String(value);\n return text.replace(/\\b[a-z][a-z\\d+.-]*:\\/\\/[^\\s\"'<>]+/gi, (match) => {\n try {\n const url = new URL(match);\n return `${url.protocol}//${url.host}`;\n } catch {\n return '[unparseable URL]';\n }\n });\n}\n\n// Deepest `cause` level toLogInfo() follows, which also ends a cyclic chain\nconst MAX_LOGGED_CAUSES = 5;\n\n/**\n * An error for an operator log line: the `toInfo()` fields plus the `cause`\n * chain that `toInfo()` leaves out, each level as `redactedErrorText()` gives it\n */\nexport function toLogInfo(\n value: unknown,\n): CommerceErrorInfo & { readonly cause?: readonly string[] } {\n const error = toCommerceError(value);\n const cause: string[] = [];\n let current = error.cause;\n while (current !== undefined && cause.length < MAX_LOGGED_CAUSES) {\n cause.push(redactedErrorText(current));\n current = current instanceof Error ? current.cause : undefined;\n }\n return cause.length > 0 ? { ...error.toInfo(), cause } : error.toInfo();\n}\n","export * from './codes';\nexport * from './commerce-error';\n","/** A non-null, non-array object. The prototype is not checked */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","/**\n * Gateway-defined wire envelopes and carriers. FROZEN CONTRACT.\n *\n * The HTTP routes and the MCP and A2A adapters build their \"payment required\"\n * and \"error\" bodies with these helpers, so those surfaces send the same\n * shapes. The ACP adapter maps errors to ACP's own error format instead.\n */\n\nimport { CommerceError, type CommerceErrorCode } from '../errors';\nimport { isRecord } from '../is-record';\nimport type { AuthorizationRequirement, AuthorizationSubmission } from './authorization';\nimport type { DecimalAmount, IsoTimestamp, PaymentMethodName } from './common';\nimport type { PaymentSubmission } from './payment';\nimport type { DeliveredOutcome, PaymentRequiredOutcome } from './request';\nimport type { CommerceResource } from './resource';\n\n/**\n * Reserved input property carrying a payment proof on protocols with no header\n * channel (MCP tool calls, A2A message data). HTTP uses a header instead.\n */\nexport const PAYMENT_INPUT_FIELD = '_payment';\n\n/**\n * HTTP request header carrying an x402 payment proof. MPP proofs use\n * `Authorization: Payment ...` instead.\n *\n * The x402 v2 header names, lowercased as Node presents incoming headers. v1's\n * `X-PAYMENT` / `X-PAYMENT-RESPONSE` pair is not accepted: honoring both\n * versions would mean two verification paths for the same money.\n */\nexport const PAYMENT_HEADER = 'payment-signature';\n\n/** HTTP response header carrying the settlement result */\nexport const PAYMENT_RESPONSE_HEADER = 'payment-response';\n\n/**\n * Reserved input property carrying an authorization proof, the counterpart of\n * {@link PAYMENT_INPUT_FIELD}.\n *\n * `_payment` is a bare string whose method is taken from the resource's first\n * payment method. This field is a `{ method, payload }` object, because the\n * method of a security control should be stated, not inferred.\n */\nexport const AUTHORIZATION_INPUT_FIELD = '_authorization';\n\n/**\n * Every input property name the gateway claims for itself. The config loader\n * rejects a resource declaring one, protocol adapters lift them out of client\n * input, and the pipeline strips them again as defense in depth.\n */\nexport const RESERVED_INPUT_FIELDS: readonly string[] = [\n PAYMENT_INPUT_FIELD,\n AUTHORIZATION_INPUT_FIELD,\n];\n\n/**\n * HTTP request header carrying the authorization proof: base64url-encoded JSON\n * of the same `{ method, payload }` object the reserved input field carries.\n *\n * An Agent Commerce carrier, not a header from any authorization\n * specification. It is namespaced rather than reusing `Authorization`, which\n * already carries other credentials, including MPP payment proofs.\n */\nexport const AUTHORIZATION_HEADER = 'agent-authorization';\n\n/**\n * Hard cap on the encoded `Agent-Authorization` header.\n *\n * Node's default limit is 16 KiB across all request headers, and a request over\n * it is refused before the gateway sees it. Capping well below that gives an\n * oversized proof a deterministic `AUTHORIZATION_INVALID` naming the limit.\n */\nexport const MAX_AUTHORIZATION_HEADER_BYTES = 8192;\n\n/**\n * HTTP response header carrying the base64 x402 challenge on a 402.\n *\n * The body still carries the richer {@link PaymentRequiredEnvelope}, the only\n * channel MCP has, but an x402 v2 client reads the challenge from this header\n * and ignores the body, so both are sent.\n */\nexport const PAYMENT_REQUIRED_HEADER = 'payment-required';\n\n/**\n * Key under which a protocol adapter attaches a {@link DeliverySummary} to its\n * result metadata: MCP's `CallToolResult._meta` and the A2A task artifact's\n * metadata.\n *\n * Part of the frozen contract because producer and consumer must agree on it;\n * both import this constant. Follows MCP's `<namespace>/<name>` convention for\n * `_meta` keys.\n */\nexport const DELIVERY_SUMMARY_META_KEY = 'agent-commerce/delivery';\n\nexport interface PaymentRequiredEnvelope {\n readonly status: 'payment-required';\n readonly code: 'PAYMENT_REQUIRED';\n readonly requestId: string;\n readonly resourceId: string;\n readonly message: string;\n readonly payment: {\n readonly provider: PaymentMethodName;\n readonly version: string;\n readonly amount: DecimalAmount;\n readonly currency: string;\n readonly destination: string;\n readonly network?: string;\n readonly asset?: string;\n readonly expiresAt?: IsoTimestamp;\n /** Provider-native requirement objects, passed through verbatim */\n readonly accepts: readonly Readonly<Record<string, unknown>>[];\n /**\n * The provider's own challenge document, verbatim (see\n * {@link PaymentChallenge.envelope}). Present for providers that have one;\n * a buyer's protocol client can hand it straight to its SDK.\n */\n readonly envelope?: Readonly<Record<string, unknown>>;\n };\n /**\n * Present only when the resource also requires an authorization proof, so a\n * client learns before it spends anything that paying alone will not get the\n * resource delivered. A client that ignores the field sees the plain\n * envelope. The proof comes from the merchant's own approval flow, outside\n * the gateway.\n */\n readonly authorization?: {\n readonly required: readonly AuthorizationRequirement[];\n };\n}\n\nexport interface ErrorEnvelope {\n readonly status: 'error';\n readonly code: CommerceErrorCode;\n readonly message: string;\n readonly retryable: boolean;\n readonly requestId?: string;\n readonly resourceId?: string;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * What a buyer learns about their own completed purchase: the request, whether\n * it settled, and the settlement reference they can check on-chain. The\n * merchant's ledger is not theirs to read, which is why `/api/receipts` is an\n * operator route behind `server.adminToken`.\n */\nexport interface DeliverySummary {\n readonly requestId: string;\n readonly resourceId: string;\n readonly receiptId: string;\n readonly deliveredAt: IsoTimestamp;\n readonly payment?: {\n readonly status: 'verified' | 'settled' | 'rejected';\n readonly amount: DecimalAmount;\n readonly currency: string;\n /** Settlement reference, e.g. an on-chain transaction hash */\n readonly externalReference?: string;\n readonly network?: string;\n };\n}\n\n/** Build the payer-facing summary of a delivered outcome */\nexport function toDeliverySummary(outcome: DeliveredOutcome): DeliverySummary {\n const p = outcome.payment;\n return {\n requestId: outcome.requestId,\n resourceId: outcome.resourceId,\n receiptId: outcome.receipt.id,\n deliveredAt: outcome.receipt.deliveredAt,\n ...(p !== undefined\n ? {\n payment: {\n status: p.status,\n amount: p.amount,\n currency: p.currency,\n ...(p.externalReference !== undefined\n ? { externalReference: p.externalReference }\n : {}),\n ...(p.network !== undefined ? { network: p.network } : {}),\n },\n }\n : {}),\n };\n}\n\nexport function toPaymentRequiredEnvelope(\n outcome: PaymentRequiredOutcome,\n): PaymentRequiredEnvelope {\n const r = outcome.requirement;\n return {\n status: 'payment-required',\n code: 'PAYMENT_REQUIRED',\n requestId: outcome.requestId,\n resourceId: outcome.resourceId,\n message: `Payment of ${r.amount} ${r.currency} is required for resource \"${outcome.resourceId}\". Retry with a ${r.provider} payment proof.`,\n payment: {\n provider: r.provider,\n version: r.challenge.version,\n amount: r.amount,\n currency: r.currency,\n destination: r.destination,\n ...(r.network !== undefined ? { network: r.network } : {}),\n ...(r.asset !== undefined ? { asset: r.asset } : {}),\n ...(r.expiresAt !== undefined ? { expiresAt: r.expiresAt } : {}),\n accepts: r.challenge.accepts,\n ...(r.challenge.envelope !== undefined ? { envelope: r.challenge.envelope } : {}),\n },\n ...(outcome.authorization !== undefined && outcome.authorization.length > 0\n ? { authorization: { required: outcome.authorization } }\n : {}),\n };\n}\n\nexport function toErrorEnvelope(error: CommerceError): ErrorEnvelope {\n const info = error.toInfo();\n return {\n status: 'error',\n code: info.code,\n message: info.message,\n retryable: info.retryable,\n ...(info.requestId !== undefined ? { requestId: info.requestId } : {}),\n ...(info.resourceId !== undefined ? { resourceId: info.resourceId } : {}),\n ...(info.details !== undefined ? { details: info.details } : {}),\n };\n}\n\nexport function isPaymentRequiredEnvelope(value: unknown): value is PaymentRequiredEnvelope {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as PaymentRequiredEnvelope).status === 'payment-required' &&\n typeof (value as PaymentRequiredEnvelope).payment === 'object'\n );\n}\n\n/**\n * Parses the `{ method, payload }` authorization object, whichever carrier\n * brought it. Absent returns `undefined`; malformed throws\n * `AUTHORIZATION_INVALID`.\n *\n * An unusable `_payment` is dropped, which leaves the buyer a 402 to act on. A\n * dropped authorization would instead come back as \"not authorized\", with no\n * way to tell a rejected mandate from a typo in the object around it.\n */\nexport function parseAuthorizationSubmission(\n value: unknown,\n requestId?: string,\n): AuthorizationSubmission | undefined {\n if (value === undefined || value === null) return undefined;\n\n const fail = (detail: string): never => {\n throw new CommerceError('AUTHORIZATION_INVALID', `Malformed authorization: ${detail}`, {\n ...(requestId !== undefined ? { requestId } : {}),\n });\n };\n\n if (!isRecord(value)) {\n return fail(`expected an object with \"method\" and \"payload\", got ${typeof value}`);\n }\n const method = value['method'];\n const payload = value['payload'];\n\n // Compared against the literal rather than a registry: a second method needs\n // a second verifier, a deliberate addition rather than a string that starts\n // working because a client sent it\n if (method !== 'ap2') {\n fail(`unsupported method ${typeof method === 'string' ? `\"${method}\"` : typeof method}`);\n }\n if (typeof payload !== 'string' || payload.length === 0) {\n fail('\"payload\" must be a non-empty string');\n }\n\n return { method: 'ap2', payload: payload as string };\n}\n\n/**\n * Decodes the base64url JSON `Agent-Authorization` header. The size check runs\n * on the encoded value, so an oversized header costs a length comparison rather\n * than a decode and a JSON parse.\n */\nexport function parseAuthorizationHeader(\n raw: string | readonly string[] | undefined,\n requestId?: string,\n): AuthorizationSubmission | undefined {\n const value = Array.isArray(raw) ? raw[0] : (raw as string | undefined);\n if (value === undefined || value.length === 0) return undefined;\n\n const fail = (detail: string): never => {\n throw new CommerceError('AUTHORIZATION_INVALID', `Malformed authorization: ${detail}`, {\n ...(requestId !== undefined ? { requestId } : {}),\n });\n };\n\n if (Buffer.byteLength(value, 'utf8') > MAX_AUTHORIZATION_HEADER_BYTES) {\n fail(`header exceeds the ${MAX_AUTHORIZATION_HEADER_BYTES}-byte limit`);\n }\n\n let decoded: unknown;\n try {\n decoded = JSON.parse(Buffer.from(value, 'base64url').toString('utf8'));\n } catch {\n // Nothing from the exception is repeated back: a JSON parse error quotes\n // the input it choked on, which here is whatever the caller sent\n fail('header is not base64url-encoded JSON');\n }\n return parseAuthorizationSubmission(decoded, requestId);\n}\n\n/**\n * Splits raw client input into resource input plus the reserved fields, for\n * protocols that carry them in the input object (MCP tool arguments, A2A\n * message data). HTTP carries both in headers.\n *\n * A payment proof is labeled with the resource's first payment method.\n * `createGateway` puts provider-backed methods first so the label matches the\n * pipeline's selection; a custom registry must keep that order. A resource with\n * no payment method gets no payment proof, so the request reaches the pipeline\n * unpaid.\n */\nexport function extractReservedInputFields(\n rawInput: Record<string, unknown>,\n resource: CommerceResource | undefined,\n requestId?: string,\n): {\n input: Record<string, unknown>;\n payment?: PaymentSubmission;\n authorization?: AuthorizationSubmission;\n} {\n const {\n [PAYMENT_INPUT_FIELD]: paymentValue,\n [AUTHORIZATION_INPUT_FIELD]: authorizationValue,\n ...input\n } = rawInput;\n\n const method = resource?.paymentMethods[0];\n const payment =\n typeof paymentValue === 'string' && paymentValue.length > 0 && method !== undefined\n ? ({ method, payload: paymentValue } satisfies PaymentSubmission)\n : undefined;\n const authorization = parseAuthorizationSubmission(authorizationValue, requestId);\n\n return {\n input,\n ...(payment !== undefined ? { payment } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n };\n}\n","/**\n * Minimal structural logger. Core does not depend on pino; the gateway injects\n * a pino instance that satisfies this shape.\n *\n * Never log secrets: private keys, seed phrases, Authorization headers or\n * payment authorization payloads.\n */\nexport interface Logger {\n debug(obj: Record<string, unknown>, msg?: string): void;\n info(obj: Record<string, unknown>, msg?: string): void;\n warn(obj: Record<string, unknown>, msg?: string): void;\n error(obj: Record<string, unknown>, msg?: string): void;\n child(bindings: Record<string, unknown>): Logger;\n}\n\n/** A logger that discards everything */\nexport const NOOP_LOGGER: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n child: () => NOOP_LOGGER,\n};\n","/**\n * Protocol adapter boundary. FROZEN CONTRACT.\n *\n * An adapter translates a protocol's wire format into a `CanonicalRequest`,\n * hands it to the execution pipeline and maps the outcome back. It must not\n * call merchant backends, implement payment logic or hold its own copy of the\n * canonical model. A failure while starting or serving one adapter must not\n * stop the others.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { AdapterDescriptor, AdapterHealth, ProtocolName } from '../domain/common';\nimport type { EventSink } from '../domain/event';\nimport type { ExecutionPipeline } from '../domain/request';\nimport type { ResourceRegistry } from '../domain/resource';\nimport type { Logger } from './logger';\nimport type { Clock, IdGenerator } from './runtime';\n\n/** Everything an adapter is given. Nothing else is available to it */\nexport interface ProtocolAdapterContext {\n readonly pipeline: ExecutionPipeline;\n readonly resources: ResourceRegistry;\n readonly events: EventSink;\n readonly logger: Logger;\n readonly clock: Clock;\n readonly ids: IdGenerator;\n /** Externally reachable base URL of the gateway, from config */\n readonly publicBaseUrl: string;\n}\n\nexport interface ProtocolAdapter {\n readonly name: ProtocolName;\n readonly descriptor: AdapterDescriptor;\n\n start(context: ProtocolAdapterContext): Promise<void>;\n health(): Promise<AdapterHealth>;\n stop(): Promise<void>;\n}\n\n/**\n * A protocol adapter served over HTTP. The gateway mounts `handleHttp` at\n * `mountPath` with raw Node request and response objects, so adapters stay\n * independent of the HTTP framework.\n *\n * Guarantee: `req` arrives with its body stream unread. The gateway suppresses\n * every body parser on the mount, so an adapter whose SDK reads the body itself\n * (MCP's Streamable HTTP transport) can do so. The adapter owns reading,\n * size-limiting beyond the gateway's own cap, and parsing.\n *\n * The guarantee can break silently. Fastify prefers its exact-match\n * `application/json` and `text/plain` parsers over a `'*'` wildcard, so a\n * wildcard no-op alone lets the JSON parser drain the body and the adapter\n * reads an empty stream. The MCP conformance suite drives `handleHttp` over a\n * bare `node:http` server and cannot catch it, so any change to adapter mounting\n * needs a test that POSTs a JSON body through the real gateway and asserts the\n * adapter received it intact.\n */\nexport interface HttpProtocolAdapter extends ProtocolAdapter {\n /** Path prefix the gateway mounts this adapter at, e.g. '/mcp' */\n readonly mountPath: string;\n handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void>;\n /**\n * Fixed paths this adapter owns outside its mount, for protocols whose\n * specification pins a discovery URL (A2A's `/.well-known/agent-card.json`).\n * The gateway mounts them with the same guarantees as `mountPath`: unread\n * body, concurrency cap and failure isolation.\n */\n readonly additionalHttpRoutes?: readonly AdapterHttpRoute[];\n}\n\n/**\n * One fixed, method-scoped route owned by an adapter. Unlike `mountPath` it\n * registers no wildcard and matches exactly the path given.\n */\nexport interface AdapterHttpRoute {\n readonly method: 'GET' | 'POST';\n /** Absolute gateway path, e.g. '/.well-known/agent-card.json' */\n readonly path: string;\n handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void>;\n}\n\nexport function isHttpProtocolAdapter(adapter: ProtocolAdapter): adapter is HttpProtocolAdapter {\n return typeof (adapter as HttpProtocolAdapter).handleHttp === 'function';\n}\n","// Time and ids are injected so tests can be deterministic\nimport type { IsoTimestamp } from '../domain/common';\n\nexport interface Clock {\n now(): Date;\n nowIso(): IsoTimestamp;\n /** Milliseconds since an arbitrary origin; use for durations only */\n monotonicMs(): number;\n}\n\nexport interface IdGenerator {\n /** Opaque, collision-resistant identifier */\n next(prefix?: string): string;\n}\n\nexport const systemClock: Clock = {\n now: () => new Date(),\n nowIso: () => new Date().toISOString(),\n monotonicMs: () => performance.now(),\n};\n","/**\n * FROZEN PUBLIC CONTRACT since v0.1.0-alpha (freeze record:\n * docs/contracts.md). The canonical domain model, errors and injection\n * interfaces are re-exported here. Changes to this public API require contract\n * review; `npm run check:contract` compares the resolved types with a committed\n * baseline.\n *\n * Do not redeclare these shapes locally. If something is missing, add it here\n * rather than creating a parallel type.\n */\n\nexport type {\n AuthorizationFinalizeContext,\n AuthorizationProvider,\n AuthorizationRecord,\n AuthorizationRequirement,\n AuthorizationSubmission,\n AuthorizationVerification,\n AuthorizationVerificationContext,\n} from './domain/authorization';\n// --- canonical domain ------------------------------------------------------\nexport type {\n AdapterDescriptor,\n AdapterHealth,\n AuthorizationMethodName,\n DecimalAmount,\n IsoTimestamp,\n JsonSchema,\n PaymentMethodName,\n ProtocolName,\n} from './domain/common';\nexport { PAYMENT_METHOD_NAMES, PROTOCOL_NAMES } from './domain/common';\nexport type { CommerceEvent, CommerceEventType, EventSink } from './domain/event';\nexport { COMMERCE_EVENT_TYPES } from './domain/event';\n\nexport type {\n PaymentChallenge,\n PaymentContext,\n PaymentProvider,\n PaymentRequirement,\n PaymentResult,\n PaymentSettlementContext,\n PaymentSubmission,\n PaymentVerificationContext,\n} from './domain/payment';\n\nexport type { CommerceReceipt, PaymentAttempt } from './domain/receipt';\nexport type {\n CanonicalRequest,\n DeliveredOutcome,\n ExecutionOutcome,\n ExecutionPipeline,\n PaymentRequiredOutcome,\n} from './domain/request';\nexport type {\n BackendHandler,\n BackendMethod,\n CommerceResource,\n Pricing,\n ResourceRegistry,\n} from './domain/resource';\nexport { DEFAULT_BACKEND_TIMEOUT_MS } from './domain/resource';\nexport type {\n DeliverySummary,\n ErrorEnvelope,\n PaymentRequiredEnvelope,\n} from './domain/wire';\nexport {\n AUTHORIZATION_HEADER,\n AUTHORIZATION_INPUT_FIELD,\n DELIVERY_SUMMARY_META_KEY,\n extractReservedInputFields,\n isPaymentRequiredEnvelope,\n MAX_AUTHORIZATION_HEADER_BYTES,\n PAYMENT_HEADER,\n PAYMENT_INPUT_FIELD,\n PAYMENT_REQUIRED_HEADER,\n PAYMENT_RESPONSE_HEADER,\n parseAuthorizationHeader,\n parseAuthorizationSubmission,\n RESERVED_INPUT_FIELDS,\n toDeliverySummary,\n toErrorEnvelope,\n toPaymentRequiredEnvelope,\n} from './domain/wire';\n\n// --- errors ----------------------------------------------------------------\nexport type { CommerceErrorCode, CommerceErrorInfo, CommerceErrorOptions } from './errors';\nexport {\n COMMERCE_ERROR_CODES,\n COMMERCE_ERROR_HTTP_STATUS,\n CommerceError,\n isCommerceError,\n RETRYABLE_ERROR_CODES,\n toCommerceError,\n} from './errors';\n\n// --- injection boundaries --------------------------------------------------\nexport type { BackendExecutor, BackendRequest, BackendResponse } from './interfaces/backend';\nexport type { Logger } from './interfaces/logger';\nexport { NOOP_LOGGER } from './interfaces/logger';\nexport type {\n AdapterHttpRoute,\n HttpProtocolAdapter,\n ProtocolAdapter,\n ProtocolAdapterContext,\n} from './interfaces/protocol-adapter';\nexport { isHttpProtocolAdapter } from './interfaces/protocol-adapter';\nexport type { Clock, IdGenerator } from './interfaces/runtime';\nexport { systemClock } from './interfaces/runtime';\nexport type {\n ListOptions,\n PaymentAttemptReservation,\n PaymentAttemptUpdate,\n ReceiptStore,\n} from './interfaces/store';\n","/**\n * Canonical commerce domain model, typed errors and injection interfaces. No\n * x402, EVM, MCP or JSON-RPC type belongs in src/core; adapters map protocol\n * shapes at their boundaries.\n */\nexport * from './public-types';\n","/**\n * Pinned AP2 identifiers and key policy.\n *\n * AP2 v0.2.0 (2026-04-28, commit b4587ac) is the tagged release this gateway\n * verifies against; unversioned `main` is never implemented against. Config,\n * the verifier and `doctor` all read these, so a bump lands in one place.\n */\n\nexport const AP2_SPEC_VERSION = '0.2.0';\n\n/**\n * Direct only. Autonomous mode needs open mandates, cnf-bound agent keys and\n * constraint evaluation over `checkout.line_items`, none of which is\n * implemented, so it is refused rather than partly served.\n */\nexport const AP2_MODES = ['direct'] as const;\nexport type Ap2Mode = (typeof AP2_MODES)[number];\n\n/**\n * A single algorithm, so `alg=none` and the HMAC family are excluded by\n * construction rather than by a denylist\n */\nexport const AP2_SIGNING_ALGORITHM = 'ES256';\n\n/** The key type and curve ES256 implies. Any other pair is refused at load */\nexport const AP2_KEY_TYPE = 'EC';\nexport const AP2_JWK_CURVE = 'P-256';\n\n/** Byte length of a P-256 coordinate, before base64url encoding */\nexport const AP2_JWK_COORDINATE_BYTES = 32;\n\n/**\n * JWK members a verification key may carry. An allowlist, so private material\n * (`d`) and URL members (`x5u`, `jku`) are refused without the list naming\n * them. Keys are configured inline and never fetched; see docs/security.md.\n */\nexport const AP2_JWK_MEMBERS = ['kty', 'crv', 'x', 'y', 'kid', 'alg', 'use'] as const;\n\n/**\n * Compared against this literal, never as a prefix. `mandate.checkout.open.1`\n * carries spending constraints nothing here evaluates, so accepting it would\n * tell a buyer their limits were checked when nothing read them.\n */\nexport const AP2_CHECKOUT_MANDATE_VCT = 'mandate.checkout.1';\n\n/**\n * Merchant checkout JWTs declare this gateway-specific profile; AP2 leaves\n * the checkout payload out of scope. The identifier is a namespace that\n * clients do not dereference. Merchants sign it into each checkout JWT, so\n * changing the expected value would reject previously signed JWTs.\n */\nexport const AP2_CHECKOUT_PROFILE = 'agent-commerce/ap2/checkout/v1';\n\n/**\n * The only accepted SD-JWT `_sd_alg` (an absent one means sha-256). Any other\n * value is refused rather than hashed as sha-256, which would check a\n * presentation under an algorithm it never claimed.\n */\nexport const AP2_DIGEST_ALGORITHM = 'sha-256';\n\n/** Seconds of clock skew tolerated on mandate and checkout time claims */\nexport const AP2_DEFAULT_CLOCK_SKEW_SECONDS = 60;\n\n/**\n * Skew as wide as a mandate's validity window would stop `exp` rejecting\n * anything. An operator who needs more than five minutes has a clock to fix.\n */\nexport const AP2_MAX_CLOCK_SKEW_SECONDS = 300;\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 * The pipeline implementation: resource registry, backend executor, store event\n * sink and the pipeline itself. Internal to the package: other `src/` areas and\n * tests import it, but it is outside the frozen `public-types.ts` barrel and no\n * package entry point exports it.\n */\n\nexport type { HttpBackendExecutorOptions } from './backend-http';\nexport {\n extractPathParameterNames,\n findUnparsedBraceToken,\n HttpBackendExecutor,\n validateBackendRequestShape,\n} from './backend-http';\nexport type { CreateExecutionPipelineOptions } from './pipeline';\nexport { createExecutionPipeline } from './pipeline';\nexport { createResourceRegistry } from './registry';\nexport type { CreateStoreEventSinkOptions } from './store-event-sink';\nexport { createStoreEventSink } from './store-event-sink';\nexport type { FieldError, ValidationResult, Validator } from './validation';\nexport { compileJsonSchema, isObjectSchemaNode } from './validation';\n","/**\n * The one MPP profile this rail targets.\n *\n * MPP combines a core HTTP authentication layer, an intent, a method and\n * optional extensions. These constants identify the selected combination and\n * the exact specification revision.\n *\n * Importing this metadata does not load `mppx`.\n */\n\n/** Upstream specification repository the pinned drafts were read from */\nexport const MPP_SPEC_REPOSITORY = 'https://github.com/tempoxyz/mpp-specs';\n\n/**\n * Upstream commit the pinned drafts were read at.\n *\n * A draft's content can change without its `-00` name changing, so the name\n * alone does not identify a document; the commit does.\n */\nexport const MPP_SPEC_COMMIT = '806fdb8b8c92cda5c84b8660558921b6bbeef7e0';\n\n/** The core HTTP authentication draft, the `charge` intent, and its EVM method */\nexport const MPP_SPEC_DRAFTS = {\n core: 'draft-httpauth-payment-00',\n intent: 'draft-payment-intent-charge-00',\n method: 'draft-evm-charge-00',\n} as const;\n\n/**\n * Minimum accepted `challengeSecret.length`. This is a configuration floor,\n * not an entropy check.\n */\nexport const MPP_MIN_CHALLENGE_SECRET_LENGTH = 32;\n\n/** Exact `mppx` release the rail is pinned to */\nexport const MPPX_VERSION = '0.10.1';\n\n/**\n * The pinned profile.\n *\n * `intent`, `method` and `credentialType` copy MPP wire identifiers from\n * `mppx` so this module has no peer import; tests detect drift. `assetSymbol`\n * is the pricing currency an MPP resource must use. EVM charge requests carry a\n * numeric `chainId` and token address instead.\n */\nexport const MPP_PROFILE = {\n intent: 'charge',\n method: 'evm',\n credentialType: 'authorization',\n assetSymbol: 'USDC',\n assetDecimals: 6,\n} as const;\n\n/** Supported CAIP-2 networks; gateway config applies the x402 mainnet guardrails */\nexport const MPP_NETWORKS = ['eip155:84532', 'eip155:8453'] as const;\n\nexport type MppNetwork = (typeof MPP_NETWORKS)[number];\n\n/** Default network ID, shared by Base Sepolia and the local development chain */\nexport const MPP_DEFAULT_NETWORK: MppNetwork = 'eip155:84532';\n\nexport function isMppNetwork(value: string): value is MppNetwork {\n return (MPP_NETWORKS as readonly string[]).includes(value);\n}\n\n/** Compact descriptor value naming the core draft, intent and method */\nexport const MPP_SUPPORTED_SPEC = `mpp/${MPP_SPEC_DRAFTS.core} intent=${MPP_PROFILE.intent} method=${MPP_PROFILE.method}`;\n","/**\n * The networks this gateway settles on, as data: the chain id to sign against,\n * a display name, and whether real money is involved.\n *\n * A registry rather than \"parse any `eip155:*`\": the chain id parses from any\n * such string, but whether it is a mainnet does not, and the guardrails key off\n * that. An unknown id is refused at startup instead of passing as a testnet.\n *\n * The local dev chain runs under Base Sepolia's `eip155:84532`, so nothing may\n * infer \"public network\" from the id alone. `resolveDeploymentMode` derives\n * the mode from the facilitator too, and the provider's health check confirms\n * that a local facilitator's node is Anvil.\n */\nimport { CommerceError } from '../../core';\n\n/** Chain id of the local dev chain, which Base Sepolia uses too */\nexport const LOCAL_CHAIN_ID = 84532;\n\nexport interface NetworkProfile {\n /** CAIP-2 identifier, e.g. `eip155:84532` */\n readonly id: string;\n /** Signed into the buyer's EIP-712 domain */\n readonly chainId: number;\n readonly displayName: string;\n readonly kind: 'testnet' | 'mainnet';\n /**\n * The USDC deployment this network settles in, with the EIP-712 domain the\n * token reports. Enforced on mainnet only, since a testnet may use a mock\n * token.\n *\n * `name` is the signed EIP-712 domain name, not the symbol, and the two\n * deployments differ: `\"USDC\"` on Base Sepolia, `\"USD Coin\"` on Base. The\n * values were read back from the contracts.\n */\n readonly canonicalAsset?: {\n readonly symbol: string;\n readonly address: string;\n readonly name: string;\n readonly version: string;\n };\n}\n\nconst PROFILES: readonly NetworkProfile[] = [\n {\n id: 'eip155:84532',\n chainId: 84532,\n displayName: 'Base Sepolia',\n kind: 'testnet',\n canonicalAsset: {\n symbol: 'USDC',\n address: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',\n name: 'USDC',\n version: '2',\n },\n },\n {\n id: 'eip155:8453',\n chainId: 8453,\n displayName: 'Base',\n kind: 'mainnet',\n canonicalAsset: {\n symbol: 'USDC',\n address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n name: 'USD Coin',\n version: '2',\n },\n },\n];\n\nconst BY_ID = new Map(PROFILES.map((profile) => [profile.id, profile]));\n\nexport const SUPPORTED_NETWORK_IDS: readonly string[] = PROFILES.map((p) => p.id);\n\nexport function findNetworkProfile(id: string): NetworkProfile | undefined {\n return BY_ID.get(id);\n}\n\nexport function requireNetworkProfile(id: string, path: string): NetworkProfile {\n const profile = BY_ID.get(id);\n if (!profile) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `${path}: \"${id}\" is not a supported network. Supported CAIP-2 identifiers: ${SUPPORTED_NETWORK_IDS.join(', ')}`,\n { details: { path, network: id } },\n );\n }\n return profile;\n}\n\n/**\n * What a deployment is, as opposed to the network it names. `local` comes from\n * the facilitator: the in-process facilitator makes a deployment local whatever\n * CAIP-2 id it is configured with, which lets diagnostics show `eip155:84532`\n * without claiming public Base Sepolia.\n */\nexport type DeploymentMode = 'local' | 'testnet' | 'mainnet';\n\nexport function resolveDeploymentMode(\n profile: NetworkProfile,\n facilitatorMode: 'local' | 'remote',\n): DeploymentMode {\n if (facilitatorMode === 'local') return 'local';\n return profile.kind;\n}\n\n// The banner an operator must not miss. Printed for mainnet only\nconst LIVE_MAINNET_BANNER = 'LIVE MAINNET MODE - REAL FUNDS';\n\nexport function describeDeploymentMode(mode: DeploymentMode): string {\n return mode === 'mainnet' ? LIVE_MAINNET_BANNER : mode.toUpperCase();\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 * `${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 * Anvil's well-known development accounts.\n *\n * LOCAL DEVELOPMENT ONLY - DO NOT FUND. The keys come from Foundry's public\n * default mnemonic (\"test test ... junk\"), so value sent to these addresses on\n * a real network can be taken by anyone.\n *\n * Index layout on the local demo chain:\n * 0 - deployer and local facilitator signer (pays gas, broadcasts settlement)\n * 1 - merchant settlement destination (`payTo`)\n * 2 - buyer (signs EIP-3009 authorizations; never held by the gateway)\n */\nexport interface AnvilWellKnownAccount {\n readonly address: `0x${string}`;\n readonly privateKey: `0x${string}`;\n}\n\n/** A fixed-length tuple, so indexing by the layout above is typed */\nexport const ANVIL_WELL_KNOWN_ACCOUNTS: readonly [\n AnvilWellKnownAccount,\n AnvilWellKnownAccount,\n AnvilWellKnownAccount,\n] = [\n {\n address: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266',\n privateKey: '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80',\n },\n {\n address: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8',\n privateKey: '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d',\n },\n {\n address: '0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC',\n privateKey: '0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a',\n },\n];\n\nexport const LOCAL_FACILITATOR_ACCOUNT = ANVIL_WELL_KNOWN_ACCOUNTS[0];\nexport const LOCAL_MERCHANT_ACCOUNT = ANVIL_WELL_KNOWN_ACCOUNTS[1];\nexport const LOCAL_BUYER_ACCOUNT = ANVIL_WELL_KNOWN_ACCOUNTS[2];\n\n/** Label printed wherever a dev key appears in output, logs or manifests */\nexport const DEV_KEY_LABEL = 'LOCAL DEVELOPMENT ONLY - DO NOT FUND';\n","/**\n * Rejects well-known Anvil keys and payment destinations when the RPC host\n * does not look local or private. Their private keys are published, so anyone\n * can spend what such an address receives on a public chain.\n *\n * The check uses the RPC hostname because the local chain shares Base\n * Sepolia's chain id. Both guards run at provider construction.\n */\nimport { CommerceError } from '../../core';\nimport { ANVIL_WELL_KNOWN_ACCOUNTS } from './local-chain/accounts';\n\nconst WELL_KNOWN_DEV_KEYS: ReadonlySet<string> = new Set(\n ANVIL_WELL_KNOWN_ACCOUNTS.map((a) => a.privateKey.toLowerCase()),\n);\n\nconst WELL_KNOWN_DEV_ADDRESSES: ReadonlySet<string> = new Set(\n ANVIL_WELL_KNOWN_ACCOUNTS.map((a) => a.address.toLowerCase()),\n);\n\n// `0x` plus 64 hex characters, the only shape `privateKeyToAccount` accepts\nconst PRIVATE_KEY_SHAPE = /^0x[0-9a-fA-F]{64}$/;\n\nexport function isWellKnownDevKey(privateKey: string): boolean {\n return WELL_KNOWN_DEV_KEYS.has(privateKey.toLowerCase());\n}\n\nexport function isWellKnownDevAddress(address: string): boolean {\n return WELL_KNOWN_DEV_ADDRESSES.has(address.toLowerCase());\n}\n\n/**\n * True for loopback addresses, RFC 1918 private ranges, and bare (dot-free)\n * hostnames, such as the compose service name \"anvil\".\n *\n * Bare hostnames are treated as local without resolving them. Operators must\n * point them at a private chain.\n */\nexport function isLikelyLocalOrPrivateHost(hostname: string): boolean {\n const h = hostname.toLowerCase().replace(/^\\[|\\]$/g, '');\n if (h === 'localhost' || h === '::1') return true;\n if (/^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (/^10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (/^192\\.168\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (/^172\\.(1[6-9]|2\\d|3[01])\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (!h.includes('.') && !h.includes(':')) return true; // bare hostname\n return false;\n}\n\nfunction parseHostnameOrThrow(rpcUrl: string): string {\n try {\n return new URL(rpcUrl).hostname;\n } catch (cause) {\n // Never the URL itself: RPC providers commonly put an API key in the path,\n // and this message reaches startup output and CI logs\n throw new CommerceError('CONFIG_INVALID', 'x402 provider: rpcUrl is not a valid URL', {\n cause,\n });\n }\n}\n\n/** Origin only, for diagnostics: RPC URLs often carry an API key in the path or query */\nexport function describeRpc(rpcUrl: string): string {\n try {\n return new URL(rpcUrl).origin;\n } catch {\n return '[unparseable rpcUrl]';\n }\n}\n\n/**\n * Throws CONFIG_INVALID if `signerPrivateKey` is not shaped like a private key,\n * or if it is a well-known dev key and the RPC is not local.\n *\n * The shape check runs first, so a truncated key is reported as malformed\n * instead of passing as \"not a dev key\".\n */\nexport function assertDevKeyIsLocalOnly(rpcUrl: string, signerPrivateKey: string): void {\n if (!PRIVATE_KEY_SHAPE.test(signerPrivateKey)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'x402 provider: facilitator.signerPrivateKey is not a well-formed private key ' +\n '(expected \"0x\" followed by exactly 64 hex characters).',\n );\n }\n\n if (!isWellKnownDevKey(signerPrivateKey)) return; // the operator's own key\n\n const hostname = parseHostnameOrThrow(rpcUrl);\n\n if (!isLikelyLocalOrPrivateHost(hostname)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'x402 provider: facilitator.signerPrivateKey is a well-known Anvil development key, but rpcUrl ' +\n `${describeRpc(rpcUrl)} does not look like a local/private chain. A public dev key must never sign against ` +\n 'a public network: it is instantly drainable and can grief real settlements via nonce exhaustion. ' +\n 'Use a real facilitator key for any non-local RPC, or point rpcUrl at your local/dev chain.',\n );\n }\n}\n\n/**\n * Throws CONFIG_INVALID if `payTo` is a well-known Anvil address and `rpcUrl`\n * does not look local or private.\n *\n * Guards the receiving side, in every facilitator mode. `agent-commerce init`\n * defaults `payTo` to a well-known address for the local demo, and on a real\n * network that default sends every payment where anyone can sweep it.\n */\nexport function assertPayToIsNotDevAddress(rpcUrl: string, payTo: string): void {\n if (!isWellKnownDevAddress(payTo)) return;\n\n const hostname = parseHostnameOrThrow(rpcUrl);\n\n if (!isLikelyLocalOrPrivateHost(hostname)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: \"payTo\" (${payTo}) is a well-known Anvil development address, but rpcUrl ` +\n `${describeRpc(rpcUrl)} does not look like a local/private chain. The private key behind that address ` +\n 'is public knowledge, so any revenue settled to it is immediately spendable by anyone. Set ' +\n '\"payTo\" to your own merchant wallet for any non-local RPC, or point rpcUrl at your ' +\n 'local/dev chain.',\n );\n }\n}\n","/**\n * What must hold before this gateway may settle a payment on the configured\n * network. Two callers share these checks: the provider runs them at\n * construction, so a library consumer who skips our config loader still gets\n * them, and the config loader runs them, so `validate` and `doctor` report\n * them too.\n *\n * Both run before any request, because a failure found in `settle()` would\n * come after the pipeline reserved the buyer's replay key.\n *\n * Imports no peer (no viem, no `@x402/*`), so the CLI can load it.\n */\nimport { CommerceError } from '../../core';\nimport { isLikelyLocalOrPrivateHost, isWellKnownDevAddress } from './dev-key-guard';\nimport {\n type DeploymentMode,\n type NetworkProfile,\n requireNetworkProfile,\n resolveDeploymentMode,\n} from './networks';\n\n/**\n * How the gateway authenticates to a remote facilitator.\n *\n * - `none`: send no credential; use it when the facilitator accepts\n * anonymous requests.\n * - `bearer`: send a static token; no extra peer package is needed.\n * - `cdp`: Coinbase Developer Platform. The optional peer `@coinbase/x402`,\n * imported only for this type, signs a fresh JWT per request.\n *\n * Any other auth type is refused at config load.\n */\nexport type FacilitatorAuth =\n | { readonly type: 'none' }\n | { readonly type: 'bearer'; readonly token: string }\n | { readonly type: 'cdp'; readonly apiKeyId: string; readonly apiKeySecret: string };\n\nexport type X402FacilitatorConfig =\n | { readonly mode: 'local'; readonly signerPrivateKey: string }\n | { readonly mode: 'remote'; readonly url: string; readonly auth: FacilitatorAuth };\n\nexport interface X402DeploymentInput {\n readonly network: string;\n readonly payTo: string;\n readonly asset: string;\n /** EIP-712 domain of the asset, as the token itself reports it */\n readonly assetName?: string;\n readonly assetVersion?: string;\n readonly facilitator: X402FacilitatorConfig;\n /** Must be `true` before anything settles on a mainnet */\n readonly allowMainnet?: boolean;\n /**\n * Must be `true` on mainnet when facilitator auth is `none`. A separate\n * decision from `allowMainnet`: it accepts settling without an account at\n * the facilitator, under its anonymous-access limits.\n */\n readonly allowUnauthenticatedFacilitator?: boolean;\n /** Error-path prefix, `payments.x402` by default */\n readonly configPath?: string;\n /** Settlement-recipient field named in errors, `payTo` by default */\n readonly payToField?: string;\n}\n\nexport interface X402Deployment {\n readonly profile: NetworkProfile;\n readonly mode: DeploymentMode;\n}\n\nfunction invalid(message: string, path: string): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, { details: { path } });\n}\n\n/**\n * Resolves the deployment and refuses the combinations that could move real\n * money by accident. The network must resolve first; the other checks are\n * independent.\n */\nexport function resolveX402Deployment(input: X402DeploymentInput): X402Deployment {\n const at = input.configPath ?? 'payments.x402';\n const payTo = input.payToField ?? 'payTo';\n const profile = requireNetworkProfile(input.network, `${at}.network`);\n const mode = resolveDeploymentMode(profile, input.facilitator.mode);\n\n // Local mode keeps a gas-paying key in the gateway process. A compromise\n // could expose that key, so mainnet requires a remote facilitator.\n if (profile.kind === 'mainnet' && input.facilitator.mode === 'local') {\n throw invalid(\n `${at}: network \"${profile.id}\" (${profile.displayName}) is a mainnet and cannot be served by facilitator.mode \"local\". A mainnet deployment must settle through a remote facilitator.`,\n `${at}.facilitator.mode`,\n );\n }\n\n if (mode === 'mainnet' && input.allowMainnet !== true) {\n throw invalid(\n `${at}: network \"${profile.id}\" (${profile.displayName}) settles real funds. Set ${at}.allowMainnet: true to acknowledge this explicitly - it is never the default.`,\n `${at}.allowMainnet`,\n );\n }\n\n if (input.facilitator.mode === 'remote') {\n assertFacilitatorUrlIsSafe(input.facilitator.url, mode, at);\n // The authorization fixes recipient, amount and chain, so a facilitator\n // cannot redirect funds. A credential adds an account: rate limits, terms\n // and support. On mainnet, going without one is an explicit choice.\n if (\n mode === 'mainnet' &&\n input.facilitator.auth.type === 'none' &&\n input.allowUnauthenticatedFacilitator !== true\n ) {\n throw invalid(\n `${at}: no credential is configured for facilitator ${describeOrigin(input.facilitator.url)} on mainnet. Set ${at}.allowUnauthenticatedFacilitator: true to accept anonymous access and the facilitator's limits, or configure facilitator.auth.`,\n `${at}.allowUnauthenticatedFacilitator`,\n );\n }\n // A blank credential reaches the facilitator as \"unauthenticated\" and fails\n // every payment after the buyer signed. `${VAR:- }` resolving to whitespace\n // is the usual cause.\n for (const [field, value] of credentialFields(input.facilitator.auth)) {\n if (value.trim() === '') {\n throw invalid(\n `${at}: facilitator.auth.type is \"${input.facilitator.auth.type}\" but ${field} is empty. An empty credential is refused rather than sent.`,\n `${at}.facilitator.auth.${field}`,\n );\n }\n }\n }\n\n // The config loader's address check refuses this too; repeated here for a\n // library consumer who calls `createX402PaymentProvider` without it\n if (/^0x0{40}$/i.test(input.payTo)) {\n throw invalid(\n `${at}: \"${payTo}\" is the zero address. Every payment settled there is destroyed.`,\n `${at}.${payTo}`,\n );\n }\n\n // Anyone can spend from a well-known Anvil address. `dev-key-guard` refuses\n // one behind a public RPC; this refuses one on any non-local deployment,\n // whose RPC host says nothing about where a remote facilitator settles.\n if (mode !== 'local' && isWellKnownDevAddress(input.payTo)) {\n throw invalid(\n `${at}: \"${payTo}\" (${input.payTo}) is a well-known Anvil development address and this is a ${mode} deployment. Anyone can spend what settles there. Set ${payTo} to your own merchant wallet.`,\n `${at}.${payTo}`,\n );\n }\n\n // Mainnet only: a testnet is where pointing at a mock token is normal\n const canonical = profile.canonicalAsset;\n if (mode === 'mainnet' && canonical) {\n if (!sameAddress(input.asset, canonical.address)) {\n throw invalid(\n `${at}: asset ${input.asset} is not ${canonical.symbol} on ${profile.displayName} (expected ${canonical.address}). Settling a mainnet payment in an unintended token is refused.`,\n `${at}.asset`,\n );\n }\n // The buyer signs the EIP-712 domain and the scheme checks it. A wrong one\n // refuses every payment with `invalid_exact_evm_token_name_mismatch` after\n // the buyer signed, so it is caught here, before the gateway starts.\n if (input.assetName !== undefined && input.assetName !== canonical.name) {\n throw invalid(\n `${at}: assetName \"${input.assetName}\" is not the EIP-712 domain name ${canonical.symbol} reports on ${profile.displayName} (expected \"${canonical.name}\"). Every payment would be refused after the buyer signed.`,\n `${at}.assetName`,\n );\n }\n if (input.assetVersion !== undefined && input.assetVersion !== canonical.version) {\n throw invalid(\n `${at}: assetVersion \"${input.assetVersion}\" is not the EIP-712 domain version ${canonical.symbol} reports on ${profile.displayName} (expected \"${canonical.version}\").`,\n `${at}.assetVersion`,\n );\n }\n }\n\n return { profile, mode };\n}\n\n/**\n * A facilitator sees every payment authorization this gateway handles. Plain\n * HTTP puts those on the wire in the clear and lets anyone in the path rewrite\n * a settlement result, so it is allowed only to a local or private host, and\n * never on a mainnet.\n */\nfunction assertFacilitatorUrlIsSafe(url: string, mode: DeploymentMode, at: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch (cause) {\n throw new CommerceError('CONFIG_INVALID', `${at}: facilitator.url is not a valid URL`, {\n cause,\n details: { path: `${at}.facilitator.url` },\n });\n }\n\n if (parsed.protocol === 'https:') return;\n if (parsed.protocol !== 'http:') {\n throw invalid(\n `${at}: facilitator ${describeOrigin(url)} must be reached over https (or http on a local/private host); got \"${parsed.protocol}//\"`,\n `${at}.facilitator.url`,\n );\n }\n if (mode !== 'mainnet' && isLikelyLocalOrPrivateHost(parsed.hostname)) return;\n\n // The origin, never the whole URL: the path can carry a tenant or an API\n // key, and this message reaches `validate`, `doctor`, startup output and CI logs\n throw invalid(\n `${at}: facilitator ${describeOrigin(url)} is reached over plain HTTP. Payment authorizations and settlement results would travel unencrypted. Use https, or point at a local/private host on a non-mainnet deployment.`,\n `${at}.facilitator.url`,\n );\n}\n\n// Origin only: a facilitator URL can carry a tenant path or an API key\nfunction describeOrigin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return '[unparseable facilitator.url]';\n }\n}\n\n// The secret-bearing fields of an auth block, for emptiness checks only. Never logged\nfunction credentialFields(auth: FacilitatorAuth): readonly (readonly [string, string])[] {\n switch (auth.type) {\n case 'bearer':\n return [['token', auth.token]];\n case 'cdp':\n return [\n ['apiKeyId', auth.apiKeyId],\n ['apiKeySecret', auth.apiKeySecret],\n ];\n default:\n return [];\n }\n}\n\nfunction sameAddress(a: string, b: string): boolean {\n return a.toLowerCase() === b.toLowerCase();\n}\n","/**\n * MCP protocol constants shared by the config layer, the adapter and the\n * OpenAPI importer.\n *\n * Kept dependency-free: `src/config` validates tool names at load time, so\n * anything imported here would become a config-load dependency too, and the\n * MCP SDK is an optional peer the main entry and CLI must never load.\n */\n\n/** Characters SEP-986 allows in an MCP tool name, as a regex character class body */\nexport const MCP_TOOL_NAME_CHARS = 'A-Za-z0-9._-';\n\n/** Longest MCP tool name SEP-986 allows */\nexport const MCP_TOOL_NAME_MAX_LENGTH = 128;\n\n/**\n * MCP tool names per SEP-986: 1-128 chars of [A-Za-z0-9._-], the SDK's own\n * `TOOL_NAME_REGEX`, which it does not export. Config refuses an mcp-exposed\n * resource whose id fails it; the low-level `Server` checks no names, so the\n * adapter also skips such an id with a warning.\n */\nexport const MCP_TOOL_NAME_PATTERN = new RegExp(\n `^[${MCP_TOOL_NAME_CHARS}]{1,${MCP_TOOL_NAME_MAX_LENGTH}}$`,\n);\n","/**\n * `config.yaml` schema, validation and normalization into the canonical\n * `GatewayConfig` (docs/contracts.md).\n *\n * 1. Zod validates shape: types, required fields, unknown keys. Numeric and\n * boolean leaves accept their native type or a string, because env\n * substitution produces strings. Zod transforms interact badly with\n * `.strict()` inference, so coercion happens in plain TypeScript in step 2.\n * 2. A business-rule pass coerces those leaves and checks what needs a\n * specific message: cross-references, disabled protocols and payment\n * methods, dynamic pricing, addresses, duplicate trust entries.\n *\n * Env substitution (`${VAR}` / `${VAR:-default}`) runs over the raw value\n * before both steps, so numeric and boolean fields can be templated. The one\n * exception is `version:`, checked before substitution: it decides whether this\n * parser understands the document at all, so it cannot depend on the\n * environment.\n */\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","// `config.yaml` schema, loader and environment substitution\n\nexport { substituteEnv } from './env';\nexport type { LoadConfigOptions } from './load';\nexport { loadConfig } from './load';\nexport type { GatewayConfig } from './schema';\nexport { parseConfig } from './schema';\n","import { Command } from 'commander';\nimport { DEFAULT_CONFIG_FILENAME } from '../config/filename';\nimport { PROTOCOL_NAMES } from '../core';\nimport { runDemo } from './commands/demo';\nimport { printDoctorReport, runDoctor } from './commands/doctor';\nimport { runImportOpenApi } from './commands/import-openapi';\nimport { runInit } from './commands/init';\nimport { runValidate } from './commands/validate';\nimport { runVersion } from './commands/version';\nimport { type Io, processIo } from './lib/io';\nimport { readVersionReport } from './lib/versions';\n\n/**\n * Builds the `agent-commerce` Commander program.\n *\n * `io` is injectable so tests can capture output. With `exitOverride()` and\n * `configureOutput()`, `--help` and parse errors never call `process.exit()`,\n * so the caller (index.ts or a test) controls the process lifecycle.\n */\nexport function buildProgram(io: Io = processIo): Command {\n const program = new Command();\n\n program\n .name('agent-commerce')\n .description('CLI for the Agent Commerce Gateway: init, import, validate, doctor, demo.')\n // `--version` prints the CLI version only; the `version` subcommand also\n // lists the pinned protocol/SDK versions. Both read `readVersionReport()`,\n // so they cannot disagree.\n .version(readVersionReport().cliVersion, '-v, --version', 'Print the CLI version.')\n .exitOverride()\n .configureOutput({\n writeOut: (str) => io.stdout(str.replace(/\\n+$/, '')),\n writeErr: (str) => io.stderr(str.replace(/\\n+$/, '')),\n });\n\n program\n .command('version')\n .description('Print the CLI version and pinned protocol/SDK versions.')\n .action(() => {\n process.exitCode = runVersion(io);\n });\n\n program\n .command('validate')\n .description(`Validate ${DEFAULT_CONFIG_FILENAME} and exit non-zero if it is invalid.`)\n .option('--config <path>', `path to ${DEFAULT_CONFIG_FILENAME}`)\n .action(async (opts: { config?: string }) => {\n const code = await runValidate(\n opts.config !== undefined ? { configPath: opts.config } : {},\n io,\n );\n process.exitCode = code;\n });\n\n program\n .command('doctor')\n .description('Diagnose config, gateway, backend, protocol and payment health.')\n .option('--config <path>', `path to ${DEFAULT_CONFIG_FILENAME}`)\n .option(\n '--gateway <url>',\n 'gateway base URL (default: derived from config, else http://localhost:8080)',\n )\n .option('--json', 'emit machine-readable JSON instead of a formatted report', false)\n .action(async (opts: { config?: string; gateway?: string; json?: boolean }) => {\n const report = await runDoctor({\n ...(opts.config !== undefined ? { configPath: opts.config } : {}),\n ...(opts.gateway !== undefined ? { gatewayUrl: opts.gateway } : {}),\n });\n printDoctorReport(report, io, opts.json === true);\n process.exitCode = report.exitCode;\n });\n\n program\n .command('init')\n .description(`Interactively generate ${DEFAULT_CONFIG_FILENAME}.`)\n .option('--output <path>', 'output path', DEFAULT_CONFIG_FILENAME)\n .option('--force', 'overwrite an existing file', false)\n .option('--yes', 'use non-interactive defaults (required for scripting/tests)', false)\n .action(async (opts: { output: string; force: boolean; yes: boolean }) => {\n const code = await runInit({ outputPath: opts.output, force: opts.force, yes: opts.yes }, io);\n process.exitCode = code;\n });\n\n // A command group, so another importer can be added beside `openapi`\n // without renaming it\n const importCommand = program\n .command('import')\n .description('Generate Agent Commerce resource drafts from an API description.');\n\n importCommand\n .command('openapi')\n .description('Convert a local OpenAPI 3.0/3.1/3.2 document into resource drafts.')\n .argument('<source>', 'path to a local .yaml, .yml or .json OpenAPI document')\n .option(\n '--output <path>',\n 'output path (default: <source name without extension>.agent-commerce.yaml in the current directory)',\n )\n .option('--force', 'overwrite an existing output file', false)\n .option('--base-url <url>', 'backend base URL, overriding the document servers')\n .option(\n '--operation <operationId>',\n 'import only this operation (repeatable)',\n collect,\n undefined,\n )\n .option('--tag <tag>', 'import only operations with this tag (repeatable, OR-ed)', collect)\n .option('--free', 'mark generated resources as pricing.type free', false)\n .option('--expose <protocols>', `comma-separated: ${PROTOCOL_NAMES.join(',')}`)\n .option('--strict', 'exit non-zero when the import produced warnings', false)\n .option('--json', 'emit a machine-readable summary instead of a report', false)\n .action(\n async (\n source: string,\n opts: {\n output?: string;\n force: boolean;\n baseUrl?: string;\n operation?: string[];\n tag?: string[];\n free: boolean;\n expose?: string;\n strict: boolean;\n json: boolean;\n },\n ) => {\n process.exitCode = await runImportOpenApi(\n {\n source,\n ...(opts.output !== undefined ? { output: opts.output } : {}),\n force: opts.force,\n ...(opts.baseUrl !== undefined ? { baseUrl: opts.baseUrl } : {}),\n ...(opts.operation !== undefined ? { operations: opts.operation } : {}),\n ...(opts.tag !== undefined ? { tags: opts.tag } : {}),\n free: opts.free,\n ...(opts.expose !== undefined ? { expose: opts.expose } : {}),\n strict: opts.strict,\n json: opts.json,\n },\n io,\n );\n },\n );\n\n program\n .command('demo')\n .description(\n 'Start the local stack with docker compose (waiting for healthy services), then run the demo agent. Run it from a repo clone.',\n )\n .action(async () => {\n process.exitCode = await runDemo(io);\n });\n\n return program;\n}\n\n// Commander's repeatable-option collector\nfunction collect(value: string, previous: string[] | undefined): string[] {\n return [...(previous ?? []), value];\n}\n","/**\n * `agent-commerce demo`: runs `docker compose up` and then `npm run demo:agent`,\n * the README quickstart without its `doctor` check. `--wait` holds the first\n * step until every compose service with a healthcheck reports healthy. Each\n * step's exit code is checked, and a failing step is reported with the command\n * to retry it.\n */\nimport type { Io } from '../lib/io';\n\nexport interface DemoStep {\n readonly name: string;\n readonly command: string;\n readonly args: readonly string[];\n}\n\nexport interface RunResult {\n readonly code: number;\n readonly stderrTail?: string;\n}\n\nexport type RunCommand = (command: string, args: readonly string[]) => Promise<RunResult>;\n\nexport interface DemoDeps {\n readonly run?: RunCommand;\n readonly steps?: readonly DemoStep[];\n}\n\nexport function defaultDemoSteps(): readonly DemoStep[] {\n return [\n {\n name: 'Start the local stack: chain, merchant, gateway and dashboard (docker compose)',\n command: 'docker',\n args: ['compose', 'up', '--build', '--detach', '--wait'],\n },\n { name: 'Run the deterministic buyer agent', command: 'npm', args: ['run', 'demo:agent'] },\n ];\n}\n\n/** `agent-commerce demo`. Returns the process exit code */\nexport async function runDemo(io: Io, deps: DemoDeps = {}): Promise<number> {\n const steps = deps.steps ?? defaultDemoSteps();\n const run = deps.run ?? execCommand;\n\n io.stdout('agent-commerce demo: starting the local stack, then running the buyer agent');\n for (const step of steps) {\n io.stdout('');\n io.stdout(`==> ${step.name}`);\n io.stdout(` $ ${step.command} ${step.args.join(' ')}`);\n const result = await run(step.command, step.args);\n if (result.code !== 0) {\n io.stderr(`FAIL \"${step.name}\" exited with code ${result.code}.`);\n if (result.stderrTail !== undefined && result.stderrTail.length > 0) {\n io.stderr(result.stderrTail);\n }\n io.stderr('');\n io.stderr('Nothing further was run. To retry manually:');\n io.stderr(` ${step.command} ${step.args.join(' ')}`);\n return 1;\n }\n io.stdout(`OK ${step.name}`);\n }\n io.stdout('');\n io.stdout('PASS Demo is up. Try: agent-commerce doctor --config config-demo.yaml');\n return 0;\n}\n\nasync function execCommand(command: string, args: readonly string[]): Promise<RunResult> {\n const { spawn } = await import('node:child_process');\n return new Promise((resolvePromise) => {\n let stderr = '';\n const child = spawn(command, args, { stdio: ['ignore', 'inherit', 'pipe'] });\n child.stderr?.on('data', (chunk: Buffer) => {\n stderr += chunk.toString('utf8');\n });\n child.on('error', (err) => {\n resolvePromise({ code: 1, stderrTail: err.message });\n });\n child.on('close', (code) => {\n const tail = stderr.trim().split('\\n').slice(-10).join('\\n');\n resolvePromise({ code: code ?? 1, ...(tail.length > 0 ? { stderrTail: tail } : {}) });\n });\n });\n}\n","import { accessSync, existsSync, constants as fsConstants } from 'node:fs';\nimport { dirname } from 'node:path';\nimport picocolors from 'picocolors';\n// Constants and a descriptor only: the AP2 provider would pull the optional\n// peers `jose`, `@sd-jwt/core` and `canonicalize` into the CLI bundle\nimport {\n AP2_CHECKOUT_MANDATE_VCT,\n AP2_CHECKOUT_PROFILE,\n AP2_SPEC_VERSION,\n} from '../../authorization/ap2/constants';\nimport { AP2_UNSUPPORTED } from '../../authorization/ap2/descriptor';\nimport { type CommerceResource, isCommerceError, type ReceiptStore } from '../../core';\nimport { extractPathParameterNames } from '../../core/execution';\nimport {\n MPP_PROFILE,\n MPP_SPEC_COMMIT,\n MPP_SPEC_DRAFTS,\n MPPX_VERSION,\n} from '../../payments/mpp/constants';\nimport type { X402FacilitatorConfig } from '../../payments/x402/guardrails';\nimport {\n type DeploymentMode,\n describeDeploymentMode,\n findNetworkProfile,\n resolveDeploymentMode,\n} from '../../payments/x402/networks';\n// Narrow modules, not the protocol barrels: the CLI must pull in no protocol SDK\nimport {\n A2A_AGENT_CARD_PATH,\n A2A_PROTOCOL_BINDING,\n A2A_PROTOCOL_VERSION,\n A2A_SPEC_VERSION,\n} from '../../protocols/a2a/constants';\nimport { A2A_UNSUPPORTED } from '../../protocols/a2a/descriptor';\nimport {\n ACP_API_VERSION,\n ACP_SPEC_VERSION,\n ACP_WELL_KNOWN_PATH,\n} from '../../protocols/acp/constants';\nimport { ACP_UNSUPPORTED } from '../../protocols/acp/descriptor';\nimport { createSqliteReceiptStore } from '../../storage/receipts';\nimport { type ConfigLoader, type GatewayConfig, loadConfigDynamic } from '../lib/config-client';\nimport { type FetchLike, fetchJson } from '../lib/http';\nimport { PLACEHOLDER_ASSET_ADDRESS } from '../lib/init-config';\nimport type { Io } from '../lib/io';\nimport {\n fillEnvFromLocalChainManifest,\n LOCAL_CHAIN_MANIFEST_PATH,\n MANIFEST_FILLABLE_ENV_VAR_NAMES,\n type ManifestEnvFill,\n} from '../lib/manifest-env';\nimport { maskMiddle } from '../lib/mask';\nimport { readVersionReport } from '../lib/versions';\n\nexport type CheckStatus = 'PASS' | 'WARN' | 'FAIL' | 'INFO';\n\nexport interface DoctorCheck {\n readonly name: string;\n readonly status: CheckStatus;\n readonly detail: string;\n}\n\nexport interface DoctorReport {\n readonly checks: readonly DoctorCheck[];\n readonly score: { readonly passed: number; readonly total: number };\n readonly exitCode: number;\n}\n\nexport interface DoctorOptions {\n readonly configPath?: string;\n readonly gatewayUrl?: string;\n}\n\nexport interface DoctorDeps {\n readonly fetchImpl?: FetchLike;\n readonly loadConfig?: ConfigLoader;\n readonly createStore?: (path: string) => ReceiptStore;\n readonly fillEnvFromManifest?: (env: NodeJS.ProcessEnv) => ManifestEnvFill;\n}\n\nconst CHECK_TIMEOUT_MS = 1500;\n\nfunction deriveGatewayUrl(explicit: string | undefined, config: GatewayConfig | undefined): string {\n if (explicit !== undefined) return explicit.replace(/\\/$/, '');\n if (config !== undefined) {\n // `0.0.0.0` and `::` mean all interfaces, so probe loopback. An IPv6\n // literal such as `::1` must be bracketed, or the URL is invalid\n // (`http://::1:8080`).\n const raw = config.server.host;\n const host = raw === '0.0.0.0' ? '127.0.0.1' : raw === '::' ? '::1' : raw;\n const authority = host.includes(':') ? `[${host}]` : host;\n return `http://${authority}:${config.server.port}`;\n }\n return 'http://localhost:8080';\n}\n\n/**\n * Fills `{param}` slots with a probe value, using the runtime's own grammar\n * (`extractPathParameterNames`). A looser local pattern would fill a token the\n * runtime leaves literal, such as `{report id}`, and report the backend\n * reachable at a URL no real request uses. Unrecognized tokens stay as they\n * are, so the probe hits what the gateway would send.\n */\nfunction substitutePathParams(url: string): string {\n let filled = url;\n for (const name of extractPathParameterNames(url)) {\n filled = filled.replaceAll(`{${name}}`, 'demo-check');\n }\n return filled;\n}\n\n// Shared settlement fields; `payTo` holds x402 `payTo` or MPP `recipient`\ninterface LiveX402 {\n readonly asset: string;\n readonly network: string;\n readonly payTo: string;\n}\n\n// Result of reading a live x402 or MPP settlement block\ntype LiveX402Result = LiveX402 | 'disabled' | undefined;\n\n/**\n * Extracts the effective settlement fields from the well-known document.\n * Explicit `enabled: false` is a mismatch; absent, malformed, or incomplete\n * data leaves the comparison inconclusive.\n */\nfunction extractWellKnownX402(\n body: Record<string, unknown> | undefined,\n rail: 'x402' | 'mpp' = 'x402',\n): LiveX402Result {\n const payments = body?.['payments'];\n if (typeof payments !== 'object' || payments === null) return undefined;\n const block = (payments as Record<string, unknown>)[rail];\n if (typeof block !== 'object' || block === null) return undefined;\n const rec = block as Record<string, unknown>;\n if (rec['enabled'] === false) return 'disabled';\n if (rec['enabled'] !== true) return undefined;\n const { asset, network } = rec;\n const payTo = rec[rail === 'mpp' ? 'recipient' : 'payTo'];\n if (typeof asset !== 'string' || typeof network !== 'string' || typeof payTo !== 'string') {\n return undefined;\n }\n return { asset, network, payTo };\n}\n\n// Checksum-insensitive, as config validation treats addresses\nfunction sameAddress(a: string, b: string): boolean {\n return a.toLowerCase() === b.toLowerCase();\n}\n\n/**\n * Compares live settlement fields with local config. A mismatch names both\n * values so the operator knows what to fix.\n */\nfunction findX402Mismatch(\n configured: LiveX402,\n live: LiveX402,\n payToField = 'payTo',\n): string | undefined {\n const diffs: string[] = [];\n if (!sameAddress(configured.asset, live.asset)) {\n diffs.push(\n `asset: gateway is using ${live.asset} but local config resolves to ${configured.asset}`,\n );\n }\n if (configured.network !== live.network) {\n diffs.push(\n `network: gateway is using \"${live.network}\" but local config resolves to \"${configured.network}\"`,\n );\n }\n if (!sameAddress(configured.payTo, live.payTo)) {\n diffs.push(\n `${payToField}: gateway is using ${live.payTo} but local config resolves to ${configured.payTo}`,\n );\n }\n if (diffs.length === 0) return undefined;\n return `${diffs.join('; ')}; the gateway may be running against an older deployment - restart it or re-run chain:deploy`;\n}\n\n/**\n * Where a rail settles and through which facilitator. Chain id 84532 is both\n * the local dev chain and public Base Sepolia, so the deployment mode (network\n * plus facilitator) says which one this is. Local mode names the public\n * network only as sharing its chain id, never as the place of settlement.\n * `parseConfig` refuses an unknown network, so an absent profile means another\n * loader produced this config, and the text says so rather than guessing.\n */\nfunction describeSettlement(\n network: string,\n facilitator: X402FacilitatorConfig,\n): { readonly mode: DeploymentMode | undefined; readonly where: string; readonly via: string } {\n const profile = findNetworkProfile(network);\n const mode = profile ? resolveDeploymentMode(profile, facilitator.mode) : undefined;\n const where =\n profile === undefined || mode === undefined\n ? `unknown network ${network}`\n : mode === 'local'\n ? `LOCAL dev chain (${network}, chain id shared with ${profile.displayName})`\n : `${describeDeploymentMode(mode)} on ${profile.displayName} (${network})`;\n const via =\n facilitator.mode === 'local' ? 'local (in-process)' : `remote (auth=${facilitator.auth.type})`;\n return { mode, where, via };\n}\n\n// Reports rather than re-checks: config load already enforced every guardrail\n// (src/payments/x402/guardrails.ts, shared by x402 and MPP). An operator about\n// to move real money sees which guarantees they rely on, including an\n// unauthenticated facilitator the config accepted through\n// `allowUnauthenticatedFacilitator`.\nfunction mainnetSafetyCheck(\n name: string,\n payToField: 'payTo' | 'recipient',\n facilitator: X402FacilitatorConfig,\n): DoctorCheck {\n const unauthenticated = facilitator.mode === 'remote' && facilitator.auth.type === 'none';\n return {\n name,\n status: unauthenticated ? 'WARN' : 'INFO',\n detail: unauthenticated\n ? `${describeDeploymentMode('mainnet')}: no credential is sent to the remote facilitator ` +\n '(accepted via allowUnauthenticatedFacilitator); its anonymous-access ' +\n 'limits apply. Config load also requires ' +\n `allowMainnet, HTTPS, a non-development ${payToField} and the canonical asset. ` +\n 'Payments fail closed.'\n : `${describeDeploymentMode('mainnet')}. Enforced at config load: explicit allowMainnet ` +\n `opt-in, remote facilitator over HTTPS with a credential, non-development ${payToField}, ` +\n 'and the canonical asset for this network. Payments fail closed.',\n };\n}\n\n// Issuer ids and how many keys each carries. Never a key\nfunction describeIssuers(\n label: string,\n issuers: readonly { readonly issuer: string; readonly keys: readonly unknown[] }[],\n): string {\n const described = issuers\n .map(\n (entry) => `${entry.issuer} (${entry.keys.length} key${entry.keys.length === 1 ? '' : 's'})`,\n )\n .join(', ');\n return `${label} issuers: ${described}`;\n}\n\n// Whether an existing file is writable, without creating one\nfunction isWritableFile(path: string): boolean {\n try {\n accessSync(path, fsConstants.W_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n// A SQLite store file, diagnosed without creating it (see the Storage check in\n// `runDoctor`). `suffix` is appended to every detail.\nfunction storeFileCheck(\n name: string,\n path: string,\n risk: { readonly inMemory: string; readonly unwritable: string },\n suffix = '',\n): DoctorCheck {\n if (path === ':memory:') {\n return {\n name,\n status: 'WARN',\n detail: `in-memory store: ${risk.inMemory}; use a file path in production${suffix}`,\n };\n }\n if (existsSync(path)) {\n return isWritableFile(path)\n ? { name, status: 'PASS', detail: `writable at \"${path}\"${suffix}` }\n : {\n name,\n status: 'FAIL',\n detail: `\"${path}\" exists but is not writable by this user, so ${risk.unwritable}${suffix}`,\n };\n }\n return { name, status: 'WARN', detail: `${missingStoreDetail(path)}${suffix}` };\n}\n\n// Every SQLite store opens through `openSqliteDatabase`, which creates the file\n// and a missing directory, so one wording covers them all\nfunction missingStoreDetail(path: string): string {\n const directory = dirname(path);\n return directory !== '.' && !existsSync(directory)\n ? `no store at \"${path}\" and its directory does not exist. Both are created when the gateway starts, provided the path is writable`\n : `no store at \"${path}\" yet. It is created the first time the gateway starts`;\n}\n\n/**\n * The resource mapped to each checkout operation, re-checked against the rules\n * config enforces: present, acp-exposed and free to invoke. Resource ids are\n * printed because an operator needs them to fix a mapping; the mapping is\n * config, not a secret.\n */\nfunction acpMappingCheck(\n config: GatewayConfig,\n operations: Readonly<Record<string, string>>,\n): DoctorCheck {\n const byId = new Map(config.resources.map((resource) => [resource.id, resource]));\n const problems: string[] = [];\n\n for (const [operation, resourceId] of Object.entries(operations)) {\n const resource = byId.get(resourceId);\n if (resource === undefined) {\n problems.push(`${operation} -> \"${resourceId}\" does not exist`);\n continue;\n }\n if (!resource.exposedVia.includes('acp')) {\n problems.push(`${operation} -> \"${resourceId}\" is not exposed via acp`);\n }\n // ACP checkout carries the merchant's own purchase payment; charging for\n // the invocation as well would put two payment layers on one call\n if (resource.pricing.type !== 'free' || resource.paymentMethods.length > 0) {\n problems.push(`${operation} -> \"${resourceId}\" is not free to invoke`);\n }\n }\n\n if (problems.length > 0) {\n return { name: 'ACP checkout mapping', status: 'FAIL', detail: problems.join('; ') };\n }\n return {\n name: 'ACP checkout mapping',\n status: 'PASS',\n detail: `5 operations mapped to free acp-exposed resources (${Object.values(operations).join(', ')})`,\n };\n}\n\n/** `agent-commerce doctor [--config] [--gateway] [--json]` */\nexport async function runDoctor(\n options: DoctorOptions,\n deps: DoctorDeps = {},\n): Promise<DoctorReport> {\n const fetchImpl = deps.fetchImpl ?? globalThis.fetch;\n const loadConfig = deps.loadConfig ?? loadConfigDynamic;\n const createStore = deps.createStore ?? ((path: string) => createSqliteReceiptStore({ path }));\n const fillEnvFromManifest = deps.fillEnvFromManifest ?? fillEnvFromLocalChainManifest;\n\n const checks: DoctorCheck[] = [];\n let config: GatewayConfig | undefined;\n\n // 1. Config\n const { env, filled, manifestFound } = fillEnvFromManifest(process.env);\n const filledSuffix =\n filled.length > 0\n ? ` (using local chain manifest ${LOCAL_CHAIN_MANIFEST_PATH} for ${filled.join(', ')})`\n : '';\n try {\n config = await loadConfig({\n ...(options.configPath !== undefined ? { path: options.configPath } : {}),\n env,\n });\n checks.push({\n name: 'Config',\n status: 'PASS',\n detail: `valid: ${config.resources.length} resource(s), merchant \"${config.merchant.name}\"${filledSuffix}`,\n });\n } catch (err) {\n const variable = isCommerceError(err) ? err.details?.['variable'] : undefined;\n const hint =\n !manifestFound &&\n typeof variable === 'string' &&\n MANIFEST_FILLABLE_ENV_VAR_NAMES.has(variable)\n ? `. Run \"npm run chain:deploy\": it writes ${LOCAL_CHAIN_MANIFEST_PATH}, which fills local X402_*/MERCHANT_WALLET placeholders automatically`\n : '';\n checks.push({\n name: 'Config',\n status: 'FAIL',\n detail: `${err instanceof Error ? err.message : String(err)}${hint}`,\n });\n }\n\n const gatewayUrl = deriveGatewayUrl(options.gatewayUrl, config);\n\n // 2. Gateway\n const health = await fetchJson(fetchImpl, `${gatewayUrl}/health`, CHECK_TIMEOUT_MS);\n let gatewayUp = false;\n if (!health.ok) {\n checks.push({\n name: 'Gateway',\n status: 'FAIL',\n detail: `unreachable at ${gatewayUrl} (${health.error ?? `HTTP ${health.status}`})`,\n });\n } else {\n gatewayUp = true;\n const ready = await fetchJson(fetchImpl, `${gatewayUrl}/ready`, CHECK_TIMEOUT_MS);\n checks.push(\n ready.ok\n ? { name: 'Gateway', status: 'PASS', detail: `healthy and ready at ${gatewayUrl}` }\n : {\n name: 'Gateway',\n status: 'WARN',\n detail: `healthy but not ready at ${gatewayUrl} (${ready.error ?? `HTTP ${ready.status}`})`,\n },\n );\n }\n\n // 3. Backend(s)\n if (config === undefined) {\n checks.push({ name: 'Backend', status: 'WARN', detail: 'skipped: config invalid' });\n } else if (config.resources.length === 0) {\n checks.push({ name: 'Backend', status: 'INFO', detail: 'no resources configured' });\n } else {\n const resources = config.resources as readonly CommerceResource[];\n const urls: string[] = [...new Set(resources.map((r) => substitutePathParams(r.handler.url)))];\n const results = await Promise.all(\n urls.map((url) => fetchJson(fetchImpl, url, CHECK_TIMEOUT_MS)),\n );\n const reachable = results.filter((r) => r.status !== 0).length;\n const status: CheckStatus =\n reachable === urls.length ? 'PASS' : reachable === 0 ? 'FAIL' : 'WARN';\n checks.push({\n name: 'Backend',\n status,\n detail: `${reachable}/${urls.length} backend host(s) reachable`,\n });\n }\n\n // 4. Well-known document (feeds Protocols + Protocol versions)\n const wellKnown = gatewayUp\n ? await fetchJson<Record<string, unknown>>(\n fetchImpl,\n `${gatewayUrl}/.well-known/agent-commerce`,\n CHECK_TIMEOUT_MS,\n )\n : undefined;\n\n // 5. Protocols\n if (config === undefined) {\n checks.push({ name: 'Protocols', status: 'WARN', detail: 'skipped: config invalid' });\n } else if (wellKnown === undefined || !wellKnown.ok) {\n checks.push({ name: 'Protocols', status: 'FAIL', detail: 'well-known document unreachable' });\n } else {\n const mcpMountPath = config.protocols.mcp.enabled ? config.protocols.mcp.mountPath : undefined;\n const a2aMountPath = config.protocols.a2a.enabled ? config.protocols.a2a.mountPath : undefined;\n checks.push({\n name: 'Protocols',\n status: 'PASS',\n detail: `http=${config.protocols.http.enabled ? 'on' : 'off'} mcp=${config.protocols.mcp.enabled ? `on (${mcpMountPath})` : 'off'} a2a=${config.protocols.a2a.enabled ? `on (${a2aMountPath})` : 'off'} acp=${config.protocols.acp.enabled ? `on (${config.protocols.acp.mountPath})` : 'off'}`,\n });\n }\n\n // 5b. A2A specifics, from the pins rather than the live gateway. The spec\n // revision and the negotiation version look alike, so each is named.\n if (config === undefined) {\n checks.push({ name: 'A2A', status: 'WARN', detail: 'skipped: config invalid' });\n } else if (!config.protocols.a2a.enabled) {\n checks.push({ name: 'A2A', status: 'INFO', detail: 'disabled' });\n } else {\n checks.push({\n name: 'A2A',\n status: 'PASS',\n detail: `experimental · spec ${A2A_SPEC_VERSION} · protocol ${A2A_PROTOCOL_VERSION} · binding ${A2A_PROTOCOL_BINDING} · mount ${config.protocols.a2a.mountPath} · card ${A2A_AGENT_CARD_PATH}`,\n });\n // Listed in full, as are ACP's and AP2's below: a count does not tell an\n // operator whether the one feature their client needs is missing\n checks.push({\n name: 'A2A unsupported',\n status: 'INFO',\n detail: A2A_UNSUPPORTED.join(', '),\n });\n }\n\n // 5c. ACP specifics, from config and the pins: the well-known document omits\n // the bearer token, the idempotency path and the operation mapping. This\n // report prints the path and the mapping, never the token.\n if (config === undefined) {\n checks.push({ name: 'ACP', status: 'WARN', detail: 'skipped: config invalid' });\n } else if (!config.protocols.acp.enabled) {\n checks.push({ name: 'ACP', status: 'INFO', detail: 'disabled' });\n } else {\n const acp = config.protocols.acp;\n checks.push({\n name: 'ACP',\n status: 'PASS',\n detail: `experimental · spec ${ACP_SPEC_VERSION} · API-Version ${ACP_API_VERSION} · service checkout · mount ${acp.mountPath} · discovery ${ACP_WELL_KNOWN_PATH}`,\n });\n\n // Whether a token is configured and its length, never the token. Config\n // refuses an empty one.\n checks.push({\n name: 'ACP auth',\n status: 'PASS',\n detail: `bearer token configured (${acp.auth.token.length} characters, not shown)`,\n });\n\n checks.push(\n storeFileCheck(\n 'ACP idempotency',\n acp.idempotency.path,\n {\n inMemory: 'replay protection is lost on every restart',\n unwritable: 'the adapter cannot claim idempotency keys',\n },\n ` (retention ${acp.idempotency.retentionHours}h)`,\n ),\n );\n checks.push(acpMappingCheck(config, acp.checkout.operations));\n\n checks.push({\n name: 'ACP unsupported',\n status: 'INFO',\n detail: ACP_UNSUPPORTED.join(', '),\n });\n }\n\n // 5d. AP2 authorization, from config and the pins. Verification keys are\n // public but still trust policy nobody asked this report to print, so only\n // issuer ids and key counts appear.\n const ap2 = config?.authorization?.ap2;\n if (config === undefined) {\n checks.push({ name: 'AP2', status: 'WARN', detail: 'skipped: config invalid' });\n } else if (ap2 === undefined || !ap2.enabled) {\n checks.push({ name: 'AP2', status: 'INFO', detail: 'disabled' });\n } else {\n checks.push({\n name: 'AP2',\n status: 'PASS',\n detail: `experimental · spec ${AP2_SPEC_VERSION} · mode ${ap2.mode} · ${AP2_CHECKOUT_MANDATE_VCT} · profile ${AP2_CHECKOUT_PROFILE} · clock skew ${ap2.clockSkewSeconds}s`,\n });\n\n // Two lists, reported separately: signing the merchant's checkout\n // documents must not read as the power to issue mandates\n checks.push({\n name: 'AP2 trust',\n status: 'PASS',\n detail: `${describeIssuers('mandate', ap2.trust.mandateIssuers)} · ${describeIssuers('checkout', ap2.trust.checkoutIssuers)}`,\n });\n\n checks.push(\n storeFileCheck('AP2 replay store', ap2.replay.path, {\n inMemory:\n 'every spent mandate is forgotten on restart, so one could authorize a second purchase',\n unwritable: 'no mandate could be recorded as spent',\n }),\n );\n\n // Resource ids, so an operator can see exactly which purchases now need a\n // mandate. An empty list means AP2 is configured and gating nothing.\n const gated = config.resources.filter((resource) =>\n resource.authorization?.required.includes('ap2'),\n );\n checks.push({\n name: 'AP2 resources',\n status: gated.length > 0 ? 'PASS' : 'WARN',\n detail:\n gated.length > 0\n ? gated.map((resource) => resource.id).join(', ')\n : 'AP2 is enabled but no resource requires it, so every purchase settles without a mandate',\n });\n\n checks.push({\n name: 'AP2 unsupported',\n status: 'INFO',\n detail: AP2_UNSUPPORTED.join(', '),\n });\n }\n\n // 6. Payments\n const x402 = config?.payments.x402;\n if (x402 === undefined || !x402.enabled) {\n checks.push({ name: 'Payments', status: 'INFO', detail: 'x402 not configured' });\n } else {\n const { mode, where, via } = describeSettlement(x402.network, x402.facilitator);\n const summary = `x402 v2 (scheme=exact) enabled - ${where}, destination=${maskMiddle(x402.payTo)}, facilitator=${via}`;\n const live = wellKnown?.ok ? extractWellKnownX402(wellKnown.body) : undefined;\n if (sameAddress(x402.asset, PLACEHOLDER_ASSET_ADDRESS)) {\n // `init` writes this placeholder, and the live cross-check below would\n // pass it, since the gateway echoes the same config. No token contract\n // exists there, so every paid call fails (closed, with no funds at\n // risk).\n checks.push({\n name: 'Payments',\n status: 'WARN',\n detail: `${summary}, but the asset is still the init placeholder ${maskMiddle(PLACEHOLDER_ASSET_ADDRESS)}. No token contract exists there, so every paid call will fail. Set payments.x402.asset (\\${X402_ASSET} is filled from .deploy/local.json, which \"npm run chain:deploy\" writes)`,\n });\n } else if (live === 'disabled') {\n // Verified, and it disagrees: the gateway runs a different configuration\n checks.push({\n name: 'Payments',\n status: 'FAIL',\n detail: `${summary}, but the gateway at ${gatewayUrl} reports x402 disabled, so it is running a different configuration`,\n });\n } else if (live === undefined) {\n // Gateway unreachable, or the document does not say: a match cannot be\n // judged either way, so INFO rather than FAIL\n checks.push({\n name: 'Payments',\n status: 'INFO',\n detail: `${summary} (gateway's live settlement config could not be verified)`,\n });\n } else {\n const mismatch = findX402Mismatch(x402, live);\n checks.push(\n mismatch === undefined\n ? { name: 'Payments', status: 'PASS', detail: summary }\n : { name: 'Payments', status: 'FAIL', detail: mismatch },\n );\n }\n if (mode === 'mainnet') {\n checks.push(mainnetSafetyCheck('Mainnet safety', 'payTo', x402.facilitator));\n }\n }\n const mpp = config?.payments.mpp;\n if (mpp === undefined || !mpp.enabled) {\n checks.push({ name: 'Payments (MPP)', status: 'INFO', detail: 'MPP not configured' });\n } else {\n const { mode, where, via } = describeSettlement(mpp.network, mpp.facilitator);\n const summary =\n `MPP ${MPP_PROFILE.intent}/${MPP_PROFILE.method}/${MPP_PROFILE.credentialType} enabled - ` +\n `${where}, asset=${MPP_PROFILE.assetSymbol} ${maskMiddle(mpp.asset)}, ` +\n `recipient=${maskMiddle(mpp.recipient)}, facilitator=${via}, ` +\n `spec ${MPP_SPEC_DRAFTS.core}@${MPP_SPEC_COMMIT.slice(0, 7)}, mppx ${MPPX_VERSION}`;\n const configured = { asset: mpp.asset, network: mpp.network, payTo: mpp.recipient };\n const live = wellKnown?.ok ? extractWellKnownX402(wellKnown.body, 'mpp') : undefined;\n if (live === 'disabled') {\n checks.push({\n name: 'Payments (MPP)',\n status: 'FAIL',\n detail: `Local config enables MPP, but ${gatewayUrl} reports it disabled`,\n });\n } else if (live === undefined) {\n checks.push({\n name: 'Payments (MPP)',\n status: 'INFO',\n detail: `${summary} (live MPP settlement config unavailable for comparison)`,\n });\n } else {\n const mismatch = findX402Mismatch(configured, live, 'recipient');\n checks.push(\n mismatch === undefined\n ? { name: 'Payments (MPP)', status: 'PASS', detail: summary }\n : { name: 'Payments (MPP)', status: 'FAIL', detail: mismatch },\n );\n }\n if (mode === 'mainnet') {\n checks.push(mainnetSafetyCheck('Mainnet safety (MPP)', 'recipient', mpp.facilitator));\n }\n }\n\n // 7. Storage\n if (config === undefined) {\n checks.push({ name: 'Storage', status: 'WARN', detail: 'skipped: config invalid' });\n } else if (\n // Diagnose without creating: createSqliteReceiptStore creates the file,\n // so opening a wrong path (a typo, or a container path read from the\n // host) would leave an empty database and report it healthy, hiding the\n // real one. `:memory:` never exists on disk, so it takes the open branch\n // below.\n config.storage.receipts.path !== ':memory:' &&\n !existsSync(config.storage.receipts.path)\n ) {\n checks.push({\n name: 'Storage',\n status: 'WARN',\n detail:\n `${missingStoreDetail(config.storage.receipts.path)}. If the gateway is ` +\n 'already running, this path does not match the one it uses.',\n });\n } else {\n let store: ReceiptStore | undefined;\n try {\n store = createStore(config.storage.receipts.path);\n await store.init();\n const storeHealth = await store.health();\n let receiptCount: number | undefined;\n try {\n // Exact count, not a list length: listReceipts clamps every page\n receiptCount = await store.countReceipts();\n } catch {\n receiptCount = undefined;\n }\n let undeliveredCount: number | undefined;\n try {\n // Paid but undelivered purchases (see\n // `ReceiptStore.countUndeliveredReceipts`), the rows the dashboard\n // flags as \"Charged but not delivered\"\n undeliveredCount = await store.countUndeliveredReceipts();\n } catch {\n undeliveredCount = undefined;\n }\n const status: CheckStatus =\n storeHealth.status === 'pass' ? 'PASS' : storeHealth.status === 'warn' ? 'WARN' : 'FAIL';\n const receiptsSuffix =\n receiptCount !== undefined\n ? `; receipts=${receiptCount}${undeliveredCount !== undefined && undeliveredCount > 0 ? ` (${undeliveredCount} undelivered)` : ''}`\n : '';\n checks.push({\n name: 'Storage',\n status,\n detail: `${storeHealth.detail ?? 'sqlite'}${receiptsSuffix}`,\n });\n } catch (err) {\n checks.push({\n name: 'Storage',\n status: 'FAIL',\n detail: err instanceof Error ? err.message : String(err),\n });\n } finally {\n await store?.close();\n }\n }\n\n // 8. Protocol versions\n if (wellKnown?.ok) {\n checks.push({\n name: 'Protocol versions',\n status: 'PASS',\n detail: 'reported by gateway /.well-known/agent-commerce',\n });\n } else {\n const local = readVersionReport();\n checks.push({\n name: 'Protocol versions',\n status: 'INFO',\n detail: `gateway unreachable; local pins: ${local.pinned.map((p) => `${p.name}@${p.version}`).join(', ')}`,\n });\n }\n\n const scored = checks.filter((c) => c.status !== 'INFO');\n const passed = scored.filter((c) => c.status === 'PASS').length;\n const exitCode = checks.some((c) => c.status === 'FAIL') ? 1 : 0;\n\n return { checks, score: { passed, total: scored.length }, exitCode };\n}\n\nfunction statusColor(status: CheckStatus, text: string): string {\n switch (status) {\n case 'PASS':\n return picocolors.green(text);\n case 'WARN':\n return picocolors.yellow(text);\n case 'FAIL':\n return picocolors.red(text);\n case 'INFO':\n return picocolors.cyan(text);\n }\n}\n\nexport function printDoctorReport(report: DoctorReport, io: Io, json: boolean): void {\n if (json) {\n io.stdout(JSON.stringify(report, null, 2));\n return;\n }\n for (const check of report.checks) {\n const label = statusColor(check.status, check.status.padEnd(5));\n io.stdout(`${label} ${check.name.padEnd(20)} ${check.detail}`);\n }\n io.stdout('');\n io.stdout(`Score: ${report.score.passed}/${report.score.total} checks passed`);\n}\n","/**\n * Adapter self-description.\n *\n * Imports nothing but core types and the pins, so `doctor` can report AP2\n * without pulling `jose` or `@sd-jwt/core` into the CLI bundle.\n */\nimport type { AdapterDescriptor } from '../../core';\nimport {\n AP2_CHECKOUT_MANDATE_VCT,\n AP2_CHECKOUT_PROFILE,\n AP2_DIGEST_ALGORITHM,\n AP2_SIGNING_ALGORITHM,\n AP2_SPEC_VERSION,\n} from './constants';\n\n/** What this provider actually verifies */\nexport const AP2_CAPABILITIES: readonly string[] = [\n 'direct-mode',\n AP2_CHECKOUT_MANDATE_VCT,\n 'sd-jwt-presentation',\n AP2_SIGNING_ALGORITHM,\n AP2_DIGEST_ALGORITHM,\n 'static-inline-trust',\n 'merchant-checkout-jwt-binding',\n AP2_CHECKOUT_PROFILE,\n 'purchase-binding',\n 'replay-defence',\n];\n\n/**\n * Major AP2 features this provider does not support, published in its\n * descriptor and printed by `doctor`, so no client assumes full protocol\n * support\n */\nexport const AP2_UNSUPPORTED: readonly string[] = [\n // Mandate kinds. Open mandates are refused: see AP2_CHECKOUT_MANDATE_VCT\n 'autonomous mode',\n 'open checkout mandates (mandate.checkout.open.1)',\n 'intent mandates',\n 'cart mandates',\n 'spending constraint evaluation',\n 'cnf-bound agent keys',\n // Key handling. Every key is written into config by an operator\n 'JWKS and any key discovery by URL (jku, x5u)',\n 'issuer metadata fetching',\n 'key rotation without a config change',\n // Algorithms\n 'signature algorithms other than ES256',\n 'digest algorithms other than sha-256',\n // Roles this gateway does not play\n 'mandate issuance',\n 'AP2 over the ACP checkout adapter',\n];\n\nexport function buildAp2Descriptor(implementationVersion: string): AdapterDescriptor {\n return {\n name: 'ap2',\n kind: 'authorization',\n implementationVersion,\n supportedSpec: `ap2/v${AP2_SPEC_VERSION} mode=direct`,\n capabilities: AP2_CAPABILITIES,\n status: 'experimental',\n unsupported: AP2_UNSUPPORTED,\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 * 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 * 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 * 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","/**\n * The package version, resolved once for the whole package.\n *\n * The build injects `__OAC_PACKAGE_VERSION__` (tsup.config.ts), because a\n * relative manifest path resolves from the wrong depth once `src/**` is\n * bundled. From source, the root manifest is read instead. `typeof` on an\n * undeclared identifier is safe, so the source path runs without the constant.\n */\nimport { createRequire } from 'node:module';\n\ndeclare const __OAC_PACKAGE_VERSION__: string | undefined;\n\nfunction readFromManifest(): string {\n try {\n const require = createRequire(import.meta.url);\n // src/version.ts -> repository root\n return (require('../package.json') as { version?: string }).version ?? '0.0.0-unknown';\n } catch {\n return '0.0.0-unknown';\n }\n}\n\nexport const PACKAGE_VERSION: string =\n typeof __OAC_PACKAGE_VERSION__ === 'string' ? __OAC_PACKAGE_VERSION__ : readFromManifest();\n","/**\n * Opens a SQLite file with owner-only permissions. Every store that keeps a\n * SQLite file opens it here, so the hardening below exists once: the file is\n * pre-created at 0600, the WAL sidecars are narrowed once WAL creates them, and\n * an existing but unwritable file fails at startup.\n *\n * Callers own their schema; this function migrates nothing.\n */\nimport {\n accessSync,\n chmodSync,\n closeSync,\n existsSync,\n constants as fsConstants,\n mkdirSync,\n openSync,\n} from 'node:fs';\nimport { dirname } from 'node:path';\nimport Database from 'better-sqlite3';\nimport { CommerceError, type Logger } from '../core';\n\nexport interface OpenSqliteOptions {\n /** File path, or ':memory:' for tests. Parent directory is created if missing */\n readonly path: string;\n /** Names the database in operator-facing errors, e.g. \"Receipt database\" */\n readonly label: string;\n readonly logger: Logger;\n}\n\nexport function openSqliteDatabase(options: OpenSqliteOptions): Database.Database {\n const { path, label, logger } = options;\n const isFileBacked = path !== ':memory:';\n\n if (isFileBacked) {\n // 0700 on a directory this creates. A recursive mkdir leaves an existing\n // one, the operator's, with its mode.\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n }\n\n // Check write access at startup. SQLite can open a read-only database and\n // report the problem only when the first write is attempted.\n if (isFileBacked && existsSync(path)) {\n try {\n accessSync(path, fsConstants.W_OK);\n } catch {\n throw new CommerceError(\n 'STORAGE_ERROR',\n `${label} \"${path}\" exists but is not writable by this process (uid ${typeof process.getuid === 'function' ? process.getuid() : 'unknown'}). If this is a container that recently changed user, an existing volume may still be owned by the previous one - recreate it (docker compose down -v) or fix its ownership.`,\n { details: { path } },\n );\n }\n }\n\n // Create the file at 0600 before SQLite creates it at 0644 (less the umask).\n // A chmod afterwards is too late: a local user who opens the file in between\n // keeps a readable descriptor across the chmod. SQLite copies the main file's\n // mode onto the -wal/-shm sidecars, so this covers all three. `mode` applies\n // on creation only; an existing file is left to the chmod below.\n if (isFileBacked) {\n try {\n closeSync(openSync(path, 'a', 0o600));\n } catch {\n // Silent on purpose: `new Database` reports the same cause with a better\n // message, or the failure is harmless and the chmod below covers it\n }\n }\n\n const db = new Database(path);\n db.pragma('journal_mode = WAL');\n db.pragma('foreign_keys = ON');\n if (isFileBacked) restrictDatabasePermissions(path, label, logger);\n return db;\n}\n\n/**\n * Narrows the database and its WAL sidecars to owner-only. The receipt ledger\n * holds no key material, but it does hold payer and payee addresses, amounts,\n * settlement hashes, replay keys and the commerce event log.\n *\n * Runs after `journal_mode = WAL`, which creates the sidecars, and also\n * tightens a database that already existed with a looser mode. A failure only\n * warns: a filesystem without POSIX modes must not stop the gateway starting.\n */\nfunction restrictDatabasePermissions(path: string, label: string, logger: Logger): void {\n for (const file of [path, `${path}-wal`, `${path}-shm`]) {\n try {\n chmodSync(file, 0o600);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') continue;\n logger.warn(\n { file, label, error: code ?? 'unknown' },\n 'could not restrict database permissions to owner-only',\n );\n }\n }\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 * Imports `src/config` on demand, so a module that fails to load breaks only\n * the commands that read config, not `version` or `--help`. Validate, doctor\n * and init accept an injected loader for tests that do not read the filesystem.\n */\nimport type { GatewayConfig as GatewayConfigType } from '../../config';\nimport { CommerceError } from '../../core';\n\nexport type GatewayConfig = GatewayConfigType;\n\nexport interface LoadConfigOptions {\n readonly path?: string;\n readonly env?: NodeJS.ProcessEnv;\n readonly cwd?: string;\n}\n\nexport type ConfigLoader = (options?: LoadConfigOptions) => Promise<GatewayConfig>;\n\n/** Validates an already-built raw config object, without touching the disk */\nexport type ConfigParser = (raw: unknown, env?: NodeJS.ProcessEnv) => Promise<GatewayConfig>;\n\nasync function importConfig(): Promise<typeof import('../../config')> {\n try {\n return await import('../../config');\n } catch (err) {\n throw new CommerceError(\n 'INTERNAL_ERROR',\n `the configuration module could not be loaded: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\nexport async function loadConfigDynamic(options: LoadConfigOptions = {}): Promise<GatewayConfig> {\n return (await importConfig()).loadConfig(options);\n}\n\n/** Validates a raw config object in memory; `init` uses it to validate before writing */\nexport async function parseConfigDynamic(\n raw: unknown,\n env: NodeJS.ProcessEnv = process.env,\n): Promise<GatewayConfig> {\n return (await importConfig()).parseConfig(raw, env);\n}\n","/**\n * Fetch with a timeout, for `doctor`. `fetchImpl` is injected so tests can\n * pass a fake `fetch` and never touch the network.\n */\nexport type FetchLike = typeof fetch;\n\nexport interface FetchJsonResult<T> {\n readonly ok: boolean;\n readonly status: number;\n readonly body?: T;\n readonly error?: string;\n}\n\nexport async function fetchJson<T = unknown>(\n fetchImpl: FetchLike,\n url: string,\n timeoutMs = 1500,\n): Promise<FetchJsonResult<T>> {\n try {\n // The signal also bounds the body read below\n const res = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs) });\n let body: T | undefined;\n try {\n body = (await res.json()) as T;\n } catch {\n body = undefined;\n }\n return { ok: res.ok, status: res.status, ...(body !== undefined ? { body } : {}) };\n } catch (err) {\n return {\n ok: false,\n status: 0,\n error: err instanceof Error ? err.message : 'unknown fetch error',\n };\n }\n}\n","/**\n * Renders the `config.yaml` that `agent-commerce init` writes, with no prompts or IO.\n *\n * The output is the raw document `parseConfig` accepts (`resources` keyed by\n * id, with `backend`/`expose`/`payments`/`input`/`output`), not the normalized\n * `CommerceResource` shape (`handler`/`exposedVia`/`paymentMethods`/...) that\n * `loadConfig()` returns.\n *\n * The facilitator key and merchant address are Anvil's public dev accounts #0\n * and #1. Never fund them. They come from `ANVIL_WELL_KNOWN_ACCOUNTS`, the list\n * the local deploy engine and the dev-key guard also read, because a\n * hand-copied or truncated literal breaks every paid request and slips past\n * the guard. The MockUSDC `asset` is a labeled placeholder: its address exists\n * only once `npm run chain:deploy` writes `.deploy/local.json`, and config\n * rejects the zero address.\n */\n\nimport { stringify } from 'yaml';\n// Narrow module, not the `testing.ts` barrel: see manifest-env.ts\nimport { ANVIL_WELL_KNOWN_ACCOUNTS } from '../../payments/x402/local-chain/accounts';\n\n/** Anvil account #1: the merchant settlement destination, never the facilitator */\nexport const LOCAL_DEV_MERCHANT_ADDRESS = ANVIL_WELL_KNOWN_ACCOUNTS[1].address;\n/** Anvil account #0: the local facilitator signer, which settles on the dev chain only */\nexport const LOCAL_DEV_FACILITATOR_PRIVATE_KEY = ANVIL_WELL_KNOWN_ACCOUNTS[0].privateKey;\n/** Placeholder only - replace with the MockUSDC address from `.deploy/local.json` */\nexport const PLACEHOLDER_ASSET_ADDRESS = '0x000000000000000000000000000000000000dEaD';\n\nexport type InitResourceChoice = 'weather' | 'report';\nexport type InitProtocolChoice = 'http' | 'mcp';\n\nexport interface InitAnswers {\n readonly backendBaseUrl: string;\n readonly resources: readonly InitResourceChoice[];\n readonly protocols: readonly InitProtocolChoice[];\n readonly x402Enabled: boolean;\n readonly merchantPayTo: string;\n}\n\nexport function defaultInitAnswers(): InitAnswers {\n return {\n backendBaseUrl: 'http://localhost:3000',\n resources: ['weather', 'report'],\n protocols: ['http', 'mcp'],\n x402Enabled: true,\n merchantPayTo: LOCAL_DEV_MERCHANT_ADDRESS,\n };\n}\n\nfunction buildResourcesMap(answers: InitAnswers): Record<string, unknown> {\n const resources: Record<string, unknown> = {};\n const expose = [...answers.protocols];\n\n if (answers.resources.includes('weather')) {\n resources.weather = {\n name: 'Get weather',\n description: 'Deterministic demo weather lookup (free resource).',\n input: {\n type: 'object',\n properties: { city: { type: 'string' } },\n required: ['city'],\n additionalProperties: false,\n },\n backend: {\n type: 'http',\n method: 'GET',\n url: `${answers.backendBaseUrl}/api/weather/{city}`,\n },\n pricing: { type: 'free' },\n expose,\n };\n }\n\n if (answers.resources.includes('report')) {\n const paid = answers.x402Enabled;\n resources.report = {\n name: 'Get market report',\n description: 'Deterministic demo premium market report.',\n // No caller-supplied fields. Config loads a missing `input` as this same\n // closed schema; writing it out shows that in the generated file\n input: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n backend: {\n type: 'http',\n method: 'GET',\n url: `${answers.backendBaseUrl}/api/report`,\n },\n pricing: paid ? { type: 'fixed', amount: '0.01', currency: 'USDC' } : { type: 'free' },\n expose,\n ...(paid ? { payments: ['x402'] } : {}),\n };\n }\n\n return resources;\n}\n\n/** Builds the raw config object accepted by `parseConfig` (src/config) */\nexport function buildInitConfigObject(answers: InitAnswers): Record<string, unknown> {\n return {\n version: 1,\n merchant: {\n id: 'demo-merchant',\n name: 'Demo Merchant',\n publicBaseUrl: 'http://localhost:8080',\n },\n server: { port: 8080, host: '127.0.0.1' },\n storage: { receipts: { driver: 'sqlite', path: './data/receipts.db' } },\n protocols: {\n http: { enabled: answers.protocols.includes('http') },\n mcp: { enabled: answers.protocols.includes('mcp'), mountPath: '/mcp' },\n },\n resources: buildResourcesMap(answers),\n payments: answers.x402Enabled\n ? {\n x402: {\n enabled: true,\n network: 'eip155:84532',\n rpcUrl: 'http://127.0.0.1:8545',\n asset: PLACEHOLDER_ASSET_ADDRESS,\n assetName: 'MockUSDC',\n assetVersion: '2',\n assetDecimals: 6,\n payTo: answers.merchantPayTo,\n maxTimeoutSeconds: 60,\n facilitator: { mode: 'local', signerPrivateKey: LOCAL_DEV_FACILITATOR_PRIVATE_KEY },\n },\n }\n : {},\n };\n}\n\nconst HEADER = `# Generated by \\`agent-commerce init\\`.\n#\n# With x402 enabled, the facilitator signerPrivateKey is Anvil's public dev\n# account #0 and the default payTo is account #1.\n# LOCAL DEVELOPMENT ONLY - DO NOT FUND: never use them outside a local chain.\n# payments.x402.asset is a placeholder, not a real contract. Before running\n# against the local chain, run \\`npm run chain:deploy\\` and set it to the\n# MockUSDC address in \\`.deploy/local.json\\`. Before pointing this at a funded\n# network, set \\`payments.x402.payTo\\` to your own settlement address.\n#\n# server.host is loopback (127.0.0.1): binding every interface should be a\n# deliberate edit.\n#\n# server.adminToken and server.allowedOrigins are left unset, so no secret\n# lands in a file you might commit. Without a token the operator routes\n# (/api/receipts, /api/events) return 404. They serve the merchant's commerce\n# ledger: payer addresses, amounts and settlement hashes. To enable them, add\n# these keys to the server block below:\n# server:\n# adminToken: \\${ADMIN_TOKEN}\n# allowedOrigins:\n# - http://localhost:5173\n# See SECURITY.md before exposing this gateway beyond localhost.\n`;\n\nexport function renderInitConfigYaml(answers: InitAnswers): string {\n const body = stringify(buildInitConfigObject(answers), { indent: 2 });\n return `${HEADER}\\n${body}`;\n}\n","/**\n * The `.deploy/local.json` deployment manifest, whose shape docs/contracts.md\n * documents. The demo and CLI read the local MockUSDC address through\n * `readLocalChainManifest()` instead of hard-coding it.\n *\n * Imports no optional peer (zod is a regular dependency), so the CLI can load it.\n */\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { z } from 'zod';\nimport { CommerceError } from '../../../core';\n\nexport const LOCAL_CHAIN_MANIFEST_PATH = '.deploy/local.json';\n\nexport interface LocalChainManifestMerchant {\n readonly address: string;\n readonly privateKeyLabel: string;\n}\n\nexport interface LocalChainManifestKeyedAccount {\n readonly address: string;\n readonly privateKey: string;\n readonly note: string;\n}\n\nexport interface LocalChainManifest {\n readonly chainId: number;\n readonly rpcUrl: string;\n /**\n * The same chain as reached from the host. It differs from `rpcUrl` only when\n * the deployer ran inside Docker, where `rpcUrl` is a container address such\n * as \"http://anvil:8545\". Host-side consumers use `hostRpcUrl ?? rpcUrl`.\n * Optional so older manifests still parse.\n */\n readonly hostRpcUrl?: string;\n readonly asset: string;\n readonly assetName: string;\n readonly assetVersion: string;\n readonly assetDecimals: number;\n readonly merchant: LocalChainManifestMerchant;\n readonly buyer: LocalChainManifestKeyedAccount;\n readonly facilitator: LocalChainManifestKeyedAccount;\n readonly buyerInitialBalance: string;\n}\n\nconst nonEmpty = z.string().min(1, 'must be a non-empty string');\nconst keyedAccount = z.object({ address: z.string(), privateKey: z.string(), note: z.string() });\n\nconst MANIFEST_SCHEMA = z.object({\n chainId: z.number(),\n rpcUrl: nonEmpty,\n hostRpcUrl: nonEmpty.optional(),\n asset: nonEmpty,\n assetName: nonEmpty,\n assetVersion: nonEmpty,\n assetDecimals: z.number(),\n merchant: z.object({ address: z.string(), privateKeyLabel: z.string() }),\n buyer: keyedAccount,\n facilitator: keyedAccount,\n buyerInitialBalance: nonEmpty,\n});\n\n/**\n * Reads and structurally validates `.deploy/local.json`. Throws an actionable\n * error if it is missing or malformed, and no caller falls back to a\n * hard-coded address.\n */\nexport function readLocalChainManifest(cwd: string = process.cwd()): LocalChainManifest {\n const path = join(cwd, LOCAL_CHAIN_MANIFEST_PATH);\n\n if (!existsSync(path)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Local chain manifest not found at \"${path}\". Run \"npm run chain:start\" then \"npm run chain:deploy\" first.`,\n );\n }\n\n let raw: string;\n try {\n raw = readFileSync(path, 'utf8');\n } catch (cause) {\n throw new CommerceError('CONFIG_INVALID', `Could not read local chain manifest at \"${path}\".`, {\n cause,\n });\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (cause) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Local chain manifest at \"${path}\" is not valid JSON. Re-run \"npm run chain:deploy\" to regenerate it.`,\n { cause },\n );\n }\n\n const result = MANIFEST_SCHEMA.safeParse(parsed);\n if (!result.success) {\n const issue = result.error.issues[0];\n const where = issue?.path.length ? `${issue.path.join('.')}: ` : '';\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Local chain manifest at \"${path}\" is invalid: ${where}${issue?.message ?? 'unexpected shape'}. ` +\n 'Re-run \"npm run chain:deploy\".',\n );\n }\n return result.data as LocalChainManifest;\n}\n","/**\n * Local development: fills the `X402_*` and `MERCHANT_WALLET` placeholders in\n * `config.yaml` from `.deploy/local.json` (written by `npm run chain:deploy`)\n * when the shell has not set them.\n *\n * Inside `docker compose`, `docker/gateway-entrypoint.sh` exports these from\n * the manifest before the gateway starts. Host-side `validate` and `doctor`\n * have no such step, so without this the config that starts the container\n * fails on the host with \"Unresolved environment variable\". See\n * docs/contracts.md, \"Local chain deployment manifest\".\n *\n * Only unset variables are filled, so a real environment always wins, and only\n * `validate` and `doctor` call this: the config loader and gateway startup\n * never do.\n */\n// The narrow module, not the `testing.ts` barrel: the barrel also re-exports\n// the deploy engine, which imports `viem`, an optional peer.\n// esbuild keeps a bare `import 'viem'` even when the bindings are tree-shaken,\n// and the CLI would then refuse to start on a default install.\nimport {\n LOCAL_CHAIN_MANIFEST_PATH,\n type LocalChainManifest,\n readLocalChainManifest,\n} from '../../payments/x402/local-chain/manifest';\n\nexport { LOCAL_CHAIN_MANIFEST_PATH };\n\n// `config.yaml` placeholder name -> the manifest field it fills\nconst MANIFEST_ENV_VARS: readonly (readonly [string, (m: LocalChainManifest) => string])[] = [\n ['X402_ASSET', (m) => m.asset],\n ['X402_ASSET_NAME', (m) => m.assetName],\n ['X402_ASSET_VERSION', (m) => m.assetVersion],\n ['X402_ASSET_DECIMALS', (m) => String(m.assetDecimals)],\n ['MERCHANT_WALLET', (m) => m.merchant.address],\n ['X402_FACILITATOR_PRIVATE_KEY', (m) => m.facilitator.privateKey],\n];\n\n/** Names of the variables this module can fill, for matching an unresolved variable */\nexport const MANIFEST_FILLABLE_ENV_VAR_NAMES: ReadonlySet<string> = new Set(\n MANIFEST_ENV_VARS.map(([name]) => name),\n);\n\nexport interface ManifestEnvFill {\n /** `baseEnv` plus any filled variables. `baseEnv` itself is never mutated */\n readonly env: NodeJS.ProcessEnv;\n /** Names actually filled - empty when the manifest was absent or invalid, or nothing needed filling */\n readonly filled: readonly string[];\n /** True when a valid manifest was read, whether or not anything needed filling */\n readonly manifestFound: boolean;\n}\n\n/**\n * Reads `.deploy/local.json` under `cwd` and fills the unset variables in\n * {@link MANIFEST_ENV_VARS}. Never throws: with a missing or invalid manifest\n * nothing is filled, and `src/config` reports the unresolved variable as usual.\n */\nexport function fillEnvFromLocalChainManifest(\n baseEnv: NodeJS.ProcessEnv,\n cwd: string = process.cwd(),\n): ManifestEnvFill {\n let manifest: LocalChainManifest;\n try {\n manifest = readLocalChainManifest(cwd);\n } catch {\n return { env: baseEnv, filled: [], manifestFound: false };\n }\n\n const filled: string[] = [];\n const env: NodeJS.ProcessEnv = { ...baseEnv };\n for (const [name, read] of MANIFEST_ENV_VARS) {\n if (env[name] === undefined) {\n env[name] = read(manifest);\n filled.push(name);\n }\n }\n return { env, filled, manifestFound: true };\n}\n","/**\n * Shortens an address for `doctor` output: enough to eyeball, never the whole\n * value. A value too short to shorten (`length <= keep * 2`) is masked\n * entirely rather than printed whole, so a short secret passed here does not\n * leak.\n */\nexport function maskMiddle(value: string, keep = 6): string {\n if (value.length <= keep * 2) return value.length === 0 ? value : '…';\n return `${value.slice(0, keep)}…${value.slice(-4)}`;\n}\n","{\n \"name\": \"@devlab.group/agent-commerce\",\n \"version\": \"1.6.0\",\n \"description\": \"Open-source, self-hosted, non-custodial commerce and payment orchestration gateway for AI agents.\",\n \"license\": \"Apache-2.0\",\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=22\",\n \"npm\": \">=10\"\n },\n \"bin\": {\n \"agent-commerce\": \"dist/cli/index.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\"\n },\n \"./ap2\": {\n \"types\": \"./dist/ap2.d.ts\",\n \"import\": \"./dist/ap2.js\"\n },\n \"./mcp\": {\n \"types\": \"./dist/mcp.d.ts\",\n \"import\": \"./dist/mcp.js\"\n },\n \"./mpp\": {\n \"types\": \"./dist/mpp.d.ts\",\n \"import\": \"./dist/mpp.js\"\n },\n \"./x402\": {\n \"types\": \"./dist/x402.d.ts\",\n \"import\": \"./dist/x402.js\"\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\",\n \"README.md\",\n \"LICENSE\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/devlab-group/agent-commerce.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/devlab-group/agent-commerce/issues\"\n },\n \"homepage\": \"https://github.com/devlab-group/agent-commerce#readme\",\n \"keywords\": [\n \"ai-agents\",\n \"agentic-commerce\",\n \"mcp\",\n \"model-context-protocol\",\n \"x402\",\n \"payments\",\n \"web3\",\n \"commerce\",\n \"ai\",\n \"cli\",\n \"a2a\",\n \"agent-to-agent\",\n \"acp\",\n \"agent-commerce-protocol\",\n \"ap2\",\n \"agent-payment-protocol\",\n \"mpp\",\n \"machine-payments-protocol\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"prepack\": \"npm run build\",\n \"prepublishOnly\": \"npm run build && npm run verify && npm run test:cli:dist\",\n \"typecheck\": \"tsc --noEmit -p tsconfig.json && tsc --noEmit -p demo/dashboard/tsconfig.json\",\n \"lint\": \"biome check .\",\n \"lint:fix\": \"biome check --write .\",\n \"format\": \"biome format --write .\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\",\n \"test:e2e\": \"vitest run --config vitest.e2e.config.ts\",\n \"test:testnet\": \"vitest run --config vitest.testnet.config.ts\",\n \"test:mainnet\": \"vitest run --config vitest.mainnet.config.ts\",\n \"check:contract\": \"node scripts/contract-surface.mjs\",\n \"check:metadata\": \"node scripts/check-package-metadata.mjs\",\n \"verify\": \"npm run check:contract && npm run lint && npm run typecheck && npm test\",\n \"agent-commerce\": \"tsx src/cli/index.ts\",\n \"doctor\": \"tsx src/cli/index.ts doctor\",\n \"chain:start\": \"tsx scripts/chain/start-anvil.ts\",\n \"chain:deploy\": \"tsx scripts/chain/deploy.ts\",\n \"demo:merchant\": \"tsx demo/merchant/src/main.ts\",\n \"dev:merchant\": \"tsx watch demo/merchant/src/main.ts\",\n \"demo:gateway\": \"AGENT_COMMERCE_CONFIG=${AGENT_COMMERCE_CONFIG:-config-demo.yaml} tsx src/gateway/main.ts\",\n \"dev:gateway\": \"AGENT_COMMERCE_CONFIG=${AGENT_COMMERCE_CONFIG:-config-demo.yaml} tsx watch src/gateway/main.ts\",\n \"demo:dashboard\": \"vite --config demo/dashboard/vite.config.ts\",\n \"dev:dashboard\": \"vite --config demo/dashboard/vite.config.ts\",\n \"demo:agent\": \"tsx demo/agent/src/main.ts\",\n \"demo:up\": \"docker compose up --build\",\n \"demo:down\": \"docker compose down -v\",\n \"test:cli:dist\": \"node dist/cli/index.js --help && node dist/cli/index.js --version && node dist/cli/index.js version | grep -q '@x402/core' && node dist/cli/index.js version | head -1 >/dev/null && node dist/cli/index.js import openapi --help >/dev/null\",\n \"pack:dry\": \"npm pack --dry-run\"\n },\n \"dependencies\": {\n \"@clack/prompts\": \"1.7.0\",\n \"@scalar/openapi-parser\": \"0.29.0\",\n \"ajv\": \"8.20.0\",\n \"ajv-formats\": \"3.0.1\",\n \"better-sqlite3\": \"13.0.3\",\n \"commander\": \"15.0.0\",\n \"fastify\": \"5.12.0\",\n \"picocolors\": \"1.1.1\",\n \"pino\": \"10.3.1\",\n \"yaml\": \"2.9.0\",\n \"zod\": \"3.25.76\"\n },\n \"peerDependencies\": {\n \"@coinbase/x402\": \"2.1.0\",\n \"@modelcontextprotocol/sdk\": \"1.30.0\",\n \"@sd-jwt/core\": \"0.20.1\",\n \"@x402/core\": \"2.23.0\",\n \"@x402/evm\": \"2.23.0\",\n \"canonicalize\": \"5.0.0\",\n \"jose\": \"6.2.12\",\n \"mppx\": \"0.10.1\",\n \"viem\": \"2.55.18\"\n },\n \"peerDependenciesMeta\": {\n \"@coinbase/x402\": {\n \"optional\": true\n },\n \"@modelcontextprotocol/sdk\": {\n \"optional\": true\n },\n \"@sd-jwt/core\": {\n \"optional\": true\n },\n \"@x402/core\": {\n \"optional\": true\n },\n \"@x402/evm\": {\n \"optional\": true\n },\n \"canonicalize\": {\n \"optional\": true\n },\n \"jose\": {\n \"optional\": true\n },\n \"mppx\": {\n \"optional\": true\n },\n \"viem\": {\n \"optional\": true\n }\n },\n \"devDependencies\": {\n \"@a2a-js/sdk\": \"1.1.0\",\n \"@biomejs/biome\": \"2.5.9\",\n \"@coinbase/x402\": \"2.1.0\",\n \"@modelcontextprotocol/sdk\": \"1.30.0\",\n \"@sd-jwt/core\": \"0.20.1\",\n \"@types/better-sqlite3\": \"9.6.0\",\n \"@types/node\": \"24.13.3\",\n \"@types/react\": \"19.2.18\",\n \"@types/react-dom\": \"19.2.4\",\n \"@vitejs/plugin-react\": \"6.0.5\",\n \"@vitest/coverage-v8\": \"4.1.10\",\n \"@x402/core\": \"2.23.0\",\n \"@x402/evm\": \"2.23.0\",\n \"canonicalize\": \"5.0.0\",\n \"jose\": \"6.2.12\",\n \"mppx\": \"0.10.1\",\n \"pino-pretty\": \"13.1.2\",\n \"react\": \"19.0.8\",\n \"react-dom\": \"19.0.8\",\n \"tsup\": \"8.5.1\",\n \"tsx\": \"4.23.12\",\n \"typescript\": \"5.9.3\",\n \"viem\": \"2.55.18\",\n \"vite\": \"8.2.1\",\n \"vitest\": \"4.1.10\"\n },\n \"overrides\": {\n \"@coinbase/x402\": {\n \"zod\": \"3.25.76\"\n },\n \"@sd-jwt/core\": {\n \"@owf/identity-common\": \"0.3.2\"\n },\n \"@x402/core\": {\n \"zod\": \"3.25.76\"\n },\n \"@x402/evm\": {\n \"zod\": \"3.25.76\"\n }\n }\n}\n","/**\n * The CLI version (`PACKAGE_VERSION`) and the pinned protocol/SDK versions.\n * The pins come from a static JSON import of package.json, which tsup inlines,\n * so the bundle never reads the manifest by relative path.\n */\nimport manifest from '../../../package.json' with { type: 'json' };\nimport { PACKAGE_VERSION } from '../../version';\n\nexport interface PinnedVersion {\n readonly name: string;\n readonly version: string;\n readonly via: string;\n}\n\nexport interface VersionReport {\n readonly cliVersion: string;\n readonly pinned: readonly PinnedVersion[];\n}\n\n// The protocol/SDK pins (the A2A SDK is test-only, so it is not listed), each\n// with the main src/ directory that uses it\nconst PINS: readonly (readonly [name: string, via: string])[] = [\n ['@modelcontextprotocol/sdk', 'protocols/mcp'],\n ['ajv', 'protocols/acp'],\n ['ajv-formats', 'protocols/acp'],\n ['@x402/core', 'payments/x402'],\n ['@x402/evm', 'payments/x402'],\n ['@coinbase/x402', 'payments/x402'],\n ['viem', 'payments/x402'],\n ['mppx', 'payments/mpp'],\n ['jose', 'authorization/ap2'],\n ['@sd-jwt/core', 'authorization/ap2'],\n ['canonicalize', 'authorization/ap2'],\n ['@scalar/openapi-parser', 'openapi'],\n ['zod', 'config'],\n ['fastify', 'gateway'],\n ['pino', 'gateway'],\n ['better-sqlite3', 'storage'],\n];\n\n/** Pins missing from the manifest are left out rather than shown as \"unknown\" */\nexport function readVersionReport(): VersionReport {\n // Optional peers count as pins; a package in both lists reports its dependency\n const declared: Readonly<Record<string, string | undefined>> = {\n ...manifest.peerDependencies,\n ...manifest.dependencies,\n };\n const pinned = PINS.flatMap(([name, via]) => {\n const version = declared[name];\n return version === undefined ? [] : [{ name, version, via }];\n });\n return { cliVersion: PACKAGE_VERSION, pinned };\n}\n","/**\n * `agent-commerce import openapi <source>`.\n *\n * Generates reviewable resource drafts from a local OpenAPI description. It\n * never merges them into gateway config or invents commerce policy;\n * `--output config.yaml --force` replaces that file rather than merging.\n */\nimport { existsSync } from 'node:fs';\nimport { rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, extname, resolve } from 'node:path';\nimport { PROTOCOL_NAMES } from '../../core';\nimport {\n buildResourceDrafts,\n type ImportPolicy,\n type ImportResult,\n loadOpenApiDocument,\n renderResourcesYaml,\n} from '../../openapi';\nimport type { Io } from '../lib/io';\n\nexport interface ImportOpenApiOptions {\n readonly source: string;\n readonly output?: string;\n readonly force?: boolean;\n readonly baseUrl?: string;\n readonly operations?: readonly string[];\n readonly tags?: readonly string[];\n readonly free?: boolean;\n readonly expose?: string;\n readonly strict?: boolean;\n readonly json?: boolean;\n}\n\nexport interface ImportOpenApiDeps {\n readonly fileExists?: (path: string) => boolean;\n readonly writeFile?: (path: string, content: string) => Promise<void>;\n}\n\n/** `<source name without extension>.agent-commerce.yaml`, in the working directory */\nexport function defaultOutputPath(source: string): string {\n const name = basename(source);\n const stem = name.slice(0, name.length - extname(name).length) || name;\n return `${stem}.agent-commerce.yaml`;\n}\n\nexport async function runImportOpenApi(\n options: ImportOpenApiOptions,\n io: Io,\n deps: ImportOpenApiDeps = {},\n): Promise<number> {\n const fileExists = deps.fileExists ?? existsSync;\n const outputPath = options.output ?? defaultOutputPath(options.source);\n\n const policy = buildPolicy(options);\n if (typeof policy === 'string') {\n io.stderr(`FAIL ${policy}`);\n return 1;\n }\n\n // Checked before the import runs: an existing file the operator did not ask\n // to replace is a stop\n if (fileExists(outputPath) && options.force !== true) {\n io.stderr(`FAIL ${outputPath} already exists. Re-run with --force to overwrite.`);\n return 1;\n }\n\n let result: ImportResult;\n try {\n const loaded = await loadOpenApiDocument(options.source);\n result = buildResourceDrafts(loaded, {\n ...(options.baseUrl !== undefined ? { baseUrl: options.baseUrl } : {}),\n ...(Object.keys(policy).length > 0 ? { policy } : {}),\n ...(options.operations !== undefined || options.tags !== undefined\n ? {\n include: {\n ...(options.operations !== undefined ? { operationIds: options.operations } : {}),\n ...(options.tags !== undefined ? { tags: options.tags } : {}),\n },\n }\n : {}),\n });\n } catch (error) {\n io.stderr(`FAIL ${error instanceof Error ? error.message : String(error)}`);\n return 1;\n }\n\n const skipped = result.diagnostics.filter((entry) => entry.severity === 'error');\n const warnings = result.diagnostics.filter((entry) => entry.severity === 'warning');\n\n const failures: string[] = [];\n if (result.unmatchedOperationIds.length > 0) {\n failures.push(`no operation matched ${result.unmatchedOperationIds.join(', ')}`);\n }\n if (result.drafts.length === 0) {\n failures.push('no supported operations were imported');\n }\n if (options.strict === true && warnings.length > 0) {\n failures.push(`${warnings.length} warning(s) with --strict`);\n }\n\n // Nothing is written when the run failed: a half-useful file that the next\n // command silently picks up is worse than no file\n const wrote = failures.length === 0;\n if (wrote) {\n try {\n await writeAtomically(outputPath, renderResourcesYaml(result), deps);\n } catch (error) {\n io.stderr(`FAIL ${outputPath} could not be written: ${describe(error)}`);\n return 1;\n }\n }\n\n if (options.json === true) {\n io.stdout(\n JSON.stringify(\n {\n source: options.source,\n openapi: result.version,\n output: wrote ? outputPath : null,\n imported: result.drafts.length,\n skipped: skipped.length,\n warnings: warnings.length,\n resources: result.drafts.map((draft) => ({\n id: draft.id,\n source: draft.source,\n ...(draft.operationId !== undefined ? { operationId: draft.operationId } : {}),\n tags: draft.tags,\n })),\n diagnostics: result.diagnostics,\n unmatchedOperationIds: result.unmatchedOperationIds,\n exitCode: failures.length === 0 ? 0 : 1,\n },\n null,\n 2,\n ),\n );\n } else {\n printSummary(result, { outputPath, wrote, policy }, io);\n }\n\n for (const failure of failures) io.stderr(`FAIL ${failure}`);\n return failures.length === 0 ? 0 : 1;\n}\n\n// A usage error comes back as the message to print\nfunction buildPolicy(options: ImportOpenApiOptions): ImportPolicy | string {\n const policy: { pricing?: Record<string, unknown>; expose?: readonly string[] } = {};\n if (options.free === true) policy.pricing = { type: 'free' };\n if (options.expose !== undefined) {\n const requested = options.expose\n .split(',')\n .map((name) => name.trim())\n .filter((name) => name !== '');\n if (requested.length === 0) {\n return `--expose needs at least one protocol (${PROTOCOL_NAMES.join(', ')})`;\n }\n for (const name of requested) {\n if (!PROTOCOL_NAMES.includes(name as (typeof PROTOCOL_NAMES)[number])) {\n return `--expose \"${name}\" is not a supported protocol. Supported: ${PROTOCOL_NAMES.join(', ')}`;\n }\n }\n policy.expose = requested;\n }\n return policy;\n}\n\nasync function writeAtomically(\n outputPath: string,\n content: string,\n deps: ImportOpenApiDeps,\n): Promise<void> {\n if (deps.writeFile !== undefined) {\n await deps.writeFile(outputPath, content);\n return;\n }\n // Temp sibling then rename: a crash or a full disk must not leave a\n // half-written file where a complete one used to be\n const target = resolve(outputPath);\n const temporary = `${target}.${process.pid}.tmp`;\n try {\n await writeFile(temporary, content, 'utf8');\n await rename(temporary, target);\n } catch (error) {\n await rm(temporary, { force: true });\n throw error;\n }\n}\n\nfunction printSummary(\n result: ImportResult,\n context: { outputPath: string; wrote: boolean; policy: ImportPolicy },\n io: Io,\n): void {\n const skipped = result.diagnostics.filter((entry) => entry.severity === 'error');\n const warnings = result.diagnostics.filter((entry) => entry.severity === 'warning');\n\n io.stdout(`OpenAPI ${result.version}: ${result.sourcePath}`);\n io.stdout('');\n io.stdout(`Imported: ${result.drafts.length}`);\n io.stdout(`Skipped: ${skipped.length}`);\n io.stdout(`Warnings: ${warnings.length}`);\n\n if (skipped.length > 0) {\n io.stdout('');\n io.stdout('Skipped operations:');\n for (const entry of skipped) io.stdout(` ${entry.message}`);\n }\n if (warnings.length > 0) {\n io.stdout('');\n io.stdout('Warnings:');\n for (const entry of warnings) io.stdout(` ${entry.message}`);\n }\n\n if (context.wrote) {\n io.stdout('');\n io.stdout('Generated:');\n io.stdout(` ${context.outputPath}`);\n }\n\n io.stdout('');\n if (context.policy.pricing === undefined || context.policy.expose === undefined) {\n io.stdout('Pricing/exposure were not inferred.');\n }\n io.stdout('Review the generated resources before merging them into config.yaml.');\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Turns OpenAPI path operations into a deterministic list of candidates.\n *\n * Determinism is the point: a resource id is what an agent discovers and\n * hard-codes, so it must depend only on the document, never on iteration order\n * or on how many times the importer has run. Anything ambiguous fails the\n * import instead of being silently renamed.\n */\nimport type { BackendMethod } from '../core/domain/resource';\nimport { CommerceError } from '../core/errors';\nimport { findUnparsedBraceToken } from '../core/execution';\nimport { isRecord } from '../core/is-record';\nimport { MCP_TOOL_NAME_CHARS, MCP_TOOL_NAME_MAX_LENGTH } from '../protocols/mcp/constants';\nimport { dereference } from './refs';\nimport type { ImportDiagnostic, LoadedOpenApiDocument, OpenApiOperationCandidate } from './types';\n\nconst SUPPORTED_METHODS: Readonly<Record<string, BackendMethod>> = {\n get: 'GET',\n post: 'POST',\n put: 'PUT',\n patch: 'PATCH',\n delete: 'DELETE',\n};\n\n// Path Item members that are not operations. Any other key, except an `x-`\n// extension, that is not a supported method gets a diagnostic.\nconst NON_OPERATION_KEYS = new Set(['summary', 'description', 'servers', 'parameters', '$ref']);\n\n// Runs of characters outside the MCP tool-name set, which config requires of an\n// mcp-exposed resource id\nconst ID_DISALLOWED = new RegExp(`[^${MCP_TOOL_NAME_CHARS}]+`, 'g');\n\nexport interface DiscoverOptions {\n /** CLI `--base-url`. Wins over every server declared in the document */\n readonly baseUrl?: string;\n}\n\nexport interface DiscoveryResult {\n readonly operations: readonly OpenApiOperationCandidate[];\n readonly diagnostics: readonly ImportDiagnostic[];\n}\n\nexport function discoverOperations(\n loaded: LoadedOpenApiDocument,\n options: DiscoverOptions = {},\n): DiscoveryResult {\n const { document } = loaded;\n const diagnostics: ImportDiagnostic[] = [];\n const operations: OpenApiOperationCandidate[] = [];\n // resource id -> the `METHOD path` that claimed it, for the collision message\n const claimed = new Map<string, string>();\n\n if (options.baseUrl !== undefined) assertAbsoluteHttpUrl(options.baseUrl, '--base-url');\n\n const paths = document['paths'];\n if (!isRecord(paths)) {\n return { operations, diagnostics };\n }\n\n const rootServers = document['servers'];\n const rootSecurity = document['security'];\n\n for (const [path, rawPathItem] of Object.entries(paths)) {\n if (path.startsWith('x-')) continue;\n if (!path.startsWith('/')) {\n diagnostics.push({\n severity: 'warning',\n code: 'invalid-path-key',\n operation: path,\n message: `Skipped \"${path}\": a Paths key must start with \"/\"`,\n });\n continue;\n }\n const pathItem = dereference(document, rawPathItem).value;\n if (!isRecord(pathItem)) continue;\n\n const unsupportedMethod = (name: string): void => {\n diagnostics.push({\n severity: 'warning',\n code: 'unsupported-method',\n operation: `${name.toUpperCase()} ${path}`,\n message: `Skipped ${name.toUpperCase()} ${path}: only GET, POST, PUT, PATCH and DELETE are supported`,\n });\n };\n\n for (const [key, rawOperation] of Object.entries(pathItem)) {\n if (NON_OPERATION_KEYS.has(key) || key.startsWith('x-')) continue;\n // OpenAPI 3.2 maps each method outside the fixed fields to its operation\n if (key === 'additionalOperations') {\n if (isRecord(rawOperation))\n for (const name of Object.keys(rawOperation)) unsupportedMethod(name);\n continue;\n }\n const method = SUPPORTED_METHODS[key.toLowerCase()];\n if (method === undefined) {\n unsupportedMethod(key);\n continue;\n }\n const operation = dereference(document, rawOperation).value;\n if (!isRecord(operation)) continue;\n\n const where = `${method} ${path}`;\n const operationId =\n typeof operation['operationId'] === 'string' ? operation['operationId'] : undefined;\n const resourceId = toResourceId(operationId, method, path);\n const previous = claimed.get(resourceId);\n if (previous !== undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Operations \"${previous}\" and \"${where}\" both produce the resource id \"${resourceId}\". Give one of them a distinct operationId - ids are what agents discover, so the importer will not rename either`,\n { details: { resourceId, operations: [previous, where] } },\n );\n }\n claimed.set(resourceId, where);\n\n const server = selectServer(\n document,\n [operation['servers'], pathItem['servers'], rootServers],\n { where, resourceId },\n options,\n diagnostics,\n );\n if (server === undefined) continue;\n\n const backendUrl = `${server.replace(/\\/+$/, '')}${path}`;\n const stray = findUnparsedBraceToken(backendUrl);\n if (stray !== undefined) {\n diagnostics.push({\n severity: 'error',\n code: 'unsupported-path-template',\n operation: resourceId,\n message: `Skipped ${where}: path template \"${stray}\" uses characters the gateway cannot substitute (allowed: A-Z a-z 0-9 _ . -)`,\n });\n continue;\n }\n\n const summary = typeof operation['summary'] === 'string' ? operation['summary'] : undefined;\n const description =\n typeof operation['description'] === 'string' ? operation['description'] : summary;\n const security = operation['security'] ?? rootSecurity;\n\n operations.push({\n resourceId,\n method,\n path,\n backendUrl,\n ...(operationId !== undefined ? { operationId } : {}),\n tags: toArray(operation['tags']).filter((tag): tag is string => typeof tag === 'string'),\n name: summary ?? operationId ?? resourceId,\n ...(description !== undefined ? { description } : {}),\n parameters: [\n ...toArray(pathItem['parameters']),\n // Operation parameters last: `mergeParameters` lets the later one win,\n // the OpenAPI override rule (same `name` and `in`)\n ...toArray(operation['parameters']),\n ],\n ...(operation['requestBody'] !== undefined\n ? { requestBody: operation['requestBody'] }\n : {}),\n ...(operation['responses'] !== undefined ? { responses: operation['responses'] } : {}),\n security: toArray(security),\n });\n }\n }\n\n return { operations, diagnostics };\n}\n\n/**\n * `operationId` if it survives normalization, otherwise `method_path`.\n *\n * No counters and no random suffixes: two runs over the same document must\n * produce the same ids, and a collision is reported rather than papered over.\n */\nfunction toResourceId(\n operationId: string | undefined,\n method: BackendMethod,\n path: string,\n): string {\n const fromOperationId = operationId === undefined ? '' : normalizeId(operationId);\n if (fromOperationId !== '') return fromOperationId;\n return normalizeId(`${method.toLowerCase()}_${path}`);\n}\n\nfunction normalizeId(value: string): string {\n return value\n .replace(ID_DISALLOWED, '_')\n .replace(/_+/g, '_')\n .replace(/^[_.-]+|[_.-]+$/g, '')\n .slice(0, MCP_TOOL_NAME_MAX_LENGTH);\n}\n\n/**\n * `--base-url` > operation servers > path-item servers > root servers.\n *\n * A relative server URL (`/v1`, the OpenAPI default of `/`) names no host, and\n * guessing one from the filename or from localhost would silently point a\n * merchant's gateway at the wrong backend - so it is refused and `--base-url`\n * asked for instead.\n */\nfunction selectServer(\n document: Record<string, unknown>,\n candidates: readonly unknown[],\n context: { readonly where: string; readonly resourceId: string },\n options: DiscoverOptions,\n diagnostics: ImportDiagnostic[],\n): string | undefined {\n if (options.baseUrl !== undefined) return options.baseUrl;\n\n for (const candidate of candidates) {\n const servers = toArray(candidate);\n const first = servers.length > 0 ? dereference(document, servers[0]).value : undefined;\n if (!isRecord(first)) continue;\n const url = first['url'];\n if (typeof url !== 'string' || url === '') continue;\n\n const substituted = substituteServerVariables(url, first['variables'], context, diagnostics);\n if (substituted === undefined) return undefined;\n const issue = describeServerUrlIssue(substituted);\n if (issue !== undefined) {\n diagnostics.push({\n severity: 'error',\n code: issue.code,\n operation: context.resourceId,\n message: `Skipped ${context.where}: server URL \"${substituted}\" ${issue.reason}. Pass --base-url`,\n });\n return undefined;\n }\n return substituted;\n }\n\n diagnostics.push({\n severity: 'error',\n code: 'no-server-url',\n operation: context.resourceId,\n message: `Skipped ${context.where}: the document declares no server URL. Pass --base-url`,\n });\n return undefined;\n}\n\nfunction substituteServerVariables(\n url: string,\n variables: unknown,\n context: { readonly where: string; readonly resourceId: string },\n diagnostics: ImportDiagnostic[],\n): string | undefined {\n if (!url.includes('{')) return url;\n const declared = isRecord(variables) ? variables : {};\n const used: string[] = [];\n let missing: string | undefined;\n const substituted = url.replace(/\\{([^{}]*)\\}/g, (match, name: string) => {\n const variable = declared[name];\n const fallback = isRecord(variable) ? variable['default'] : undefined;\n if (typeof fallback !== 'string') {\n missing = name;\n return match;\n }\n used.push(`${name}=${fallback}`);\n return fallback;\n });\n if (missing !== undefined) {\n diagnostics.push({\n severity: 'error',\n code: 'server-variable-without-default',\n operation: context.resourceId,\n message: `Skipped ${context.where}: server variable \"{${missing}}\" has no default value. Pass --base-url`,\n });\n return undefined;\n }\n if (used.length > 0) {\n diagnostics.push({\n severity: 'warning',\n code: 'server-variable-default',\n operation: context.resourceId,\n message: `Server URL for ${context.where} uses declared defaults (${used.join(', ')}); override with --base-url if that is not the deployment you mean`,\n });\n }\n return substituted;\n}\n\n/**\n * An absolute http(s) origin plus path, and nothing after it. A query or\n * fragment on the base would land *before* the operation path once the two\n * are concatenated (`.../api?key=x` + `/users/{id}`), producing a URL that\n * parses fine and calls the wrong endpoint.\n */\nfunction isAbsoluteHttpUrl(value: string): boolean {\n return describeServerUrlIssue(value) === undefined;\n}\n\nfunction describeServerUrlIssue(\n value: string,\n):\n | { readonly code: 'relative-server-url' | 'invalid-server-url'; readonly reason: string }\n | undefined {\n try {\n const parsed = new URL(value);\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n return { code: 'invalid-server-url', reason: 'must use http:// or https://' };\n }\n if (parsed.search !== '' || parsed.hash !== '') {\n return {\n code: 'invalid-server-url',\n reason: 'must not contain a query string or fragment',\n };\n }\n return undefined;\n } catch {\n return {\n code: 'relative-server-url',\n reason: 'is relative or malformed, so no backend host is known',\n };\n }\n}\n\nfunction assertAbsoluteHttpUrl(value: string, label: string): void {\n if (!isAbsoluteHttpUrl(value)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `${label} \"${value}\" must be an absolute http:// or https:// URL with no query string or fragment`,\n { details: { value } },\n );\n }\n}\n\nfunction toArray(value: unknown): readonly unknown[] {\n return Array.isArray(value) ? value : [];\n}\n","/**\n * Lazy internal `$ref` resolution.\n *\n * The document is deliberately *not* dereferenced up front: a recursive schema\n * (`Node.children[] -> Node`) expands without bound, turning a 30 kB file into\n * an out-of-memory kill. Each pointer is followed on demand instead, carrying\n * the chain that led to it so a cycle is a diagnostic rather than a hang.\n */\nimport { CommerceError } from '../core/errors';\n\n// Bounds a pathological but non-cyclic chain of `$ref`s pointing at `$ref`s\nconst MAX_REF_DEPTH = 100;\n\nexport interface Dereferenced {\n readonly value: unknown;\n /** Pointers already followed, oldest first. Pass it back in to keep detecting cycles */\n readonly stack: readonly string[];\n}\n\nexport function isRefNode(value: unknown): value is { $ref: string } {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { $ref?: unknown }).$ref === 'string'\n );\n}\n\n/**\n * Follows a chain of `$ref` nodes to the first value that is not one.\n *\n * Throws `CONFIG_INVALID` for a cycle, an unresolvable pointer, or an external\n * reference - the last is refused at load time too, so reaching it here means\n * a caller built a node the loader never saw.\n */\nexport function dereference(\n document: Record<string, unknown>,\n node: unknown,\n stack: readonly string[] = [],\n): Dereferenced {\n let current = node;\n let chain = stack;\n while (isRefNode(current)) {\n const pointer = current.$ref;\n if (!pointer.startsWith('#')) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `OpenAPI document contains an external reference \"${pointer}\". Only internal references (#/...) are supported`,\n { details: { ref: pointer } },\n );\n }\n if (chain.includes(pointer)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `OpenAPI reference \"${pointer}\" is circular (${[...chain, pointer].join(' -> ')})`,\n { details: { ref: pointer, chain: [...chain, pointer] } },\n );\n }\n if (chain.length >= MAX_REF_DEPTH) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `OpenAPI reference chain exceeds ${MAX_REF_DEPTH} hops at \"${pointer}\"`,\n { details: { ref: pointer } },\n );\n }\n current = resolvePointer(document, pointer);\n chain = [...chain, pointer];\n }\n return { value: current, stack: chain };\n}\n\n// RFC 6901 JSON Pointer in a URI fragment: `#` is the document, `#/` its \"\" key\nfunction resolvePointer(document: Record<string, unknown>, ref: string): unknown {\n const pointer = ref.slice(1);\n if (pointer === '') return document;\n if (!pointer.startsWith('/')) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `OpenAPI reference \"${ref}\" is not a JSON Pointer. Plain names and anchors are not supported`,\n { details: { ref } },\n );\n }\n let current: unknown = document;\n for (const rawSegment of pointer.slice(1).split('/')) {\n let decoded: string;\n try {\n decoded = decodeURIComponent(rawSegment);\n } catch {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `OpenAPI reference \"${ref}\" contains a malformed percent-escape`,\n { details: { ref } },\n );\n }\n // `~1` before `~0`, per RFC 6901: the other order decodes `~01` to \"/\"\n // instead of \"~1\"\n const segment = decoded.replaceAll('~1', '/').replaceAll('~0', '~');\n if (Array.isArray(current)) {\n const index = Number(segment);\n current = Number.isInteger(index) ? current[index] : undefined;\n } else if (typeof current === 'object' && current !== null) {\n // Own members only: \"__proto__\" would otherwise resolve to Object.prototype,\n // which converts to a schema that accepts anything\n current = Object.hasOwn(current, segment)\n ? (current as Record<string, unknown>)[segment]\n : undefined;\n } else {\n current = undefined;\n }\n if (current === undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `OpenAPI reference \"${ref}\" does not resolve to anything in the document`,\n { details: { ref } },\n );\n }\n }\n return current;\n}\n","/**\n * Operation candidates -> Agent Commerce resource drafts.\n *\n * A draft describes the *API shape* and nothing else. Pricing, exposure and\n * payment methods are commerce policy: an OpenAPI document has no opinion on\n * whether an operation should cost money or be visible to agents, so guessing\n * one would put a merchant's endpoint on an agent network - or give it away\n * free - on the strength of a file that never mentioned either. Without\n * explicit CLI policy the generated file is deliberately incomplete: it will\n * not load until a human fills those fields in.\n */\nimport { win32 } from 'node:path';\nimport { Document, type Node, type Pair, type YAMLMap } from 'yaml';\nimport type { JsonSchema } from '../core/domain/common';\nimport { isRecord } from '../core/is-record';\nimport { discoverOperations } from './discover';\nimport { dereference } from './refs';\nimport { mapRequest, pickJsonMediaType } from './request';\nimport { convertSchema } from './schema';\nimport type {\n ImportDiagnostic,\n LoadedOpenApiDocument,\n OpenApiOperationCandidate,\n OpenApiVersion,\n} from './types';\n\n/** Commerce policy the operator supplied explicitly. Never inferred */\nexport interface ImportPolicy {\n readonly pricing?: Record<string, unknown>;\n readonly expose?: readonly string[];\n}\n\nexport interface ImportOptions {\n readonly baseUrl?: string;\n readonly policy?: ImportPolicy;\n /** `--operation` / `--tag`. Applied before mapping, so unselected operations produce no noise */\n readonly include?: {\n readonly operationIds?: readonly string[];\n /** Multiple tags are OR-ed */\n readonly tags?: readonly string[];\n };\n}\n\nexport interface ResourceDraft {\n readonly id: string;\n readonly operationId?: string;\n readonly tags: readonly string[];\n /** `METHOD /path`, for the console summary */\n readonly source: string;\n /** YAML-ready, in the field order it will be written in */\n readonly resource: Record<string, unknown>;\n /** Comment lines written above this resource */\n readonly review: readonly string[];\n}\n\nexport interface ImportResult {\n readonly version: OpenApiVersion;\n readonly sourcePath: string;\n readonly drafts: readonly ResourceDraft[];\n readonly diagnostics: readonly ImportDiagnostic[];\n /** `--operation` values that matched nothing. The CLI exits non-zero on these */\n readonly unmatchedOperationIds: readonly string[];\n}\n\nexport function buildResourceDrafts(\n loaded: LoadedOpenApiDocument,\n options: ImportOptions = {},\n): ImportResult {\n const discovery = discoverOperations(\n loaded,\n options.baseUrl !== undefined ? { baseUrl: options.baseUrl } : {},\n );\n const diagnostics: ImportDiagnostic[] = [];\n const drafts: ResourceDraft[] = [];\n\n const wanted = options.include?.operationIds;\n const wantedTags = options.include?.tags;\n const matched = new Set<string>();\n const selected = new Set<string>();\n\n for (const candidate of discovery.operations) {\n if (wanted !== undefined && !selects(wanted, candidate)) continue;\n if (wantedTags !== undefined && !candidate.tags.some((tag) => wantedTags.includes(tag))) {\n continue;\n }\n if (wanted !== undefined) {\n for (const id of wanted) if (selects([id], candidate)) matched.add(id);\n }\n selected.add(candidate.resourceId);\n\n const mapping = mapRequest(loaded, candidate);\n diagnostics.push(...mapping.diagnostics);\n if (!mapping.supported) continue;\n\n const dropped = new Set(mapping.droppedKeywords);\n const output = selectOutputSchema(loaded.document, candidate, diagnostics, dropped);\n if (dropped.size > 0) {\n diagnostics.push({\n severity: 'warning',\n code: 'unenforced-schema-constraints',\n operation: candidate.resourceId,\n message: `${candidate.resourceId}: dropped ${[...dropped].join(', ')} - this gateway validates structure only, and keeping them would advertise checks it never performs`,\n });\n }\n\n const review: string[] = [];\n if (declaresSecurity(candidate)) {\n diagnostics.push({\n severity: 'warning',\n code: 'backend-authentication-required',\n operation: candidate.resourceId,\n message: `${candidate.resourceId} declares backend authentication. OpenAPI credentials were not imported. Configure backend.headers with environment placeholders before enabling the resource`,\n });\n review.push(\n 'This operation declares backend authentication. No credential was imported.',\n 'Add it under backend.headers with an ${ENV_VAR} placeholder before enabling.',\n );\n }\n if (options.policy?.pricing === undefined || options.policy.expose === undefined) {\n review.push(\n 'REVIEW: pricing and exposure are not inferred from OpenAPI. Add e.g.',\n ' pricing: { type: free } # or { type: fixed, amount: \"0.01\", currency: USDC } with payments: [x402]',\n ' expose: [http] # http | mcp | a2a | acp',\n );\n }\n\n drafts.push({\n id: candidate.resourceId,\n ...(candidate.operationId !== undefined ? { operationId: candidate.operationId } : {}),\n tags: candidate.tags,\n source: `${candidate.method} ${candidate.path}`,\n resource: {\n name: candidate.name,\n ...(candidate.description !== undefined ? { description: candidate.description } : {}),\n input: mapping.inputSchema,\n ...(output !== undefined ? { output } : {}),\n backend: {\n type: 'http',\n method: candidate.method,\n url: candidate.backendUrl,\n ...(mapping.contentType !== undefined\n ? { headers: { 'Content-Type': mapping.contentType } }\n : {}),\n ...(Object.keys(mapping.inputBindings).length > 0\n ? { inputBindings: mapping.inputBindings }\n : {}),\n },\n // Written only when the operator supplied it (see the file header)\n ...(options.policy?.pricing !== undefined ? { pricing: options.policy.pricing } : {}),\n ...(options.policy?.expose !== undefined ? { expose: [...options.policy.expose] } : {}),\n },\n review,\n });\n }\n\n return {\n version: loaded.version,\n sourcePath: loaded.sourcePath,\n drafts,\n diagnostics: [\n ...selectDiscoveryDiagnostics(discovery.diagnostics, options.include, selected),\n ...diagnostics,\n ],\n unmatchedOperationIds: (wanted ?? []).filter((id) => !matched.has(id)),\n };\n}\n\n// With a selection, a discovery finding counts only for a selected operation\n// or one named by `--operation`, so an unrelated one cannot fail `--strict`\nfunction selectDiscoveryDiagnostics(\n found: readonly ImportDiagnostic[],\n include: ImportOptions['include'],\n selected: ReadonlySet<string>,\n): readonly ImportDiagnostic[] {\n if (include?.operationIds === undefined && include?.tags === undefined) return found;\n return found.filter(\n ({ operation }) =>\n operation === undefined ||\n selected.has(operation) ||\n include.operationIds?.includes(operation) === true,\n );\n}\n\n// `--operation` accepts the OpenAPI operationId or the generated resource id\nfunction selects(ids: readonly string[], candidate: OpenApiOperationCandidate): boolean {\n return (\n ids.includes(candidate.resourceId) ||\n (candidate.operationId !== undefined && ids.includes(candidate.operationId))\n );\n}\n\n// `security: []` means \"explicitly none\" and `[{}]` means optional. Neither needs a credential\nfunction declaresSecurity(candidate: OpenApiOperationCandidate): boolean {\n return candidate.security.some(\n (requirement) =>\n typeof requirement === 'object' &&\n requirement !== null &&\n Object.keys(requirement).length > 0,\n );\n}\n\n/**\n * One success response, chosen the same way every run: 200, then 201, then\n * 202, then the remaining explicit 2xx in ascending order. Status-dependent\n * unions are out of scope, so when several 2xx carry materially different\n * schemas the operator is told which one was taken rather than left to\n * discover it from the diff.\n */\nfunction selectOutputSchema(\n document: Record<string, unknown>,\n candidate: OpenApiOperationCandidate,\n diagnostics: ImportDiagnostic[],\n dropped: Set<string>,\n): JsonSchema | undefined {\n const responses = candidate.responses;\n if (!isRecord(responses)) return undefined;\n\n const successes = Object.keys(responses)\n .filter((status) => /^2\\d\\d$/.test(status))\n .sort((a, b) => rank(a) - rank(b));\n if (successes.length === 0) return undefined;\n\n const withBody = successes.flatMap((status) => {\n const response = dereference(document, responses[status]);\n if (!isRecord(response.value)) return [];\n const content = response.value['content'];\n if (!isRecord(content)) return [];\n const mediaType = pickJsonMediaType(Object.keys(content));\n if (mediaType === undefined) return [];\n const media = dereference(document, content[mediaType], response.stack).value;\n return isRecord(media) ? [{ status, media }] : [];\n });\n const chosen = withBody[0];\n if (chosen === undefined) return undefined; // 204, or no JSON representation\n\n const schemaNode = chosen.media['schema'];\n if (schemaNode === undefined) {\n diagnostics.push({\n severity: 'warning',\n code: 'missing-output-schema',\n operation: candidate.resourceId,\n message: `${candidate.resourceId}: response ${chosen.status} has JSON content without a schema; omitted the output schema`,\n });\n return undefined;\n }\n\n const converted = convertSchema(document, schemaNode);\n if (!converted.supported) {\n // Output schema is descriptive: omitting it costs discovery detail, not\n // request safety, so it never skips the operation\n diagnostics.push({\n severity: 'warning',\n code: 'unsupported-output-schema',\n operation: candidate.resourceId,\n message: `${candidate.resourceId}: omitted the output schema (${converted.reason})`,\n });\n return undefined;\n }\n for (const keyword of converted.dropped) dropped.add(keyword);\n\n if (withBody.length > 1) {\n diagnostics.push({\n severity: 'warning',\n code: 'multiple-success-responses',\n operation: candidate.resourceId,\n message: `${candidate.resourceId}: responses ${withBody.map(({ status }) => status).join(', ')} all carry a JSON body; used ${chosen.status}`,\n });\n }\n return converted.schema;\n}\n\nfunction rank(status: string): number {\n const preferred = ['200', '201', '202'].indexOf(status);\n return preferred === -1 ? 100 + Number(status) : preferred;\n}\n\n/**\n * Renders the drafts as a config fragment: the same `resources:` shape\n * `config.yaml` uses, so a reviewed block can be moved across whole\n */\nexport function renderResourcesYaml(result: ImportResult): string {\n const resources: Record<string, unknown> = {};\n for (const draft of result.drafts) resources[draft.id] = draft.resource;\n\n const doc = new Document({ resources });\n doc.commentBefore = [\n ' Generated by agent-commerce import openapi. Review before use.',\n // win32.basename splits on both / and \\\n ` Source: ${win32.basename(result.sourcePath)} (OpenAPI ${result.version})`,\n ' Merge the resources below into config.yaml once pricing, exposure and',\n ' any backend authentication have been decided.',\n ].join('\\n');\n\n // Comments hang off the key node; a Pair has nowhere to put one. Map items\n // are in insertion order, which is draft order.\n const map = doc.getIn(['resources'], true) as YAMLMap | undefined;\n map?.items.forEach((item, index) => {\n const draft = result.drafts[index];\n const key = (item as Pair<Node, unknown>).key;\n if (draft === undefined || draft.review.length === 0 || key === null) return;\n key.commentBefore = draft.review.map((line) => ` ${line}`).join('\\n');\n });\n\n // lineWidth 0 disables folding: a wrapped description would otherwise\n // re-flow whenever an unrelated word changed, and the generated file is\n // meant to be reviewed in a diff\n return doc.toString({ lineWidth: 0 });\n}\n","/**\n * OpenAPI parameters and request body -> a canonical input schema plus\n * `backend.inputBindings`.\n *\n * Locations are namespaced (`path` / `query` / `body`) so a `?id=` and a\n * `{id}` in the same operation cannot collide, and so the executor can source\n * each group independently. Anything the executor would not send the way the\n * API expects is refused rather than approximated: a required parameter we\n * cannot represent skips the operation, an optional one is omitted with a\n * warning. Approximating it would produce a resource that looks importable,\n * takes payment, and then calls the backend wrongly.\n */\nimport type { JsonSchema } from '../core/domain/common';\nimport { extractPathParameterNames } from '../core/execution';\nimport { isRecord } from '../core/is-record';\nimport { dereference } from './refs';\nimport { convertSchema, isPrimitiveSchema, type SchemaConversion } from './schema';\nimport type { ImportDiagnostic, LoadedOpenApiDocument, OpenApiOperationCandidate } from './types';\n\n// Top-level input property names, which are also the binding values\nconst PATH_GROUP = 'path';\nconst QUERY_GROUP = 'query';\nconst BODY_GROUP = 'body';\n\n/**\n * OpenAPI: parameters named these \"SHALL be ignored\" - they are transport\n * concerns, and `Authorization` in particular is operator configuration that\n * must never become an agent-supplied input\n */\nconst IGNORED_HEADER_NAMES = new Set(['accept', 'content-type', 'authorization']);\n\n// Serialization styles the executor's plain `key=value` query cannot produce\nconst UNSUPPORTED_QUERY_STYLES = new Set(['deepObject', 'spaceDelimited', 'pipeDelimited']);\n\nexport interface RequestBindings {\n readonly path?: string;\n readonly query?: string;\n readonly body?: string;\n}\n\nexport type RequestMapping =\n | {\n readonly supported: true;\n readonly inputSchema: JsonSchema;\n readonly inputBindings: RequestBindings;\n /** Set only for a vendor `+json` body, which needs a static Content-Type */\n readonly contentType?: string;\n /** Schema constraints dropped because the gateway does not enforce them */\n readonly droppedKeywords: readonly string[];\n readonly diagnostics: readonly ImportDiagnostic[];\n }\n | { readonly supported: false; readonly diagnostics: readonly ImportDiagnostic[] };\n\nexport function mapRequest(\n loaded: LoadedOpenApiDocument,\n candidate: OpenApiOperationCandidate,\n): RequestMapping {\n const { document } = loaded;\n const diagnostics: ImportDiagnostic[] = [];\n const dropped = new Set<string>();\n const operation = candidate.resourceId;\n\n const warn = (code: string, message: string): void => {\n diagnostics.push({ severity: 'warning', code, operation, message });\n };\n const skip = (code: string, message: string): RequestMapping => {\n diagnostics.push({\n severity: 'error',\n code,\n operation,\n message: `Skipped ${candidate.method} ${candidate.path}: ${message}`,\n });\n return { supported: false, diagnostics };\n };\n\n const pathProperties: Record<string, unknown> = {};\n const queryProperties: Record<string, unknown> = {};\n const requiredQuery: string[] = [];\n const templateParams = new Set(extractPathParameterNames(candidate.path));\n\n for (const parameter of mergeParameters(document, candidate.parameters)) {\n const name = typeof parameter['name'] === 'string' ? parameter['name'] : undefined;\n const location = typeof parameter['in'] === 'string' ? parameter['in'] : undefined;\n if (name === undefined || location === undefined) continue;\n const required = parameter['required'] === true || location === 'path';\n const label = `${location} parameter \"${name}\"`;\n\n if (location === 'header' || location === 'cookie') {\n if (location === 'header' && IGNORED_HEADER_NAMES.has(name.toLowerCase())) continue;\n if (required) {\n return skip(\n 'unsupported-required-parameter',\n `${label} is required, and ${location} parameters are operator configuration in this release, not agent input`,\n );\n }\n warn(\n 'unsupported-optional-parameter',\n `Omitted optional ${label}: ${location} parameters are not imported. Configure it under backend.headers if the API needs it`,\n );\n continue;\n }\n if (location !== 'path' && location !== 'query') {\n if (required) return skip('unsupported-required-parameter', `${label} has unknown location`);\n warn('unsupported-optional-parameter', `Omitted optional ${label}: unknown location`);\n continue;\n }\n\n const converted = convertParameter(document, parameter, location);\n if (!converted.supported) {\n if (required) return skip('unsupported-required-parameter', `${label} ${converted.reason}`);\n warn('unsupported-optional-parameter', `Omitted optional ${label}: it ${converted.reason}`);\n continue;\n }\n for (const keyword of converted.dropped) dropped.add(keyword);\n\n if (location === 'path') {\n if (!templateParams.has(name)) {\n warn(\n 'path-parameter-not-in-template',\n `Ignored path parameter \"${name}\": it does not appear in \"${candidate.path}\"`,\n );\n continue;\n }\n pathProperties[name] = converted.schema;\n } else {\n queryProperties[name] = converted.schema;\n if (required) requiredQuery.push(name);\n }\n }\n\n for (const param of templateParams) {\n if (!Object.hasOwn(pathProperties, param)) {\n return skip(\n 'undeclared-path-parameter',\n `\"{${param}}\" appears in the path but is not declared as a path parameter, so a caller could never supply it`,\n );\n }\n }\n\n const body = resolveBody(document, candidate);\n if (body.kind === 'unsupported') {\n if (body.required) return skip('unsupported-request-body', body.reason);\n warn('unsupported-request-body', `Omitted the request body: ${body.reason}`);\n }\n if (body.kind === 'schema') {\n for (const keyword of body.dropped) dropped.add(keyword);\n }\n\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n const bindings: { path?: string; query?: string; body?: string } = {};\n\n if (Object.keys(pathProperties).length > 0) {\n properties[PATH_GROUP] = closedObject(pathProperties, Object.keys(pathProperties));\n // OpenAPI path parameters are always required, and a missing one makes the\n // request unbuildable - which on a paid resource is payment with no\n // delivery, so config rejects the shape at load time too\n required.push(PATH_GROUP);\n bindings.path = PATH_GROUP;\n }\n if (Object.keys(queryProperties).length > 0) {\n properties[QUERY_GROUP] = closedObject(queryProperties, requiredQuery);\n if (requiredQuery.length > 0) required.push(QUERY_GROUP);\n bindings.query = QUERY_GROUP;\n }\n if (body.kind === 'schema') {\n properties[BODY_GROUP] = body.schema;\n if (body.required) required.push(BODY_GROUP);\n bindings.body = BODY_GROUP;\n }\n\n return {\n supported: true,\n inputSchema: {\n type: 'object',\n properties,\n ...(required.length > 0 ? { required } : {}),\n additionalProperties: false,\n },\n inputBindings: bindings,\n ...(body.kind === 'schema' && body.contentType !== undefined\n ? { contentType: body.contentType }\n : {}),\n droppedKeywords: [...dropped],\n diagnostics,\n };\n}\n\n/**\n * Path Item parameters first, operation parameters second, with the OpenAPI\n * identity rule: a parameter is the same one when `name` *and* `in` match, and\n * the operation's own definition wins\n */\nfunction mergeParameters(\n document: Record<string, unknown>,\n parameters: readonly unknown[],\n): Record<string, unknown>[] {\n const byIdentity = new Map<string, Record<string, unknown>>();\n for (const raw of parameters) {\n const parameter = dereference(document, raw).value;\n if (!isRecord(parameter)) continue;\n byIdentity.set(`${String(parameter['in'])}:${String(parameter['name'])}`, parameter);\n }\n return [...byIdentity.values()];\n}\n\n/**\n * The parameter's schema, if the executor can send the parameter the way the\n * API reads it. It writes one `key=value` pair per query parameter and\n * substitutes one URL-encoded value per path segment, so anything that\n * serializes to several pairs or to a structured segment is not supported.\n * Each `reason` reads as a predicate of the parameter.\n */\nfunction convertParameter(\n document: Record<string, unknown>,\n parameter: Record<string, unknown>,\n location: 'path' | 'query',\n): SchemaConversion {\n const unsupported = (reason: string): SchemaConversion => ({ supported: false, reason });\n // Assigned as a key, it replaces the group object's prototype instead of\n // adding the parameter\n if (parameter['name'] === '__proto__') {\n return unsupported('has a name that cannot be an input key');\n }\n if (parameter['content'] !== undefined) {\n return unsupported(\n 'uses the `content` form, whose media-type serialization the gateway does not perform',\n );\n }\n const style = parameter['style'];\n if (location === 'query' && typeof style === 'string' && UNSUPPORTED_QUERY_STYLES.has(style)) {\n return unsupported(`uses style \"${style}\", which the gateway does not serialize`);\n }\n if (location === 'path' && typeof style === 'string' && style !== 'simple') {\n return unsupported(`uses style \"${style}\"; the gateway substitutes plain values only`);\n }\n const converted = convertSchema(document, parameter['schema']);\n if (!converted.supported) return unsupported(`has an unusable schema: ${converted.reason}`);\n if (!isPrimitiveSchema(converted.schema)) {\n return unsupported(\n 'is not a primitive; object and array parameters need serialization the gateway does not perform',\n );\n }\n return converted;\n}\n\ntype BodyResult =\n | { readonly kind: 'none' }\n | {\n readonly kind: 'schema';\n readonly schema: JsonSchema;\n readonly required: boolean;\n readonly contentType?: string;\n readonly dropped: readonly string[];\n }\n | { readonly kind: 'unsupported'; readonly required: boolean; readonly reason: string };\n\nfunction resolveBody(\n document: Record<string, unknown>,\n candidate: OpenApiOperationCandidate,\n): BodyResult {\n if (candidate.requestBody === undefined) return { kind: 'none' };\n const resolvedBody = dereference(document, candidate.requestBody);\n const requestBody = resolvedBody.value;\n if (!isRecord(requestBody)) return { kind: 'none' };\n const required = requestBody['required'] === true;\n\n if (candidate.method === 'GET' || candidate.method === 'DELETE') {\n // The executor sends no body on these, and config refuses a body binding\n // for them. Silently generating one would produce a resource whose\n // payload never arrives.\n return {\n kind: 'unsupported',\n required: false,\n reason: `a ${candidate.method} request body is not sent by the gateway`,\n };\n }\n\n const content = requestBody['content'];\n if (!isRecord(content)) return { kind: 'none' };\n const mediaType = pickJsonMediaType(Object.keys(content));\n if (mediaType === undefined) {\n return {\n kind: 'unsupported',\n required,\n reason: `no JSON request body content type (found: ${Object.keys(content).join(', ') || 'none'}). Only application/json and application/*+json are supported - multipart and form data are never serialized as JSON`,\n };\n }\n const media = dereference(document, content[mediaType], resolvedBody.stack).value;\n const schemaNode = isRecord(media) ? media['schema'] : undefined;\n if (schemaNode === undefined) {\n // A body with no schema accepts anything. `additionalProperties: true` is\n // written out because the config loader closes every object schema that\n // does not state it.\n return {\n kind: 'schema',\n schema: { type: 'object', additionalProperties: true },\n required,\n ...(mediaType === 'application/json' ? {} : { contentType: mediaType }),\n dropped: [],\n };\n }\n const converted = convertSchema(document, schemaNode);\n if (!converted.supported) return { kind: 'unsupported', required, reason: converted.reason };\n return {\n kind: 'schema',\n schema: converted.schema,\n required,\n ...(mediaType === 'application/json' ? {} : { contentType: mediaType }),\n dropped: converted.dropped,\n };\n}\n\n/** Exact `application/json` wins; otherwise the first `+json` in sorted order */\nexport function pickJsonMediaType(keys: readonly string[]): string | undefined {\n const normalized = keys.map((key) => ({ key, type: key.split(';')[0]?.trim().toLowerCase() }));\n const exact = normalized.find((entry) => entry.type === 'application/json');\n if (exact !== undefined) return exact.key;\n return [...normalized]\n .sort((a, b) => (a.type ?? '').localeCompare(b.type ?? ''))\n .find((entry) => entry.type?.startsWith('application/') && entry.type.endsWith('+json'))?.key;\n}\n\nfunction closedObject(\n properties: Record<string, unknown>,\n required: readonly string[],\n): JsonSchema {\n return {\n type: 'object',\n properties,\n ...(required.length > 0 ? { required: [...required] } : {}),\n additionalProperties: false,\n };\n}\n","/**\n * OpenAPI schema -> the JSON Schema subset this gateway enforces.\n *\n * `src/core`'s validator enforces `type`/`properties`/`required`/\n * `additionalProperties`/`enum`/`items` and ignores everything else, so a\n * copied `pattern` or `oneOf` would advertise validation to agents that no\n * code performs - and on a paid resource the buyer pays before the backend\n * sees the request. Unenforceable constraints are dropped from the generated\n * schema and reported, never carried along quietly.\n */\nimport { isDeepStrictEqual } from 'node:util';\nimport type { JsonSchema } from '../core/domain/common';\nimport { isCommerceError } from '../core/errors';\nimport { isRecord } from '../core/is-record';\nimport { dereference } from './refs';\n\n// The types `compileJsonSchema` enforces\nconst SUPPORTED_TYPES = new Set([\n 'object',\n 'string',\n 'number',\n 'integer',\n 'boolean',\n 'array',\n 'null',\n]);\n\n// Copied through: descriptive, never a constraint, so it cannot overstate\nconst METADATA_KEYWORDS = ['title', 'description', 'default', 'example', 'examples', 'deprecated'];\n\n/**\n * Annotations, not constraints: dropping them changes nothing a caller could\n * observe, so they are not worth telling the operator about. Reporting them\n * would bury the keywords that *do* matter (`pattern`, `minimum`, `format`)\n * in noise, which is how a real warning gets ignored.\n */\nconst ANNOTATION_KEYWORDS = new Set([\n 'xml',\n 'externalDocs',\n 'readOnly',\n 'writeOnly',\n '$schema',\n '$id',\n '$comment',\n '$defs',\n 'definitions',\n]);\n\nexport type SchemaConversion =\n | {\n readonly supported: true;\n readonly schema: JsonSchema;\n /** Keyword names encountered and dropped, deduplicated, in first-seen order */\n readonly dropped: readonly string[];\n }\n | { readonly supported: false; readonly reason: string };\n\n/** Types a path or query parameter may have: the executor stringifies one value */\nexport function isPrimitiveSchema(schema: JsonSchema): boolean {\n const types = typeList(schema['type']);\n if (types === undefined) return false;\n return types.every((type) => type !== 'object' && type !== 'array' && SUPPORTED_TYPES.has(type));\n}\n\nexport function convertSchema(\n document: Record<string, unknown>,\n node: unknown,\n stack: readonly string[] = [],\n): SchemaConversion {\n const dropped = new Set<string>();\n try {\n const schema = convertNode(document, node, stack, dropped);\n return { supported: true, schema, dropped: [...dropped] };\n } catch (error) {\n if (error instanceof UnsupportedSchema) return { supported: false, reason: error.message };\n // A reference cycle or a dangling pointer arrives as CONFIG_INVALID from\n // the resolver. For a *schema* that is a skip-this-operation condition,\n // not a fail-the-whole-import one: the rest of the document is fine.\n if (isCommerceError(error)) return { supported: false, reason: error.message };\n throw error;\n }\n}\n\nclass UnsupportedSchema extends Error {}\n\nfunction convertNode(\n document: Record<string, unknown>,\n node: unknown,\n stack: readonly string[],\n dropped: Set<string>,\n): JsonSchema {\n // OpenAPI 3.1 allows boolean schemas: `true` accepts anything, `false`\n // accepts nothing - and nothing is not a request shape we can generate\n if (node === true) return {};\n if (node === false) throw new UnsupportedSchema('schema is `false`, which accepts no value');\n\n const resolved = dereference(document, node, stack);\n const schemaNode = resolved.value;\n if (!isRecord(schemaNode)) throw new UnsupportedSchema('schema node is not an object');\n\n if (Array.isArray(schemaNode['allOf'])) {\n return mergeAllOf(document, schemaNode, resolved.stack, dropped);\n }\n for (const keyword of ['oneOf', 'anyOf', 'not', 'discriminator']) {\n if (Object.hasOwn(schemaNode, keyword)) {\n throw new UnsupportedSchema(\n `schema uses \"${keyword}\", which this gateway cannot enforce - accepting it would advertise validation that never runs`,\n );\n }\n }\n\n const result: Record<string, unknown> = {};\n const types = resolveTypes(schemaNode);\n if (types !== undefined) result['type'] = types.length === 1 ? types[0] : types;\n\n for (const keyword of METADATA_KEYWORDS) {\n if (Object.hasOwn(schemaNode, keyword)) result[keyword] = schemaNode[keyword];\n }\n if (Array.isArray(schemaNode['enum'])) result['enum'] = [...schemaNode['enum']];\n\n const properties = schemaNode['properties'];\n if (isRecord(properties)) {\n const converted: Record<string, unknown> = {};\n for (const [name, sub] of Object.entries(properties)) {\n // Assigned as a key, it replaces `converted`'s prototype instead of adding\n // the property, which `required` may still name\n if (name === '__proto__') {\n throw new UnsupportedSchema(\n 'schema declares a \"__proto__\" property, which cannot be imported',\n );\n }\n converted[name] = convertNode(document, sub, resolved.stack, dropped);\n }\n result['properties'] = converted;\n }\n\n // Independent of `properties`: `required` without them is legal, and core's\n // validator enforces it, so dropping it here would be a silent weakening.\n // Emitted here so every generated object schema orders its keys the same\n // way - the output is meant to be reviewed in a diff.\n const required = schemaNode['required'];\n if (Array.isArray(required)) {\n const names = required.filter((name): name is string => typeof name === 'string');\n if (names.length > 0) result['required'] = names;\n }\n\n const additional = schemaNode['additionalProperties'];\n if (typeof additional === 'boolean') {\n result['additionalProperties'] = additional;\n } else if (additional !== undefined) {\n result['additionalProperties'] = convertNode(document, additional, resolved.stack, dropped);\n } else if (isRecord(properties)) {\n result['additionalProperties'] = false;\n }\n\n const items = schemaNode['items'];\n if (Array.isArray(items)) {\n // Tuple `items` is not enforced; keeping it would look like it was\n dropped.add('items (tuple form)');\n } else if (items !== undefined) {\n result['items'] = convertNode(document, items, resolved.stack, dropped);\n }\n\n for (const keyword of Object.keys(schemaNode)) {\n if (isCarriedKeyword(keyword) || ANNOTATION_KEYWORDS.has(keyword) || keyword.startsWith('x-')) {\n continue;\n }\n dropped.add(keyword);\n }\n\n return result;\n}\n\nfunction isCarriedKeyword(keyword: string): boolean {\n return (\n keyword === 'type' ||\n keyword === 'properties' ||\n keyword === 'required' ||\n keyword === 'additionalProperties' ||\n keyword === 'enum' ||\n keyword === 'items' ||\n keyword === 'nullable' ||\n keyword === '$ref' ||\n METADATA_KEYWORDS.includes(keyword)\n );\n}\n\n/**\n * OpenAPI 3.0's `nullable: true` becomes draft-2020-12's union type, which is\n * what the runtime validator understands. 3.1 already writes it that way.\n */\nfunction resolveTypes(schema: Record<string, unknown>): string[] | undefined {\n const declared = typeList(schema['type']);\n if (declared === undefined) return undefined;\n const known = declared.filter((type) => SUPPORTED_TYPES.has(type));\n if (known.length === 0) {\n throw new UnsupportedSchema(`schema type \"${String(schema['type'])}\" is not a JSON type`);\n }\n if (schema['nullable'] === true && !known.includes('null')) known.push('null');\n return known;\n}\n\nfunction typeList(raw: unknown): string[] | undefined {\n if (typeof raw === 'string') return [raw];\n if (Array.isArray(raw) && raw.every((entry) => typeof entry === 'string')) {\n return raw as string[];\n }\n return undefined;\n}\n\n/**\n * A simple `allOf` of object schemas is merged; anything else is refused.\n *\n * Merging is only safe while the branches agree - two branches declaring the\n * same property differently have a meaning (\"both must hold\") that this\n * validator cannot express, and picking one would quietly accept requests the\n * API rejects, or reject ones it accepts.\n */\nfunction mergeAllOf(\n document: Record<string, unknown>,\n schema: Record<string, unknown>,\n stack: readonly string[],\n dropped: Set<string>,\n): JsonSchema {\n const branches = schema['allOf'] as readonly unknown[];\n const siblings = { ...schema };\n delete siblings['allOf'];\n\n const merged: Record<string, unknown> = { type: 'object', properties: {}, required: [] };\n const properties = merged['properties'] as Record<string, unknown>;\n const required = new Set<string>();\n let open = false;\n\n const parts = [...branches, ...(Object.keys(siblings).length > 0 ? [siblings] : [])];\n for (const branch of parts) {\n const converted = convertNode(document, branch, stack, dropped);\n const types = typeList(converted['type']);\n if (types !== undefined && !types.includes('object')) {\n throw new UnsupportedSchema('allOf mixes object and non-object schemas');\n }\n const branchProperties = converted['properties'];\n if (isRecord(branchProperties)) {\n for (const [name, sub] of Object.entries(branchProperties)) {\n const existing = properties[name];\n if (existing !== undefined && !isDeepStrictEqual(existing, sub)) {\n throw new UnsupportedSchema(\n `allOf branches declare property \"${name}\" differently, which cannot be merged`,\n );\n }\n properties[name] = sub;\n }\n }\n for (const name of Array.isArray(converted['required']) ? converted['required'] : []) {\n if (typeof name === 'string') required.add(name);\n }\n for (const keyword of ['enum', 'items']) {\n if (Object.hasOwn(converted, keyword)) {\n throw new UnsupportedSchema(`allOf branch uses \"${keyword}\", which cannot be merged`);\n }\n }\n for (const keyword of METADATA_KEYWORDS) {\n if (Object.hasOwn(converted, keyword) && !Object.hasOwn(merged, keyword)) {\n merged[keyword] = converted[keyword];\n }\n }\n // A branch that allows extra properties keeps the merge open. A schema for\n // them constrains the other branches' properties too, which the merged\n // `properties` cannot express.\n const additional = converted['additionalProperties'];\n if (additional === true) open = true;\n else if (isRecord(additional)) {\n throw new UnsupportedSchema(\n 'allOf branch constrains additionalProperties, which cannot be merged',\n );\n }\n }\n\n if (required.size > 0) merged['required'] = [...required];\n else delete merged['required'];\n merged['additionalProperties'] = open;\n return merged;\n}\n","/**\n * Reads and validates a local OpenAPI description.\n *\n * Offline by construction: the document is parsed here, every `$ref` is\n * checked to be internal *before* the validator ever sees the document, and no\n * URL-fetching plugin is passed to it. The importer must not turn \"point it at\n * your API description\" into \"the gateway machine makes outbound requests to\n * whatever the file names\".\n */\nimport { open, stat } from 'node:fs/promises';\nimport { extname } from 'node:path';\nimport { validate } from '@scalar/openapi-parser';\nimport { parse as parseYaml } from 'yaml';\nimport { CommerceError } from '../core/errors';\nimport type { LoadedOpenApiDocument, OpenApiVersion } from './types';\n\n/** Generous for a hand-written description; small enough that a stray file is refused */\nexport const MAX_SOURCE_BYTES = 10 * 1024 * 1024;\n\nconst SUPPORTED_EXTENSIONS = new Set(['.yaml', '.yml', '.json']);\nconst SUPPORTED_VERSIONS: ReadonlySet<string> = new Set(['3.0', '3.1', '3.2']);\n\nfunction invalid(\n message: string,\n details: Record<string, unknown>,\n cause?: unknown,\n): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, {\n details,\n ...(cause !== undefined ? { cause } : {}),\n });\n}\n\n// The size from `stat` does not bound the read: a device or a pipe reports 0\nasync function readCapped(sourcePath: string, details: Record<string, unknown>): Promise<string> {\n const buffer = Buffer.alloc(MAX_SOURCE_BYTES + 1);\n let length = 0;\n try {\n const handle = await open(sourcePath, 'r');\n try {\n while (length < buffer.length) {\n const { bytesRead } = await handle.read(buffer, length, buffer.length - length, null);\n if (bytesRead === 0) break;\n length += bytesRead;\n }\n } finally {\n await handle.close();\n }\n } catch (error) {\n throw invalid(`OpenAPI document \"${sourcePath}\" could not be read`, details, error);\n }\n if (length > MAX_SOURCE_BYTES) {\n throw invalid(`OpenAPI document \"${sourcePath}\" is over the ${MAX_SOURCE_BYTES}-byte limit`, {\n ...details,\n maxBytes: MAX_SOURCE_BYTES,\n });\n }\n return buffer.toString('utf8', 0, length);\n}\n\nexport async function loadOpenApiDocument(sourcePath: string): Promise<LoadedOpenApiDocument> {\n const details = { sourcePath };\n\n let stats: Awaited<ReturnType<typeof stat>>;\n try {\n stats = await stat(sourcePath);\n } catch (error) {\n throw invalid(`OpenAPI document \"${sourcePath}\" could not be read`, details, error);\n }\n if (stats.isDirectory()) {\n throw invalid(`\"${sourcePath}\" is a directory, not an OpenAPI document`, details);\n }\n if (stats.size > MAX_SOURCE_BYTES) {\n throw invalid(\n `OpenAPI document \"${sourcePath}\" is ${stats.size} bytes, over the ${MAX_SOURCE_BYTES}-byte limit`,\n { ...details, size: stats.size, maxBytes: MAX_SOURCE_BYTES },\n );\n }\n\n const extension = extname(sourcePath).toLowerCase();\n if (!SUPPORTED_EXTENSIONS.has(extension)) {\n throw invalid(\n `OpenAPI document \"${sourcePath}\" has an unsupported extension \"${extension || '(none)'}\". Supported: .yaml, .yml, .json`,\n details,\n );\n }\n\n const source = await readCapped(sourcePath, details);\n if (source.trim() === '') {\n throw invalid(`OpenAPI document \"${sourcePath}\" is empty`, details);\n }\n\n let parsed: unknown;\n try {\n // YAML is a superset of JSON, but JSON.parse gives the better message for a\n // file that claims to be JSON, and refuses YAML a .json file should not\n // contain\n parsed = extension === '.json' ? JSON.parse(source) : parseYaml(source);\n } catch (error) {\n throw invalid(\n `OpenAPI document \"${sourcePath}\" is not valid ${extension === '.json' ? 'JSON' : 'YAML'}: ${error instanceof Error ? error.message : String(error)}`,\n details,\n error,\n );\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw invalid(`OpenAPI document \"${sourcePath}\" is not an object`, details);\n }\n const document = parsed as Record<string, unknown>;\n\n const version = readVersion(document, sourcePath);\n // Before validation, not after: the validator resolves references, and the\n // no-network guarantee is only worth something if nothing external ever\n // reaches it\n rejectUnsupportedReferences(document, sourcePath);\n\n const result = await validate(document);\n if (!result.valid) {\n const first = result.errors?.[0];\n throw invalid(\n `OpenAPI document \"${sourcePath}\" is not a valid OpenAPI ${version} description: ${first ? `${first.message}${first.path ? ` (at ${first.path})` : ''}` : 'unknown validation error'}`,\n { ...details, errors: result.errors?.slice(0, 10) ?? [] },\n );\n }\n\n return { version, document, sourcePath };\n}\n\n/**\n * The `openapi` field decides, not the validator's own verdict: the validator\n * happily calls a Swagger 2.0 document valid, and importing one would mean\n * `host`/`basePath`/`schemes` and body-parameter conversion semantics that\n * nothing downstream understands. Refuse it by name so the operator is told to\n * convert rather than left guessing.\n */\nfunction readVersion(document: Record<string, unknown>, sourcePath: string): OpenApiVersion {\n const details = { sourcePath };\n if (typeof document['swagger'] === 'string') {\n throw invalid(\n `\"${sourcePath}\" is a Swagger ${document['swagger']} document. Only OpenAPI 3.0, 3.1 and 3.2 are supported - convert it first`,\n details,\n );\n }\n const declared = document['openapi'];\n if (typeof declared !== 'string') {\n throw invalid(`\"${sourcePath}\" has no \"openapi\" version field`, details);\n }\n const featureVersion = /^(\\d+\\.\\d+)(?:\\.|$)/.exec(declared)?.[1];\n if (featureVersion === undefined || !SUPPORTED_VERSIONS.has(featureVersion)) {\n throw invalid(\n `OpenAPI version \"${declared}\" is not supported. Supported: 3.0.x, 3.1.x, 3.2.x`,\n { ...details, version: declared },\n );\n }\n return featureVersion as OpenApiVersion;\n}\n\n/**\n * An external `$ref` is refused rather than fetched or read from disk: either\n * would be the importer acting on behalf of a document it was only asked to\n * read, by an outbound request or a filesystem read outside the source file.\n * Multi-file descriptions are out of scope, and refusing beats a silent partial\n * import. A malformed percent-escape is refused here too, because the\n * validator throws a bare `URIError` on one.\n */\nfunction rejectUnsupportedReferences(document: Record<string, unknown>, sourcePath: string): void {\n // Iterative with a seen set: YAML aliases can make the parsed graph cyclic,\n // and a deeply nested document would otherwise blow the call stack\n const seen = new WeakSet<object>();\n const queue: unknown[] = [document];\n while (queue.length > 0) {\n const node = queue.pop();\n if (typeof node !== 'object' || node === null) continue;\n if (seen.has(node)) continue;\n seen.add(node);\n if (Array.isArray(node)) {\n queue.push(...node);\n continue;\n }\n for (const [key, value] of Object.entries(node)) {\n if (key === '$ref' && typeof value === 'string') {\n if (!value.startsWith('#')) {\n throw invalid(\n `OpenAPI document \"${sourcePath}\" contains an external reference \"${value}\". Only internal references (#/...) are supported; the importer performs no network or filesystem lookups`,\n { sourcePath, ref: value },\n );\n }\n if (!isPercentDecodable(value)) {\n throw invalid(\n `OpenAPI document \"${sourcePath}\" contains a reference \"${value}\" with a malformed percent-escape`,\n { sourcePath, ref: value },\n );\n }\n }\n queue.push(value);\n }\n }\n}\n\nfunction isPercentDecodable(value: string): boolean {\n try {\n decodeURIComponent(value);\n return true;\n } catch {\n return false;\n }\n}\n","import { existsSync, mkdirSync } from 'node:fs';\nimport { writeFile } from 'node:fs/promises';\nimport { dirname, resolve } from 'node:path';\nimport * as clack from '@clack/prompts';\nimport { DEFAULT_CONFIG_FILENAME } from '../../config/filename';\nimport {\n type ConfigLoader,\n type ConfigParser,\n type GatewayConfig,\n loadConfigDynamic,\n parseConfigDynamic,\n} from '../lib/config-client';\nimport {\n buildInitConfigObject,\n defaultInitAnswers,\n type InitAnswers,\n type InitProtocolChoice,\n type InitResourceChoice,\n renderInitConfigYaml,\n} from '../lib/init-config';\nimport type { Io } from '../lib/io';\nimport { formatConfigError } from './validate';\n\nexport interface InitOptions {\n readonly outputPath?: string;\n readonly force?: boolean;\n readonly yes?: boolean;\n}\n\nexport interface InitDeps {\n readonly loadConfig?: ConfigLoader;\n readonly parseConfig?: ConfigParser;\n readonly collectAnswers?: () => Promise<InitAnswers | undefined>;\n readonly fileExists?: (path: string) => boolean;\n readonly writeFile?: (path: string, content: string) => Promise<void>;\n}\n\n/** The interactive prompt flow, exported so tests can drive it with a mocked `@clack/prompts` */\nexport async function collectAnswersInteractive(): Promise<InitAnswers | undefined> {\n clack.intro('agent-commerce init');\n\n const backendBaseUrl = await clack.text({\n message: 'Backend base URL (your existing merchant API)',\n initialValue: 'http://localhost:3000',\n // Checked here, where the user can retype it, rather than as a config error later\n validate: (value) => {\n const trimmed = (value ?? '').trim();\n if (trimmed.length === 0) return 'Required';\n let parsed: URL;\n try {\n parsed = new URL(trimmed);\n } catch {\n return 'Must be an absolute URL, e.g. http://localhost:3000';\n }\n return parsed.protocol === 'http:' || parsed.protocol === 'https:'\n ? undefined\n : 'Must use http:// or https://';\n },\n });\n if (clack.isCancel(backendBaseUrl)) {\n clack.cancel('Aborted.');\n return undefined;\n }\n\n const resources = await clack.multiselect<InitResourceChoice>({\n message: 'Which example resource(s) do you want to expose?',\n options: [\n { value: 'weather', label: 'Weather (free)' },\n { value: 'report', label: 'Market report (paid)' },\n ],\n initialValues: ['weather', 'report'],\n required: false,\n });\n if (clack.isCancel(resources)) {\n clack.cancel('Aborted.');\n return undefined;\n }\n\n const protocols = await clack.multiselect<InitProtocolChoice>({\n message: 'Which protocols should be enabled?',\n options: [\n { value: 'http', label: 'HTTP' },\n { value: 'mcp', label: 'MCP' },\n ],\n initialValues: ['http', 'mcp'],\n // Every resource needs at least one protocol in `expose`\n required: true,\n });\n if (clack.isCancel(protocols)) {\n clack.cancel('Aborted.');\n return undefined;\n }\n\n const x402Enabled = await clack.confirm({ message: 'Enable x402 payments?', initialValue: true });\n if (clack.isCancel(x402Enabled)) {\n clack.cancel('Aborted.');\n return undefined;\n }\n\n let merchantPayTo = defaultInitAnswers().merchantPayTo;\n if (x402Enabled) {\n const answer = await clack.text({\n message: 'Merchant settlement address (enter an address you control)',\n initialValue: merchantPayTo,\n validate: (value) => {\n const trimmed = (value ?? '').trim();\n if (trimmed.length === 0) return 'Required';\n // The shape config enforces, checked here so a typo can be retyped\n return /^0x[0-9a-fA-F]{40}$/.test(trimmed)\n ? undefined\n : 'Must be a 0x-prefixed 20-byte EVM address (42 characters)';\n },\n });\n if (clack.isCancel(answer)) {\n clack.cancel('Aborted.');\n return undefined;\n }\n merchantPayTo = answer;\n }\n\n clack.outro('Configuration answers collected.');\n\n return { backendBaseUrl, resources, protocols, x402Enabled, merchantPayTo };\n}\n\n/** `agent-commerce init [--yes] [--force] [--output <path>]` */\nexport async function runInit(options: InitOptions, io: Io, deps: InitDeps = {}): Promise<number> {\n const outputPath = options.outputPath ?? DEFAULT_CONFIG_FILENAME;\n const loadConfig = deps.loadConfig ?? loadConfigDynamic;\n const parseConfigInMemory = deps.parseConfig ?? parseConfigDynamic;\n const fileExists = deps.fileExists ?? existsSync;\n const writeFileImpl =\n deps.writeFile ??\n (async (path: string, content: string) => {\n await writeFile(path, content, 'utf8');\n });\n\n if (fileExists(outputPath) && options.force !== true) {\n io.stderr(`FAIL ${outputPath} already exists. Re-run with --force to overwrite.`);\n return 1;\n }\n\n const answers =\n options.yes === true\n ? defaultInitAnswers()\n : await (deps.collectAnswers ?? collectAnswersInteractive)();\n\n if (answers === undefined) {\n io.stderr('FAIL init aborted, nothing was written.');\n return 1;\n }\n\n // Validate before writing. When the answers fail validation nothing is\n // written, and the config error names the field to fix.\n let config: GatewayConfig;\n try {\n config = await parseConfigInMemory(buildInitConfigObject(answers));\n } catch (err) {\n io.stderr(formatConfigError(err));\n io.stderr(`FAIL Nothing was written to ${outputPath}.`);\n return 1;\n }\n\n const yamlContent = renderInitConfigYaml(answers);\n mkdirSync(dirname(resolve(outputPath)), { recursive: true });\n await writeFileImpl(outputPath, yamlContent);\n io.stdout(`PASS Wrote ${outputPath}`);\n io.stdout(`PASS ${outputPath} is valid: ${config.resources.length} resource(s)`);\n\n // The file is a YAML serialization of the object just validated, plus a\n // comment header. Loading it back catches the one failure the in-memory\n // check cannot see: a rendering bug.\n try {\n await loadConfig({ path: outputPath });\n } catch (err) {\n io.stderr(formatConfigError(err));\n io.stderr(\n `FAIL ${outputPath} was written but does not parse, although the same answers validated in memory. This is a bug in the config renderer; please report it.`,\n );\n return 1;\n }\n\n io.stdout('');\n io.stdout('Next steps:');\n io.stdout(` agent-commerce validate --config ${outputPath}`);\n // No `npm run dev:*`: those scripts exist only in a repo clone, and the\n // compose line says it needs one\n io.stdout(' docker compose up # start the local demo stack (from a repo clone)');\n io.stdout(` agent-commerce doctor --config ${outputPath}`);\n\n return 0;\n}\n","import { isCommerceError } from '../../core';\nimport { type ConfigLoader, loadConfigDynamic } from '../lib/config-client';\nimport type { Io } from '../lib/io';\nimport {\n fillEnvFromLocalChainManifest,\n LOCAL_CHAIN_MANIFEST_PATH,\n MANIFEST_FILLABLE_ENV_VAR_NAMES,\n type ManifestEnvFill,\n} from '../lib/manifest-env';\n\nexport interface ValidateOptions {\n readonly configPath?: string;\n}\n\nexport interface ValidateDeps {\n readonly loadConfig?: ConfigLoader;\n readonly fillEnvFromManifest?: (env: NodeJS.ProcessEnv) => ManifestEnvFill;\n}\n\n/**\n * Formats a config-loading failure into an actionable report.\n *\n * `src/config` reports file, YAML, schema and environment failures as\n * `CommerceError('CONFIG_INVALID')` with structured details, and\n * `config-client` reports a config module that fails to load as\n * `INTERNAL_ERROR`. Nothing here adds a resolved `${ENV}` value: the config\n * error names only the variable.\n *\n * When no manifest was found, an unresolved variable that `.deploy/local.json`\n * would supply gets a hint to run `npm run chain:deploy` (see\n * `../lib/manifest-env`).\n */\nexport function formatConfigError(err: unknown, manifestFound = false): string {\n if (isCommerceError(err)) {\n const lines = [`FAIL ${err.code}: ${err.message}`];\n if (err.details !== undefined) {\n lines.push(` details: ${JSON.stringify(err.details)}`);\n }\n const variable = err.details?.['variable'];\n if (\n !manifestFound &&\n typeof variable === 'string' &&\n MANIFEST_FILLABLE_ENV_VAR_NAMES.has(variable)\n ) {\n lines.push(\n ` hint: \"npm run chain:deploy\" writes ${LOCAL_CHAIN_MANIFEST_PATH}, which validate/doctor read automatically to fill local X402_*/MERCHANT_WALLET placeholders.`,\n );\n }\n return lines.join('\\n');\n }\n if (err instanceof Error) {\n return `FAIL ${err.message}`;\n }\n return `FAIL ${String(err)}`;\n}\n\n/** `agent-commerce validate [--config <path>]`. Exits non-zero on invalid configuration */\nexport async function runValidate(\n options: ValidateOptions,\n io: Io,\n deps: ValidateDeps = {},\n): Promise<number> {\n const loadConfig = deps.loadConfig ?? loadConfigDynamic;\n const fillEnvFromManifest = deps.fillEnvFromManifest ?? fillEnvFromLocalChainManifest;\n const { env, filled, manifestFound } = fillEnvFromManifest(process.env);\n if (filled.length > 0) {\n io.stdout(`using local chain manifest ${LOCAL_CHAIN_MANIFEST_PATH} for ${filled.join(', ')}`);\n }\n try {\n const config = await loadConfig({\n ...(options.configPath !== undefined ? { path: options.configPath } : {}),\n env,\n });\n io.stdout('PASS Configuration is valid');\n io.stdout(` merchant: ${config.merchant.name} (${config.merchant.id})`);\n io.stdout(` resources: ${config.resources.length}`);\n io.stdout(\n ` protocols: http=${config.protocols.http.enabled ? 'on' : 'off'} mcp=${config.protocols.mcp.enabled ? 'on' : 'off'} a2a=${config.protocols.a2a.enabled ? 'on' : 'off'} acp=${config.protocols.acp.enabled ? 'on' : 'off'}`,\n );\n const onOff = (enabled: boolean | undefined): string => (enabled === true ? 'on' : 'off');\n io.stdout(\n ` payments: x402=${onOff(config.payments.x402?.enabled)} mpp=${onOff(config.payments.mpp?.enabled)}`,\n );\n io.stdout(` authorization: ap2=${onOff(config.authorization?.ap2.enabled)}`);\n return 0;\n } catch (err) {\n io.stderr(formatConfigError(err, manifestFound));\n return 1;\n }\n}\n","import type { Io } from '../lib/io';\nimport { readVersionReport, type VersionReport } from '../lib/versions';\n\nexport interface VersionDeps {\n readonly readVersionReport?: () => VersionReport;\n}\n\n/** `agent-commerce version`: the CLI version and the pinned protocol/SDK versions */\nexport function runVersion(io: Io, deps: VersionDeps = {}): number {\n const report = (deps.readVersionReport ?? readVersionReport)();\n io.stdout(`agent-commerce v${report.cliVersion}`);\n if (report.pinned.length > 0) {\n io.stdout('');\n io.stdout('Pinned protocol / SDK versions:');\n const width = Math.max(...report.pinned.map((pin) => pin.name.length));\n for (const pin of report.pinned) {\n io.stdout(` ${pin.name.padEnd(width)} ${pin.version.padEnd(12)} (via ${pin.via})`);\n }\n }\n return 0;\n}\n","/**\n * Injectable stdout/stderr, so command logic is testable without capturing\n * the real process streams\n */\nexport interface Io {\n stdout(line: string): void;\n stderr(line: string): void;\n}\n\nexport const processIo: Io = {\n stdout: (line) => {\n process.stdout.write(`${line}\\n`);\n },\n stderr: (line) => {\n process.stderr.write(`${line}\\n`);\n },\n};\n","#!/usr/bin/env node\nimport { CommanderError } from 'commander';\nimport { buildProgram } from './program';\n\n/**\n * `agent-commerce version | grep -q x402` closes the pipe on grep's first\n * match while the CLI is still writing. Node reports that as an unhandled\n * `EPIPE` error and aborts with a stack trace, so a command that did what was\n * asked would read as a crash. Exit quietly on `EPIPE`; any other stream error\n * still throws.\n */\nfor (const stream of [process.stdout, process.stderr]) {\n stream.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EPIPE') process.exit(0);\n throw err;\n });\n}\n\nasync function main(): Promise<void> {\n const program = buildProgram();\n try {\n await program.parseAsync(process.argv);\n } catch (err) {\n if (err instanceof CommanderError) {\n process.exitCode = err.exitCode;\n return;\n }\n throw err;\n }\n}\n\nvoid main();\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/config/filename.ts","../../src/core/domain/common.ts","../../src/core/domain/event.ts","../../src/core/domain/resource.ts","../../src/core/errors/codes.ts","../../src/core/errors/commerce-error.ts","../../src/core/errors/index.ts","../../src/core/is-record.ts","../../src/core/domain/wire.ts","../../src/core/interfaces/logger.ts","../../src/core/interfaces/protocol-adapter.ts","../../src/core/interfaces/runtime.ts","../../src/core/public-types.ts","../../src/core/index.ts","../../src/authorization/ap2/constants.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/core/execution/index.ts","../../src/payments/mpp/constants.ts","../../src/payments/x402/networks.ts","../../src/protocols/acp/constants.ts","../../src/config/env.ts","../../src/payments/x402/local-chain/accounts.ts","../../src/payments/x402/dev-key-guard.ts","../../src/payments/x402/guardrails.ts","../../src/protocols/mcp/constants.ts","../../src/config/schema.ts","../../src/config/load.ts","../../src/config/index.ts","../../src/cli/program.ts","../../src/cli/commands/demo.ts","../../src/cli/commands/doctor.ts","../../src/authorization/ap2/descriptor.ts","../../src/protocols/a2a/constants.ts","../../src/protocols/a2a/descriptor.ts","../../src/protocols/acp/descriptor.ts","../../src/storage/receipts/store.ts","../../src/version.ts","../../src/storage/sqlite.ts","../../src/storage/receipts/redact.ts","../../src/storage/receipts/rows.ts","../../src/storage/receipts/schema.ts","../../src/cli/lib/config-client.ts","../../src/cli/lib/http.ts","../../src/cli/lib/init-config.ts","../../src/payments/x402/local-chain/manifest.ts","../../src/cli/lib/manifest-env.ts","../../src/cli/lib/mask.ts","../../package.json","../../src/cli/lib/versions.ts","../../src/cli/commands/import-openapi.ts","../../src/openapi/discover.ts","../../src/openapi/refs.ts","../../src/openapi/draft.ts","../../src/openapi/request.ts","../../src/openapi/schema.ts","../../src/openapi/load.ts","../../src/cli/commands/init.ts","../../src/cli/commands/validate.ts","../../src/cli/commands/version.ts","../../src/cli/lib/io.ts","../../src/cli/index.ts"],"names":["init_constants","path","text","fs","parseYaml","fsConstants","accessSync","z","existsSync","sameAddress","dirname","loadConfig","typeList","open","isDeepStrictEqual","required","invalid","extname","resolve","writeFile","mkdirSync"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAS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AACH;AAEA,eAAe,IAAA,GAAsB;AACnC,EAAA,MAAM,UAAU,YAAA,EAAa;AAC7B,EAAA,IAAI;AACF,IAAA,MAAM,OAAA,CAAQ,UAAA,CAAW,OAAA,CAAQ,IAAI,CAAA;AAAA,EACvC,SAAS,GAAA,EAAK;AACZ,IAAA,IAAI,eAAe,cAAA,EAAgB;AACjC,MAAA,OAAA,CAAQ,WAAW,GAAA,CAAI,QAAA;AACvB,MAAA;AAAA,IACF;AACA,IAAA,MAAM,GAAA;AAAA,EACR;AACF;AAEA,KAAK,IAAA,EAAK","file":"index.js","sourcesContent":["/**\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","// Shared primitive aliases for the canonical domain model. FROZEN CONTRACT\n\n/**\n * A JSON Schema document (in practice a draft 2020-12 subset). Deliberately\n * loose: adapters translate it to their own schema representation. Never treat\n * it as trusted input without validation.\n */\nexport type JsonSchema = Record<string, unknown>;\n\n/** Protocol surfaces a resource can be exposed through */\nexport type ProtocolName = 'http' | 'mcp' | 'a2a' | 'acp';\n\n// A Record over the union fails to compile when a name is missing or extra\nconst PROTOCOL_NAME_KEYS: Record<ProtocolName, true> = {\n http: true,\n mcp: true,\n a2a: true,\n acp: true,\n};\n\n/**\n * The same names as a value, for code that checks one at runtime: config\n * validation and the OpenAPI importer's `--expose`\n */\nexport const PROTOCOL_NAMES: readonly ProtocolName[] = Object.keys(\n PROTOCOL_NAME_KEYS,\n) as ProtocolName[];\n\n/**\n * Payment rails a resource can accept.\n *\n * A resource's list is an ordered candidate list, not a buyer-selected menu.\n * The pipeline uses the first method with an enabled provider, and a\n * rejection ends the request instead of trying another rail. Config requires at\n * least one named rail to be enabled and permits others that are not.\n */\nexport type PaymentMethodName = 'x402' | 'mpp';\n\n// Checked for completeness the same way as PROTOCOL_NAME_KEYS\nconst PAYMENT_METHOD_NAME_KEYS: Record<PaymentMethodName, true> = { x402: true, mpp: true };\n\n/** The same names as a value, for config validation */\nexport const PAYMENT_METHOD_NAMES: readonly PaymentMethodName[] = Object.keys(\n PAYMENT_METHOD_NAME_KEYS,\n) as PaymentMethodName[];\n\n/**\n * Authorization methods a resource can require. Neither a transport nor a\n * payment rail: it proves the purchase was approved, and sits beside the\n * payment rather than replacing it.\n */\nexport type AuthorizationMethodName = 'ap2';\n\n/** ISO-8601 timestamp string, always UTC with millisecond precision */\nexport type IsoTimestamp = string;\n\n/**\n * A decimal amount as a string in the currency's display unit (for example\n * \"0.01\" USDC), never a float and never base units. Payment providers convert\n * it to on-chain base units.\n */\nexport type DecimalAmount = string;\n\n/** Health of an individual adapter or subsystem */\nexport interface AdapterHealth {\n readonly status: 'pass' | 'warn' | 'fail';\n readonly detail?: string;\n readonly checkedAt: IsoTimestamp;\n readonly durationMs?: number;\n}\n\n/** Describes an adapter's supported surface for diagnostics */\nexport interface AdapterDescriptor {\n readonly name: string;\n readonly kind: 'protocol' | 'payment' | 'storage' | 'authorization';\n /** Version of this adapter implementation, independent of the spec */\n readonly implementationVersion: string;\n /** Exact pinned specification revision this adapter targets */\n readonly supportedSpec: string;\n readonly capabilities: readonly string[];\n readonly status: 'stable' | 'experimental' | 'planned';\n /** Capabilities explicitly not implemented, printed by `doctor` */\n readonly unsupported?: readonly string[];\n}\n","/**\n * Canonical commerce events. FROZEN CONTRACT. Every event in one flow shares\n * one `requestId`, which correlates logs, payment attempts, backend calls and\n * receipts.\n */\nimport type { IsoTimestamp } from './common';\n\nexport const COMMERCE_EVENT_TYPES = [\n 'resource.discovered',\n 'resource.requested',\n 'payment.required',\n 'payment.rejected',\n 'payment.verified',\n 'payment.settled',\n // The same two types for every authorization method, so an audit-trail\n // reader never has to know what AP2 is\n 'authorization.verified',\n 'authorization.rejected',\n 'backend.called',\n 'backend.failed',\n 'resource.delivered',\n] as const;\n\nexport type CommerceEventType = (typeof COMMERCE_EVENT_TYPES)[number];\n\nexport interface CommerceEvent {\n readonly id: string;\n readonly type: CommerceEventType;\n readonly requestId: string;\n readonly resourceId?: string;\n readonly at: IsoTimestamp;\n /** Protocol adapter that originated the request, e.g. 'mcp' or 'http' */\n readonly adapter?: string;\n readonly paymentProvider?: string;\n readonly durationMs?: number;\n readonly status?: 'ok' | 'error';\n /** Non-secret, structured detail. Must never contain keys, headers or proofs */\n readonly data?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Sink for canonical events. `emit` must not throw: a sink failure must never\n * fail an otherwise successful commerce flow.\n */\nexport interface EventSink {\n emit(event: CommerceEvent): Promise<void>;\n}\n","// Canonical resource model. FROZEN CONTRACT\nimport type {\n AuthorizationMethodName,\n DecimalAmount,\n JsonSchema,\n PaymentMethodName,\n ProtocolName,\n} from './common';\n\n/** HTTP methods a backend handler may use */\nexport type BackendMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * How the gateway calls the merchant's existing backend.\n *\n * Backend URLs come from operator configuration only, never from users or\n * agents (docs/security.md, SSRF). Secret header values belong in `${ENV_VAR}`\n * placeholders resolved by the config loader, not in plaintext configuration.\n */\nexport interface BackendHandler {\n readonly type: 'http';\n readonly method: BackendMethod;\n readonly url: string;\n readonly headers?: Readonly<Record<string, string>>;\n /** Hard upper bound on the backend call. Defaults to `DEFAULT_BACKEND_TIMEOUT_MS` */\n readonly timeoutMs?: number;\n /**\n * Names the top-level input properties carrying each part of the request.\n *\n * When absent, `{param}` values come from top-level input and everything left\n * over becomes the query string (GET/DELETE) or the whole JSON body\n * (POST/PUT/PATCH). That cannot express an operation with path, query and\n * body at once, such as `POST /users/{userId}/orders?notify=true`.\n *\n * When present, each group comes from its named property, and top-level input\n * that no binding names is not forwarded.\n */\n readonly inputBindings?: {\n readonly path?: string;\n readonly query?: string;\n readonly body?: string;\n };\n}\n\n/** Default backend timeout when a resource does not specify one */\nexport const DEFAULT_BACKEND_TIMEOUT_MS = 10_000;\n\n/**\n * Canonical pricing. `dynamic` exists in the type for forward compatibility;\n * config validation rejects it and the pipeline refuses it as defense in depth.\n */\nexport type Pricing =\n | { readonly type: 'free' }\n | {\n readonly type: 'fixed';\n readonly amount: DecimalAmount;\n readonly currency: string;\n }\n | {\n readonly type: 'dynamic';\n readonly resolver: string;\n };\n\n/**\n * A merchant capability exposed to agents. Protocol adapters map it outward and\n * never define their own parallel notion of a resource.\n */\nexport interface CommerceResource {\n readonly id: string;\n readonly name: string;\n readonly description?: string;\n readonly inputSchema?: JsonSchema;\n readonly outputSchema?: JsonSchema;\n readonly handler: BackendHandler;\n readonly pricing: Pricing;\n readonly exposedVia: readonly ProtocolName[];\n readonly paymentMethods: readonly PaymentMethodName[];\n /**\n * Authorization the buyer must present in addition to payment. Opt-in per\n * resource. It sits beside `paymentMethods`, not inside it, because an\n * authorization method is not a payment rail and must never be selectable as\n * one.\n */\n readonly authorization?: {\n readonly required: readonly AuthorizationMethodName[];\n };\n}\n\n/** Read-only view of every configured resource */\nexport interface ResourceRegistry {\n get(id: string): CommerceResource | undefined;\n list(): readonly CommerceResource[];\n /** Resources exposed through a given protocol surface */\n listExposedVia(protocol: ProtocolName): readonly CommerceResource[];\n has(id: string): boolean;\n}\n","/**\n * Typed domain error codes. FROZEN CONTRACT. Protocol adapters map them into\n * their own response format. Never throw a bare string or untyped Error across\n * an area boundary.\n */\nexport const COMMERCE_ERROR_CODES = [\n 'CONFIG_INVALID',\n 'RESOURCE_NOT_FOUND',\n 'INPUT_INVALID',\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 'BACKEND_TIMEOUT',\n 'BACKEND_ERROR',\n 'PROTOCOL_UNSUPPORTED',\n 'GATEWAY_BUSY',\n 'STORAGE_ERROR',\n 'INTERNAL_ERROR',\n] as const;\n\nexport type CommerceErrorCode = (typeof COMMERCE_ERROR_CODES)[number];\n\n/**\n * Canonical HTTP status for each error code. Every payment failure maps to a\n * 4xx or 5xx status, never to a delivery.\n */\nexport const COMMERCE_ERROR_HTTP_STATUS: Readonly<Record<CommerceErrorCode, number>> = {\n CONFIG_INVALID: 500,\n RESOURCE_NOT_FOUND: 404,\n INPUT_INVALID: 400,\n PAYMENT_REQUIRED: 402,\n PAYMENT_INVALID: 402,\n PAYMENT_REPLAYED: 409,\n PAYMENT_PROVIDER_UNAVAILABLE: 503,\n PAYMENT_SETTLEMENT_FAILED: 502,\n // 403, not 402: a 402 tells a client to pay and retry, which cannot fix a\n // missing or rejected mandate, and a client that auto-pays on 402 would be\n // charged for a request that was never going to be delivered\n AUTHORIZATION_REQUIRED: 403,\n AUTHORIZATION_INVALID: 403,\n AUTHORIZATION_REPLAYED: 409,\n AUTHORIZATION_PROVIDER_UNAVAILABLE: 503,\n BACKEND_TIMEOUT: 504,\n BACKEND_ERROR: 502,\n PROTOCOL_UNSUPPORTED: 501,\n GATEWAY_BUSY: 503,\n STORAGE_ERROR: 500,\n INTERNAL_ERROR: 500,\n};\n\n/** Codes for which a client may reasonably retry the same request */\nexport const RETRYABLE_ERROR_CODES: ReadonlySet<CommerceErrorCode> = new Set([\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n // The verifier or replay store was unreachable, so the mandate got no\n // verdict. The same proof can verify once the outage clears.\n 'AUTHORIZATION_PROVIDER_UNAVAILABLE',\n 'BACKEND_TIMEOUT',\n // Load shedding is transient: the caller should back off and try again.\n // Clients act on this flag, and leaving it out would make a momentary\n // throttle look like a permanent failure.\n 'GATEWAY_BUSY',\n]);\n","// The single error type crossing area boundaries. FROZEN CONTRACT\nimport { COMMERCE_ERROR_HTTP_STATUS, type CommerceErrorCode, RETRYABLE_ERROR_CODES } from './codes';\n\nexport interface CommerceErrorOptions {\n /** Structured, non-secret detail safe to return to a client */\n readonly details?: Readonly<Record<string, unknown>>;\n readonly cause?: unknown;\n readonly requestId?: string;\n readonly resourceId?: string;\n /** Override the default HTTP status for this code */\n readonly httpStatus?: number;\n}\n\n/** Serializable wire form of a CommerceError */\nexport interface CommerceErrorInfo {\n readonly code: CommerceErrorCode;\n readonly message: string;\n readonly httpStatus: number;\n readonly retryable: boolean;\n readonly requestId?: string;\n readonly resourceId?: string;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\nexport class CommerceError extends Error {\n readonly code: CommerceErrorCode;\n readonly httpStatus: number;\n readonly retryable: boolean;\n readonly details?: Readonly<Record<string, unknown>>;\n readonly requestId?: string;\n readonly resourceId?: string;\n\n constructor(code: CommerceErrorCode, message: string, options: CommerceErrorOptions = {}) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = 'CommerceError';\n this.code = code;\n this.httpStatus = options.httpStatus ?? COMMERCE_ERROR_HTTP_STATUS[code];\n this.retryable = RETRYABLE_ERROR_CODES.has(code);\n if (options.details !== undefined) this.details = options.details;\n if (options.requestId !== undefined) this.requestId = options.requestId;\n if (options.resourceId !== undefined) this.resourceId = options.resourceId;\n Error.captureStackTrace?.(this, CommerceError);\n }\n\n /** Non-secret, client-safe representation. `cause` is never included */\n toInfo(): CommerceErrorInfo {\n return {\n code: this.code,\n message: this.message,\n httpStatus: this.httpStatus,\n retryable: this.retryable,\n ...(this.requestId !== undefined ? { requestId: this.requestId } : {}),\n ...(this.resourceId !== undefined ? { resourceId: this.resourceId } : {}),\n ...(this.details !== undefined ? { details: this.details } : {}),\n };\n }\n}\n\nexport function isCommerceError(value: unknown): value is CommerceError {\n return value instanceof CommerceError;\n}\n\n/**\n * Passes an existing CommerceError through. Other thrown values become a\n * CommerceError with a caller-chosen message, for example\n * `toCommerceError(err, 'BACKEND_ERROR', 'Backend call failed')`.\n *\n * Arbitrary Error messages may contain internal URLs, hostnames or file paths.\n * The original value remains on `cause` for internal logging; `toInfo()` and\n * `toErrorEnvelope()` do not serialize it.\n */\nexport function toCommerceError(\n value: unknown,\n fallbackCode: CommerceErrorCode = 'INTERNAL_ERROR',\n fallbackMessage = 'Unexpected internal error',\n): CommerceError {\n if (isCommerceError(value)) return value;\n return new CommerceError(fallbackCode, fallbackMessage, { cause: value });\n}\n\n/** A thrown value reduced to its message and name, for a log line */\nexport function 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/**\n * `Name: message` for a log line, with every URL cut to its scheme and host,\n * because a backend or RPC URL can carry a credential in its userinfo, path or\n * query\n */\nexport function redactedErrorText(value: unknown): string {\n const text = value instanceof Error ? `${value.name}: ${value.message}` : String(value);\n return text.replace(/\\b[a-z][a-z\\d+.-]*:\\/\\/[^\\s\"'<>]+/gi, (match) => {\n try {\n const url = new URL(match);\n return `${url.protocol}//${url.host}`;\n } catch {\n return '[unparseable URL]';\n }\n });\n}\n\n// Deepest `cause` level toLogInfo() follows, which also ends a cyclic chain\nconst MAX_LOGGED_CAUSES = 5;\n\n/**\n * An error for an operator log line: the `toInfo()` fields plus the `cause`\n * chain that `toInfo()` leaves out, each level as `redactedErrorText()` gives it\n */\nexport function toLogInfo(\n value: unknown,\n): CommerceErrorInfo & { readonly cause?: readonly string[] } {\n const error = toCommerceError(value);\n const cause: string[] = [];\n let current = error.cause;\n while (current !== undefined && cause.length < MAX_LOGGED_CAUSES) {\n cause.push(redactedErrorText(current));\n current = current instanceof Error ? current.cause : undefined;\n }\n return cause.length > 0 ? { ...error.toInfo(), cause } : error.toInfo();\n}\n","export * from './codes';\nexport * from './commerce-error';\n","/** A non-null, non-array object. The prototype is not checked */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","/**\n * Gateway-defined wire envelopes and carriers. FROZEN CONTRACT.\n *\n * The HTTP routes and the MCP and A2A adapters build their \"payment required\"\n * and \"error\" bodies with these helpers, so those surfaces send the same\n * shapes. The ACP adapter maps errors to ACP's own error format instead.\n */\n\nimport { CommerceError, type CommerceErrorCode } from '../errors';\nimport { isRecord } from '../is-record';\nimport type { AuthorizationRequirement, AuthorizationSubmission } from './authorization';\nimport type { DecimalAmount, IsoTimestamp, PaymentMethodName } from './common';\nimport type { PaymentSubmission } from './payment';\nimport type { DeliveredOutcome, PaymentRequiredOutcome } from './request';\nimport type { CommerceResource } from './resource';\n\n/**\n * Reserved input property carrying a payment proof on protocols with no header\n * channel (MCP tool calls, A2A message data). HTTP uses a header instead.\n */\nexport const PAYMENT_INPUT_FIELD = '_payment';\n\n/**\n * HTTP request header carrying an x402 payment proof. MPP proofs use\n * `Authorization: Payment ...` instead.\n *\n * The x402 v2 header names, lowercased as Node presents incoming headers. v1's\n * `X-PAYMENT` / `X-PAYMENT-RESPONSE` pair is not accepted: honoring both\n * versions would mean two verification paths for the same money.\n */\nexport const PAYMENT_HEADER = 'payment-signature';\n\n/** HTTP response header carrying the settlement result */\nexport const PAYMENT_RESPONSE_HEADER = 'payment-response';\n\n/**\n * Reserved input property carrying an authorization proof, the counterpart of\n * {@link PAYMENT_INPUT_FIELD}.\n *\n * `_payment` is a bare string whose method is taken from the resource's first\n * payment method. This field is a `{ method, payload }` object, because the\n * method of a security control should be stated, not inferred.\n */\nexport const AUTHORIZATION_INPUT_FIELD = '_authorization';\n\n/**\n * Every input property name the gateway claims for itself. The config loader\n * rejects a resource declaring one, protocol adapters lift them out of client\n * input, and the pipeline strips them again as defense in depth.\n */\nexport const RESERVED_INPUT_FIELDS: readonly string[] = [\n PAYMENT_INPUT_FIELD,\n AUTHORIZATION_INPUT_FIELD,\n];\n\n/**\n * HTTP request header carrying the authorization proof: base64url-encoded JSON\n * of the same `{ method, payload }` object the reserved input field carries.\n *\n * An Agent Commerce carrier, not a header from any authorization\n * specification. It is namespaced rather than reusing `Authorization`, which\n * already carries other credentials, including MPP payment proofs.\n */\nexport const AUTHORIZATION_HEADER = 'agent-authorization';\n\n/**\n * Hard cap on the encoded `Agent-Authorization` header.\n *\n * Node's default limit is 16 KiB across all request headers, and a request over\n * it is refused before the gateway sees it. Capping well below that gives an\n * oversized proof a deterministic `AUTHORIZATION_INVALID` naming the limit.\n */\nexport const MAX_AUTHORIZATION_HEADER_BYTES = 8192;\n\n/**\n * HTTP response header carrying the base64 x402 challenge on a 402.\n *\n * The body still carries the richer {@link PaymentRequiredEnvelope}, the only\n * channel MCP has, but an x402 v2 client reads the challenge from this header\n * and ignores the body, so both are sent.\n */\nexport const PAYMENT_REQUIRED_HEADER = 'payment-required';\n\n/**\n * Key under which a protocol adapter attaches a {@link DeliverySummary} to its\n * result metadata: MCP's `CallToolResult._meta` and the A2A task artifact's\n * metadata.\n *\n * Part of the frozen contract because producer and consumer must agree on it;\n * both import this constant. Follows MCP's `<namespace>/<name>` convention for\n * `_meta` keys.\n */\nexport const DELIVERY_SUMMARY_META_KEY = 'agent-commerce/delivery';\n\nexport interface PaymentRequiredEnvelope {\n readonly status: 'payment-required';\n readonly code: 'PAYMENT_REQUIRED';\n readonly requestId: string;\n readonly resourceId: string;\n readonly message: string;\n readonly payment: {\n readonly provider: PaymentMethodName;\n readonly version: string;\n readonly amount: DecimalAmount;\n readonly currency: string;\n readonly destination: string;\n readonly network?: string;\n readonly asset?: string;\n readonly expiresAt?: IsoTimestamp;\n /** Provider-native requirement objects, passed through verbatim */\n readonly accepts: readonly Readonly<Record<string, unknown>>[];\n /**\n * The provider's own challenge document, verbatim (see\n * {@link PaymentChallenge.envelope}). Present for providers that have one;\n * a buyer's protocol client can hand it straight to its SDK.\n */\n readonly envelope?: Readonly<Record<string, unknown>>;\n };\n /**\n * Present only when the resource also requires an authorization proof, so a\n * client learns before it spends anything that paying alone will not get the\n * resource delivered. A client that ignores the field sees the plain\n * envelope. The proof comes from the merchant's own approval flow, outside\n * the gateway.\n */\n readonly authorization?: {\n readonly required: readonly AuthorizationRequirement[];\n };\n}\n\nexport interface ErrorEnvelope {\n readonly status: 'error';\n readonly code: CommerceErrorCode;\n readonly message: string;\n readonly retryable: boolean;\n readonly requestId?: string;\n readonly resourceId?: string;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * What a buyer learns about their own completed purchase: the request, whether\n * it settled, and the settlement reference they can check on-chain. The\n * merchant's ledger is not theirs to read, which is why `/api/receipts` is an\n * operator route behind `server.adminToken`.\n */\nexport interface DeliverySummary {\n readonly requestId: string;\n readonly resourceId: string;\n readonly receiptId: string;\n readonly deliveredAt: IsoTimestamp;\n readonly payment?: {\n readonly status: 'verified' | 'settled' | 'rejected';\n readonly amount: DecimalAmount;\n readonly currency: string;\n /** Settlement reference, e.g. an on-chain transaction hash */\n readonly externalReference?: string;\n readonly network?: string;\n };\n}\n\n/** Build the payer-facing summary of a delivered outcome */\nexport function toDeliverySummary(outcome: DeliveredOutcome): DeliverySummary {\n const p = outcome.payment;\n return {\n requestId: outcome.requestId,\n resourceId: outcome.resourceId,\n receiptId: outcome.receipt.id,\n deliveredAt: outcome.receipt.deliveredAt,\n ...(p !== undefined\n ? {\n payment: {\n status: p.status,\n amount: p.amount,\n currency: p.currency,\n ...(p.externalReference !== undefined\n ? { externalReference: p.externalReference }\n : {}),\n ...(p.network !== undefined ? { network: p.network } : {}),\n },\n }\n : {}),\n };\n}\n\nexport function toPaymentRequiredEnvelope(\n outcome: PaymentRequiredOutcome,\n): PaymentRequiredEnvelope {\n const r = outcome.requirement;\n return {\n status: 'payment-required',\n code: 'PAYMENT_REQUIRED',\n requestId: outcome.requestId,\n resourceId: outcome.resourceId,\n message: `Payment of ${r.amount} ${r.currency} is required for resource \"${outcome.resourceId}\". Retry with a ${r.provider} payment proof.`,\n payment: {\n provider: r.provider,\n version: r.challenge.version,\n amount: r.amount,\n currency: r.currency,\n destination: r.destination,\n ...(r.network !== undefined ? { network: r.network } : {}),\n ...(r.asset !== undefined ? { asset: r.asset } : {}),\n ...(r.expiresAt !== undefined ? { expiresAt: r.expiresAt } : {}),\n accepts: r.challenge.accepts,\n ...(r.challenge.envelope !== undefined ? { envelope: r.challenge.envelope } : {}),\n },\n ...(outcome.authorization !== undefined && outcome.authorization.length > 0\n ? { authorization: { required: outcome.authorization } }\n : {}),\n };\n}\n\nexport function toErrorEnvelope(error: CommerceError): ErrorEnvelope {\n const info = error.toInfo();\n return {\n status: 'error',\n code: info.code,\n message: info.message,\n retryable: info.retryable,\n ...(info.requestId !== undefined ? { requestId: info.requestId } : {}),\n ...(info.resourceId !== undefined ? { resourceId: info.resourceId } : {}),\n ...(info.details !== undefined ? { details: info.details } : {}),\n };\n}\n\nexport function isPaymentRequiredEnvelope(value: unknown): value is PaymentRequiredEnvelope {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as PaymentRequiredEnvelope).status === 'payment-required' &&\n typeof (value as PaymentRequiredEnvelope).payment === 'object'\n );\n}\n\n/**\n * Parses the `{ method, payload }` authorization object, whichever carrier\n * brought it. Absent returns `undefined`; malformed throws\n * `AUTHORIZATION_INVALID`.\n *\n * An unusable `_payment` is dropped, which leaves the buyer a 402 to act on. A\n * dropped authorization would instead come back as \"not authorized\", with no\n * way to tell a rejected mandate from a typo in the object around it.\n */\nexport function parseAuthorizationSubmission(\n value: unknown,\n requestId?: string,\n): AuthorizationSubmission | undefined {\n if (value === undefined || value === null) return undefined;\n\n const fail = (detail: string): never => {\n throw new CommerceError('AUTHORIZATION_INVALID', `Malformed authorization: ${detail}`, {\n ...(requestId !== undefined ? { requestId } : {}),\n });\n };\n\n if (!isRecord(value)) {\n return fail(`expected an object with \"method\" and \"payload\", got ${typeof value}`);\n }\n const method = value['method'];\n const payload = value['payload'];\n\n // Compared against the literal rather than a registry: a second method needs\n // a second verifier, a deliberate addition rather than a string that starts\n // working because a client sent it\n if (method !== 'ap2') {\n fail(`unsupported method ${typeof method === 'string' ? `\"${method}\"` : typeof method}`);\n }\n if (typeof payload !== 'string' || payload.length === 0) {\n fail('\"payload\" must be a non-empty string');\n }\n\n return { method: 'ap2', payload: payload as string };\n}\n\n/**\n * Decodes the base64url JSON `Agent-Authorization` header. The size check runs\n * on the encoded value, so an oversized header costs a length comparison rather\n * than a decode and a JSON parse.\n */\nexport function parseAuthorizationHeader(\n raw: string | readonly string[] | undefined,\n requestId?: string,\n): AuthorizationSubmission | undefined {\n const value = Array.isArray(raw) ? raw[0] : (raw as string | undefined);\n if (value === undefined || value.length === 0) return undefined;\n\n const fail = (detail: string): never => {\n throw new CommerceError('AUTHORIZATION_INVALID', `Malformed authorization: ${detail}`, {\n ...(requestId !== undefined ? { requestId } : {}),\n });\n };\n\n if (Buffer.byteLength(value, 'utf8') > MAX_AUTHORIZATION_HEADER_BYTES) {\n fail(`header exceeds the ${MAX_AUTHORIZATION_HEADER_BYTES}-byte limit`);\n }\n\n let decoded: unknown;\n try {\n decoded = JSON.parse(Buffer.from(value, 'base64url').toString('utf8'));\n } catch {\n // Nothing from the exception is repeated back: a JSON parse error quotes\n // the input it choked on, which here is whatever the caller sent\n fail('header is not base64url-encoded JSON');\n }\n return parseAuthorizationSubmission(decoded, requestId);\n}\n\n/**\n * Splits raw client input into resource input plus the reserved fields, for\n * protocols that carry them in the input object (MCP tool arguments, A2A\n * message data). HTTP carries both in headers.\n *\n * A payment proof is labeled with the resource's first payment method.\n * `createGateway` puts provider-backed methods first so the label matches the\n * pipeline's selection; a custom registry must keep that order. A resource with\n * no payment method gets no payment proof, so the request reaches the pipeline\n * unpaid.\n */\nexport function extractReservedInputFields(\n rawInput: Record<string, unknown>,\n resource: CommerceResource | undefined,\n requestId?: string,\n): {\n input: Record<string, unknown>;\n payment?: PaymentSubmission;\n authorization?: AuthorizationSubmission;\n} {\n const {\n [PAYMENT_INPUT_FIELD]: paymentValue,\n [AUTHORIZATION_INPUT_FIELD]: authorizationValue,\n ...input\n } = rawInput;\n\n const method = resource?.paymentMethods[0];\n const payment =\n typeof paymentValue === 'string' && paymentValue.length > 0 && method !== undefined\n ? ({ method, payload: paymentValue } satisfies PaymentSubmission)\n : undefined;\n const authorization = parseAuthorizationSubmission(authorizationValue, requestId);\n\n return {\n input,\n ...(payment !== undefined ? { payment } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n };\n}\n","/**\n * Minimal structural logger. Core does not depend on pino; the gateway injects\n * a pino instance that satisfies this shape.\n *\n * Never log secrets: private keys, seed phrases, Authorization headers or\n * payment authorization payloads.\n */\nexport interface Logger {\n debug(obj: Record<string, unknown>, msg?: string): void;\n info(obj: Record<string, unknown>, msg?: string): void;\n warn(obj: Record<string, unknown>, msg?: string): void;\n error(obj: Record<string, unknown>, msg?: string): void;\n child(bindings: Record<string, unknown>): Logger;\n}\n\n/** A logger that discards everything */\nexport const NOOP_LOGGER: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n child: () => NOOP_LOGGER,\n};\n","/**\n * Protocol adapter boundary. FROZEN CONTRACT.\n *\n * An adapter translates a protocol's wire format into a `CanonicalRequest`,\n * hands it to the execution pipeline and maps the outcome back. It must not\n * call merchant backends, implement payment logic or hold its own copy of the\n * canonical model. A failure while starting or serving one adapter must not\n * stop the others.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { AdapterDescriptor, AdapterHealth, ProtocolName } from '../domain/common';\nimport type { EventSink } from '../domain/event';\nimport type { ExecutionPipeline } from '../domain/request';\nimport type { ResourceRegistry } from '../domain/resource';\nimport type { Logger } from './logger';\nimport type { Clock, IdGenerator } from './runtime';\n\n/** Everything an adapter is given. Nothing else is available to it */\nexport interface ProtocolAdapterContext {\n readonly pipeline: ExecutionPipeline;\n readonly resources: ResourceRegistry;\n readonly events: EventSink;\n readonly logger: Logger;\n readonly clock: Clock;\n readonly ids: IdGenerator;\n /** Externally reachable base URL of the gateway, from config */\n readonly publicBaseUrl: string;\n}\n\nexport interface ProtocolAdapter {\n readonly name: ProtocolName;\n readonly descriptor: AdapterDescriptor;\n\n start(context: ProtocolAdapterContext): Promise<void>;\n health(): Promise<AdapterHealth>;\n stop(): Promise<void>;\n}\n\n/**\n * A protocol adapter served over HTTP. The gateway mounts `handleHttp` at\n * `mountPath` with raw Node request and response objects, so adapters stay\n * independent of the HTTP framework.\n *\n * Guarantee: `req` arrives with its body stream unread. The gateway suppresses\n * every body parser on the mount, so an adapter whose SDK reads the body itself\n * (MCP's Streamable HTTP transport) can do so. The adapter owns reading,\n * size-limiting beyond the gateway's own cap, and parsing.\n *\n * The guarantee can break silently. Fastify prefers its exact-match\n * `application/json` and `text/plain` parsers over a `'*'` wildcard, so a\n * wildcard no-op alone lets the JSON parser drain the body and the adapter\n * reads an empty stream. The MCP conformance suite drives `handleHttp` over a\n * bare `node:http` server and cannot catch it, so any change to adapter mounting\n * needs a test that POSTs a JSON body through the real gateway and asserts the\n * adapter received it intact.\n */\nexport interface HttpProtocolAdapter extends ProtocolAdapter {\n /** Path prefix the gateway mounts this adapter at, e.g. '/mcp' */\n readonly mountPath: string;\n handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void>;\n /**\n * Fixed paths this adapter owns outside its mount, for protocols whose\n * specification pins a discovery URL (A2A's `/.well-known/agent-card.json`).\n * The gateway mounts them with the same guarantees as `mountPath`: unread\n * body, concurrency cap and failure isolation.\n */\n readonly additionalHttpRoutes?: readonly AdapterHttpRoute[];\n}\n\n/**\n * One fixed, method-scoped route owned by an adapter. Unlike `mountPath` it\n * registers no wildcard and matches exactly the path given.\n */\nexport interface AdapterHttpRoute {\n readonly method: 'GET' | 'POST';\n /** Absolute gateway path, e.g. '/.well-known/agent-card.json' */\n readonly path: string;\n handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void>;\n}\n\nexport function isHttpProtocolAdapter(adapter: ProtocolAdapter): adapter is HttpProtocolAdapter {\n return typeof (adapter as HttpProtocolAdapter).handleHttp === 'function';\n}\n","// Time and ids are injected so tests can be deterministic\nimport type { IsoTimestamp } from '../domain/common';\n\nexport interface Clock {\n now(): Date;\n nowIso(): IsoTimestamp;\n /** Milliseconds since an arbitrary origin; use for durations only */\n monotonicMs(): number;\n}\n\nexport interface IdGenerator {\n /** Opaque, collision-resistant identifier */\n next(prefix?: string): string;\n}\n\nexport const systemClock: Clock = {\n now: () => new Date(),\n nowIso: () => new Date().toISOString(),\n monotonicMs: () => performance.now(),\n};\n","/**\n * FROZEN PUBLIC CONTRACT since v0.1.0-alpha (freeze record:\n * docs/contracts.md). The canonical domain model, errors and injection\n * interfaces are re-exported here. Changes to this public API require contract\n * review; `npm run check:contract` compares the resolved types with a committed\n * baseline.\n *\n * Do not redeclare these shapes locally. If something is missing, add it here\n * rather than creating a parallel type.\n */\n\nexport type {\n AuthorizationFinalizeContext,\n AuthorizationProvider,\n AuthorizationRecord,\n AuthorizationRequirement,\n AuthorizationSubmission,\n AuthorizationVerification,\n AuthorizationVerificationContext,\n} from './domain/authorization';\n// --- canonical domain ------------------------------------------------------\nexport type {\n AdapterDescriptor,\n AdapterHealth,\n AuthorizationMethodName,\n DecimalAmount,\n IsoTimestamp,\n JsonSchema,\n PaymentMethodName,\n ProtocolName,\n} from './domain/common';\nexport { PAYMENT_METHOD_NAMES, PROTOCOL_NAMES } from './domain/common';\nexport type { CommerceEvent, CommerceEventType, EventSink } from './domain/event';\nexport { COMMERCE_EVENT_TYPES } from './domain/event';\n\nexport type {\n PaymentChallenge,\n PaymentContext,\n PaymentProvider,\n PaymentRequirement,\n PaymentResult,\n PaymentSettlementContext,\n PaymentSubmission,\n PaymentVerificationContext,\n} from './domain/payment';\n\nexport type { CommerceReceipt, PaymentAttempt } from './domain/receipt';\nexport type {\n CanonicalRequest,\n DeliveredOutcome,\n ExecutionOutcome,\n ExecutionPipeline,\n PaymentRequiredOutcome,\n} from './domain/request';\nexport type {\n BackendHandler,\n BackendMethod,\n CommerceResource,\n Pricing,\n ResourceRegistry,\n} from './domain/resource';\nexport { DEFAULT_BACKEND_TIMEOUT_MS } from './domain/resource';\nexport type {\n DeliverySummary,\n ErrorEnvelope,\n PaymentRequiredEnvelope,\n} from './domain/wire';\nexport {\n AUTHORIZATION_HEADER,\n AUTHORIZATION_INPUT_FIELD,\n DELIVERY_SUMMARY_META_KEY,\n extractReservedInputFields,\n isPaymentRequiredEnvelope,\n MAX_AUTHORIZATION_HEADER_BYTES,\n PAYMENT_HEADER,\n PAYMENT_INPUT_FIELD,\n PAYMENT_REQUIRED_HEADER,\n PAYMENT_RESPONSE_HEADER,\n parseAuthorizationHeader,\n parseAuthorizationSubmission,\n RESERVED_INPUT_FIELDS,\n toDeliverySummary,\n toErrorEnvelope,\n toPaymentRequiredEnvelope,\n} from './domain/wire';\n\n// --- errors ----------------------------------------------------------------\nexport type { CommerceErrorCode, CommerceErrorInfo, CommerceErrorOptions } from './errors';\nexport {\n COMMERCE_ERROR_CODES,\n COMMERCE_ERROR_HTTP_STATUS,\n CommerceError,\n isCommerceError,\n RETRYABLE_ERROR_CODES,\n toCommerceError,\n} from './errors';\n\n// --- injection boundaries --------------------------------------------------\nexport type { BackendExecutor, BackendRequest, BackendResponse } from './interfaces/backend';\nexport type { Logger } from './interfaces/logger';\nexport { NOOP_LOGGER } from './interfaces/logger';\nexport type {\n AdapterHttpRoute,\n HttpProtocolAdapter,\n ProtocolAdapter,\n ProtocolAdapterContext,\n} from './interfaces/protocol-adapter';\nexport { isHttpProtocolAdapter } from './interfaces/protocol-adapter';\nexport type { Clock, IdGenerator } from './interfaces/runtime';\nexport { systemClock } from './interfaces/runtime';\nexport type {\n ListOptions,\n PaymentAttemptReservation,\n PaymentAttemptUpdate,\n ReceiptStore,\n} from './interfaces/store';\n","/**\n * Canonical commerce domain model, typed errors and injection interfaces. No\n * x402, EVM, MCP or JSON-RPC type belongs in src/core; adapters map protocol\n * shapes at their boundaries.\n */\nexport * from './public-types';\n","/**\n * Pinned AP2 identifiers and key policy.\n *\n * AP2 v0.2.0 (2026-04-28, commit b4587ac) is the tagged release this gateway\n * verifies against; unversioned `main` is never implemented against. Config,\n * the verifier and `doctor` all read these, so a bump lands in one place.\n */\n\nexport const AP2_SPEC_VERSION = '0.2.0';\n\n/**\n * Direct only. Autonomous mode needs open mandates, cnf-bound agent keys and\n * constraint evaluation over `checkout.line_items`, none of which is\n * implemented, so it is refused rather than partly served.\n */\nexport const AP2_MODES = ['direct'] as const;\nexport type Ap2Mode = (typeof AP2_MODES)[number];\n\n/**\n * A single algorithm, so `alg=none` and the HMAC family are excluded by\n * construction rather than by a denylist\n */\nexport const AP2_SIGNING_ALGORITHM = 'ES256';\n\n/** The key type and curve ES256 implies. Any other pair is refused at load */\nexport const AP2_KEY_TYPE = 'EC';\nexport const AP2_JWK_CURVE = 'P-256';\n\n/** Byte length of a P-256 coordinate, before base64url encoding */\nexport const AP2_JWK_COORDINATE_BYTES = 32;\n\n/**\n * JWK members a verification key may carry. An allowlist, so private material\n * (`d`) and URL members (`x5u`, `jku`) are refused without the list naming\n * them. Keys are configured inline and never fetched; see docs/security.md.\n */\nexport const AP2_JWK_MEMBERS = ['kty', 'crv', 'x', 'y', 'kid', 'alg', 'use'] as const;\n\n/**\n * Compared against this literal, never as a prefix. `mandate.checkout.open.1`\n * carries spending constraints nothing here evaluates, so accepting it would\n * tell a buyer their limits were checked when nothing read them.\n */\nexport const AP2_CHECKOUT_MANDATE_VCT = 'mandate.checkout.1';\n\n/**\n * Merchant checkout JWTs declare this gateway-specific profile; AP2 leaves\n * the checkout payload out of scope. The identifier is a namespace that\n * clients do not dereference. Merchants sign it into each checkout JWT, so\n * changing the expected value would reject previously signed JWTs.\n */\nexport const AP2_CHECKOUT_PROFILE = 'agent-commerce/ap2/checkout/v1';\n\n/**\n * The only accepted SD-JWT `_sd_alg` (an absent one means sha-256). Any other\n * value is refused rather than hashed as sha-256, which would check a\n * presentation under an algorithm it never claimed.\n */\nexport const AP2_DIGEST_ALGORITHM = 'sha-256';\n\n/** Seconds of clock skew tolerated on mandate and checkout time claims */\nexport const AP2_DEFAULT_CLOCK_SKEW_SECONDS = 60;\n\n/**\n * Skew as wide as a mandate's validity window would stop `exp` rejecting\n * anything. An operator who needs more than five minutes has a clock to fix.\n */\nexport const AP2_MAX_CLOCK_SKEW_SECONDS = 300;\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 * The pipeline implementation: resource registry, backend executor, store event\n * sink and the pipeline itself. Internal to the package: other `src/` areas and\n * tests import it, but it is outside the frozen `public-types.ts` barrel and no\n * package entry point exports it.\n */\n\nexport type { HttpBackendExecutorOptions } from './backend-http';\nexport {\n extractPathParameterNames,\n findUnparsedBraceToken,\n HttpBackendExecutor,\n validateBackendRequestShape,\n} from './backend-http';\nexport type { CreateExecutionPipelineOptions } from './pipeline';\nexport { createExecutionPipeline } from './pipeline';\nexport { createResourceRegistry } from './registry';\nexport type { CreateStoreEventSinkOptions } from './store-event-sink';\nexport { createStoreEventSink } from './store-event-sink';\nexport type { FieldError, ValidationResult, Validator } from './validation';\nexport { compileJsonSchema, isObjectSchemaNode } from './validation';\n","/**\n * The one MPP profile this rail targets.\n *\n * MPP combines a core HTTP authentication layer, an intent, a method and\n * optional extensions. These constants identify the selected combination and\n * the exact specification revision.\n *\n * Importing this metadata does not load `mppx`.\n */\n\n/** Upstream specification repository the pinned drafts were read from */\nexport const MPP_SPEC_REPOSITORY = 'https://github.com/tempoxyz/mpp-specs';\n\n/**\n * Upstream commit the pinned drafts were read at.\n *\n * A draft's content can change without its `-00` name changing, so the name\n * alone does not identify a document; the commit does.\n */\nexport const MPP_SPEC_COMMIT = '806fdb8b8c92cda5c84b8660558921b6bbeef7e0';\n\n/** The core HTTP authentication draft, the `charge` intent, and its EVM method */\nexport const MPP_SPEC_DRAFTS = {\n core: 'draft-httpauth-payment-00',\n intent: 'draft-payment-intent-charge-00',\n method: 'draft-evm-charge-00',\n} as const;\n\n/**\n * Minimum accepted `challengeSecret.length`. This is a configuration floor,\n * not an entropy check.\n */\nexport const MPP_MIN_CHALLENGE_SECRET_LENGTH = 32;\n\n/** Exact `mppx` release the rail is pinned to */\nexport const MPPX_VERSION = '0.10.1';\n\n/**\n * The pinned profile.\n *\n * `intent`, `method` and `credentialType` copy MPP wire identifiers from\n * `mppx` so this module has no peer import; tests detect drift. `assetSymbol`\n * is the pricing currency an MPP resource must use. EVM charge requests carry a\n * numeric `chainId` and token address instead.\n */\nexport const MPP_PROFILE = {\n intent: 'charge',\n method: 'evm',\n credentialType: 'authorization',\n assetSymbol: 'USDC',\n assetDecimals: 6,\n} as const;\n\n/** Supported CAIP-2 networks; gateway config applies the x402 mainnet guardrails */\nexport const MPP_NETWORKS = ['eip155:84532', 'eip155:8453'] as const;\n\nexport type MppNetwork = (typeof MPP_NETWORKS)[number];\n\n/** Default network ID, shared by Base Sepolia and the local development chain */\nexport const MPP_DEFAULT_NETWORK: MppNetwork = 'eip155:84532';\n\nexport function isMppNetwork(value: string): value is MppNetwork {\n return (MPP_NETWORKS as readonly string[]).includes(value);\n}\n\n/** Compact descriptor value naming the core draft, intent and method */\nexport const MPP_SUPPORTED_SPEC = `mpp/${MPP_SPEC_DRAFTS.core} intent=${MPP_PROFILE.intent} method=${MPP_PROFILE.method}`;\n","/**\n * The networks this gateway settles on, as data: the chain id to sign against,\n * a display name, and whether real money is involved.\n *\n * A registry rather than \"parse any `eip155:*`\": the chain id parses from any\n * such string, but whether it is a mainnet does not, and the guardrails key off\n * that. An unknown id is refused at startup instead of passing as a testnet.\n *\n * The local dev chain runs under Base Sepolia's `eip155:84532`, so nothing may\n * infer \"public network\" from the id alone. `resolveDeploymentMode` derives\n * the mode from the facilitator too, and the provider's health check confirms\n * that a local facilitator's node is Anvil.\n */\nimport { CommerceError } from '../../core';\n\n/** Chain id of the local dev chain, which Base Sepolia uses too */\nexport const LOCAL_CHAIN_ID = 84532;\n\nexport interface NetworkProfile {\n /** CAIP-2 identifier, e.g. `eip155:84532` */\n readonly id: string;\n /** Signed into the buyer's EIP-712 domain */\n readonly chainId: number;\n readonly displayName: string;\n readonly kind: 'testnet' | 'mainnet';\n /**\n * The USDC deployment this network settles in, with the EIP-712 domain the\n * token reports. Enforced on mainnet only, since a testnet may use a mock\n * token.\n *\n * `name` is the signed EIP-712 domain name, not the symbol, and the two\n * deployments differ: `\"USDC\"` on Base Sepolia, `\"USD Coin\"` on Base. The\n * values were read back from the contracts.\n */\n readonly canonicalAsset?: {\n readonly symbol: string;\n readonly address: string;\n readonly name: string;\n readonly version: string;\n };\n}\n\nconst PROFILES: readonly NetworkProfile[] = [\n {\n id: 'eip155:84532',\n chainId: 84532,\n displayName: 'Base Sepolia',\n kind: 'testnet',\n canonicalAsset: {\n symbol: 'USDC',\n address: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',\n name: 'USDC',\n version: '2',\n },\n },\n {\n id: 'eip155:8453',\n chainId: 8453,\n displayName: 'Base',\n kind: 'mainnet',\n canonicalAsset: {\n symbol: 'USDC',\n address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n name: 'USD Coin',\n version: '2',\n },\n },\n];\n\nconst BY_ID = new Map(PROFILES.map((profile) => [profile.id, profile]));\n\nexport const SUPPORTED_NETWORK_IDS: readonly string[] = PROFILES.map((p) => p.id);\n\nexport function findNetworkProfile(id: string): NetworkProfile | undefined {\n return BY_ID.get(id);\n}\n\nexport function requireNetworkProfile(id: string, path: string): NetworkProfile {\n const profile = BY_ID.get(id);\n if (!profile) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `${path}: \"${id}\" is not a supported network. Supported CAIP-2 identifiers: ${SUPPORTED_NETWORK_IDS.join(', ')}`,\n { details: { path, network: id } },\n );\n }\n return profile;\n}\n\n/**\n * What a deployment is, as opposed to the network it names. `local` comes from\n * the facilitator: the in-process facilitator makes a deployment local whatever\n * CAIP-2 id it is configured with, which lets diagnostics show `eip155:84532`\n * without claiming public Base Sepolia.\n */\nexport type DeploymentMode = 'local' | 'testnet' | 'mainnet';\n\nexport function resolveDeploymentMode(\n profile: NetworkProfile,\n facilitatorMode: 'local' | 'remote',\n): DeploymentMode {\n if (facilitatorMode === 'local') return 'local';\n return profile.kind;\n}\n\n// The banner an operator must not miss. Printed for mainnet only\nconst LIVE_MAINNET_BANNER = 'LIVE MAINNET MODE - REAL FUNDS';\n\nexport function describeDeploymentMode(mode: DeploymentMode): string {\n return mode === 'mainnet' ? LIVE_MAINNET_BANNER : mode.toUpperCase();\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 * `${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 * Anvil's well-known development accounts.\n *\n * LOCAL DEVELOPMENT ONLY - DO NOT FUND. The keys come from Foundry's public\n * default mnemonic (\"test test ... junk\"), so value sent to these addresses on\n * a real network can be taken by anyone.\n *\n * Index layout on the local demo chain:\n * 0 - deployer and local facilitator signer (pays gas, broadcasts settlement)\n * 1 - merchant settlement destination (`payTo`)\n * 2 - buyer (signs EIP-3009 authorizations; never held by the gateway)\n */\nexport interface AnvilWellKnownAccount {\n readonly address: `0x${string}`;\n readonly privateKey: `0x${string}`;\n}\n\n/** A fixed-length tuple, so indexing by the layout above is typed */\nexport const ANVIL_WELL_KNOWN_ACCOUNTS: readonly [\n AnvilWellKnownAccount,\n AnvilWellKnownAccount,\n AnvilWellKnownAccount,\n] = [\n {\n address: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266',\n privateKey: '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80',\n },\n {\n address: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8',\n privateKey: '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d',\n },\n {\n address: '0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC',\n privateKey: '0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a',\n },\n];\n\nexport const LOCAL_FACILITATOR_ACCOUNT = ANVIL_WELL_KNOWN_ACCOUNTS[0];\nexport const LOCAL_MERCHANT_ACCOUNT = ANVIL_WELL_KNOWN_ACCOUNTS[1];\nexport const LOCAL_BUYER_ACCOUNT = ANVIL_WELL_KNOWN_ACCOUNTS[2];\n\n/** Label printed wherever a dev key appears in output, logs or manifests */\nexport const DEV_KEY_LABEL = 'LOCAL DEVELOPMENT ONLY - DO NOT FUND';\n","/**\n * Rejects well-known Anvil keys and payment destinations when the RPC host\n * does not look local or private. Their private keys are published, so anyone\n * can spend what such an address receives on a public chain.\n *\n * The check uses the RPC hostname because the local chain shares Base\n * Sepolia's chain id. Both guards run at provider construction.\n */\nimport { CommerceError } from '../../core';\nimport { ANVIL_WELL_KNOWN_ACCOUNTS } from './local-chain/accounts';\n\nconst WELL_KNOWN_DEV_KEYS: ReadonlySet<string> = new Set(\n ANVIL_WELL_KNOWN_ACCOUNTS.map((a) => a.privateKey.toLowerCase()),\n);\n\nconst WELL_KNOWN_DEV_ADDRESSES: ReadonlySet<string> = new Set(\n ANVIL_WELL_KNOWN_ACCOUNTS.map((a) => a.address.toLowerCase()),\n);\n\n// `0x` plus 64 hex characters, the only shape `privateKeyToAccount` accepts\nconst PRIVATE_KEY_SHAPE = /^0x[0-9a-fA-F]{64}$/;\n\nexport function isWellKnownDevKey(privateKey: string): boolean {\n return WELL_KNOWN_DEV_KEYS.has(privateKey.toLowerCase());\n}\n\nexport function isWellKnownDevAddress(address: string): boolean {\n return WELL_KNOWN_DEV_ADDRESSES.has(address.toLowerCase());\n}\n\n/**\n * True for loopback addresses, RFC 1918 private ranges, and bare (dot-free)\n * hostnames, such as the compose service name \"anvil\".\n *\n * Bare hostnames are treated as local without resolving them. Operators must\n * point them at a private chain.\n */\nexport function isLikelyLocalOrPrivateHost(hostname: string): boolean {\n const h = hostname.toLowerCase().replace(/^\\[|\\]$/g, '');\n if (h === 'localhost' || h === '::1') return true;\n if (/^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (/^10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (/^192\\.168\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (/^172\\.(1[6-9]|2\\d|3[01])\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (!h.includes('.') && !h.includes(':')) return true; // bare hostname\n return false;\n}\n\nfunction parseHostnameOrThrow(rpcUrl: string): string {\n try {\n return new URL(rpcUrl).hostname;\n } catch (cause) {\n // Never the URL itself: RPC providers commonly put an API key in the path,\n // and this message reaches startup output and CI logs\n throw new CommerceError('CONFIG_INVALID', 'x402 provider: rpcUrl is not a valid URL', {\n cause,\n });\n }\n}\n\n/** Origin only, for diagnostics: RPC URLs often carry an API key in the path or query */\nexport function describeRpc(rpcUrl: string): string {\n try {\n return new URL(rpcUrl).origin;\n } catch {\n return '[unparseable rpcUrl]';\n }\n}\n\n/**\n * Throws CONFIG_INVALID if `signerPrivateKey` is not shaped like a private key,\n * or if it is a well-known dev key and the RPC is not local.\n *\n * The shape check runs first, so a truncated key is reported as malformed\n * instead of passing as \"not a dev key\".\n */\nexport function assertDevKeyIsLocalOnly(rpcUrl: string, signerPrivateKey: string): void {\n if (!PRIVATE_KEY_SHAPE.test(signerPrivateKey)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'x402 provider: facilitator.signerPrivateKey is not a well-formed private key ' +\n '(expected \"0x\" followed by exactly 64 hex characters).',\n );\n }\n\n if (!isWellKnownDevKey(signerPrivateKey)) return; // the operator's own key\n\n const hostname = parseHostnameOrThrow(rpcUrl);\n\n if (!isLikelyLocalOrPrivateHost(hostname)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'x402 provider: facilitator.signerPrivateKey is a well-known Anvil development key, but rpcUrl ' +\n `${describeRpc(rpcUrl)} does not look like a local/private chain. A public dev key must never sign against ` +\n 'a public network: it is instantly drainable and can grief real settlements via nonce exhaustion. ' +\n 'Use a real facilitator key for any non-local RPC, or point rpcUrl at your local/dev chain.',\n );\n }\n}\n\n/**\n * Throws CONFIG_INVALID if `payTo` is a well-known Anvil address and `rpcUrl`\n * does not look local or private.\n *\n * Guards the receiving side, in every facilitator mode. `agent-commerce init`\n * defaults `payTo` to a well-known address for the local demo, and on a real\n * network that default sends every payment where anyone can sweep it.\n */\nexport function assertPayToIsNotDevAddress(rpcUrl: string, payTo: string): void {\n if (!isWellKnownDevAddress(payTo)) return;\n\n const hostname = parseHostnameOrThrow(rpcUrl);\n\n if (!isLikelyLocalOrPrivateHost(hostname)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: \"payTo\" (${payTo}) is a well-known Anvil development address, but rpcUrl ` +\n `${describeRpc(rpcUrl)} does not look like a local/private chain. The private key behind that address ` +\n 'is public knowledge, so any revenue settled to it is immediately spendable by anyone. Set ' +\n '\"payTo\" to your own merchant wallet for any non-local RPC, or point rpcUrl at your ' +\n 'local/dev chain.',\n );\n }\n}\n","/**\n * What must hold before this gateway may settle a payment on the configured\n * network. Two callers share these checks: the provider runs them at\n * construction, so a library consumer who skips our config loader still gets\n * them, and the config loader runs them, so `validate` and `doctor` report\n * them too.\n *\n * Both run before any request, because a failure found in `settle()` would\n * come after the pipeline reserved the buyer's replay key.\n *\n * Imports no peer (no viem, no `@x402/*`), so the CLI can load it.\n */\nimport { CommerceError } from '../../core';\nimport { isLikelyLocalOrPrivateHost, isWellKnownDevAddress } from './dev-key-guard';\nimport {\n type DeploymentMode,\n type NetworkProfile,\n requireNetworkProfile,\n resolveDeploymentMode,\n} from './networks';\n\n/**\n * How the gateway authenticates to a remote facilitator.\n *\n * - `none`: send no credential; use it when the facilitator accepts\n * anonymous requests.\n * - `bearer`: send a static token; no extra peer package is needed.\n * - `cdp`: Coinbase Developer Platform. The optional peer `@coinbase/x402`,\n * imported only for this type, signs a fresh JWT per request.\n *\n * Any other auth type is refused at config load.\n */\nexport type FacilitatorAuth =\n | { readonly type: 'none' }\n | { readonly type: 'bearer'; readonly token: string }\n | { readonly type: 'cdp'; readonly apiKeyId: string; readonly apiKeySecret: string };\n\nexport type X402FacilitatorConfig =\n | { readonly mode: 'local'; readonly signerPrivateKey: string }\n | { readonly mode: 'remote'; readonly url: string; readonly auth: FacilitatorAuth };\n\nexport interface X402DeploymentInput {\n readonly network: string;\n readonly payTo: string;\n readonly asset: string;\n /** EIP-712 domain of the asset, as the token itself reports it */\n readonly assetName?: string;\n readonly assetVersion?: string;\n readonly facilitator: X402FacilitatorConfig;\n /** Must be `true` before anything settles on a mainnet */\n readonly allowMainnet?: boolean;\n /**\n * Must be `true` on mainnet when facilitator auth is `none`. A separate\n * decision from `allowMainnet`: it accepts settling without an account at\n * the facilitator, under its anonymous-access limits.\n */\n readonly allowUnauthenticatedFacilitator?: boolean;\n /** Error-path prefix, `payments.x402` by default */\n readonly configPath?: string;\n /** Settlement-recipient field named in errors, `payTo` by default */\n readonly payToField?: string;\n}\n\nexport interface X402Deployment {\n readonly profile: NetworkProfile;\n readonly mode: DeploymentMode;\n}\n\nfunction invalid(message: string, path: string): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, { details: { path } });\n}\n\n/**\n * Resolves the deployment and refuses the combinations that could move real\n * money by accident. The network must resolve first; the other checks are\n * independent.\n */\nexport function resolveX402Deployment(input: X402DeploymentInput): X402Deployment {\n const at = input.configPath ?? 'payments.x402';\n const payTo = input.payToField ?? 'payTo';\n const profile = requireNetworkProfile(input.network, `${at}.network`);\n const mode = resolveDeploymentMode(profile, input.facilitator.mode);\n\n // Local mode keeps a gas-paying key in the gateway process. A compromise\n // could expose that key, so mainnet requires a remote facilitator.\n if (profile.kind === 'mainnet' && input.facilitator.mode === 'local') {\n throw invalid(\n `${at}: network \"${profile.id}\" (${profile.displayName}) is a mainnet and cannot be served by facilitator.mode \"local\". A mainnet deployment must settle through a remote facilitator.`,\n `${at}.facilitator.mode`,\n );\n }\n\n if (mode === 'mainnet' && input.allowMainnet !== true) {\n throw invalid(\n `${at}: network \"${profile.id}\" (${profile.displayName}) settles real funds. Set ${at}.allowMainnet: true to acknowledge this explicitly - it is never the default.`,\n `${at}.allowMainnet`,\n );\n }\n\n if (input.facilitator.mode === 'remote') {\n assertFacilitatorUrlIsSafe(input.facilitator.url, mode, at);\n // The authorization fixes recipient, amount and chain, so a facilitator\n // cannot redirect funds. A credential adds an account: rate limits, terms\n // and support. On mainnet, going without one is an explicit choice.\n if (\n mode === 'mainnet' &&\n input.facilitator.auth.type === 'none' &&\n input.allowUnauthenticatedFacilitator !== true\n ) {\n throw invalid(\n `${at}: no credential is configured for facilitator ${describeOrigin(input.facilitator.url)} on mainnet. Set ${at}.allowUnauthenticatedFacilitator: true to accept anonymous access and the facilitator's limits, or configure facilitator.auth.`,\n `${at}.allowUnauthenticatedFacilitator`,\n );\n }\n // A blank credential reaches the facilitator as \"unauthenticated\" and fails\n // every payment after the buyer signed. `${VAR:- }` resolving to whitespace\n // is the usual cause.\n for (const [field, value] of credentialFields(input.facilitator.auth)) {\n if (value.trim() === '') {\n throw invalid(\n `${at}: facilitator.auth.type is \"${input.facilitator.auth.type}\" but ${field} is empty. An empty credential is refused rather than sent.`,\n `${at}.facilitator.auth.${field}`,\n );\n }\n }\n }\n\n // The config loader's address check refuses this too; repeated here for a\n // library consumer who calls `createX402PaymentProvider` without it\n if (/^0x0{40}$/i.test(input.payTo)) {\n throw invalid(\n `${at}: \"${payTo}\" is the zero address. Every payment settled there is destroyed.`,\n `${at}.${payTo}`,\n );\n }\n\n // Anyone can spend from a well-known Anvil address. `dev-key-guard` refuses\n // one behind a public RPC; this refuses one on any non-local deployment,\n // whose RPC host says nothing about where a remote facilitator settles.\n if (mode !== 'local' && isWellKnownDevAddress(input.payTo)) {\n throw invalid(\n `${at}: \"${payTo}\" (${input.payTo}) is a well-known Anvil development address and this is a ${mode} deployment. Anyone can spend what settles there. Set ${payTo} to your own merchant wallet.`,\n `${at}.${payTo}`,\n );\n }\n\n // Mainnet only: a testnet is where pointing at a mock token is normal\n const canonical = profile.canonicalAsset;\n if (mode === 'mainnet' && canonical) {\n if (!sameAddress(input.asset, canonical.address)) {\n throw invalid(\n `${at}: asset ${input.asset} is not ${canonical.symbol} on ${profile.displayName} (expected ${canonical.address}). Settling a mainnet payment in an unintended token is refused.`,\n `${at}.asset`,\n );\n }\n // The buyer signs the EIP-712 domain and the scheme checks it. A wrong one\n // refuses every payment with `invalid_exact_evm_token_name_mismatch` after\n // the buyer signed, so it is caught here, before the gateway starts.\n if (input.assetName !== undefined && input.assetName !== canonical.name) {\n throw invalid(\n `${at}: assetName \"${input.assetName}\" is not the EIP-712 domain name ${canonical.symbol} reports on ${profile.displayName} (expected \"${canonical.name}\"). Every payment would be refused after the buyer signed.`,\n `${at}.assetName`,\n );\n }\n if (input.assetVersion !== undefined && input.assetVersion !== canonical.version) {\n throw invalid(\n `${at}: assetVersion \"${input.assetVersion}\" is not the EIP-712 domain version ${canonical.symbol} reports on ${profile.displayName} (expected \"${canonical.version}\").`,\n `${at}.assetVersion`,\n );\n }\n }\n\n return { profile, mode };\n}\n\n/**\n * A facilitator sees every payment authorization this gateway handles. Plain\n * HTTP puts those on the wire in the clear and lets anyone in the path rewrite\n * a settlement result, so it is allowed only to a local or private host, and\n * never on a mainnet.\n */\nfunction assertFacilitatorUrlIsSafe(url: string, mode: DeploymentMode, at: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch (cause) {\n throw new CommerceError('CONFIG_INVALID', `${at}: facilitator.url is not a valid URL`, {\n cause,\n details: { path: `${at}.facilitator.url` },\n });\n }\n\n if (parsed.protocol === 'https:') return;\n if (parsed.protocol !== 'http:') {\n throw invalid(\n `${at}: facilitator ${describeOrigin(url)} must be reached over https (or http on a local/private host); got \"${parsed.protocol}//\"`,\n `${at}.facilitator.url`,\n );\n }\n if (mode !== 'mainnet' && isLikelyLocalOrPrivateHost(parsed.hostname)) return;\n\n // The origin, never the whole URL: the path can carry a tenant or an API\n // key, and this message reaches `validate`, `doctor`, startup output and CI logs\n throw invalid(\n `${at}: facilitator ${describeOrigin(url)} is reached over plain HTTP. Payment authorizations and settlement results would travel unencrypted. Use https, or point at a local/private host on a non-mainnet deployment.`,\n `${at}.facilitator.url`,\n );\n}\n\n// Origin only: a facilitator URL can carry a tenant path or an API key\nfunction describeOrigin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return '[unparseable facilitator.url]';\n }\n}\n\n// The secret-bearing fields of an auth block, for emptiness checks only. Never logged\nfunction credentialFields(auth: FacilitatorAuth): readonly (readonly [string, string])[] {\n switch (auth.type) {\n case 'bearer':\n return [['token', auth.token]];\n case 'cdp':\n return [\n ['apiKeyId', auth.apiKeyId],\n ['apiKeySecret', auth.apiKeySecret],\n ];\n default:\n return [];\n }\n}\n\nfunction sameAddress(a: string, b: string): boolean {\n return a.toLowerCase() === b.toLowerCase();\n}\n","/**\n * MCP protocol constants shared by the config layer, the adapter and the\n * OpenAPI importer.\n *\n * Kept dependency-free: `src/config` validates tool names at load time, so\n * anything imported here would become a config-load dependency too, and the\n * MCP SDK is an optional peer the main entry and CLI must never load.\n */\n\n/** Characters SEP-986 allows in an MCP tool name, as a regex character class body */\nexport const MCP_TOOL_NAME_CHARS = 'A-Za-z0-9._-';\n\n/** Longest MCP tool name SEP-986 allows */\nexport const MCP_TOOL_NAME_MAX_LENGTH = 128;\n\n/**\n * MCP tool names per SEP-986: 1-128 chars of [A-Za-z0-9._-], the SDK's own\n * `TOOL_NAME_REGEX`, which it does not export. Config refuses an mcp-exposed\n * resource whose id fails it; the low-level `Server` checks no names, so the\n * adapter also skips such an id with a warning.\n */\nexport const MCP_TOOL_NAME_PATTERN = new RegExp(\n `^[${MCP_TOOL_NAME_CHARS}]{1,${MCP_TOOL_NAME_MAX_LENGTH}}$`,\n);\n","/**\n * `config.yaml` schema, validation and normalization into the canonical\n * `GatewayConfig` (docs/contracts.md).\n *\n * 1. Zod validates shape: types, required fields, unknown keys. Numeric and\n * boolean leaves accept their native type or a string, because env\n * substitution produces strings. Zod transforms interact badly with\n * `.strict()` inference, so coercion happens in plain TypeScript in step 2.\n * 2. A business-rule pass coerces those leaves and checks what needs a\n * specific message: cross-references, disabled protocols and payment\n * methods, dynamic pricing, addresses, duplicate trust entries.\n *\n * Env substitution (`${VAR}` / `${VAR:-default}`) runs over the raw value\n * before both steps, so numeric and boolean fields can be templated. The one\n * exception is `version:`, checked before substitution: it decides whether this\n * parser understands the document at all, so it cannot depend on the\n * environment.\n */\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","// `config.yaml` schema, loader and environment substitution\n\nexport { substituteEnv } from './env';\nexport type { LoadConfigOptions } from './load';\nexport { loadConfig } from './load';\nexport type { GatewayConfig } from './schema';\nexport { parseConfig } from './schema';\n","import { Command } from 'commander';\nimport { DEFAULT_CONFIG_FILENAME } from '../config/filename';\nimport { PROTOCOL_NAMES } from '../core';\nimport { runDemo } from './commands/demo';\nimport { printDoctorReport, runDoctor } from './commands/doctor';\nimport { runImportOpenApi } from './commands/import-openapi';\nimport { runInit } from './commands/init';\nimport { runValidate } from './commands/validate';\nimport { runVersion } from './commands/version';\nimport { type Io, processIo } from './lib/io';\nimport { readVersionReport } from './lib/versions';\n\n/**\n * Builds the `agent-commerce` Commander program.\n *\n * `io` is injectable so tests can capture output. With `exitOverride()` and\n * `configureOutput()`, `--help` and parse errors never call `process.exit()`,\n * so the caller (index.ts or a test) controls the process lifecycle.\n */\nexport function buildProgram(io: Io = processIo): Command {\n const program = new Command();\n\n program\n .name('agent-commerce')\n .description('CLI for the Agent Commerce Gateway: init, import, validate, doctor, demo.')\n // `--version` prints the CLI version only; the `version` subcommand also\n // lists the pinned protocol/SDK versions. Both read `readVersionReport()`,\n // so they cannot disagree.\n .version(readVersionReport().cliVersion, '-v, --version', 'Print the CLI version.')\n .exitOverride()\n .configureOutput({\n writeOut: (str) => io.stdout(str.replace(/\\n+$/, '')),\n writeErr: (str) => io.stderr(str.replace(/\\n+$/, '')),\n });\n\n program\n .command('version')\n .description('Print the CLI version and pinned protocol/SDK versions.')\n .action(() => {\n process.exitCode = runVersion(io);\n });\n\n program\n .command('validate')\n .description(`Validate ${DEFAULT_CONFIG_FILENAME} and exit non-zero if it is invalid.`)\n .option('--config <path>', `path to ${DEFAULT_CONFIG_FILENAME}`)\n .action(async (opts: { config?: string }) => {\n const code = await runValidate(\n opts.config !== undefined ? { configPath: opts.config } : {},\n io,\n );\n process.exitCode = code;\n });\n\n program\n .command('doctor')\n .description('Diagnose config, gateway, backend, protocol and payment health.')\n .option('--config <path>', `path to ${DEFAULT_CONFIG_FILENAME}`)\n .option(\n '--gateway <url>',\n 'gateway base URL (default: derived from config, else http://localhost:8080)',\n )\n .option('--json', 'emit machine-readable JSON instead of a formatted report', false)\n .action(async (opts: { config?: string; gateway?: string; json?: boolean }) => {\n const report = await runDoctor({\n ...(opts.config !== undefined ? { configPath: opts.config } : {}),\n ...(opts.gateway !== undefined ? { gatewayUrl: opts.gateway } : {}),\n });\n printDoctorReport(report, io, opts.json === true);\n process.exitCode = report.exitCode;\n });\n\n program\n .command('init')\n .description(`Interactively generate ${DEFAULT_CONFIG_FILENAME}.`)\n .option('--output <path>', 'output path', DEFAULT_CONFIG_FILENAME)\n .option('--force', 'overwrite an existing file', false)\n .option('--yes', 'use non-interactive defaults (required for scripting/tests)', false)\n .action(async (opts: { output: string; force: boolean; yes: boolean }) => {\n const code = await runInit({ outputPath: opts.output, force: opts.force, yes: opts.yes }, io);\n process.exitCode = code;\n });\n\n // A command group, so another importer can be added beside `openapi`\n // without renaming it\n const importCommand = program\n .command('import')\n .description('Generate Agent Commerce resource drafts from an API description.');\n\n importCommand\n .command('openapi')\n .description('Convert a local OpenAPI 3.0/3.1/3.2 document into resource drafts.')\n .argument('<source>', 'path to a local .yaml, .yml or .json OpenAPI document')\n .option(\n '--output <path>',\n 'output path (default: <source name without extension>.agent-commerce.yaml in the current directory)',\n )\n .option('--force', 'overwrite an existing output file', false)\n .option('--base-url <url>', 'backend base URL, overriding the document servers')\n .option(\n '--operation <operationId>',\n 'import only this operation (repeatable)',\n collect,\n undefined,\n )\n .option('--tag <tag>', 'import only operations with this tag (repeatable, OR-ed)', collect)\n .option('--free', 'mark generated resources as pricing.type free', false)\n .option('--expose <protocols>', `comma-separated: ${PROTOCOL_NAMES.join(',')}`)\n .option('--strict', 'exit non-zero when the import produced warnings', false)\n .option('--json', 'emit a machine-readable summary instead of a report', false)\n .action(\n async (\n source: string,\n opts: {\n output?: string;\n force: boolean;\n baseUrl?: string;\n operation?: string[];\n tag?: string[];\n free: boolean;\n expose?: string;\n strict: boolean;\n json: boolean;\n },\n ) => {\n process.exitCode = await runImportOpenApi(\n {\n source,\n ...(opts.output !== undefined ? { output: opts.output } : {}),\n force: opts.force,\n ...(opts.baseUrl !== undefined ? { baseUrl: opts.baseUrl } : {}),\n ...(opts.operation !== undefined ? { operations: opts.operation } : {}),\n ...(opts.tag !== undefined ? { tags: opts.tag } : {}),\n free: opts.free,\n ...(opts.expose !== undefined ? { expose: opts.expose } : {}),\n strict: opts.strict,\n json: opts.json,\n },\n io,\n );\n },\n );\n\n program\n .command('demo')\n .description(\n 'Start the local stack with docker compose (waiting for healthy services), then run the demo agent. Run it from a repo clone.',\n )\n .action(async () => {\n process.exitCode = await runDemo(io);\n });\n\n return program;\n}\n\n// Commander's repeatable-option collector\nfunction collect(value: string, previous: string[] | undefined): string[] {\n return [...(previous ?? []), value];\n}\n","/**\n * `agent-commerce demo`: runs `docker compose up` and then `npm run demo:agent`,\n * the README quickstart without its `doctor` check. `--wait` holds the first\n * step until every compose service with a healthcheck reports healthy. Each\n * step's exit code is checked, and a failing step is reported with the command\n * to retry it.\n */\nimport type { Io } from '../lib/io';\n\nexport interface DemoStep {\n readonly name: string;\n readonly command: string;\n readonly args: readonly string[];\n}\n\nexport interface RunResult {\n readonly code: number;\n readonly stderrTail?: string;\n}\n\nexport type RunCommand = (command: string, args: readonly string[]) => Promise<RunResult>;\n\nexport interface DemoDeps {\n readonly run?: RunCommand;\n readonly steps?: readonly DemoStep[];\n}\n\nexport function defaultDemoSteps(): readonly DemoStep[] {\n return [\n {\n name: 'Start the local stack: chain, merchant, gateway and dashboard (docker compose)',\n command: 'docker',\n args: ['compose', 'up', '--build', '--detach', '--wait'],\n },\n { name: 'Run the deterministic buyer agent', command: 'npm', args: ['run', 'demo:agent'] },\n ];\n}\n\n/** `agent-commerce demo`. Returns the process exit code */\nexport async function runDemo(io: Io, deps: DemoDeps = {}): Promise<number> {\n const steps = deps.steps ?? defaultDemoSteps();\n const run = deps.run ?? execCommand;\n\n io.stdout('agent-commerce demo: starting the local stack, then running the buyer agent');\n for (const step of steps) {\n io.stdout('');\n io.stdout(`==> ${step.name}`);\n io.stdout(` $ ${step.command} ${step.args.join(' ')}`);\n const result = await run(step.command, step.args);\n if (result.code !== 0) {\n io.stderr(`FAIL \"${step.name}\" exited with code ${result.code}.`);\n if (result.stderrTail !== undefined && result.stderrTail.length > 0) {\n io.stderr(result.stderrTail);\n }\n io.stderr('');\n io.stderr('Nothing further was run. To retry manually:');\n io.stderr(` ${step.command} ${step.args.join(' ')}`);\n return 1;\n }\n io.stdout(`OK ${step.name}`);\n }\n io.stdout('');\n io.stdout('PASS Demo is up. Try: agent-commerce doctor --config config-demo.yaml');\n return 0;\n}\n\nasync function execCommand(command: string, args: readonly string[]): Promise<RunResult> {\n const { spawn } = await import('node:child_process');\n return new Promise((resolvePromise) => {\n let stderr = '';\n const child = spawn(command, args, { stdio: ['ignore', 'inherit', 'pipe'] });\n child.stderr?.on('data', (chunk: Buffer) => {\n stderr += chunk.toString('utf8');\n });\n child.on('error', (err) => {\n resolvePromise({ code: 1, stderrTail: err.message });\n });\n child.on('close', (code) => {\n const tail = stderr.trim().split('\\n').slice(-10).join('\\n');\n resolvePromise({ code: code ?? 1, ...(tail.length > 0 ? { stderrTail: tail } : {}) });\n });\n });\n}\n","import { accessSync, existsSync, constants as fsConstants } from 'node:fs';\nimport { dirname } from 'node:path';\nimport picocolors from 'picocolors';\n// Constants and a descriptor only: the AP2 provider would pull the optional\n// peers `jose`, `@sd-jwt/core` and `canonicalize` into the CLI bundle\nimport {\n AP2_CHECKOUT_MANDATE_VCT,\n AP2_CHECKOUT_PROFILE,\n AP2_SPEC_VERSION,\n} from '../../authorization/ap2/constants';\nimport { AP2_UNSUPPORTED } from '../../authorization/ap2/descriptor';\nimport { type CommerceResource, isCommerceError, type ReceiptStore } from '../../core';\nimport { extractPathParameterNames } from '../../core/execution';\nimport {\n MPP_PROFILE,\n MPP_SPEC_COMMIT,\n MPP_SPEC_DRAFTS,\n MPPX_VERSION,\n} from '../../payments/mpp/constants';\nimport type { X402FacilitatorConfig } from '../../payments/x402/guardrails';\nimport {\n type DeploymentMode,\n describeDeploymentMode,\n findNetworkProfile,\n resolveDeploymentMode,\n} from '../../payments/x402/networks';\n// Narrow modules, not the protocol barrels: the CLI must pull in no protocol SDK\nimport {\n A2A_AGENT_CARD_PATH,\n A2A_PROTOCOL_BINDING,\n A2A_PROTOCOL_VERSION,\n A2A_SPEC_VERSION,\n} from '../../protocols/a2a/constants';\nimport { A2A_UNSUPPORTED } from '../../protocols/a2a/descriptor';\nimport {\n ACP_API_VERSION,\n ACP_SPEC_VERSION,\n ACP_WELL_KNOWN_PATH,\n} from '../../protocols/acp/constants';\nimport { ACP_UNSUPPORTED } from '../../protocols/acp/descriptor';\nimport { createSqliteReceiptStore } from '../../storage/receipts';\nimport { type ConfigLoader, type GatewayConfig, loadConfigDynamic } from '../lib/config-client';\nimport { type FetchLike, fetchJson } from '../lib/http';\nimport { PLACEHOLDER_ASSET_ADDRESS } from '../lib/init-config';\nimport type { Io } from '../lib/io';\nimport {\n fillEnvFromLocalChainManifest,\n LOCAL_CHAIN_MANIFEST_PATH,\n MANIFEST_FILLABLE_ENV_VAR_NAMES,\n type ManifestEnvFill,\n} from '../lib/manifest-env';\nimport { maskMiddle } from '../lib/mask';\nimport { readVersionReport } from '../lib/versions';\n\nexport type CheckStatus = 'PASS' | 'WARN' | 'FAIL' | 'INFO';\n\nexport interface DoctorCheck {\n readonly name: string;\n readonly status: CheckStatus;\n readonly detail: string;\n}\n\nexport interface DoctorReport {\n readonly checks: readonly DoctorCheck[];\n readonly score: { readonly passed: number; readonly total: number };\n readonly exitCode: number;\n}\n\nexport interface DoctorOptions {\n readonly configPath?: string;\n readonly gatewayUrl?: string;\n}\n\nexport interface DoctorDeps {\n readonly fetchImpl?: FetchLike;\n readonly loadConfig?: ConfigLoader;\n readonly createStore?: (path: string) => ReceiptStore;\n readonly fillEnvFromManifest?: (env: NodeJS.ProcessEnv) => ManifestEnvFill;\n}\n\nconst CHECK_TIMEOUT_MS = 1500;\n\nfunction deriveGatewayUrl(explicit: string | undefined, config: GatewayConfig | undefined): string {\n if (explicit !== undefined) return explicit.replace(/\\/$/, '');\n if (config !== undefined) {\n // `0.0.0.0` and `::` mean all interfaces, so probe loopback. An IPv6\n // literal such as `::1` must be bracketed, or the URL is invalid\n // (`http://::1:8080`).\n const raw = config.server.host;\n const host = raw === '0.0.0.0' ? '127.0.0.1' : raw === '::' ? '::1' : raw;\n const authority = host.includes(':') ? `[${host}]` : host;\n return `http://${authority}:${config.server.port}`;\n }\n return 'http://localhost:8080';\n}\n\n/**\n * Fills `{param}` slots with a probe value, using the runtime's own grammar\n * (`extractPathParameterNames`). A looser local pattern would fill a token the\n * runtime leaves literal, such as `{report id}`, and report the backend\n * reachable at a URL no real request uses. Unrecognized tokens stay as they\n * are, so the probe hits what the gateway would send.\n */\nfunction substitutePathParams(url: string): string {\n let filled = url;\n for (const name of extractPathParameterNames(url)) {\n filled = filled.replaceAll(`{${name}}`, 'demo-check');\n }\n return filled;\n}\n\n// Shared settlement fields; `payTo` holds x402 `payTo` or MPP `recipient`\ninterface LiveX402 {\n readonly asset: string;\n readonly network: string;\n readonly payTo: string;\n}\n\n// Result of reading a live x402 or MPP settlement block\ntype LiveX402Result = LiveX402 | 'disabled' | undefined;\n\n/**\n * Extracts the effective settlement fields from the well-known document.\n * Explicit `enabled: false` is a mismatch; absent, malformed, or incomplete\n * data leaves the comparison inconclusive.\n */\nfunction extractWellKnownX402(\n body: Record<string, unknown> | undefined,\n rail: 'x402' | 'mpp' = 'x402',\n): LiveX402Result {\n const payments = body?.['payments'];\n if (typeof payments !== 'object' || payments === null) return undefined;\n const block = (payments as Record<string, unknown>)[rail];\n if (typeof block !== 'object' || block === null) return undefined;\n const rec = block as Record<string, unknown>;\n if (rec['enabled'] === false) return 'disabled';\n if (rec['enabled'] !== true) return undefined;\n const { asset, network } = rec;\n const payTo = rec[rail === 'mpp' ? 'recipient' : 'payTo'];\n if (typeof asset !== 'string' || typeof network !== 'string' || typeof payTo !== 'string') {\n return undefined;\n }\n return { asset, network, payTo };\n}\n\n// Checksum-insensitive, as config validation treats addresses\nfunction sameAddress(a: string, b: string): boolean {\n return a.toLowerCase() === b.toLowerCase();\n}\n\n/**\n * Compares live settlement fields with local config. A mismatch names both\n * values so the operator knows what to fix.\n */\nfunction findX402Mismatch(\n configured: LiveX402,\n live: LiveX402,\n payToField = 'payTo',\n): string | undefined {\n const diffs: string[] = [];\n if (!sameAddress(configured.asset, live.asset)) {\n diffs.push(\n `asset: gateway is using ${live.asset} but local config resolves to ${configured.asset}`,\n );\n }\n if (configured.network !== live.network) {\n diffs.push(\n `network: gateway is using \"${live.network}\" but local config resolves to \"${configured.network}\"`,\n );\n }\n if (!sameAddress(configured.payTo, live.payTo)) {\n diffs.push(\n `${payToField}: gateway is using ${live.payTo} but local config resolves to ${configured.payTo}`,\n );\n }\n if (diffs.length === 0) return undefined;\n return `${diffs.join('; ')}; the gateway may be running against an older deployment - restart it or re-run chain:deploy`;\n}\n\n/**\n * Where a rail settles and through which facilitator. Chain id 84532 is both\n * the local dev chain and public Base Sepolia, so the deployment mode (network\n * plus facilitator) says which one this is. Local mode names the public\n * network only as sharing its chain id, never as the place of settlement.\n * `parseConfig` refuses an unknown network, so an absent profile means another\n * loader produced this config, and the text says so rather than guessing.\n */\nfunction describeSettlement(\n network: string,\n facilitator: X402FacilitatorConfig,\n): { readonly mode: DeploymentMode | undefined; readonly where: string; readonly via: string } {\n const profile = findNetworkProfile(network);\n const mode = profile ? resolveDeploymentMode(profile, facilitator.mode) : undefined;\n const where =\n profile === undefined || mode === undefined\n ? `unknown network ${network}`\n : mode === 'local'\n ? `LOCAL dev chain (${network}, chain id shared with ${profile.displayName})`\n : `${describeDeploymentMode(mode)} on ${profile.displayName} (${network})`;\n const via =\n facilitator.mode === 'local' ? 'local (in-process)' : `remote (auth=${facilitator.auth.type})`;\n return { mode, where, via };\n}\n\n// Reports rather than re-checks: config load already enforced every guardrail\n// (src/payments/x402/guardrails.ts, shared by x402 and MPP). An operator about\n// to move real money sees which guarantees they rely on, including an\n// unauthenticated facilitator the config accepted through\n// `allowUnauthenticatedFacilitator`.\nfunction mainnetSafetyCheck(\n name: string,\n payToField: 'payTo' | 'recipient',\n facilitator: X402FacilitatorConfig,\n): DoctorCheck {\n const unauthenticated = facilitator.mode === 'remote' && facilitator.auth.type === 'none';\n return {\n name,\n status: unauthenticated ? 'WARN' : 'INFO',\n detail: unauthenticated\n ? `${describeDeploymentMode('mainnet')}: no credential is sent to the remote facilitator ` +\n '(accepted via allowUnauthenticatedFacilitator); its anonymous-access ' +\n 'limits apply. Config load also requires ' +\n `allowMainnet, HTTPS, a non-development ${payToField} and the canonical asset. ` +\n 'Payments fail closed.'\n : `${describeDeploymentMode('mainnet')}. Enforced at config load: explicit allowMainnet ` +\n `opt-in, remote facilitator over HTTPS with a credential, non-development ${payToField}, ` +\n 'and the canonical asset for this network. Payments fail closed.',\n };\n}\n\n// Issuer ids and how many keys each carries. Never a key\nfunction describeIssuers(\n label: string,\n issuers: readonly { readonly issuer: string; readonly keys: readonly unknown[] }[],\n): string {\n const described = issuers\n .map(\n (entry) => `${entry.issuer} (${entry.keys.length} key${entry.keys.length === 1 ? '' : 's'})`,\n )\n .join(', ');\n return `${label} issuers: ${described}`;\n}\n\n// Whether an existing file is writable, without creating one\nfunction isWritableFile(path: string): boolean {\n try {\n accessSync(path, fsConstants.W_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n// A SQLite store file, diagnosed without creating it (see the Storage check in\n// `runDoctor`). `suffix` is appended to every detail.\nfunction storeFileCheck(\n name: string,\n path: string,\n risk: { readonly inMemory: string; readonly unwritable: string },\n suffix = '',\n): DoctorCheck {\n if (path === ':memory:') {\n return {\n name,\n status: 'WARN',\n detail: `in-memory store: ${risk.inMemory}; use a file path in production${suffix}`,\n };\n }\n if (existsSync(path)) {\n return isWritableFile(path)\n ? { name, status: 'PASS', detail: `writable at \"${path}\"${suffix}` }\n : {\n name,\n status: 'FAIL',\n detail: `\"${path}\" exists but is not writable by this user, so ${risk.unwritable}${suffix}`,\n };\n }\n return { name, status: 'WARN', detail: `${missingStoreDetail(path)}${suffix}` };\n}\n\n// Every SQLite store opens through `openSqliteDatabase`, which creates the file\n// and a missing directory, so one wording covers them all\nfunction missingStoreDetail(path: string): string {\n const directory = dirname(path);\n return directory !== '.' && !existsSync(directory)\n ? `no store at \"${path}\" and its directory does not exist. Both are created when the gateway starts, provided the path is writable`\n : `no store at \"${path}\" yet. It is created the first time the gateway starts`;\n}\n\n/**\n * The resource mapped to each checkout operation, re-checked against the rules\n * config enforces: present, acp-exposed and free to invoke. Resource ids are\n * printed because an operator needs them to fix a mapping; the mapping is\n * config, not a secret.\n */\nfunction acpMappingCheck(\n config: GatewayConfig,\n operations: Readonly<Record<string, string>>,\n): DoctorCheck {\n const byId = new Map(config.resources.map((resource) => [resource.id, resource]));\n const problems: string[] = [];\n\n for (const [operation, resourceId] of Object.entries(operations)) {\n const resource = byId.get(resourceId);\n if (resource === undefined) {\n problems.push(`${operation} -> \"${resourceId}\" does not exist`);\n continue;\n }\n if (!resource.exposedVia.includes('acp')) {\n problems.push(`${operation} -> \"${resourceId}\" is not exposed via acp`);\n }\n // ACP checkout carries the merchant's own purchase payment; charging for\n // the invocation as well would put two payment layers on one call\n if (resource.pricing.type !== 'free' || resource.paymentMethods.length > 0) {\n problems.push(`${operation} -> \"${resourceId}\" is not free to invoke`);\n }\n }\n\n if (problems.length > 0) {\n return { name: 'ACP checkout mapping', status: 'FAIL', detail: problems.join('; ') };\n }\n return {\n name: 'ACP checkout mapping',\n status: 'PASS',\n detail: `5 operations mapped to free acp-exposed resources (${Object.values(operations).join(', ')})`,\n };\n}\n\n/** `agent-commerce doctor [--config] [--gateway] [--json]` */\nexport async function runDoctor(\n options: DoctorOptions,\n deps: DoctorDeps = {},\n): Promise<DoctorReport> {\n const fetchImpl = deps.fetchImpl ?? globalThis.fetch;\n const loadConfig = deps.loadConfig ?? loadConfigDynamic;\n const createStore = deps.createStore ?? ((path: string) => createSqliteReceiptStore({ path }));\n const fillEnvFromManifest = deps.fillEnvFromManifest ?? fillEnvFromLocalChainManifest;\n\n const checks: DoctorCheck[] = [];\n let config: GatewayConfig | undefined;\n\n // 1. Config\n const { env, filled, manifestFound } = fillEnvFromManifest(process.env);\n const filledSuffix =\n filled.length > 0\n ? ` (using local chain manifest ${LOCAL_CHAIN_MANIFEST_PATH} for ${filled.join(', ')})`\n : '';\n try {\n config = await loadConfig({\n ...(options.configPath !== undefined ? { path: options.configPath } : {}),\n env,\n });\n checks.push({\n name: 'Config',\n status: 'PASS',\n detail: `valid: ${config.resources.length} resource(s), merchant \"${config.merchant.name}\"${filledSuffix}`,\n });\n } catch (err) {\n const variable = isCommerceError(err) ? err.details?.['variable'] : undefined;\n const hint =\n !manifestFound &&\n typeof variable === 'string' &&\n MANIFEST_FILLABLE_ENV_VAR_NAMES.has(variable)\n ? `. Run \"npm run chain:deploy\": it writes ${LOCAL_CHAIN_MANIFEST_PATH}, which fills local X402_*/MERCHANT_WALLET placeholders automatically`\n : '';\n checks.push({\n name: 'Config',\n status: 'FAIL',\n detail: `${err instanceof Error ? err.message : String(err)}${hint}`,\n });\n }\n\n const gatewayUrl = deriveGatewayUrl(options.gatewayUrl, config);\n\n // 2. Gateway\n const health = await fetchJson(fetchImpl, `${gatewayUrl}/health`, CHECK_TIMEOUT_MS);\n let gatewayUp = false;\n if (!health.ok) {\n checks.push({\n name: 'Gateway',\n status: 'FAIL',\n detail: `unreachable at ${gatewayUrl} (${health.error ?? `HTTP ${health.status}`})`,\n });\n } else {\n gatewayUp = true;\n const ready = await fetchJson(fetchImpl, `${gatewayUrl}/ready`, CHECK_TIMEOUT_MS);\n checks.push(\n ready.ok\n ? { name: 'Gateway', status: 'PASS', detail: `healthy and ready at ${gatewayUrl}` }\n : {\n name: 'Gateway',\n status: 'WARN',\n detail: `healthy but not ready at ${gatewayUrl} (${ready.error ?? `HTTP ${ready.status}`})`,\n },\n );\n }\n\n // 3. Backend(s)\n if (config === undefined) {\n checks.push({ name: 'Backend', status: 'WARN', detail: 'skipped: config invalid' });\n } else if (config.resources.length === 0) {\n checks.push({ name: 'Backend', status: 'INFO', detail: 'no resources configured' });\n } else {\n const resources = config.resources as readonly CommerceResource[];\n const urls: string[] = [...new Set(resources.map((r) => substitutePathParams(r.handler.url)))];\n const results = await Promise.all(\n urls.map((url) => fetchJson(fetchImpl, url, CHECK_TIMEOUT_MS)),\n );\n const reachable = results.filter((r) => r.status !== 0).length;\n const status: CheckStatus =\n reachable === urls.length ? 'PASS' : reachable === 0 ? 'FAIL' : 'WARN';\n checks.push({\n name: 'Backend',\n status,\n detail: `${reachable}/${urls.length} backend host(s) reachable`,\n });\n }\n\n // 4. Well-known document (feeds Protocols + Protocol versions)\n const wellKnown = gatewayUp\n ? await fetchJson<Record<string, unknown>>(\n fetchImpl,\n `${gatewayUrl}/.well-known/agent-commerce`,\n CHECK_TIMEOUT_MS,\n )\n : undefined;\n\n // 5. Protocols\n if (config === undefined) {\n checks.push({ name: 'Protocols', status: 'WARN', detail: 'skipped: config invalid' });\n } else if (wellKnown === undefined || !wellKnown.ok) {\n checks.push({ name: 'Protocols', status: 'FAIL', detail: 'well-known document unreachable' });\n } else {\n const mcpMountPath = config.protocols.mcp.enabled ? config.protocols.mcp.mountPath : undefined;\n const a2aMountPath = config.protocols.a2a.enabled ? config.protocols.a2a.mountPath : undefined;\n checks.push({\n name: 'Protocols',\n status: 'PASS',\n detail: `http=${config.protocols.http.enabled ? 'on' : 'off'} mcp=${config.protocols.mcp.enabled ? `on (${mcpMountPath})` : 'off'} a2a=${config.protocols.a2a.enabled ? `on (${a2aMountPath})` : 'off'} acp=${config.protocols.acp.enabled ? `on (${config.protocols.acp.mountPath})` : 'off'}`,\n });\n }\n\n // 5b. A2A specifics, from the pins rather than the live gateway. The spec\n // revision and the negotiation version look alike, so each is named.\n if (config === undefined) {\n checks.push({ name: 'A2A', status: 'WARN', detail: 'skipped: config invalid' });\n } else if (!config.protocols.a2a.enabled) {\n checks.push({ name: 'A2A', status: 'INFO', detail: 'disabled' });\n } else {\n checks.push({\n name: 'A2A',\n status: 'PASS',\n detail: `experimental · spec ${A2A_SPEC_VERSION} · protocol ${A2A_PROTOCOL_VERSION} · binding ${A2A_PROTOCOL_BINDING} · mount ${config.protocols.a2a.mountPath} · card ${A2A_AGENT_CARD_PATH}`,\n });\n // Listed in full, as are ACP's and AP2's below: a count does not tell an\n // operator whether the one feature their client needs is missing\n checks.push({\n name: 'A2A unsupported',\n status: 'INFO',\n detail: A2A_UNSUPPORTED.join(', '),\n });\n }\n\n // 5c. ACP specifics, from config and the pins: the well-known document omits\n // the bearer token, the idempotency path and the operation mapping. This\n // report prints the path and the mapping, never the token.\n if (config === undefined) {\n checks.push({ name: 'ACP', status: 'WARN', detail: 'skipped: config invalid' });\n } else if (!config.protocols.acp.enabled) {\n checks.push({ name: 'ACP', status: 'INFO', detail: 'disabled' });\n } else {\n const acp = config.protocols.acp;\n checks.push({\n name: 'ACP',\n status: 'PASS',\n detail: `experimental · spec ${ACP_SPEC_VERSION} · API-Version ${ACP_API_VERSION} · service checkout · mount ${acp.mountPath} · discovery ${ACP_WELL_KNOWN_PATH}`,\n });\n\n // Whether a token is configured and its length, never the token. Config\n // refuses an empty one.\n checks.push({\n name: 'ACP auth',\n status: 'PASS',\n detail: `bearer token configured (${acp.auth.token.length} characters, not shown)`,\n });\n\n checks.push(\n storeFileCheck(\n 'ACP idempotency',\n acp.idempotency.path,\n {\n inMemory: 'replay protection is lost on every restart',\n unwritable: 'the adapter cannot claim idempotency keys',\n },\n ` (retention ${acp.idempotency.retentionHours}h)`,\n ),\n );\n checks.push(acpMappingCheck(config, acp.checkout.operations));\n\n checks.push({\n name: 'ACP unsupported',\n status: 'INFO',\n detail: ACP_UNSUPPORTED.join(', '),\n });\n }\n\n // 5d. AP2 authorization, from config and the pins. Verification keys are\n // public but still trust policy nobody asked this report to print, so only\n // issuer ids and key counts appear.\n const ap2 = config?.authorization?.ap2;\n if (config === undefined) {\n checks.push({ name: 'AP2', status: 'WARN', detail: 'skipped: config invalid' });\n } else if (ap2 === undefined || !ap2.enabled) {\n checks.push({ name: 'AP2', status: 'INFO', detail: 'disabled' });\n } else {\n checks.push({\n name: 'AP2',\n status: 'PASS',\n detail: `experimental · spec ${AP2_SPEC_VERSION} · mode ${ap2.mode} · ${AP2_CHECKOUT_MANDATE_VCT} · profile ${AP2_CHECKOUT_PROFILE} · clock skew ${ap2.clockSkewSeconds}s`,\n });\n\n // Two lists, reported separately: signing the merchant's checkout\n // documents must not read as the power to issue mandates\n checks.push({\n name: 'AP2 trust',\n status: 'PASS',\n detail: `${describeIssuers('mandate', ap2.trust.mandateIssuers)} · ${describeIssuers('checkout', ap2.trust.checkoutIssuers)}`,\n });\n\n checks.push(\n storeFileCheck('AP2 replay store', ap2.replay.path, {\n inMemory:\n 'every spent mandate is forgotten on restart, so one could authorize a second purchase',\n unwritable: 'no mandate could be recorded as spent',\n }),\n );\n\n // Resource ids, so an operator can see exactly which purchases now need a\n // mandate. An empty list means AP2 is configured and gating nothing.\n const gated = config.resources.filter((resource) =>\n resource.authorization?.required.includes('ap2'),\n );\n checks.push({\n name: 'AP2 resources',\n status: gated.length > 0 ? 'PASS' : 'WARN',\n detail:\n gated.length > 0\n ? gated.map((resource) => resource.id).join(', ')\n : 'AP2 is enabled but no resource requires it, so every purchase settles without a mandate',\n });\n\n checks.push({\n name: 'AP2 unsupported',\n status: 'INFO',\n detail: AP2_UNSUPPORTED.join(', '),\n });\n }\n\n // 6. Payments\n const x402 = config?.payments.x402;\n if (x402 === undefined || !x402.enabled) {\n checks.push({ name: 'Payments', status: 'INFO', detail: 'x402 not configured' });\n } else {\n const { mode, where, via } = describeSettlement(x402.network, x402.facilitator);\n const summary = `x402 v2 (scheme=exact) enabled - ${where}, destination=${maskMiddle(x402.payTo)}, facilitator=${via}`;\n const live = wellKnown?.ok ? extractWellKnownX402(wellKnown.body) : undefined;\n if (sameAddress(x402.asset, PLACEHOLDER_ASSET_ADDRESS)) {\n // `init` writes this placeholder, and the live cross-check below would\n // pass it, since the gateway echoes the same config. No token contract\n // exists there, so every paid call fails (closed, with no funds at\n // risk).\n checks.push({\n name: 'Payments',\n status: 'WARN',\n detail: `${summary}, but the asset is still the init placeholder ${maskMiddle(PLACEHOLDER_ASSET_ADDRESS)}. No token contract exists there, so every paid call will fail. Set payments.x402.asset (\\${X402_ASSET} is filled from .deploy/local.json, which \"npm run chain:deploy\" writes)`,\n });\n } else if (live === 'disabled') {\n // Verified, and it disagrees: the gateway runs a different configuration\n checks.push({\n name: 'Payments',\n status: 'FAIL',\n detail: `${summary}, but the gateway at ${gatewayUrl} reports x402 disabled, so it is running a different configuration`,\n });\n } else if (live === undefined) {\n // Gateway unreachable, or the document does not say: a match cannot be\n // judged either way, so INFO rather than FAIL\n checks.push({\n name: 'Payments',\n status: 'INFO',\n detail: `${summary} (gateway's live settlement config could not be verified)`,\n });\n } else {\n const mismatch = findX402Mismatch(x402, live);\n checks.push(\n mismatch === undefined\n ? { name: 'Payments', status: 'PASS', detail: summary }\n : { name: 'Payments', status: 'FAIL', detail: mismatch },\n );\n }\n if (mode === 'mainnet') {\n checks.push(mainnetSafetyCheck('Mainnet safety', 'payTo', x402.facilitator));\n }\n }\n const mpp = config?.payments.mpp;\n if (mpp === undefined || !mpp.enabled) {\n checks.push({ name: 'Payments (MPP)', status: 'INFO', detail: 'MPP not configured' });\n } else {\n const { mode, where, via } = describeSettlement(mpp.network, mpp.facilitator);\n const summary =\n `MPP ${MPP_PROFILE.intent}/${MPP_PROFILE.method}/${MPP_PROFILE.credentialType} enabled - ` +\n `${where}, asset=${MPP_PROFILE.assetSymbol} ${maskMiddle(mpp.asset)}, ` +\n `recipient=${maskMiddle(mpp.recipient)}, facilitator=${via}, ` +\n `spec ${MPP_SPEC_DRAFTS.core}@${MPP_SPEC_COMMIT.slice(0, 7)}, mppx ${MPPX_VERSION}`;\n const configured = { asset: mpp.asset, network: mpp.network, payTo: mpp.recipient };\n const live = wellKnown?.ok ? extractWellKnownX402(wellKnown.body, 'mpp') : undefined;\n if (live === 'disabled') {\n checks.push({\n name: 'Payments (MPP)',\n status: 'FAIL',\n detail: `Local config enables MPP, but ${gatewayUrl} reports it disabled`,\n });\n } else if (live === undefined) {\n checks.push({\n name: 'Payments (MPP)',\n status: 'INFO',\n detail: `${summary} (live MPP settlement config unavailable for comparison)`,\n });\n } else {\n const mismatch = findX402Mismatch(configured, live, 'recipient');\n checks.push(\n mismatch === undefined\n ? { name: 'Payments (MPP)', status: 'PASS', detail: summary }\n : { name: 'Payments (MPP)', status: 'FAIL', detail: mismatch },\n );\n }\n if (mode === 'mainnet') {\n checks.push(mainnetSafetyCheck('Mainnet safety (MPP)', 'recipient', mpp.facilitator));\n }\n }\n\n // 7. Storage\n if (config === undefined) {\n checks.push({ name: 'Storage', status: 'WARN', detail: 'skipped: config invalid' });\n } else if (\n // Diagnose without creating: createSqliteReceiptStore creates the file,\n // so opening a wrong path (a typo, or a container path read from the\n // host) would leave an empty database and report it healthy, hiding the\n // real one. `:memory:` never exists on disk, so it takes the open branch\n // below.\n config.storage.receipts.path !== ':memory:' &&\n !existsSync(config.storage.receipts.path)\n ) {\n checks.push({\n name: 'Storage',\n status: 'WARN',\n detail:\n `${missingStoreDetail(config.storage.receipts.path)}. If the gateway is ` +\n 'already running, this path does not match the one it uses.',\n });\n } else {\n let store: ReceiptStore | undefined;\n try {\n store = createStore(config.storage.receipts.path);\n await store.init();\n const storeHealth = await store.health();\n let receiptCount: number | undefined;\n try {\n // Exact count, not a list length: listReceipts clamps every page\n receiptCount = await store.countReceipts();\n } catch {\n receiptCount = undefined;\n }\n let undeliveredCount: number | undefined;\n try {\n // Paid but undelivered purchases (see\n // `ReceiptStore.countUndeliveredReceipts`), the rows the dashboard\n // flags as \"Charged but not delivered\"\n undeliveredCount = await store.countUndeliveredReceipts();\n } catch {\n undeliveredCount = undefined;\n }\n const status: CheckStatus =\n storeHealth.status === 'pass' ? 'PASS' : storeHealth.status === 'warn' ? 'WARN' : 'FAIL';\n const receiptsSuffix =\n receiptCount !== undefined\n ? `; receipts=${receiptCount}${undeliveredCount !== undefined && undeliveredCount > 0 ? ` (${undeliveredCount} undelivered)` : ''}`\n : '';\n checks.push({\n name: 'Storage',\n status,\n detail: `${storeHealth.detail ?? 'sqlite'}${receiptsSuffix}`,\n });\n } catch (err) {\n checks.push({\n name: 'Storage',\n status: 'FAIL',\n detail: err instanceof Error ? err.message : String(err),\n });\n } finally {\n await store?.close();\n }\n }\n\n // 8. Protocol versions\n if (wellKnown?.ok) {\n checks.push({\n name: 'Protocol versions',\n status: 'PASS',\n detail: 'reported by gateway /.well-known/agent-commerce',\n });\n } else {\n const local = readVersionReport();\n checks.push({\n name: 'Protocol versions',\n status: 'INFO',\n detail: `gateway unreachable; local pins: ${local.pinned.map((p) => `${p.name}@${p.version}`).join(', ')}`,\n });\n }\n\n const scored = checks.filter((c) => c.status !== 'INFO');\n const passed = scored.filter((c) => c.status === 'PASS').length;\n const exitCode = checks.some((c) => c.status === 'FAIL') ? 1 : 0;\n\n return { checks, score: { passed, total: scored.length }, exitCode };\n}\n\nfunction statusColor(status: CheckStatus, text: string): string {\n switch (status) {\n case 'PASS':\n return picocolors.green(text);\n case 'WARN':\n return picocolors.yellow(text);\n case 'FAIL':\n return picocolors.red(text);\n case 'INFO':\n return picocolors.cyan(text);\n }\n}\n\nexport function printDoctorReport(report: DoctorReport, io: Io, json: boolean): void {\n if (json) {\n io.stdout(JSON.stringify(report, null, 2));\n return;\n }\n for (const check of report.checks) {\n const label = statusColor(check.status, check.status.padEnd(5));\n io.stdout(`${label} ${check.name.padEnd(20)} ${check.detail}`);\n }\n io.stdout('');\n io.stdout(`Score: ${report.score.passed}/${report.score.total} checks passed`);\n}\n","/**\n * Adapter self-description.\n *\n * Imports nothing but core types and the pins, so `doctor` can report AP2\n * without pulling `jose` or `@sd-jwt/core` into the CLI bundle.\n */\nimport type { AdapterDescriptor } from '../../core';\nimport {\n AP2_CHECKOUT_MANDATE_VCT,\n AP2_CHECKOUT_PROFILE,\n AP2_DIGEST_ALGORITHM,\n AP2_SIGNING_ALGORITHM,\n AP2_SPEC_VERSION,\n} from './constants';\n\n/** What this provider actually verifies */\nexport const AP2_CAPABILITIES: readonly string[] = [\n 'direct-mode',\n AP2_CHECKOUT_MANDATE_VCT,\n 'sd-jwt-presentation',\n AP2_SIGNING_ALGORITHM,\n AP2_DIGEST_ALGORITHM,\n 'static-inline-trust',\n 'merchant-checkout-jwt-binding',\n AP2_CHECKOUT_PROFILE,\n 'purchase-binding',\n 'replay-defence',\n];\n\n/**\n * Major AP2 features this provider does not support, published in its\n * descriptor and printed by `doctor`, so no client assumes full protocol\n * support\n */\nexport const AP2_UNSUPPORTED: readonly string[] = [\n // Mandate kinds. Open mandates are refused: see AP2_CHECKOUT_MANDATE_VCT\n 'autonomous mode',\n 'open checkout mandates (mandate.checkout.open.1)',\n 'intent mandates',\n 'cart mandates',\n 'spending constraint evaluation',\n 'cnf-bound agent keys',\n // Key handling. Every key is written into config by an operator\n 'JWKS and any key discovery by URL (jku, x5u)',\n 'issuer metadata fetching',\n 'key rotation without a config change',\n // Algorithms\n 'signature algorithms other than ES256',\n 'digest algorithms other than sha-256',\n // Roles this gateway does not play\n 'mandate issuance',\n 'AP2 over the ACP checkout adapter',\n];\n\nexport function buildAp2Descriptor(implementationVersion: string): AdapterDescriptor {\n return {\n name: 'ap2',\n kind: 'authorization',\n implementationVersion,\n supportedSpec: `ap2/v${AP2_SPEC_VERSION} mode=direct`,\n capabilities: AP2_CAPABILITIES,\n status: 'experimental',\n unsupported: AP2_UNSUPPORTED,\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 * 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 * 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 * 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","/**\n * The package version, resolved once for the whole package.\n *\n * The build injects `__OAC_PACKAGE_VERSION__` (tsup.config.ts), because a\n * relative manifest path resolves from the wrong depth once `src/**` is\n * bundled. From source, the root manifest is read instead. `typeof` on an\n * undeclared identifier is safe, so the source path runs without the constant.\n */\nimport { createRequire } from 'node:module';\n\ndeclare const __OAC_PACKAGE_VERSION__: string | undefined;\n\nfunction readFromManifest(): string {\n try {\n const require = createRequire(import.meta.url);\n // src/version.ts -> repository root\n return (require('../package.json') as { version?: string }).version ?? '0.0.0-unknown';\n } catch {\n return '0.0.0-unknown';\n }\n}\n\nexport const PACKAGE_VERSION: string =\n typeof __OAC_PACKAGE_VERSION__ === 'string' ? __OAC_PACKAGE_VERSION__ : readFromManifest();\n","/**\n * Opens a SQLite file with owner-only permissions. Every store that keeps a\n * SQLite file opens it here, so the hardening below exists once: the file is\n * pre-created at 0600, the WAL sidecars are narrowed once WAL creates them, and\n * an existing but unwritable file fails at startup.\n *\n * Callers own their schema; this function migrates nothing.\n */\nimport {\n accessSync,\n chmodSync,\n closeSync,\n existsSync,\n constants as fsConstants,\n mkdirSync,\n openSync,\n} from 'node:fs';\nimport { dirname } from 'node:path';\nimport Database from 'better-sqlite3';\nimport { CommerceError, type Logger } from '../core';\n\nexport interface OpenSqliteOptions {\n /** File path, or ':memory:' for tests. Parent directory is created if missing */\n readonly path: string;\n /** Names the database in operator-facing errors, e.g. \"Receipt database\" */\n readonly label: string;\n readonly logger: Logger;\n}\n\nexport function openSqliteDatabase(options: OpenSqliteOptions): Database.Database {\n const { path, label, logger } = options;\n const isFileBacked = path !== ':memory:';\n\n if (isFileBacked) {\n // 0700 on a directory this creates. A recursive mkdir leaves an existing\n // one, the operator's, with its mode.\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n }\n\n // Check write access at startup. SQLite can open a read-only database and\n // report the problem only when the first write is attempted.\n if (isFileBacked && existsSync(path)) {\n try {\n accessSync(path, fsConstants.W_OK);\n } catch {\n throw new CommerceError(\n 'STORAGE_ERROR',\n `${label} \"${path}\" exists but is not writable by this process (uid ${typeof process.getuid === 'function' ? process.getuid() : 'unknown'}). If this is a container that recently changed user, an existing volume may still be owned by the previous one - recreate it (docker compose down -v) or fix its ownership.`,\n { details: { path } },\n );\n }\n }\n\n // Create the file at 0600 before SQLite creates it at 0644 (less the umask).\n // A chmod afterwards is too late: a local user who opens the file in between\n // keeps a readable descriptor across the chmod. SQLite copies the main file's\n // mode onto the -wal/-shm sidecars, so this covers all three. `mode` applies\n // on creation only; an existing file is left to the chmod below.\n if (isFileBacked) {\n try {\n closeSync(openSync(path, 'a', 0o600));\n } catch {\n // Silent on purpose: `new Database` reports the same cause with a better\n // message, or the failure is harmless and the chmod below covers it\n }\n }\n\n const db = new Database(path);\n db.pragma('journal_mode = WAL');\n db.pragma('foreign_keys = ON');\n if (isFileBacked) restrictDatabasePermissions(path, label, logger);\n return db;\n}\n\n/**\n * Narrows the database and its WAL sidecars to owner-only. The receipt ledger\n * holds no key material, but it does hold payer and payee addresses, amounts,\n * settlement hashes, replay keys and the commerce event log.\n *\n * Runs after `journal_mode = WAL`, which creates the sidecars, and also\n * tightens a database that already existed with a looser mode. A failure only\n * warns: a filesystem without POSIX modes must not stop the gateway starting.\n */\nfunction restrictDatabasePermissions(path: string, label: string, logger: Logger): void {\n for (const file of [path, `${path}-wal`, `${path}-shm`]) {\n try {\n chmodSync(file, 0o600);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') continue;\n logger.warn(\n { file, label, error: code ?? 'unknown' },\n 'could not restrict database permissions to owner-only',\n );\n }\n }\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 * Imports `src/config` on demand, so a module that fails to load breaks only\n * the commands that read config, not `version` or `--help`. Validate, doctor\n * and init accept an injected loader for tests that do not read the filesystem.\n */\nimport type { GatewayConfig as GatewayConfigType } from '../../config';\nimport { CommerceError } from '../../core';\n\nexport type GatewayConfig = GatewayConfigType;\n\nexport interface LoadConfigOptions {\n readonly path?: string;\n readonly env?: NodeJS.ProcessEnv;\n readonly cwd?: string;\n}\n\nexport type ConfigLoader = (options?: LoadConfigOptions) => Promise<GatewayConfig>;\n\n/** Validates an already-built raw config object, without touching the disk */\nexport type ConfigParser = (raw: unknown, env?: NodeJS.ProcessEnv) => Promise<GatewayConfig>;\n\nasync function importConfig(): Promise<typeof import('../../config')> {\n try {\n return await import('../../config');\n } catch (err) {\n throw new CommerceError(\n 'INTERNAL_ERROR',\n `the configuration module could not be loaded: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\nexport async function loadConfigDynamic(options: LoadConfigOptions = {}): Promise<GatewayConfig> {\n return (await importConfig()).loadConfig(options);\n}\n\n/** Validates a raw config object in memory; `init` uses it to validate before writing */\nexport async function parseConfigDynamic(\n raw: unknown,\n env: NodeJS.ProcessEnv = process.env,\n): Promise<GatewayConfig> {\n return (await importConfig()).parseConfig(raw, env);\n}\n","/**\n * Fetch with a timeout, for `doctor`. `fetchImpl` is injected so tests can\n * pass a fake `fetch` and never touch the network.\n */\nexport type FetchLike = typeof fetch;\n\nexport interface FetchJsonResult<T> {\n readonly ok: boolean;\n readonly status: number;\n readonly body?: T;\n readonly error?: string;\n}\n\nexport async function fetchJson<T = unknown>(\n fetchImpl: FetchLike,\n url: string,\n timeoutMs = 1500,\n): Promise<FetchJsonResult<T>> {\n try {\n // The signal also bounds the body read below\n const res = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs) });\n let body: T | undefined;\n try {\n body = (await res.json()) as T;\n } catch {\n body = undefined;\n }\n return { ok: res.ok, status: res.status, ...(body !== undefined ? { body } : {}) };\n } catch (err) {\n return {\n ok: false,\n status: 0,\n error: err instanceof Error ? err.message : 'unknown fetch error',\n };\n }\n}\n","/**\n * Renders the `config.yaml` that `agent-commerce init` writes, with no prompts or IO.\n *\n * The output is the raw document `parseConfig` accepts (`resources` keyed by\n * id, with `backend`/`expose`/`payments`/`input`/`output`), not the normalized\n * `CommerceResource` shape (`handler`/`exposedVia`/`paymentMethods`/...) that\n * `loadConfig()` returns.\n *\n * The facilitator key and merchant address are Anvil's public dev accounts #0\n * and #1. Never fund them. They come from `ANVIL_WELL_KNOWN_ACCOUNTS`, the list\n * the local deploy engine and the dev-key guard also read, because a\n * hand-copied or truncated literal breaks every paid request and slips past\n * the guard. The MockUSDC `asset` is a labeled placeholder: its address exists\n * only once `npm run chain:deploy` writes `.deploy/local.json`, and config\n * rejects the zero address.\n */\n\nimport { stringify } from 'yaml';\n// Narrow module, not the `testing.ts` barrel: see manifest-env.ts\nimport { ANVIL_WELL_KNOWN_ACCOUNTS } from '../../payments/x402/local-chain/accounts';\n\n/** Anvil account #1: the merchant settlement destination, never the facilitator */\nexport const LOCAL_DEV_MERCHANT_ADDRESS = ANVIL_WELL_KNOWN_ACCOUNTS[1].address;\n/** Anvil account #0: the local facilitator signer, which settles on the dev chain only */\nexport const LOCAL_DEV_FACILITATOR_PRIVATE_KEY = ANVIL_WELL_KNOWN_ACCOUNTS[0].privateKey;\n/** Placeholder only - replace with the MockUSDC address from `.deploy/local.json` */\nexport const PLACEHOLDER_ASSET_ADDRESS = '0x000000000000000000000000000000000000dEaD';\n\nexport type InitResourceChoice = 'weather' | 'report';\nexport type InitProtocolChoice = 'http' | 'mcp';\n\nexport interface InitAnswers {\n readonly backendBaseUrl: string;\n readonly resources: readonly InitResourceChoice[];\n readonly protocols: readonly InitProtocolChoice[];\n readonly x402Enabled: boolean;\n readonly merchantPayTo: string;\n}\n\nexport function defaultInitAnswers(): InitAnswers {\n return {\n backendBaseUrl: 'http://localhost:3000',\n resources: ['weather', 'report'],\n protocols: ['http', 'mcp'],\n x402Enabled: true,\n merchantPayTo: LOCAL_DEV_MERCHANT_ADDRESS,\n };\n}\n\nfunction buildResourcesMap(answers: InitAnswers): Record<string, unknown> {\n const resources: Record<string, unknown> = {};\n const expose = [...answers.protocols];\n\n if (answers.resources.includes('weather')) {\n resources.weather = {\n name: 'Get weather',\n description: 'Deterministic demo weather lookup (free resource).',\n input: {\n type: 'object',\n properties: { city: { type: 'string' } },\n required: ['city'],\n additionalProperties: false,\n },\n backend: {\n type: 'http',\n method: 'GET',\n url: `${answers.backendBaseUrl}/api/weather/{city}`,\n },\n pricing: { type: 'free' },\n expose,\n };\n }\n\n if (answers.resources.includes('report')) {\n const paid = answers.x402Enabled;\n resources.report = {\n name: 'Get market report',\n description: 'Deterministic demo premium market report.',\n // No caller-supplied fields. Config loads a missing `input` as this same\n // closed schema; writing it out shows that in the generated file\n input: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n backend: {\n type: 'http',\n method: 'GET',\n url: `${answers.backendBaseUrl}/api/report`,\n },\n pricing: paid ? { type: 'fixed', amount: '0.01', currency: 'USDC' } : { type: 'free' },\n expose,\n ...(paid ? { payments: ['x402'] } : {}),\n };\n }\n\n return resources;\n}\n\n/** Builds the raw config object accepted by `parseConfig` (src/config) */\nexport function buildInitConfigObject(answers: InitAnswers): Record<string, unknown> {\n return {\n version: 1,\n merchant: {\n id: 'demo-merchant',\n name: 'Demo Merchant',\n publicBaseUrl: 'http://localhost:8080',\n },\n server: { port: 8080, host: '127.0.0.1' },\n storage: { receipts: { driver: 'sqlite', path: './data/receipts.db' } },\n protocols: {\n http: { enabled: answers.protocols.includes('http') },\n mcp: { enabled: answers.protocols.includes('mcp'), mountPath: '/mcp' },\n },\n resources: buildResourcesMap(answers),\n payments: answers.x402Enabled\n ? {\n x402: {\n enabled: true,\n network: 'eip155:84532',\n rpcUrl: 'http://127.0.0.1:8545',\n asset: PLACEHOLDER_ASSET_ADDRESS,\n assetName: 'MockUSDC',\n assetVersion: '2',\n assetDecimals: 6,\n payTo: answers.merchantPayTo,\n maxTimeoutSeconds: 60,\n facilitator: { mode: 'local', signerPrivateKey: LOCAL_DEV_FACILITATOR_PRIVATE_KEY },\n },\n }\n : {},\n };\n}\n\nconst HEADER = `# Generated by \\`agent-commerce init\\`.\n#\n# With x402 enabled, the facilitator signerPrivateKey is Anvil's public dev\n# account #0 and the default payTo is account #1.\n# LOCAL DEVELOPMENT ONLY - DO NOT FUND: never use them outside a local chain.\n# payments.x402.asset is a placeholder, not a real contract. Before running\n# against the local chain, run \\`npm run chain:deploy\\` and set it to the\n# MockUSDC address in \\`.deploy/local.json\\`. Before pointing this at a funded\n# network, set \\`payments.x402.payTo\\` to your own settlement address.\n#\n# server.host is loopback (127.0.0.1): binding every interface should be a\n# deliberate edit.\n#\n# server.adminToken and server.allowedOrigins are left unset, so no secret\n# lands in a file you might commit. Without a token the operator routes\n# (/api/receipts, /api/events) return 404. They serve the merchant's commerce\n# ledger: payer addresses, amounts and settlement hashes. To enable them, add\n# these keys to the server block below:\n# server:\n# adminToken: \\${ADMIN_TOKEN}\n# allowedOrigins:\n# - http://localhost:5173\n# See SECURITY.md before exposing this gateway beyond localhost.\n`;\n\nexport function renderInitConfigYaml(answers: InitAnswers): string {\n const body = stringify(buildInitConfigObject(answers), { indent: 2 });\n return `${HEADER}\\n${body}`;\n}\n","/**\n * The `.deploy/local.json` deployment manifest, whose shape docs/contracts.md\n * documents. The demo and CLI read the local MockUSDC address through\n * `readLocalChainManifest()` instead of hard-coding it.\n *\n * Imports no optional peer (zod is a regular dependency), so the CLI can load it.\n */\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { z } from 'zod';\nimport { CommerceError } from '../../../core';\n\nexport const LOCAL_CHAIN_MANIFEST_PATH = '.deploy/local.json';\n\nexport interface LocalChainManifestMerchant {\n readonly address: string;\n readonly privateKeyLabel: string;\n}\n\nexport interface LocalChainManifestKeyedAccount {\n readonly address: string;\n readonly privateKey: string;\n readonly note: string;\n}\n\nexport interface LocalChainManifest {\n readonly chainId: number;\n readonly rpcUrl: string;\n /**\n * The same chain as reached from the host. It differs from `rpcUrl` only when\n * the deployer ran inside Docker, where `rpcUrl` is a container address such\n * as \"http://anvil:8545\". Host-side consumers use `hostRpcUrl ?? rpcUrl`.\n * Optional so older manifests still parse.\n */\n readonly hostRpcUrl?: string;\n readonly asset: string;\n readonly assetName: string;\n readonly assetVersion: string;\n readonly assetDecimals: number;\n readonly merchant: LocalChainManifestMerchant;\n readonly buyer: LocalChainManifestKeyedAccount;\n readonly facilitator: LocalChainManifestKeyedAccount;\n readonly buyerInitialBalance: string;\n}\n\nconst nonEmpty = z.string().min(1, 'must be a non-empty string');\nconst keyedAccount = z.object({ address: z.string(), privateKey: z.string(), note: z.string() });\n\nconst MANIFEST_SCHEMA = z.object({\n chainId: z.number(),\n rpcUrl: nonEmpty,\n hostRpcUrl: nonEmpty.optional(),\n asset: nonEmpty,\n assetName: nonEmpty,\n assetVersion: nonEmpty,\n assetDecimals: z.number(),\n merchant: z.object({ address: z.string(), privateKeyLabel: z.string() }),\n buyer: keyedAccount,\n facilitator: keyedAccount,\n buyerInitialBalance: nonEmpty,\n});\n\n/**\n * Reads and structurally validates `.deploy/local.json`. Throws an actionable\n * error if it is missing or malformed, and no caller falls back to a\n * hard-coded address.\n */\nexport function readLocalChainManifest(cwd: string = process.cwd()): LocalChainManifest {\n const path = join(cwd, LOCAL_CHAIN_MANIFEST_PATH);\n\n if (!existsSync(path)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Local chain manifest not found at \"${path}\". Run \"npm run chain:start\" then \"npm run chain:deploy\" first.`,\n );\n }\n\n let raw: string;\n try {\n raw = readFileSync(path, 'utf8');\n } catch (cause) {\n throw new CommerceError('CONFIG_INVALID', `Could not read local chain manifest at \"${path}\".`, {\n cause,\n });\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (cause) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Local chain manifest at \"${path}\" is not valid JSON. Re-run \"npm run chain:deploy\" to regenerate it.`,\n { cause },\n );\n }\n\n const result = MANIFEST_SCHEMA.safeParse(parsed);\n if (!result.success) {\n const issue = result.error.issues[0];\n const where = issue?.path.length ? `${issue.path.join('.')}: ` : '';\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Local chain manifest at \"${path}\" is invalid: ${where}${issue?.message ?? 'unexpected shape'}. ` +\n 'Re-run \"npm run chain:deploy\".',\n );\n }\n return result.data as LocalChainManifest;\n}\n","/**\n * Local development: fills the `X402_*` and `MERCHANT_WALLET` placeholders in\n * `config.yaml` from `.deploy/local.json` (written by `npm run chain:deploy`)\n * when the shell has not set them.\n *\n * Inside `docker compose`, `docker/gateway-entrypoint.sh` exports these from\n * the manifest before the gateway starts. Host-side `validate` and `doctor`\n * have no such step, so without this the config that starts the container\n * fails on the host with \"Unresolved environment variable\". See\n * docs/contracts.md, \"Local chain deployment manifest\".\n *\n * Only unset variables are filled, so a real environment always wins, and only\n * `validate` and `doctor` call this: the config loader and gateway startup\n * never do.\n */\n// The narrow module, not the `testing.ts` barrel: the barrel also re-exports\n// the deploy engine, which imports `viem`, an optional peer.\n// esbuild keeps a bare `import 'viem'` even when the bindings are tree-shaken,\n// and the CLI would then refuse to start on a default install.\nimport {\n LOCAL_CHAIN_MANIFEST_PATH,\n type LocalChainManifest,\n readLocalChainManifest,\n} from '../../payments/x402/local-chain/manifest';\n\nexport { LOCAL_CHAIN_MANIFEST_PATH };\n\n// `config.yaml` placeholder name -> the manifest field it fills\nconst MANIFEST_ENV_VARS: readonly (readonly [string, (m: LocalChainManifest) => string])[] = [\n ['X402_ASSET', (m) => m.asset],\n ['X402_ASSET_NAME', (m) => m.assetName],\n ['X402_ASSET_VERSION', (m) => m.assetVersion],\n ['X402_ASSET_DECIMALS', (m) => String(m.assetDecimals)],\n ['MERCHANT_WALLET', (m) => m.merchant.address],\n ['X402_FACILITATOR_PRIVATE_KEY', (m) => m.facilitator.privateKey],\n];\n\n/** Names of the variables this module can fill, for matching an unresolved variable */\nexport const MANIFEST_FILLABLE_ENV_VAR_NAMES: ReadonlySet<string> = new Set(\n MANIFEST_ENV_VARS.map(([name]) => name),\n);\n\nexport interface ManifestEnvFill {\n /** `baseEnv` plus any filled variables. `baseEnv` itself is never mutated */\n readonly env: NodeJS.ProcessEnv;\n /** Names actually filled - empty when the manifest was absent or invalid, or nothing needed filling */\n readonly filled: readonly string[];\n /** True when a valid manifest was read, whether or not anything needed filling */\n readonly manifestFound: boolean;\n}\n\n/**\n * Reads `.deploy/local.json` under `cwd` and fills the unset variables in\n * {@link MANIFEST_ENV_VARS}. Never throws: with a missing or invalid manifest\n * nothing is filled, and `src/config` reports the unresolved variable as usual.\n */\nexport function fillEnvFromLocalChainManifest(\n baseEnv: NodeJS.ProcessEnv,\n cwd: string = process.cwd(),\n): ManifestEnvFill {\n let manifest: LocalChainManifest;\n try {\n manifest = readLocalChainManifest(cwd);\n } catch {\n return { env: baseEnv, filled: [], manifestFound: false };\n }\n\n const filled: string[] = [];\n const env: NodeJS.ProcessEnv = { ...baseEnv };\n for (const [name, read] of MANIFEST_ENV_VARS) {\n if (env[name] === undefined) {\n env[name] = read(manifest);\n filled.push(name);\n }\n }\n return { env, filled, manifestFound: true };\n}\n","/**\n * Shortens an address for `doctor` output: enough to eyeball, never the whole\n * value. A value too short to shorten (`length <= keep * 2`) is masked\n * entirely rather than printed whole, so a short secret passed here does not\n * leak.\n */\nexport function maskMiddle(value: string, keep = 6): string {\n if (value.length <= keep * 2) return value.length === 0 ? value : '…';\n return `${value.slice(0, keep)}…${value.slice(-4)}`;\n}\n","{\n \"name\": \"@devlab.group/agent-commerce\",\n \"version\": \"1.6.1\",\n \"description\": \"Open-source, self-hosted, non-custodial commerce and payment orchestration gateway for AI agents.\",\n \"license\": \"Apache-2.0\",\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=22\",\n \"npm\": \">=10\"\n },\n \"bin\": {\n \"agent-commerce\": \"dist/cli/index.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\"\n },\n \"./ap2\": {\n \"types\": \"./dist/ap2.d.ts\",\n \"import\": \"./dist/ap2.js\"\n },\n \"./mcp\": {\n \"types\": \"./dist/mcp.d.ts\",\n \"import\": \"./dist/mcp.js\"\n },\n \"./mpp\": {\n \"types\": \"./dist/mpp.d.ts\",\n \"import\": \"./dist/mpp.js\"\n },\n \"./x402\": {\n \"types\": \"./dist/x402.d.ts\",\n \"import\": \"./dist/x402.js\"\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\",\n \"README.md\",\n \"LICENSE\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/devlab-group/agent-commerce.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/devlab-group/agent-commerce/issues\"\n },\n \"homepage\": \"https://github.com/devlab-group/agent-commerce#readme\",\n \"keywords\": [\n \"ai-agents\",\n \"agentic-commerce\",\n \"mcp\",\n \"model-context-protocol\",\n \"x402\",\n \"payments\",\n \"web3\",\n \"commerce\",\n \"ai\",\n \"cli\",\n \"a2a\",\n \"agent-to-agent\",\n \"acp\",\n \"agent-commerce-protocol\",\n \"ap2\",\n \"agent-payment-protocol\",\n \"mpp\",\n \"machine-payments-protocol\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"prepack\": \"npm run build\",\n \"prepublishOnly\": \"npm run build && npm run verify && npm run test:cli:dist\",\n \"typecheck\": \"tsc --noEmit -p tsconfig.json && tsc --noEmit -p demo/dashboard/tsconfig.json\",\n \"lint\": \"biome check .\",\n \"lint:fix\": \"biome check --write .\",\n \"format\": \"biome format --write .\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\",\n \"test:e2e\": \"vitest run --config vitest.e2e.config.ts\",\n \"test:testnet\": \"vitest run --config vitest.testnet.config.ts\",\n \"test:mainnet\": \"vitest run --config vitest.mainnet.config.ts\",\n \"check:contract\": \"node scripts/contract-surface.mjs\",\n \"check:metadata\": \"node scripts/check-package-metadata.mjs\",\n \"verify\": \"npm run check:contract && npm run lint && npm run typecheck && npm test\",\n \"agent-commerce\": \"tsx src/cli/index.ts\",\n \"doctor\": \"tsx src/cli/index.ts doctor\",\n \"chain:start\": \"tsx scripts/chain/start-anvil.ts\",\n \"chain:deploy\": \"tsx scripts/chain/deploy.ts\",\n \"demo:merchant\": \"tsx demo/merchant/src/main.ts\",\n \"dev:merchant\": \"tsx watch demo/merchant/src/main.ts\",\n \"demo:gateway\": \"AGENT_COMMERCE_CONFIG=${AGENT_COMMERCE_CONFIG:-config-demo.yaml} tsx src/gateway/main.ts\",\n \"dev:gateway\": \"AGENT_COMMERCE_CONFIG=${AGENT_COMMERCE_CONFIG:-config-demo.yaml} tsx watch src/gateway/main.ts\",\n \"demo:dashboard\": \"vite --config demo/dashboard/vite.config.ts\",\n \"dev:dashboard\": \"vite --config demo/dashboard/vite.config.ts\",\n \"demo:agent\": \"tsx demo/agent/src/main.ts\",\n \"demo:up\": \"docker compose up --build\",\n \"demo:down\": \"docker compose down -v\",\n \"test:cli:dist\": \"node dist/cli/index.js --help && node dist/cli/index.js --version && node dist/cli/index.js version | grep -q '@x402/core' && node dist/cli/index.js version | head -1 >/dev/null && node dist/cli/index.js import openapi --help >/dev/null\",\n \"pack:dry\": \"npm pack --dry-run\"\n },\n \"dependencies\": {\n \"@clack/prompts\": \"1.7.0\",\n \"@scalar/openapi-parser\": \"0.29.0\",\n \"ajv\": \"8.20.0\",\n \"ajv-formats\": \"3.0.1\",\n \"better-sqlite3\": \"13.0.3\",\n \"commander\": \"15.0.0\",\n \"fastify\": \"5.12.5\",\n \"picocolors\": \"1.1.1\",\n \"pino\": \"10.3.1\",\n \"yaml\": \"2.9.0\",\n \"zod\": \"3.25.76\"\n },\n \"peerDependencies\": {\n \"@coinbase/x402\": \"2.1.0\",\n \"@modelcontextprotocol/sdk\": \"1.30.0\",\n \"@sd-jwt/core\": \"0.20.1\",\n \"@x402/core\": \"2.23.0\",\n \"@x402/evm\": \"2.23.0\",\n \"canonicalize\": \"5.0.0\",\n \"jose\": \"6.2.12\",\n \"mppx\": \"0.10.1\",\n \"viem\": \"2.55.18\"\n },\n \"peerDependenciesMeta\": {\n \"@coinbase/x402\": {\n \"optional\": true\n },\n \"@modelcontextprotocol/sdk\": {\n \"optional\": true\n },\n \"@sd-jwt/core\": {\n \"optional\": true\n },\n \"@x402/core\": {\n \"optional\": true\n },\n \"@x402/evm\": {\n \"optional\": true\n },\n \"canonicalize\": {\n \"optional\": true\n },\n \"jose\": {\n \"optional\": true\n },\n \"mppx\": {\n \"optional\": true\n },\n \"viem\": {\n \"optional\": true\n }\n },\n \"devDependencies\": {\n \"@a2a-js/sdk\": \"1.1.0\",\n \"@biomejs/biome\": \"2.5.9\",\n \"@coinbase/x402\": \"2.1.0\",\n \"@modelcontextprotocol/sdk\": \"1.30.0\",\n \"@sd-jwt/core\": \"0.20.1\",\n \"@types/better-sqlite3\": \"9.6.0\",\n \"@types/node\": \"24.13.3\",\n \"@types/react\": \"19.2.18\",\n \"@types/react-dom\": \"19.2.4\",\n \"@vitejs/plugin-react\": \"6.0.5\",\n \"@vitest/coverage-v8\": \"4.1.11\",\n \"@x402/core\": \"2.23.0\",\n \"@x402/evm\": \"2.23.0\",\n \"canonicalize\": \"5.0.0\",\n \"jose\": \"6.2.12\",\n \"mppx\": \"0.10.1\",\n \"pino-pretty\": \"13.1.2\",\n \"react\": \"19.0.8\",\n \"react-dom\": \"19.0.8\",\n \"tsup\": \"8.5.1\",\n \"tsx\": \"4.23.12\",\n \"typescript\": \"5.9.3\",\n \"viem\": \"2.55.18\",\n \"vite\": \"8.2.1\",\n \"vitest\": \"4.1.11\"\n },\n \"overrides\": {\n \"@coinbase/x402\": {\n \"zod\": \"3.25.76\",\n \"@coinbase/cdp-sdk\": \"1.55.0\",\n \"axios\": \"1.20.0\"\n },\n \"@sd-jwt/core\": {\n \"@owf/identity-common\": \"0.3.2\"\n },\n \"@x402/core\": {\n \"zod\": \"3.25.76\"\n },\n \"@x402/evm\": {\n \"zod\": \"3.25.76\"\n }\n }\n}\n","/**\n * The CLI version (`PACKAGE_VERSION`) and the pinned protocol/SDK versions.\n * The pins come from a static JSON import of package.json, which tsup inlines,\n * so the bundle never reads the manifest by relative path.\n */\nimport manifest from '../../../package.json' with { type: 'json' };\nimport { PACKAGE_VERSION } from '../../version';\n\nexport interface PinnedVersion {\n readonly name: string;\n readonly version: string;\n readonly via: string;\n}\n\nexport interface VersionReport {\n readonly cliVersion: string;\n readonly pinned: readonly PinnedVersion[];\n}\n\n// The protocol/SDK pins (the A2A SDK is test-only, so it is not listed), each\n// with the main src/ directory that uses it\nconst PINS: readonly (readonly [name: string, via: string])[] = [\n ['@modelcontextprotocol/sdk', 'protocols/mcp'],\n ['ajv', 'protocols/acp'],\n ['ajv-formats', 'protocols/acp'],\n ['@x402/core', 'payments/x402'],\n ['@x402/evm', 'payments/x402'],\n ['@coinbase/x402', 'payments/x402'],\n ['viem', 'payments/x402'],\n ['mppx', 'payments/mpp'],\n ['jose', 'authorization/ap2'],\n ['@sd-jwt/core', 'authorization/ap2'],\n ['canonicalize', 'authorization/ap2'],\n ['@scalar/openapi-parser', 'openapi'],\n ['zod', 'config'],\n ['fastify', 'gateway'],\n ['pino', 'gateway'],\n ['better-sqlite3', 'storage'],\n];\n\n/** Pins missing from the manifest are left out rather than shown as \"unknown\" */\nexport function readVersionReport(): VersionReport {\n // Optional peers count as pins; a package in both lists reports its dependency\n const declared: Readonly<Record<string, string | undefined>> = {\n ...manifest.peerDependencies,\n ...manifest.dependencies,\n };\n const pinned = PINS.flatMap(([name, via]) => {\n const version = declared[name];\n return version === undefined ? [] : [{ name, version, via }];\n });\n return { cliVersion: PACKAGE_VERSION, pinned };\n}\n","/**\n * `agent-commerce import openapi <source>`.\n *\n * Generates reviewable resource drafts from a local OpenAPI description. It\n * never merges them into gateway config or invents commerce policy;\n * `--output config.yaml --force` replaces that file rather than merging.\n */\nimport { existsSync } from 'node:fs';\nimport { rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, extname, resolve } from 'node:path';\nimport { PROTOCOL_NAMES } from '../../core';\nimport {\n buildResourceDrafts,\n type ImportPolicy,\n type ImportResult,\n loadOpenApiDocument,\n renderResourcesYaml,\n} from '../../openapi';\nimport type { Io } from '../lib/io';\n\nexport interface ImportOpenApiOptions {\n readonly source: string;\n readonly output?: string;\n readonly force?: boolean;\n readonly baseUrl?: string;\n readonly operations?: readonly string[];\n readonly tags?: readonly string[];\n readonly free?: boolean;\n readonly expose?: string;\n readonly strict?: boolean;\n readonly json?: boolean;\n}\n\nexport interface ImportOpenApiDeps {\n readonly fileExists?: (path: string) => boolean;\n readonly writeFile?: (path: string, content: string) => Promise<void>;\n}\n\n/** `<source name without extension>.agent-commerce.yaml`, in the working directory */\nexport function defaultOutputPath(source: string): string {\n const name = basename(source);\n const stem = name.slice(0, name.length - extname(name).length) || name;\n return `${stem}.agent-commerce.yaml`;\n}\n\nexport async function runImportOpenApi(\n options: ImportOpenApiOptions,\n io: Io,\n deps: ImportOpenApiDeps = {},\n): Promise<number> {\n const fileExists = deps.fileExists ?? existsSync;\n const outputPath = options.output ?? defaultOutputPath(options.source);\n\n const policy = buildPolicy(options);\n if (typeof policy === 'string') {\n io.stderr(`FAIL ${policy}`);\n return 1;\n }\n\n // Checked before the import runs: an existing file the operator did not ask\n // to replace is a stop\n if (fileExists(outputPath) && options.force !== true) {\n io.stderr(`FAIL ${outputPath} already exists. Re-run with --force to overwrite.`);\n return 1;\n }\n\n let result: ImportResult;\n try {\n const loaded = await loadOpenApiDocument(options.source);\n result = buildResourceDrafts(loaded, {\n ...(options.baseUrl !== undefined ? { baseUrl: options.baseUrl } : {}),\n ...(Object.keys(policy).length > 0 ? { policy } : {}),\n ...(options.operations !== undefined || options.tags !== undefined\n ? {\n include: {\n ...(options.operations !== undefined ? { operationIds: options.operations } : {}),\n ...(options.tags !== undefined ? { tags: options.tags } : {}),\n },\n }\n : {}),\n });\n } catch (error) {\n io.stderr(`FAIL ${error instanceof Error ? error.message : String(error)}`);\n return 1;\n }\n\n const skipped = result.diagnostics.filter((entry) => entry.severity === 'error');\n const warnings = result.diagnostics.filter((entry) => entry.severity === 'warning');\n\n const failures: string[] = [];\n if (result.unmatchedOperationIds.length > 0) {\n failures.push(`no operation matched ${result.unmatchedOperationIds.join(', ')}`);\n }\n if (result.drafts.length === 0) {\n failures.push('no supported operations were imported');\n }\n if (options.strict === true && warnings.length > 0) {\n failures.push(`${warnings.length} warning(s) with --strict`);\n }\n\n // Nothing is written when the run failed: a half-useful file that the next\n // command silently picks up is worse than no file\n const wrote = failures.length === 0;\n if (wrote) {\n try {\n await writeAtomically(outputPath, renderResourcesYaml(result), deps);\n } catch (error) {\n io.stderr(`FAIL ${outputPath} could not be written: ${describe(error)}`);\n return 1;\n }\n }\n\n if (options.json === true) {\n io.stdout(\n JSON.stringify(\n {\n source: options.source,\n openapi: result.version,\n output: wrote ? outputPath : null,\n imported: result.drafts.length,\n skipped: skipped.length,\n warnings: warnings.length,\n resources: result.drafts.map((draft) => ({\n id: draft.id,\n source: draft.source,\n ...(draft.operationId !== undefined ? { operationId: draft.operationId } : {}),\n tags: draft.tags,\n })),\n diagnostics: result.diagnostics,\n unmatchedOperationIds: result.unmatchedOperationIds,\n exitCode: failures.length === 0 ? 0 : 1,\n },\n null,\n 2,\n ),\n );\n } else {\n printSummary(result, { outputPath, wrote, policy }, io);\n }\n\n for (const failure of failures) io.stderr(`FAIL ${failure}`);\n return failures.length === 0 ? 0 : 1;\n}\n\n// A usage error comes back as the message to print\nfunction buildPolicy(options: ImportOpenApiOptions): ImportPolicy | string {\n const policy: { pricing?: Record<string, unknown>; expose?: readonly string[] } = {};\n if (options.free === true) policy.pricing = { type: 'free' };\n if (options.expose !== undefined) {\n const requested = options.expose\n .split(',')\n .map((name) => name.trim())\n .filter((name) => name !== '');\n if (requested.length === 0) {\n return `--expose needs at least one protocol (${PROTOCOL_NAMES.join(', ')})`;\n }\n for (const name of requested) {\n if (!PROTOCOL_NAMES.includes(name as (typeof PROTOCOL_NAMES)[number])) {\n return `--expose \"${name}\" is not a supported protocol. Supported: ${PROTOCOL_NAMES.join(', ')}`;\n }\n }\n policy.expose = requested;\n }\n return policy;\n}\n\nasync function writeAtomically(\n outputPath: string,\n content: string,\n deps: ImportOpenApiDeps,\n): Promise<void> {\n if (deps.writeFile !== undefined) {\n await deps.writeFile(outputPath, content);\n return;\n }\n // Temp sibling then rename: a crash or a full disk must not leave a\n // half-written file where a complete one used to be\n const target = resolve(outputPath);\n const temporary = `${target}.${process.pid}.tmp`;\n try {\n await writeFile(temporary, content, 'utf8');\n await rename(temporary, target);\n } catch (error) {\n await rm(temporary, { force: true });\n throw error;\n }\n}\n\nfunction printSummary(\n result: ImportResult,\n context: { outputPath: string; wrote: boolean; policy: ImportPolicy },\n io: Io,\n): void {\n const skipped = result.diagnostics.filter((entry) => entry.severity === 'error');\n const warnings = result.diagnostics.filter((entry) => entry.severity === 'warning');\n\n io.stdout(`OpenAPI ${result.version}: ${result.sourcePath}`);\n io.stdout('');\n io.stdout(`Imported: ${result.drafts.length}`);\n io.stdout(`Skipped: ${skipped.length}`);\n io.stdout(`Warnings: ${warnings.length}`);\n\n if (skipped.length > 0) {\n io.stdout('');\n io.stdout('Skipped operations:');\n for (const entry of skipped) io.stdout(` ${entry.message}`);\n }\n if (warnings.length > 0) {\n io.stdout('');\n io.stdout('Warnings:');\n for (const entry of warnings) io.stdout(` ${entry.message}`);\n }\n\n if (context.wrote) {\n io.stdout('');\n io.stdout('Generated:');\n io.stdout(` ${context.outputPath}`);\n }\n\n io.stdout('');\n if (context.policy.pricing === undefined || context.policy.expose === undefined) {\n io.stdout('Pricing/exposure were not inferred.');\n }\n io.stdout('Review the generated resources before merging them into config.yaml.');\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Turns OpenAPI path operations into a deterministic list of candidates.\n *\n * Determinism is the point: a resource id is what an agent discovers and\n * hard-codes, so it must depend only on the document, never on iteration order\n * or on how many times the importer has run. Anything ambiguous fails the\n * import instead of being silently renamed.\n */\nimport type { BackendMethod } from '../core/domain/resource';\nimport { CommerceError } from '../core/errors';\nimport { findUnparsedBraceToken } from '../core/execution';\nimport { isRecord } from '../core/is-record';\nimport { MCP_TOOL_NAME_CHARS, MCP_TOOL_NAME_MAX_LENGTH } from '../protocols/mcp/constants';\nimport { dereference } from './refs';\nimport type { ImportDiagnostic, LoadedOpenApiDocument, OpenApiOperationCandidate } from './types';\n\nconst SUPPORTED_METHODS: Readonly<Record<string, BackendMethod>> = {\n get: 'GET',\n post: 'POST',\n put: 'PUT',\n patch: 'PATCH',\n delete: 'DELETE',\n};\n\n// Path Item members that are not operations. Any other key, except an `x-`\n// extension, that is not a supported method gets a diagnostic.\nconst NON_OPERATION_KEYS = new Set(['summary', 'description', 'servers', 'parameters', '$ref']);\n\n// Runs of characters outside the MCP tool-name set, which config requires of an\n// mcp-exposed resource id\nconst ID_DISALLOWED = new RegExp(`[^${MCP_TOOL_NAME_CHARS}]+`, 'g');\n\nexport interface DiscoverOptions {\n /** CLI `--base-url`. Wins over every server declared in the document */\n readonly baseUrl?: string;\n}\n\nexport interface DiscoveryResult {\n readonly operations: readonly OpenApiOperationCandidate[];\n readonly diagnostics: readonly ImportDiagnostic[];\n}\n\nexport function discoverOperations(\n loaded: LoadedOpenApiDocument,\n options: DiscoverOptions = {},\n): DiscoveryResult {\n const { document } = loaded;\n const diagnostics: ImportDiagnostic[] = [];\n const operations: OpenApiOperationCandidate[] = [];\n // resource id -> the `METHOD path` that claimed it, for the collision message\n const claimed = new Map<string, string>();\n\n if (options.baseUrl !== undefined) assertAbsoluteHttpUrl(options.baseUrl, '--base-url');\n\n const paths = document['paths'];\n if (!isRecord(paths)) {\n return { operations, diagnostics };\n }\n\n const rootServers = document['servers'];\n const rootSecurity = document['security'];\n\n for (const [path, rawPathItem] of Object.entries(paths)) {\n if (path.startsWith('x-')) continue;\n if (!path.startsWith('/')) {\n diagnostics.push({\n severity: 'warning',\n code: 'invalid-path-key',\n operation: path,\n message: `Skipped \"${path}\": a Paths key must start with \"/\"`,\n });\n continue;\n }\n const pathItem = dereference(document, rawPathItem).value;\n if (!isRecord(pathItem)) continue;\n\n const unsupportedMethod = (name: string): void => {\n diagnostics.push({\n severity: 'warning',\n code: 'unsupported-method',\n operation: `${name.toUpperCase()} ${path}`,\n message: `Skipped ${name.toUpperCase()} ${path}: only GET, POST, PUT, PATCH and DELETE are supported`,\n });\n };\n\n for (const [key, rawOperation] of Object.entries(pathItem)) {\n if (NON_OPERATION_KEYS.has(key) || key.startsWith('x-')) continue;\n // OpenAPI 3.2 maps each method outside the fixed fields to its operation\n if (key === 'additionalOperations') {\n if (isRecord(rawOperation))\n for (const name of Object.keys(rawOperation)) unsupportedMethod(name);\n continue;\n }\n const method = SUPPORTED_METHODS[key.toLowerCase()];\n if (method === undefined) {\n unsupportedMethod(key);\n continue;\n }\n const operation = dereference(document, rawOperation).value;\n if (!isRecord(operation)) continue;\n\n const where = `${method} ${path}`;\n const operationId =\n typeof operation['operationId'] === 'string' ? operation['operationId'] : undefined;\n const resourceId = toResourceId(operationId, method, path);\n const previous = claimed.get(resourceId);\n if (previous !== undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Operations \"${previous}\" and \"${where}\" both produce the resource id \"${resourceId}\". Give one of them a distinct operationId - ids are what agents discover, so the importer will not rename either`,\n { details: { resourceId, operations: [previous, where] } },\n );\n }\n claimed.set(resourceId, where);\n\n const server = selectServer(\n document,\n [operation['servers'], pathItem['servers'], rootServers],\n { where, resourceId },\n options,\n diagnostics,\n );\n if (server === undefined) continue;\n\n const backendUrl = `${server.replace(/\\/+$/, '')}${path}`;\n const stray = findUnparsedBraceToken(backendUrl);\n if (stray !== undefined) {\n diagnostics.push({\n severity: 'error',\n code: 'unsupported-path-template',\n operation: resourceId,\n message: `Skipped ${where}: path template \"${stray}\" uses characters the gateway cannot substitute (allowed: A-Z a-z 0-9 _ . -)`,\n });\n continue;\n }\n\n const summary = typeof operation['summary'] === 'string' ? operation['summary'] : undefined;\n const description =\n typeof operation['description'] === 'string' ? operation['description'] : summary;\n const security = operation['security'] ?? rootSecurity;\n\n operations.push({\n resourceId,\n method,\n path,\n backendUrl,\n ...(operationId !== undefined ? { operationId } : {}),\n tags: toArray(operation['tags']).filter((tag): tag is string => typeof tag === 'string'),\n name: summary ?? operationId ?? resourceId,\n ...(description !== undefined ? { description } : {}),\n parameters: [\n ...toArray(pathItem['parameters']),\n // Operation parameters last: `mergeParameters` lets the later one win,\n // the OpenAPI override rule (same `name` and `in`)\n ...toArray(operation['parameters']),\n ],\n ...(operation['requestBody'] !== undefined\n ? { requestBody: operation['requestBody'] }\n : {}),\n ...(operation['responses'] !== undefined ? { responses: operation['responses'] } : {}),\n security: toArray(security),\n });\n }\n }\n\n return { operations, diagnostics };\n}\n\n/**\n * `operationId` if it survives normalization, otherwise `method_path`.\n *\n * No counters and no random suffixes: two runs over the same document must\n * produce the same ids, and a collision is reported rather than papered over.\n */\nfunction toResourceId(\n operationId: string | undefined,\n method: BackendMethod,\n path: string,\n): string {\n const fromOperationId = operationId === undefined ? '' : normalizeId(operationId);\n if (fromOperationId !== '') return fromOperationId;\n return normalizeId(`${method.toLowerCase()}_${path}`);\n}\n\nfunction normalizeId(value: string): string {\n return value\n .replace(ID_DISALLOWED, '_')\n .replace(/_+/g, '_')\n .replace(/^[_.-]+|[_.-]+$/g, '')\n .slice(0, MCP_TOOL_NAME_MAX_LENGTH);\n}\n\n/**\n * `--base-url` > operation servers > path-item servers > root servers.\n *\n * A relative server URL (`/v1`, the OpenAPI default of `/`) names no host, and\n * guessing one from the filename or from localhost would silently point a\n * merchant's gateway at the wrong backend - so it is refused and `--base-url`\n * asked for instead.\n */\nfunction selectServer(\n document: Record<string, unknown>,\n candidates: readonly unknown[],\n context: { readonly where: string; readonly resourceId: string },\n options: DiscoverOptions,\n diagnostics: ImportDiagnostic[],\n): string | undefined {\n if (options.baseUrl !== undefined) return options.baseUrl;\n\n for (const candidate of candidates) {\n const servers = toArray(candidate);\n const first = servers.length > 0 ? dereference(document, servers[0]).value : undefined;\n if (!isRecord(first)) continue;\n const url = first['url'];\n if (typeof url !== 'string' || url === '') continue;\n\n const substituted = substituteServerVariables(url, first['variables'], context, diagnostics);\n if (substituted === undefined) return undefined;\n const issue = describeServerUrlIssue(substituted);\n if (issue !== undefined) {\n diagnostics.push({\n severity: 'error',\n code: issue.code,\n operation: context.resourceId,\n message: `Skipped ${context.where}: server URL \"${substituted}\" ${issue.reason}. Pass --base-url`,\n });\n return undefined;\n }\n return substituted;\n }\n\n diagnostics.push({\n severity: 'error',\n code: 'no-server-url',\n operation: context.resourceId,\n message: `Skipped ${context.where}: the document declares no server URL. Pass --base-url`,\n });\n return undefined;\n}\n\nfunction substituteServerVariables(\n url: string,\n variables: unknown,\n context: { readonly where: string; readonly resourceId: string },\n diagnostics: ImportDiagnostic[],\n): string | undefined {\n if (!url.includes('{')) return url;\n const declared = isRecord(variables) ? variables : {};\n const used: string[] = [];\n let missing: string | undefined;\n const substituted = url.replace(/\\{([^{}]*)\\}/g, (match, name: string) => {\n const variable = declared[name];\n const fallback = isRecord(variable) ? variable['default'] : undefined;\n if (typeof fallback !== 'string') {\n missing = name;\n return match;\n }\n used.push(`${name}=${fallback}`);\n return fallback;\n });\n if (missing !== undefined) {\n diagnostics.push({\n severity: 'error',\n code: 'server-variable-without-default',\n operation: context.resourceId,\n message: `Skipped ${context.where}: server variable \"{${missing}}\" has no default value. Pass --base-url`,\n });\n return undefined;\n }\n if (used.length > 0) {\n diagnostics.push({\n severity: 'warning',\n code: 'server-variable-default',\n operation: context.resourceId,\n message: `Server URL for ${context.where} uses declared defaults (${used.join(', ')}); override with --base-url if that is not the deployment you mean`,\n });\n }\n return substituted;\n}\n\n/**\n * An absolute http(s) origin plus path, and nothing after it. A query or\n * fragment on the base would land *before* the operation path once the two\n * are concatenated (`.../api?key=x` + `/users/{id}`), producing a URL that\n * parses fine and calls the wrong endpoint.\n */\nfunction isAbsoluteHttpUrl(value: string): boolean {\n return describeServerUrlIssue(value) === undefined;\n}\n\nfunction describeServerUrlIssue(\n value: string,\n):\n | { readonly code: 'relative-server-url' | 'invalid-server-url'; readonly reason: string }\n | undefined {\n try {\n const parsed = new URL(value);\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n return { code: 'invalid-server-url', reason: 'must use http:// or https://' };\n }\n if (parsed.search !== '' || parsed.hash !== '') {\n return {\n code: 'invalid-server-url',\n reason: 'must not contain a query string or fragment',\n };\n }\n return undefined;\n } catch {\n return {\n code: 'relative-server-url',\n reason: 'is relative or malformed, so no backend host is known',\n };\n }\n}\n\nfunction assertAbsoluteHttpUrl(value: string, label: string): void {\n if (!isAbsoluteHttpUrl(value)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `${label} \"${value}\" must be an absolute http:// or https:// URL with no query string or fragment`,\n { details: { value } },\n );\n }\n}\n\nfunction toArray(value: unknown): readonly unknown[] {\n return Array.isArray(value) ? value : [];\n}\n","/**\n * Lazy internal `$ref` resolution.\n *\n * The document is deliberately *not* dereferenced up front: a recursive schema\n * (`Node.children[] -> Node`) expands without bound, turning a 30 kB file into\n * an out-of-memory kill. Each pointer is followed on demand instead, carrying\n * the chain that led to it so a cycle is a diagnostic rather than a hang.\n */\nimport { CommerceError } from '../core/errors';\n\n// Bounds a pathological but non-cyclic chain of `$ref`s pointing at `$ref`s\nconst MAX_REF_DEPTH = 100;\n\nexport interface Dereferenced {\n readonly value: unknown;\n /** Pointers already followed, oldest first. Pass it back in to keep detecting cycles */\n readonly stack: readonly string[];\n}\n\nexport function isRefNode(value: unknown): value is { $ref: string } {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { $ref?: unknown }).$ref === 'string'\n );\n}\n\n/**\n * Follows a chain of `$ref` nodes to the first value that is not one.\n *\n * Throws `CONFIG_INVALID` for a cycle, an unresolvable pointer, or an external\n * reference - the last is refused at load time too, so reaching it here means\n * a caller built a node the loader never saw.\n */\nexport function dereference(\n document: Record<string, unknown>,\n node: unknown,\n stack: readonly string[] = [],\n): Dereferenced {\n let current = node;\n let chain = stack;\n while (isRefNode(current)) {\n const pointer = current.$ref;\n if (!pointer.startsWith('#')) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `OpenAPI document contains an external reference \"${pointer}\". Only internal references (#/...) are supported`,\n { details: { ref: pointer } },\n );\n }\n if (chain.includes(pointer)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `OpenAPI reference \"${pointer}\" is circular (${[...chain, pointer].join(' -> ')})`,\n { details: { ref: pointer, chain: [...chain, pointer] } },\n );\n }\n if (chain.length >= MAX_REF_DEPTH) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `OpenAPI reference chain exceeds ${MAX_REF_DEPTH} hops at \"${pointer}\"`,\n { details: { ref: pointer } },\n );\n }\n current = resolvePointer(document, pointer);\n chain = [...chain, pointer];\n }\n return { value: current, stack: chain };\n}\n\n// RFC 6901 JSON Pointer in a URI fragment: `#` is the document, `#/` its \"\" key\nfunction resolvePointer(document: Record<string, unknown>, ref: string): unknown {\n const pointer = ref.slice(1);\n if (pointer === '') return document;\n if (!pointer.startsWith('/')) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `OpenAPI reference \"${ref}\" is not a JSON Pointer. Plain names and anchors are not supported`,\n { details: { ref } },\n );\n }\n let current: unknown = document;\n for (const rawSegment of pointer.slice(1).split('/')) {\n let decoded: string;\n try {\n decoded = decodeURIComponent(rawSegment);\n } catch {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `OpenAPI reference \"${ref}\" contains a malformed percent-escape`,\n { details: { ref } },\n );\n }\n // `~1` before `~0`, per RFC 6901: the other order decodes `~01` to \"/\"\n // instead of \"~1\"\n const segment = decoded.replaceAll('~1', '/').replaceAll('~0', '~');\n if (Array.isArray(current)) {\n const index = Number(segment);\n current = Number.isInteger(index) ? current[index] : undefined;\n } else if (typeof current === 'object' && current !== null) {\n // Own members only: \"__proto__\" would otherwise resolve to Object.prototype,\n // which converts to a schema that accepts anything\n current = Object.hasOwn(current, segment)\n ? (current as Record<string, unknown>)[segment]\n : undefined;\n } else {\n current = undefined;\n }\n if (current === undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `OpenAPI reference \"${ref}\" does not resolve to anything in the document`,\n { details: { ref } },\n );\n }\n }\n return current;\n}\n","/**\n * Operation candidates -> Agent Commerce resource drafts.\n *\n * A draft describes the *API shape* and nothing else. Pricing, exposure and\n * payment methods are commerce policy: an OpenAPI document has no opinion on\n * whether an operation should cost money or be visible to agents, so guessing\n * one would put a merchant's endpoint on an agent network - or give it away\n * free - on the strength of a file that never mentioned either. Without\n * explicit CLI policy the generated file is deliberately incomplete: it will\n * not load until a human fills those fields in.\n */\nimport { win32 } from 'node:path';\nimport { Document, type Node, type Pair, type YAMLMap } from 'yaml';\nimport type { JsonSchema } from '../core/domain/common';\nimport { isRecord } from '../core/is-record';\nimport { discoverOperations } from './discover';\nimport { dereference } from './refs';\nimport { mapRequest, pickJsonMediaType } from './request';\nimport { convertSchema } from './schema';\nimport type {\n ImportDiagnostic,\n LoadedOpenApiDocument,\n OpenApiOperationCandidate,\n OpenApiVersion,\n} from './types';\n\n/** Commerce policy the operator supplied explicitly. Never inferred */\nexport interface ImportPolicy {\n readonly pricing?: Record<string, unknown>;\n readonly expose?: readonly string[];\n}\n\nexport interface ImportOptions {\n readonly baseUrl?: string;\n readonly policy?: ImportPolicy;\n /** `--operation` / `--tag`. Applied before mapping, so unselected operations produce no noise */\n readonly include?: {\n readonly operationIds?: readonly string[];\n /** Multiple tags are OR-ed */\n readonly tags?: readonly string[];\n };\n}\n\nexport interface ResourceDraft {\n readonly id: string;\n readonly operationId?: string;\n readonly tags: readonly string[];\n /** `METHOD /path`, for the console summary */\n readonly source: string;\n /** YAML-ready, in the field order it will be written in */\n readonly resource: Record<string, unknown>;\n /** Comment lines written above this resource */\n readonly review: readonly string[];\n}\n\nexport interface ImportResult {\n readonly version: OpenApiVersion;\n readonly sourcePath: string;\n readonly drafts: readonly ResourceDraft[];\n readonly diagnostics: readonly ImportDiagnostic[];\n /** `--operation` values that matched nothing. The CLI exits non-zero on these */\n readonly unmatchedOperationIds: readonly string[];\n}\n\nexport function buildResourceDrafts(\n loaded: LoadedOpenApiDocument,\n options: ImportOptions = {},\n): ImportResult {\n const discovery = discoverOperations(\n loaded,\n options.baseUrl !== undefined ? { baseUrl: options.baseUrl } : {},\n );\n const diagnostics: ImportDiagnostic[] = [];\n const drafts: ResourceDraft[] = [];\n\n const wanted = options.include?.operationIds;\n const wantedTags = options.include?.tags;\n const matched = new Set<string>();\n const selected = new Set<string>();\n\n for (const candidate of discovery.operations) {\n if (wanted !== undefined && !selects(wanted, candidate)) continue;\n if (wantedTags !== undefined && !candidate.tags.some((tag) => wantedTags.includes(tag))) {\n continue;\n }\n if (wanted !== undefined) {\n for (const id of wanted) if (selects([id], candidate)) matched.add(id);\n }\n selected.add(candidate.resourceId);\n\n const mapping = mapRequest(loaded, candidate);\n diagnostics.push(...mapping.diagnostics);\n if (!mapping.supported) continue;\n\n const dropped = new Set(mapping.droppedKeywords);\n const output = selectOutputSchema(loaded.document, candidate, diagnostics, dropped);\n if (dropped.size > 0) {\n diagnostics.push({\n severity: 'warning',\n code: 'unenforced-schema-constraints',\n operation: candidate.resourceId,\n message: `${candidate.resourceId}: dropped ${[...dropped].join(', ')} - this gateway validates structure only, and keeping them would advertise checks it never performs`,\n });\n }\n\n const review: string[] = [];\n if (declaresSecurity(candidate)) {\n diagnostics.push({\n severity: 'warning',\n code: 'backend-authentication-required',\n operation: candidate.resourceId,\n message: `${candidate.resourceId} declares backend authentication. OpenAPI credentials were not imported. Configure backend.headers with environment placeholders before enabling the resource`,\n });\n review.push(\n 'This operation declares backend authentication. No credential was imported.',\n 'Add it under backend.headers with an ${ENV_VAR} placeholder before enabling.',\n );\n }\n if (options.policy?.pricing === undefined || options.policy.expose === undefined) {\n review.push(\n 'REVIEW: pricing and exposure are not inferred from OpenAPI. Add e.g.',\n ' pricing: { type: free } # or { type: fixed, amount: \"0.01\", currency: USDC } with payments: [x402]',\n ' expose: [http] # http | mcp | a2a | acp',\n );\n }\n\n drafts.push({\n id: candidate.resourceId,\n ...(candidate.operationId !== undefined ? { operationId: candidate.operationId } : {}),\n tags: candidate.tags,\n source: `${candidate.method} ${candidate.path}`,\n resource: {\n name: candidate.name,\n ...(candidate.description !== undefined ? { description: candidate.description } : {}),\n input: mapping.inputSchema,\n ...(output !== undefined ? { output } : {}),\n backend: {\n type: 'http',\n method: candidate.method,\n url: candidate.backendUrl,\n ...(mapping.contentType !== undefined\n ? { headers: { 'Content-Type': mapping.contentType } }\n : {}),\n ...(Object.keys(mapping.inputBindings).length > 0\n ? { inputBindings: mapping.inputBindings }\n : {}),\n },\n // Written only when the operator supplied it (see the file header)\n ...(options.policy?.pricing !== undefined ? { pricing: options.policy.pricing } : {}),\n ...(options.policy?.expose !== undefined ? { expose: [...options.policy.expose] } : {}),\n },\n review,\n });\n }\n\n return {\n version: loaded.version,\n sourcePath: loaded.sourcePath,\n drafts,\n diagnostics: [\n ...selectDiscoveryDiagnostics(discovery.diagnostics, options.include, selected),\n ...diagnostics,\n ],\n unmatchedOperationIds: (wanted ?? []).filter((id) => !matched.has(id)),\n };\n}\n\n// With a selection, a discovery finding counts only for a selected operation\n// or one named by `--operation`, so an unrelated one cannot fail `--strict`\nfunction selectDiscoveryDiagnostics(\n found: readonly ImportDiagnostic[],\n include: ImportOptions['include'],\n selected: ReadonlySet<string>,\n): readonly ImportDiagnostic[] {\n if (include?.operationIds === undefined && include?.tags === undefined) return found;\n return found.filter(\n ({ operation }) =>\n operation === undefined ||\n selected.has(operation) ||\n include.operationIds?.includes(operation) === true,\n );\n}\n\n// `--operation` accepts the OpenAPI operationId or the generated resource id\nfunction selects(ids: readonly string[], candidate: OpenApiOperationCandidate): boolean {\n return (\n ids.includes(candidate.resourceId) ||\n (candidate.operationId !== undefined && ids.includes(candidate.operationId))\n );\n}\n\n// `security: []` means \"explicitly none\" and `[{}]` means optional. Neither needs a credential\nfunction declaresSecurity(candidate: OpenApiOperationCandidate): boolean {\n return candidate.security.some(\n (requirement) =>\n typeof requirement === 'object' &&\n requirement !== null &&\n Object.keys(requirement).length > 0,\n );\n}\n\n/**\n * One success response, chosen the same way every run: 200, then 201, then\n * 202, then the remaining explicit 2xx in ascending order. Status-dependent\n * unions are out of scope, so when several 2xx carry materially different\n * schemas the operator is told which one was taken rather than left to\n * discover it from the diff.\n */\nfunction selectOutputSchema(\n document: Record<string, unknown>,\n candidate: OpenApiOperationCandidate,\n diagnostics: ImportDiagnostic[],\n dropped: Set<string>,\n): JsonSchema | undefined {\n const responses = candidate.responses;\n if (!isRecord(responses)) return undefined;\n\n const successes = Object.keys(responses)\n .filter((status) => /^2\\d\\d$/.test(status))\n .sort((a, b) => rank(a) - rank(b));\n if (successes.length === 0) return undefined;\n\n const withBody = successes.flatMap((status) => {\n const response = dereference(document, responses[status]);\n if (!isRecord(response.value)) return [];\n const content = response.value['content'];\n if (!isRecord(content)) return [];\n const mediaType = pickJsonMediaType(Object.keys(content));\n if (mediaType === undefined) return [];\n const media = dereference(document, content[mediaType], response.stack).value;\n return isRecord(media) ? [{ status, media }] : [];\n });\n const chosen = withBody[0];\n if (chosen === undefined) return undefined; // 204, or no JSON representation\n\n const schemaNode = chosen.media['schema'];\n if (schemaNode === undefined) {\n diagnostics.push({\n severity: 'warning',\n code: 'missing-output-schema',\n operation: candidate.resourceId,\n message: `${candidate.resourceId}: response ${chosen.status} has JSON content without a schema; omitted the output schema`,\n });\n return undefined;\n }\n\n const converted = convertSchema(document, schemaNode);\n if (!converted.supported) {\n // Output schema is descriptive: omitting it costs discovery detail, not\n // request safety, so it never skips the operation\n diagnostics.push({\n severity: 'warning',\n code: 'unsupported-output-schema',\n operation: candidate.resourceId,\n message: `${candidate.resourceId}: omitted the output schema (${converted.reason})`,\n });\n return undefined;\n }\n for (const keyword of converted.dropped) dropped.add(keyword);\n\n if (withBody.length > 1) {\n diagnostics.push({\n severity: 'warning',\n code: 'multiple-success-responses',\n operation: candidate.resourceId,\n message: `${candidate.resourceId}: responses ${withBody.map(({ status }) => status).join(', ')} all carry a JSON body; used ${chosen.status}`,\n });\n }\n return converted.schema;\n}\n\nfunction rank(status: string): number {\n const preferred = ['200', '201', '202'].indexOf(status);\n return preferred === -1 ? 100 + Number(status) : preferred;\n}\n\n/**\n * Renders the drafts as a config fragment: the same `resources:` shape\n * `config.yaml` uses, so a reviewed block can be moved across whole\n */\nexport function renderResourcesYaml(result: ImportResult): string {\n const resources: Record<string, unknown> = {};\n for (const draft of result.drafts) resources[draft.id] = draft.resource;\n\n const doc = new Document({ resources });\n doc.commentBefore = [\n ' Generated by agent-commerce import openapi. Review before use.',\n // win32.basename splits on both / and \\\n ` Source: ${win32.basename(result.sourcePath)} (OpenAPI ${result.version})`,\n ' Merge the resources below into config.yaml once pricing, exposure and',\n ' any backend authentication have been decided.',\n ].join('\\n');\n\n // Comments hang off the key node; a Pair has nowhere to put one. Map items\n // are in insertion order, which is draft order.\n const map = doc.getIn(['resources'], true) as YAMLMap | undefined;\n map?.items.forEach((item, index) => {\n const draft = result.drafts[index];\n const key = (item as Pair<Node, unknown>).key;\n if (draft === undefined || draft.review.length === 0 || key === null) return;\n key.commentBefore = draft.review.map((line) => ` ${line}`).join('\\n');\n });\n\n // lineWidth 0 disables folding: a wrapped description would otherwise\n // re-flow whenever an unrelated word changed, and the generated file is\n // meant to be reviewed in a diff\n return doc.toString({ lineWidth: 0 });\n}\n","/**\n * OpenAPI parameters and request body -> a canonical input schema plus\n * `backend.inputBindings`.\n *\n * Locations are namespaced (`path` / `query` / `body`) so a `?id=` and a\n * `{id}` in the same operation cannot collide, and so the executor can source\n * each group independently. Anything the executor would not send the way the\n * API expects is refused rather than approximated: a required parameter we\n * cannot represent skips the operation, an optional one is omitted with a\n * warning. Approximating it would produce a resource that looks importable,\n * takes payment, and then calls the backend wrongly.\n */\nimport type { JsonSchema } from '../core/domain/common';\nimport { extractPathParameterNames } from '../core/execution';\nimport { isRecord } from '../core/is-record';\nimport { dereference } from './refs';\nimport { convertSchema, isPrimitiveSchema, type SchemaConversion } from './schema';\nimport type { ImportDiagnostic, LoadedOpenApiDocument, OpenApiOperationCandidate } from './types';\n\n// Top-level input property names, which are also the binding values\nconst PATH_GROUP = 'path';\nconst QUERY_GROUP = 'query';\nconst BODY_GROUP = 'body';\n\n/**\n * OpenAPI: parameters named these \"SHALL be ignored\" - they are transport\n * concerns, and `Authorization` in particular is operator configuration that\n * must never become an agent-supplied input\n */\nconst IGNORED_HEADER_NAMES = new Set(['accept', 'content-type', 'authorization']);\n\n// Serialization styles the executor's plain `key=value` query cannot produce\nconst UNSUPPORTED_QUERY_STYLES = new Set(['deepObject', 'spaceDelimited', 'pipeDelimited']);\n\nexport interface RequestBindings {\n readonly path?: string;\n readonly query?: string;\n readonly body?: string;\n}\n\nexport type RequestMapping =\n | {\n readonly supported: true;\n readonly inputSchema: JsonSchema;\n readonly inputBindings: RequestBindings;\n /** Set only for a vendor `+json` body, which needs a static Content-Type */\n readonly contentType?: string;\n /** Schema constraints dropped because the gateway does not enforce them */\n readonly droppedKeywords: readonly string[];\n readonly diagnostics: readonly ImportDiagnostic[];\n }\n | { readonly supported: false; readonly diagnostics: readonly ImportDiagnostic[] };\n\nexport function mapRequest(\n loaded: LoadedOpenApiDocument,\n candidate: OpenApiOperationCandidate,\n): RequestMapping {\n const { document } = loaded;\n const diagnostics: ImportDiagnostic[] = [];\n const dropped = new Set<string>();\n const operation = candidate.resourceId;\n\n const warn = (code: string, message: string): void => {\n diagnostics.push({ severity: 'warning', code, operation, message });\n };\n const skip = (code: string, message: string): RequestMapping => {\n diagnostics.push({\n severity: 'error',\n code,\n operation,\n message: `Skipped ${candidate.method} ${candidate.path}: ${message}`,\n });\n return { supported: false, diagnostics };\n };\n\n const pathProperties: Record<string, unknown> = {};\n const queryProperties: Record<string, unknown> = {};\n const requiredQuery: string[] = [];\n const templateParams = new Set(extractPathParameterNames(candidate.path));\n\n for (const parameter of mergeParameters(document, candidate.parameters)) {\n const name = typeof parameter['name'] === 'string' ? parameter['name'] : undefined;\n const location = typeof parameter['in'] === 'string' ? parameter['in'] : undefined;\n if (name === undefined || location === undefined) continue;\n const required = parameter['required'] === true || location === 'path';\n const label = `${location} parameter \"${name}\"`;\n\n if (location === 'header' || location === 'cookie') {\n if (location === 'header' && IGNORED_HEADER_NAMES.has(name.toLowerCase())) continue;\n if (required) {\n return skip(\n 'unsupported-required-parameter',\n `${label} is required, and ${location} parameters are operator configuration in this release, not agent input`,\n );\n }\n warn(\n 'unsupported-optional-parameter',\n `Omitted optional ${label}: ${location} parameters are not imported. Configure it under backend.headers if the API needs it`,\n );\n continue;\n }\n if (location !== 'path' && location !== 'query') {\n if (required) return skip('unsupported-required-parameter', `${label} has unknown location`);\n warn('unsupported-optional-parameter', `Omitted optional ${label}: unknown location`);\n continue;\n }\n\n const converted = convertParameter(document, parameter, location);\n if (!converted.supported) {\n if (required) return skip('unsupported-required-parameter', `${label} ${converted.reason}`);\n warn('unsupported-optional-parameter', `Omitted optional ${label}: it ${converted.reason}`);\n continue;\n }\n for (const keyword of converted.dropped) dropped.add(keyword);\n\n if (location === 'path') {\n if (!templateParams.has(name)) {\n warn(\n 'path-parameter-not-in-template',\n `Ignored path parameter \"${name}\": it does not appear in \"${candidate.path}\"`,\n );\n continue;\n }\n pathProperties[name] = converted.schema;\n } else {\n queryProperties[name] = converted.schema;\n if (required) requiredQuery.push(name);\n }\n }\n\n for (const param of templateParams) {\n if (!Object.hasOwn(pathProperties, param)) {\n return skip(\n 'undeclared-path-parameter',\n `\"{${param}}\" appears in the path but is not declared as a path parameter, so a caller could never supply it`,\n );\n }\n }\n\n const body = resolveBody(document, candidate);\n if (body.kind === 'unsupported') {\n if (body.required) return skip('unsupported-request-body', body.reason);\n warn('unsupported-request-body', `Omitted the request body: ${body.reason}`);\n }\n if (body.kind === 'schema') {\n for (const keyword of body.dropped) dropped.add(keyword);\n }\n\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n const bindings: { path?: string; query?: string; body?: string } = {};\n\n if (Object.keys(pathProperties).length > 0) {\n properties[PATH_GROUP] = closedObject(pathProperties, Object.keys(pathProperties));\n // OpenAPI path parameters are always required, and a missing one makes the\n // request unbuildable - which on a paid resource is payment with no\n // delivery, so config rejects the shape at load time too\n required.push(PATH_GROUP);\n bindings.path = PATH_GROUP;\n }\n if (Object.keys(queryProperties).length > 0) {\n properties[QUERY_GROUP] = closedObject(queryProperties, requiredQuery);\n if (requiredQuery.length > 0) required.push(QUERY_GROUP);\n bindings.query = QUERY_GROUP;\n }\n if (body.kind === 'schema') {\n properties[BODY_GROUP] = body.schema;\n if (body.required) required.push(BODY_GROUP);\n bindings.body = BODY_GROUP;\n }\n\n return {\n supported: true,\n inputSchema: {\n type: 'object',\n properties,\n ...(required.length > 0 ? { required } : {}),\n additionalProperties: false,\n },\n inputBindings: bindings,\n ...(body.kind === 'schema' && body.contentType !== undefined\n ? { contentType: body.contentType }\n : {}),\n droppedKeywords: [...dropped],\n diagnostics,\n };\n}\n\n/**\n * Path Item parameters first, operation parameters second, with the OpenAPI\n * identity rule: a parameter is the same one when `name` *and* `in` match, and\n * the operation's own definition wins\n */\nfunction mergeParameters(\n document: Record<string, unknown>,\n parameters: readonly unknown[],\n): Record<string, unknown>[] {\n const byIdentity = new Map<string, Record<string, unknown>>();\n for (const raw of parameters) {\n const parameter = dereference(document, raw).value;\n if (!isRecord(parameter)) continue;\n byIdentity.set(`${String(parameter['in'])}:${String(parameter['name'])}`, parameter);\n }\n return [...byIdentity.values()];\n}\n\n/**\n * The parameter's schema, if the executor can send the parameter the way the\n * API reads it. It writes one `key=value` pair per query parameter and\n * substitutes one URL-encoded value per path segment, so anything that\n * serializes to several pairs or to a structured segment is not supported.\n * Each `reason` reads as a predicate of the parameter.\n */\nfunction convertParameter(\n document: Record<string, unknown>,\n parameter: Record<string, unknown>,\n location: 'path' | 'query',\n): SchemaConversion {\n const unsupported = (reason: string): SchemaConversion => ({ supported: false, reason });\n // Assigned as a key, it replaces the group object's prototype instead of\n // adding the parameter\n if (parameter['name'] === '__proto__') {\n return unsupported('has a name that cannot be an input key');\n }\n if (parameter['content'] !== undefined) {\n return unsupported(\n 'uses the `content` form, whose media-type serialization the gateway does not perform',\n );\n }\n const style = parameter['style'];\n if (location === 'query' && typeof style === 'string' && UNSUPPORTED_QUERY_STYLES.has(style)) {\n return unsupported(`uses style \"${style}\", which the gateway does not serialize`);\n }\n if (location === 'path' && typeof style === 'string' && style !== 'simple') {\n return unsupported(`uses style \"${style}\"; the gateway substitutes plain values only`);\n }\n const converted = convertSchema(document, parameter['schema']);\n if (!converted.supported) return unsupported(`has an unusable schema: ${converted.reason}`);\n if (!isPrimitiveSchema(converted.schema)) {\n return unsupported(\n 'is not a primitive; object and array parameters need serialization the gateway does not perform',\n );\n }\n return converted;\n}\n\ntype BodyResult =\n | { readonly kind: 'none' }\n | {\n readonly kind: 'schema';\n readonly schema: JsonSchema;\n readonly required: boolean;\n readonly contentType?: string;\n readonly dropped: readonly string[];\n }\n | { readonly kind: 'unsupported'; readonly required: boolean; readonly reason: string };\n\nfunction resolveBody(\n document: Record<string, unknown>,\n candidate: OpenApiOperationCandidate,\n): BodyResult {\n if (candidate.requestBody === undefined) return { kind: 'none' };\n const resolvedBody = dereference(document, candidate.requestBody);\n const requestBody = resolvedBody.value;\n if (!isRecord(requestBody)) return { kind: 'none' };\n const required = requestBody['required'] === true;\n\n if (candidate.method === 'GET' || candidate.method === 'DELETE') {\n // The executor sends no body on these, and config refuses a body binding\n // for them. Silently generating one would produce a resource whose\n // payload never arrives.\n return {\n kind: 'unsupported',\n required: false,\n reason: `a ${candidate.method} request body is not sent by the gateway`,\n };\n }\n\n const content = requestBody['content'];\n if (!isRecord(content)) return { kind: 'none' };\n const mediaType = pickJsonMediaType(Object.keys(content));\n if (mediaType === undefined) {\n return {\n kind: 'unsupported',\n required,\n reason: `no JSON request body content type (found: ${Object.keys(content).join(', ') || 'none'}). Only application/json and application/*+json are supported - multipart and form data are never serialized as JSON`,\n };\n }\n const media = dereference(document, content[mediaType], resolvedBody.stack).value;\n const schemaNode = isRecord(media) ? media['schema'] : undefined;\n if (schemaNode === undefined) {\n // A body with no schema accepts anything. `additionalProperties: true` is\n // written out because the config loader closes every object schema that\n // does not state it.\n return {\n kind: 'schema',\n schema: { type: 'object', additionalProperties: true },\n required,\n ...(mediaType === 'application/json' ? {} : { contentType: mediaType }),\n dropped: [],\n };\n }\n const converted = convertSchema(document, schemaNode);\n if (!converted.supported) return { kind: 'unsupported', required, reason: converted.reason };\n return {\n kind: 'schema',\n schema: converted.schema,\n required,\n ...(mediaType === 'application/json' ? {} : { contentType: mediaType }),\n dropped: converted.dropped,\n };\n}\n\n/** Exact `application/json` wins; otherwise the first `+json` in sorted order */\nexport function pickJsonMediaType(keys: readonly string[]): string | undefined {\n const normalized = keys.map((key) => ({ key, type: key.split(';')[0]?.trim().toLowerCase() }));\n const exact = normalized.find((entry) => entry.type === 'application/json');\n if (exact !== undefined) return exact.key;\n return [...normalized]\n .sort((a, b) => (a.type ?? '').localeCompare(b.type ?? ''))\n .find((entry) => entry.type?.startsWith('application/') && entry.type.endsWith('+json'))?.key;\n}\n\nfunction closedObject(\n properties: Record<string, unknown>,\n required: readonly string[],\n): JsonSchema {\n return {\n type: 'object',\n properties,\n ...(required.length > 0 ? { required: [...required] } : {}),\n additionalProperties: false,\n };\n}\n","/**\n * OpenAPI schema -> the JSON Schema subset this gateway enforces.\n *\n * `src/core`'s validator enforces `type`/`properties`/`required`/\n * `additionalProperties`/`enum`/`items` and ignores everything else, so a\n * copied `pattern` or `oneOf` would advertise validation to agents that no\n * code performs - and on a paid resource the buyer pays before the backend\n * sees the request. Unenforceable constraints are dropped from the generated\n * schema and reported, never carried along quietly.\n */\nimport { isDeepStrictEqual } from 'node:util';\nimport type { JsonSchema } from '../core/domain/common';\nimport { isCommerceError } from '../core/errors';\nimport { isRecord } from '../core/is-record';\nimport { dereference } from './refs';\n\n// The types `compileJsonSchema` enforces\nconst SUPPORTED_TYPES = new Set([\n 'object',\n 'string',\n 'number',\n 'integer',\n 'boolean',\n 'array',\n 'null',\n]);\n\n// Copied through: descriptive, never a constraint, so it cannot overstate\nconst METADATA_KEYWORDS = ['title', 'description', 'default', 'example', 'examples', 'deprecated'];\n\n/**\n * Annotations, not constraints: dropping them changes nothing a caller could\n * observe, so they are not worth telling the operator about. Reporting them\n * would bury the keywords that *do* matter (`pattern`, `minimum`, `format`)\n * in noise, which is how a real warning gets ignored.\n */\nconst ANNOTATION_KEYWORDS = new Set([\n 'xml',\n 'externalDocs',\n 'readOnly',\n 'writeOnly',\n '$schema',\n '$id',\n '$comment',\n '$defs',\n 'definitions',\n]);\n\nexport type SchemaConversion =\n | {\n readonly supported: true;\n readonly schema: JsonSchema;\n /** Keyword names encountered and dropped, deduplicated, in first-seen order */\n readonly dropped: readonly string[];\n }\n | { readonly supported: false; readonly reason: string };\n\n/** Types a path or query parameter may have: the executor stringifies one value */\nexport function isPrimitiveSchema(schema: JsonSchema): boolean {\n const types = typeList(schema['type']);\n if (types === undefined) return false;\n return types.every((type) => type !== 'object' && type !== 'array' && SUPPORTED_TYPES.has(type));\n}\n\nexport function convertSchema(\n document: Record<string, unknown>,\n node: unknown,\n stack: readonly string[] = [],\n): SchemaConversion {\n const dropped = new Set<string>();\n try {\n const schema = convertNode(document, node, stack, dropped);\n return { supported: true, schema, dropped: [...dropped] };\n } catch (error) {\n if (error instanceof UnsupportedSchema) return { supported: false, reason: error.message };\n // A reference cycle or a dangling pointer arrives as CONFIG_INVALID from\n // the resolver. For a *schema* that is a skip-this-operation condition,\n // not a fail-the-whole-import one: the rest of the document is fine.\n if (isCommerceError(error)) return { supported: false, reason: error.message };\n throw error;\n }\n}\n\nclass UnsupportedSchema extends Error {}\n\nfunction convertNode(\n document: Record<string, unknown>,\n node: unknown,\n stack: readonly string[],\n dropped: Set<string>,\n): JsonSchema {\n // OpenAPI 3.1 allows boolean schemas: `true` accepts anything, `false`\n // accepts nothing - and nothing is not a request shape we can generate\n if (node === true) return {};\n if (node === false) throw new UnsupportedSchema('schema is `false`, which accepts no value');\n\n const resolved = dereference(document, node, stack);\n const schemaNode = resolved.value;\n if (!isRecord(schemaNode)) throw new UnsupportedSchema('schema node is not an object');\n\n if (Array.isArray(schemaNode['allOf'])) {\n return mergeAllOf(document, schemaNode, resolved.stack, dropped);\n }\n for (const keyword of ['oneOf', 'anyOf', 'not', 'discriminator']) {\n if (Object.hasOwn(schemaNode, keyword)) {\n throw new UnsupportedSchema(\n `schema uses \"${keyword}\", which this gateway cannot enforce - accepting it would advertise validation that never runs`,\n );\n }\n }\n\n const result: Record<string, unknown> = {};\n const types = resolveTypes(schemaNode);\n if (types !== undefined) result['type'] = types.length === 1 ? types[0] : types;\n\n for (const keyword of METADATA_KEYWORDS) {\n if (Object.hasOwn(schemaNode, keyword)) result[keyword] = schemaNode[keyword];\n }\n if (Array.isArray(schemaNode['enum'])) result['enum'] = [...schemaNode['enum']];\n\n const properties = schemaNode['properties'];\n if (isRecord(properties)) {\n const converted: Record<string, unknown> = {};\n for (const [name, sub] of Object.entries(properties)) {\n // Assigned as a key, it replaces `converted`'s prototype instead of adding\n // the property, which `required` may still name\n if (name === '__proto__') {\n throw new UnsupportedSchema(\n 'schema declares a \"__proto__\" property, which cannot be imported',\n );\n }\n converted[name] = convertNode(document, sub, resolved.stack, dropped);\n }\n result['properties'] = converted;\n }\n\n // Independent of `properties`: `required` without them is legal, and core's\n // validator enforces it, so dropping it here would be a silent weakening.\n // Emitted here so every generated object schema orders its keys the same\n // way - the output is meant to be reviewed in a diff.\n const required = schemaNode['required'];\n if (Array.isArray(required)) {\n const names = required.filter((name): name is string => typeof name === 'string');\n if (names.length > 0) result['required'] = names;\n }\n\n const additional = schemaNode['additionalProperties'];\n if (typeof additional === 'boolean') {\n result['additionalProperties'] = additional;\n } else if (additional !== undefined) {\n result['additionalProperties'] = convertNode(document, additional, resolved.stack, dropped);\n } else if (isRecord(properties)) {\n result['additionalProperties'] = false;\n }\n\n const items = schemaNode['items'];\n if (Array.isArray(items)) {\n // Tuple `items` is not enforced; keeping it would look like it was\n dropped.add('items (tuple form)');\n } else if (items !== undefined) {\n result['items'] = convertNode(document, items, resolved.stack, dropped);\n }\n\n for (const keyword of Object.keys(schemaNode)) {\n if (isCarriedKeyword(keyword) || ANNOTATION_KEYWORDS.has(keyword) || keyword.startsWith('x-')) {\n continue;\n }\n dropped.add(keyword);\n }\n\n return result;\n}\n\nfunction isCarriedKeyword(keyword: string): boolean {\n return (\n keyword === 'type' ||\n keyword === 'properties' ||\n keyword === 'required' ||\n keyword === 'additionalProperties' ||\n keyword === 'enum' ||\n keyword === 'items' ||\n keyword === 'nullable' ||\n keyword === '$ref' ||\n METADATA_KEYWORDS.includes(keyword)\n );\n}\n\n/**\n * OpenAPI 3.0's `nullable: true` becomes draft-2020-12's union type, which is\n * what the runtime validator understands. 3.1 already writes it that way.\n */\nfunction resolveTypes(schema: Record<string, unknown>): string[] | undefined {\n const declared = typeList(schema['type']);\n if (declared === undefined) return undefined;\n const known = declared.filter((type) => SUPPORTED_TYPES.has(type));\n if (known.length === 0) {\n throw new UnsupportedSchema(`schema type \"${String(schema['type'])}\" is not a JSON type`);\n }\n if (schema['nullable'] === true && !known.includes('null')) known.push('null');\n return known;\n}\n\nfunction typeList(raw: unknown): string[] | undefined {\n if (typeof raw === 'string') return [raw];\n if (Array.isArray(raw) && raw.every((entry) => typeof entry === 'string')) {\n return raw as string[];\n }\n return undefined;\n}\n\n/**\n * A simple `allOf` of object schemas is merged; anything else is refused.\n *\n * Merging is only safe while the branches agree - two branches declaring the\n * same property differently have a meaning (\"both must hold\") that this\n * validator cannot express, and picking one would quietly accept requests the\n * API rejects, or reject ones it accepts.\n */\nfunction mergeAllOf(\n document: Record<string, unknown>,\n schema: Record<string, unknown>,\n stack: readonly string[],\n dropped: Set<string>,\n): JsonSchema {\n const branches = schema['allOf'] as readonly unknown[];\n const siblings = { ...schema };\n delete siblings['allOf'];\n\n const merged: Record<string, unknown> = { type: 'object', properties: {}, required: [] };\n const properties = merged['properties'] as Record<string, unknown>;\n const required = new Set<string>();\n let open = false;\n\n const parts = [...branches, ...(Object.keys(siblings).length > 0 ? [siblings] : [])];\n for (const branch of parts) {\n const converted = convertNode(document, branch, stack, dropped);\n const types = typeList(converted['type']);\n if (types !== undefined && !types.includes('object')) {\n throw new UnsupportedSchema('allOf mixes object and non-object schemas');\n }\n const branchProperties = converted['properties'];\n if (isRecord(branchProperties)) {\n for (const [name, sub] of Object.entries(branchProperties)) {\n const existing = properties[name];\n if (existing !== undefined && !isDeepStrictEqual(existing, sub)) {\n throw new UnsupportedSchema(\n `allOf branches declare property \"${name}\" differently, which cannot be merged`,\n );\n }\n properties[name] = sub;\n }\n }\n for (const name of Array.isArray(converted['required']) ? converted['required'] : []) {\n if (typeof name === 'string') required.add(name);\n }\n for (const keyword of ['enum', 'items']) {\n if (Object.hasOwn(converted, keyword)) {\n throw new UnsupportedSchema(`allOf branch uses \"${keyword}\", which cannot be merged`);\n }\n }\n for (const keyword of METADATA_KEYWORDS) {\n if (Object.hasOwn(converted, keyword) && !Object.hasOwn(merged, keyword)) {\n merged[keyword] = converted[keyword];\n }\n }\n // A branch that allows extra properties keeps the merge open. A schema for\n // them constrains the other branches' properties too, which the merged\n // `properties` cannot express.\n const additional = converted['additionalProperties'];\n if (additional === true) open = true;\n else if (isRecord(additional)) {\n throw new UnsupportedSchema(\n 'allOf branch constrains additionalProperties, which cannot be merged',\n );\n }\n }\n\n if (required.size > 0) merged['required'] = [...required];\n else delete merged['required'];\n merged['additionalProperties'] = open;\n return merged;\n}\n","/**\n * Reads and validates a local OpenAPI description.\n *\n * Offline by construction: the document is parsed here, every `$ref` is\n * checked to be internal *before* the validator ever sees the document, and no\n * URL-fetching plugin is passed to it. The importer must not turn \"point it at\n * your API description\" into \"the gateway machine makes outbound requests to\n * whatever the file names\".\n */\nimport { open, stat } from 'node:fs/promises';\nimport { extname } from 'node:path';\nimport { validate } from '@scalar/openapi-parser';\nimport { parse as parseYaml } from 'yaml';\nimport { CommerceError } from '../core/errors';\nimport type { LoadedOpenApiDocument, OpenApiVersion } from './types';\n\n/** Generous for a hand-written description; small enough that a stray file is refused */\nexport const MAX_SOURCE_BYTES = 10 * 1024 * 1024;\n\nconst SUPPORTED_EXTENSIONS = new Set(['.yaml', '.yml', '.json']);\nconst SUPPORTED_VERSIONS: ReadonlySet<string> = new Set(['3.0', '3.1', '3.2']);\n\nfunction invalid(\n message: string,\n details: Record<string, unknown>,\n cause?: unknown,\n): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, {\n details,\n ...(cause !== undefined ? { cause } : {}),\n });\n}\n\n// The size from `stat` does not bound the read: a device or a pipe reports 0\nasync function readCapped(sourcePath: string, details: Record<string, unknown>): Promise<string> {\n const buffer = Buffer.alloc(MAX_SOURCE_BYTES + 1);\n let length = 0;\n try {\n const handle = await open(sourcePath, 'r');\n try {\n while (length < buffer.length) {\n const { bytesRead } = await handle.read(buffer, length, buffer.length - length, null);\n if (bytesRead === 0) break;\n length += bytesRead;\n }\n } finally {\n await handle.close();\n }\n } catch (error) {\n throw invalid(`OpenAPI document \"${sourcePath}\" could not be read`, details, error);\n }\n if (length > MAX_SOURCE_BYTES) {\n throw invalid(`OpenAPI document \"${sourcePath}\" is over the ${MAX_SOURCE_BYTES}-byte limit`, {\n ...details,\n maxBytes: MAX_SOURCE_BYTES,\n });\n }\n return buffer.toString('utf8', 0, length);\n}\n\nexport async function loadOpenApiDocument(sourcePath: string): Promise<LoadedOpenApiDocument> {\n const details = { sourcePath };\n\n let stats: Awaited<ReturnType<typeof stat>>;\n try {\n stats = await stat(sourcePath);\n } catch (error) {\n throw invalid(`OpenAPI document \"${sourcePath}\" could not be read`, details, error);\n }\n if (stats.isDirectory()) {\n throw invalid(`\"${sourcePath}\" is a directory, not an OpenAPI document`, details);\n }\n if (stats.size > MAX_SOURCE_BYTES) {\n throw invalid(\n `OpenAPI document \"${sourcePath}\" is ${stats.size} bytes, over the ${MAX_SOURCE_BYTES}-byte limit`,\n { ...details, size: stats.size, maxBytes: MAX_SOURCE_BYTES },\n );\n }\n\n const extension = extname(sourcePath).toLowerCase();\n if (!SUPPORTED_EXTENSIONS.has(extension)) {\n throw invalid(\n `OpenAPI document \"${sourcePath}\" has an unsupported extension \"${extension || '(none)'}\". Supported: .yaml, .yml, .json`,\n details,\n );\n }\n\n const source = await readCapped(sourcePath, details);\n if (source.trim() === '') {\n throw invalid(`OpenAPI document \"${sourcePath}\" is empty`, details);\n }\n\n let parsed: unknown;\n try {\n // YAML is a superset of JSON, but JSON.parse gives the better message for a\n // file that claims to be JSON, and refuses YAML a .json file should not\n // contain\n parsed = extension === '.json' ? JSON.parse(source) : parseYaml(source);\n } catch (error) {\n throw invalid(\n `OpenAPI document \"${sourcePath}\" is not valid ${extension === '.json' ? 'JSON' : 'YAML'}: ${error instanceof Error ? error.message : String(error)}`,\n details,\n error,\n );\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw invalid(`OpenAPI document \"${sourcePath}\" is not an object`, details);\n }\n const document = parsed as Record<string, unknown>;\n\n const version = readVersion(document, sourcePath);\n // Before validation, not after: the validator resolves references, and the\n // no-network guarantee is only worth something if nothing external ever\n // reaches it\n rejectUnsupportedReferences(document, sourcePath);\n\n const result = await validate(document);\n if (!result.valid) {\n const first = result.errors?.[0];\n throw invalid(\n `OpenAPI document \"${sourcePath}\" is not a valid OpenAPI ${version} description: ${first ? `${first.message}${first.path ? ` (at ${first.path})` : ''}` : 'unknown validation error'}`,\n { ...details, errors: result.errors?.slice(0, 10) ?? [] },\n );\n }\n\n return { version, document, sourcePath };\n}\n\n/**\n * The `openapi` field decides, not the validator's own verdict: the validator\n * happily calls a Swagger 2.0 document valid, and importing one would mean\n * `host`/`basePath`/`schemes` and body-parameter conversion semantics that\n * nothing downstream understands. Refuse it by name so the operator is told to\n * convert rather than left guessing.\n */\nfunction readVersion(document: Record<string, unknown>, sourcePath: string): OpenApiVersion {\n const details = { sourcePath };\n if (typeof document['swagger'] === 'string') {\n throw invalid(\n `\"${sourcePath}\" is a Swagger ${document['swagger']} document. Only OpenAPI 3.0, 3.1 and 3.2 are supported - convert it first`,\n details,\n );\n }\n const declared = document['openapi'];\n if (typeof declared !== 'string') {\n throw invalid(`\"${sourcePath}\" has no \"openapi\" version field`, details);\n }\n const featureVersion = /^(\\d+\\.\\d+)(?:\\.|$)/.exec(declared)?.[1];\n if (featureVersion === undefined || !SUPPORTED_VERSIONS.has(featureVersion)) {\n throw invalid(\n `OpenAPI version \"${declared}\" is not supported. Supported: 3.0.x, 3.1.x, 3.2.x`,\n { ...details, version: declared },\n );\n }\n return featureVersion as OpenApiVersion;\n}\n\n/**\n * An external `$ref` is refused rather than fetched or read from disk: either\n * would be the importer acting on behalf of a document it was only asked to\n * read, by an outbound request or a filesystem read outside the source file.\n * Multi-file descriptions are out of scope, and refusing beats a silent partial\n * import. A malformed percent-escape is refused here too, because the\n * validator throws a bare `URIError` on one.\n */\nfunction rejectUnsupportedReferences(document: Record<string, unknown>, sourcePath: string): void {\n // Iterative with a seen set: YAML aliases can make the parsed graph cyclic,\n // and a deeply nested document would otherwise blow the call stack\n const seen = new WeakSet<object>();\n const queue: unknown[] = [document];\n while (queue.length > 0) {\n const node = queue.pop();\n if (typeof node !== 'object' || node === null) continue;\n if (seen.has(node)) continue;\n seen.add(node);\n if (Array.isArray(node)) {\n queue.push(...node);\n continue;\n }\n for (const [key, value] of Object.entries(node)) {\n if (key === '$ref' && typeof value === 'string') {\n if (!value.startsWith('#')) {\n throw invalid(\n `OpenAPI document \"${sourcePath}\" contains an external reference \"${value}\". Only internal references (#/...) are supported; the importer performs no network or filesystem lookups`,\n { sourcePath, ref: value },\n );\n }\n if (!isPercentDecodable(value)) {\n throw invalid(\n `OpenAPI document \"${sourcePath}\" contains a reference \"${value}\" with a malformed percent-escape`,\n { sourcePath, ref: value },\n );\n }\n }\n queue.push(value);\n }\n }\n}\n\nfunction isPercentDecodable(value: string): boolean {\n try {\n decodeURIComponent(value);\n return true;\n } catch {\n return false;\n }\n}\n","import { existsSync, mkdirSync } from 'node:fs';\nimport { writeFile } from 'node:fs/promises';\nimport { dirname, resolve } from 'node:path';\nimport * as clack from '@clack/prompts';\nimport { DEFAULT_CONFIG_FILENAME } from '../../config/filename';\nimport {\n type ConfigLoader,\n type ConfigParser,\n type GatewayConfig,\n loadConfigDynamic,\n parseConfigDynamic,\n} from '../lib/config-client';\nimport {\n buildInitConfigObject,\n defaultInitAnswers,\n type InitAnswers,\n type InitProtocolChoice,\n type InitResourceChoice,\n renderInitConfigYaml,\n} from '../lib/init-config';\nimport type { Io } from '../lib/io';\nimport { formatConfigError } from './validate';\n\nexport interface InitOptions {\n readonly outputPath?: string;\n readonly force?: boolean;\n readonly yes?: boolean;\n}\n\nexport interface InitDeps {\n readonly loadConfig?: ConfigLoader;\n readonly parseConfig?: ConfigParser;\n readonly collectAnswers?: () => Promise<InitAnswers | undefined>;\n readonly fileExists?: (path: string) => boolean;\n readonly writeFile?: (path: string, content: string) => Promise<void>;\n}\n\n/** The interactive prompt flow, exported so tests can drive it with a mocked `@clack/prompts` */\nexport async function collectAnswersInteractive(): Promise<InitAnswers | undefined> {\n clack.intro('agent-commerce init');\n\n const backendBaseUrl = await clack.text({\n message: 'Backend base URL (your existing merchant API)',\n initialValue: 'http://localhost:3000',\n // Checked here, where the user can retype it, rather than as a config error later\n validate: (value) => {\n const trimmed = (value ?? '').trim();\n if (trimmed.length === 0) return 'Required';\n let parsed: URL;\n try {\n parsed = new URL(trimmed);\n } catch {\n return 'Must be an absolute URL, e.g. http://localhost:3000';\n }\n return parsed.protocol === 'http:' || parsed.protocol === 'https:'\n ? undefined\n : 'Must use http:// or https://';\n },\n });\n if (clack.isCancel(backendBaseUrl)) {\n clack.cancel('Aborted.');\n return undefined;\n }\n\n const resources = await clack.multiselect<InitResourceChoice>({\n message: 'Which example resource(s) do you want to expose?',\n options: [\n { value: 'weather', label: 'Weather (free)' },\n { value: 'report', label: 'Market report (paid)' },\n ],\n initialValues: ['weather', 'report'],\n required: false,\n });\n if (clack.isCancel(resources)) {\n clack.cancel('Aborted.');\n return undefined;\n }\n\n const protocols = await clack.multiselect<InitProtocolChoice>({\n message: 'Which protocols should be enabled?',\n options: [\n { value: 'http', label: 'HTTP' },\n { value: 'mcp', label: 'MCP' },\n ],\n initialValues: ['http', 'mcp'],\n // Every resource needs at least one protocol in `expose`\n required: true,\n });\n if (clack.isCancel(protocols)) {\n clack.cancel('Aborted.');\n return undefined;\n }\n\n const x402Enabled = await clack.confirm({ message: 'Enable x402 payments?', initialValue: true });\n if (clack.isCancel(x402Enabled)) {\n clack.cancel('Aborted.');\n return undefined;\n }\n\n let merchantPayTo = defaultInitAnswers().merchantPayTo;\n if (x402Enabled) {\n const answer = await clack.text({\n message: 'Merchant settlement address (enter an address you control)',\n initialValue: merchantPayTo,\n validate: (value) => {\n const trimmed = (value ?? '').trim();\n if (trimmed.length === 0) return 'Required';\n // The shape config enforces, checked here so a typo can be retyped\n return /^0x[0-9a-fA-F]{40}$/.test(trimmed)\n ? undefined\n : 'Must be a 0x-prefixed 20-byte EVM address (42 characters)';\n },\n });\n if (clack.isCancel(answer)) {\n clack.cancel('Aborted.');\n return undefined;\n }\n merchantPayTo = answer;\n }\n\n clack.outro('Configuration answers collected.');\n\n return { backendBaseUrl, resources, protocols, x402Enabled, merchantPayTo };\n}\n\n/** `agent-commerce init [--yes] [--force] [--output <path>]` */\nexport async function runInit(options: InitOptions, io: Io, deps: InitDeps = {}): Promise<number> {\n const outputPath = options.outputPath ?? DEFAULT_CONFIG_FILENAME;\n const loadConfig = deps.loadConfig ?? loadConfigDynamic;\n const parseConfigInMemory = deps.parseConfig ?? parseConfigDynamic;\n const fileExists = deps.fileExists ?? existsSync;\n const writeFileImpl =\n deps.writeFile ??\n (async (path: string, content: string) => {\n await writeFile(path, content, 'utf8');\n });\n\n if (fileExists(outputPath) && options.force !== true) {\n io.stderr(`FAIL ${outputPath} already exists. Re-run with --force to overwrite.`);\n return 1;\n }\n\n const answers =\n options.yes === true\n ? defaultInitAnswers()\n : await (deps.collectAnswers ?? collectAnswersInteractive)();\n\n if (answers === undefined) {\n io.stderr('FAIL init aborted, nothing was written.');\n return 1;\n }\n\n // Validate before writing. When the answers fail validation nothing is\n // written, and the config error names the field to fix.\n let config: GatewayConfig;\n try {\n config = await parseConfigInMemory(buildInitConfigObject(answers));\n } catch (err) {\n io.stderr(formatConfigError(err));\n io.stderr(`FAIL Nothing was written to ${outputPath}.`);\n return 1;\n }\n\n const yamlContent = renderInitConfigYaml(answers);\n mkdirSync(dirname(resolve(outputPath)), { recursive: true });\n await writeFileImpl(outputPath, yamlContent);\n io.stdout(`PASS Wrote ${outputPath}`);\n io.stdout(`PASS ${outputPath} is valid: ${config.resources.length} resource(s)`);\n\n // The file is a YAML serialization of the object just validated, plus a\n // comment header. Loading it back catches the one failure the in-memory\n // check cannot see: a rendering bug.\n try {\n await loadConfig({ path: outputPath });\n } catch (err) {\n io.stderr(formatConfigError(err));\n io.stderr(\n `FAIL ${outputPath} was written but does not parse, although the same answers validated in memory. This is a bug in the config renderer; please report it.`,\n );\n return 1;\n }\n\n io.stdout('');\n io.stdout('Next steps:');\n io.stdout(` agent-commerce validate --config ${outputPath}`);\n // No `npm run dev:*`: those scripts exist only in a repo clone, and the\n // compose line says it needs one\n io.stdout(' docker compose up # start the local demo stack (from a repo clone)');\n io.stdout(` agent-commerce doctor --config ${outputPath}`);\n\n return 0;\n}\n","import { isCommerceError } from '../../core';\nimport { type ConfigLoader, loadConfigDynamic } from '../lib/config-client';\nimport type { Io } from '../lib/io';\nimport {\n fillEnvFromLocalChainManifest,\n LOCAL_CHAIN_MANIFEST_PATH,\n MANIFEST_FILLABLE_ENV_VAR_NAMES,\n type ManifestEnvFill,\n} from '../lib/manifest-env';\n\nexport interface ValidateOptions {\n readonly configPath?: string;\n}\n\nexport interface ValidateDeps {\n readonly loadConfig?: ConfigLoader;\n readonly fillEnvFromManifest?: (env: NodeJS.ProcessEnv) => ManifestEnvFill;\n}\n\n/**\n * Formats a config-loading failure into an actionable report.\n *\n * `src/config` reports file, YAML, schema and environment failures as\n * `CommerceError('CONFIG_INVALID')` with structured details, and\n * `config-client` reports a config module that fails to load as\n * `INTERNAL_ERROR`. Nothing here adds a resolved `${ENV}` value: the config\n * error names only the variable.\n *\n * When no manifest was found, an unresolved variable that `.deploy/local.json`\n * would supply gets a hint to run `npm run chain:deploy` (see\n * `../lib/manifest-env`).\n */\nexport function formatConfigError(err: unknown, manifestFound = false): string {\n if (isCommerceError(err)) {\n const lines = [`FAIL ${err.code}: ${err.message}`];\n if (err.details !== undefined) {\n lines.push(` details: ${JSON.stringify(err.details)}`);\n }\n const variable = err.details?.['variable'];\n if (\n !manifestFound &&\n typeof variable === 'string' &&\n MANIFEST_FILLABLE_ENV_VAR_NAMES.has(variable)\n ) {\n lines.push(\n ` hint: \"npm run chain:deploy\" writes ${LOCAL_CHAIN_MANIFEST_PATH}, which validate/doctor read automatically to fill local X402_*/MERCHANT_WALLET placeholders.`,\n );\n }\n return lines.join('\\n');\n }\n if (err instanceof Error) {\n return `FAIL ${err.message}`;\n }\n return `FAIL ${String(err)}`;\n}\n\n/** `agent-commerce validate [--config <path>]`. Exits non-zero on invalid configuration */\nexport async function runValidate(\n options: ValidateOptions,\n io: Io,\n deps: ValidateDeps = {},\n): Promise<number> {\n const loadConfig = deps.loadConfig ?? loadConfigDynamic;\n const fillEnvFromManifest = deps.fillEnvFromManifest ?? fillEnvFromLocalChainManifest;\n const { env, filled, manifestFound } = fillEnvFromManifest(process.env);\n if (filled.length > 0) {\n io.stdout(`using local chain manifest ${LOCAL_CHAIN_MANIFEST_PATH} for ${filled.join(', ')}`);\n }\n try {\n const config = await loadConfig({\n ...(options.configPath !== undefined ? { path: options.configPath } : {}),\n env,\n });\n io.stdout('PASS Configuration is valid');\n io.stdout(` merchant: ${config.merchant.name} (${config.merchant.id})`);\n io.stdout(` resources: ${config.resources.length}`);\n io.stdout(\n ` protocols: http=${config.protocols.http.enabled ? 'on' : 'off'} mcp=${config.protocols.mcp.enabled ? 'on' : 'off'} a2a=${config.protocols.a2a.enabled ? 'on' : 'off'} acp=${config.protocols.acp.enabled ? 'on' : 'off'}`,\n );\n const onOff = (enabled: boolean | undefined): string => (enabled === true ? 'on' : 'off');\n io.stdout(\n ` payments: x402=${onOff(config.payments.x402?.enabled)} mpp=${onOff(config.payments.mpp?.enabled)}`,\n );\n io.stdout(` authorization: ap2=${onOff(config.authorization?.ap2.enabled)}`);\n return 0;\n } catch (err) {\n io.stderr(formatConfigError(err, manifestFound));\n return 1;\n }\n}\n","import type { Io } from '../lib/io';\nimport { readVersionReport, type VersionReport } from '../lib/versions';\n\nexport interface VersionDeps {\n readonly readVersionReport?: () => VersionReport;\n}\n\n/** `agent-commerce version`: the CLI version and the pinned protocol/SDK versions */\nexport function runVersion(io: Io, deps: VersionDeps = {}): number {\n const report = (deps.readVersionReport ?? readVersionReport)();\n io.stdout(`agent-commerce v${report.cliVersion}`);\n if (report.pinned.length > 0) {\n io.stdout('');\n io.stdout('Pinned protocol / SDK versions:');\n const width = Math.max(...report.pinned.map((pin) => pin.name.length));\n for (const pin of report.pinned) {\n io.stdout(` ${pin.name.padEnd(width)} ${pin.version.padEnd(12)} (via ${pin.via})`);\n }\n }\n return 0;\n}\n","/**\n * Injectable stdout/stderr, so command logic is testable without capturing\n * the real process streams\n */\nexport interface Io {\n stdout(line: string): void;\n stderr(line: string): void;\n}\n\nexport const processIo: Io = {\n stdout: (line) => {\n process.stdout.write(`${line}\\n`);\n },\n stderr: (line) => {\n process.stderr.write(`${line}\\n`);\n },\n};\n","#!/usr/bin/env node\nimport { CommanderError } from 'commander';\nimport { buildProgram } from './program';\n\n/**\n * `agent-commerce version | grep -q x402` closes the pipe on grep's first\n * match while the CLI is still writing. Node reports that as an unhandled\n * `EPIPE` error and aborts with a stack trace, so a command that did what was\n * asked would read as a crash. Exit quietly on `EPIPE`; any other stream error\n * still throws.\n */\nfor (const stream of [process.stdout, process.stderr]) {\n stream.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EPIPE') process.exit(0);\n throw err;\n });\n}\n\nasync function main(): Promise<void> {\n const program = buildProgram();\n try {\n await program.parseAsync(process.argv);\n } catch (err) {\n if (err instanceof CommanderError) {\n process.exitCode = err.exitCode;\n return;\n }\n throw err;\n }\n}\n\nvoid main();\n"]}
|