@devlab.group/agent-commerce 2.3.0 → 2.4.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.
Files changed (62) hide show
  1. package/README.md +17 -13
  2. package/dist/ap2.d.ts +6 -5
  3. package/dist/ap2.js +3 -3
  4. package/dist/{authorization-CMkIuAkO.d.ts → authorization-DjAecwuW.d.ts} +1 -1
  5. package/dist/{chunk-TNS7U5Q4.js → chunk-CXWC5LWM.js} +200 -8
  6. package/dist/chunk-CXWC5LWM.js.map +1 -0
  7. package/dist/{chunk-Q5TII32R.js → chunk-DTKU3Z2M.js} +3 -3
  8. package/dist/{chunk-Q5TII32R.js.map → chunk-DTKU3Z2M.js.map} +1 -1
  9. package/dist/{chunk-XVU46YAH.js → chunk-QPV3EGJO.js} +4 -4
  10. package/dist/{chunk-XVU46YAH.js.map → chunk-QPV3EGJO.js.map} +1 -1
  11. package/dist/{chunk-4ZSE5DCH.js → chunk-WZW5ORZH.js} +3 -3
  12. package/dist/{chunk-4ZSE5DCH.js.map → chunk-WZW5ORZH.js.map} +1 -1
  13. package/dist/cli/{ap2-GINAXBFV.js → ap2-GWSP4LYY.js} +3 -3
  14. package/dist/cli/{ap2-GINAXBFV.js.map → ap2-GWSP4LYY.js.map} +1 -1
  15. package/dist/cli/{chunk-55N55KL4.js → chunk-G2JEY7MB.js} +22 -6
  16. package/dist/cli/chunk-G2JEY7MB.js.map +1 -0
  17. package/dist/cli/{chunk-KABFUZ6L.js → chunk-GJIMDMYT.js} +4 -4
  18. package/dist/cli/{chunk-KABFUZ6L.js.map → chunk-GJIMDMYT.js.map} +1 -1
  19. package/dist/cli/chunk-ITWNSS2B.js +8 -0
  20. package/dist/cli/{chunk-DYHVNKRB.js.map → chunk-ITWNSS2B.js.map} +1 -1
  21. package/dist/cli/{chunk-2LN5PO5I.js → chunk-PIMFPCNZ.js} +3 -2
  22. package/dist/cli/chunk-PIMFPCNZ.js.map +1 -0
  23. package/dist/cli/{chunk-BR7CMJOE.js → chunk-TNMLDPUO.js} +200 -8
  24. package/dist/cli/chunk-TNMLDPUO.js.map +1 -0
  25. package/dist/cli/{chunk-KTV52MCU.js → chunk-WYOGIANL.js} +3 -3
  26. package/dist/cli/{chunk-KTV52MCU.js.map → chunk-WYOGIANL.js.map} +1 -1
  27. package/dist/cli/{config-ZOFHJ5FB.js → config-UI4EDG4L.js} +5 -5
  28. package/dist/cli/{config-ZOFHJ5FB.js.map → config-UI4EDG4L.js.map} +1 -1
  29. package/dist/cli/index.js +87 -8
  30. package/dist/cli/index.js.map +1 -1
  31. package/dist/cli/{mcp-V3BNRUWL.js → mcp-PGBRWZVA.js} +3 -3
  32. package/dist/cli/{mcp-V3BNRUWL.js.map → mcp-PGBRWZVA.js.map} +1 -1
  33. package/dist/cli/{provider-BTIFALIT.js → provider-I2ESL6RS.js} +9 -6
  34. package/dist/cli/provider-I2ESL6RS.js.map +1 -0
  35. package/dist/cli/{run-DS2KXUTW.js → run-JK4ERPJV.js} +23 -12
  36. package/dist/cli/run-JK4ERPJV.js.map +1 -0
  37. package/dist/cli/{x402-YTKFNWVQ.js → x402-7WBFZQXV.js} +6 -6
  38. package/dist/cli/{x402-YTKFNWVQ.js.map → x402-7WBFZQXV.js.map} +1 -1
  39. package/dist/{constants-nackLItD.d.ts → constants-BG22tE8S.d.ts} +2 -1
  40. package/dist/index.d.ts +19 -11
  41. package/dist/index.js +32 -7
  42. package/dist/index.js.map +1 -1
  43. package/dist/mcp.d.ts +5 -4
  44. package/dist/mcp.js +1 -1
  45. package/dist/mpp.d.ts +5 -4
  46. package/dist/mpp.js +7 -4
  47. package/dist/mpp.js.map +1 -1
  48. package/dist/{networks-DTWRlj-K.d.ts → networks-DDHYJLcg.d.ts} +2 -1
  49. package/dist/{protocol-adapter-CfxU8Z2T.d.ts → protocol-adapter-C9odYl6l.d.ts} +4 -3
  50. package/dist/{runtime-7vLNYvmU.d.ts → runtime-Cl_BLVZV.d.ts} +8 -1
  51. package/dist/{types-CVw6Sf46.d.ts → types-j7MnUXYN.d.ts} +2 -1
  52. package/dist/x402.d.ts +27 -18
  53. package/dist/x402.js +4 -4
  54. package/package.json +6 -6
  55. package/dist/chunk-TNS7U5Q4.js.map +0 -1
  56. package/dist/cli/chunk-2LN5PO5I.js.map +0 -1
  57. package/dist/cli/chunk-55N55KL4.js.map +0 -1
  58. package/dist/cli/chunk-BR7CMJOE.js.map +0 -1
  59. package/dist/cli/chunk-DYHVNKRB.js +0 -8
  60. package/dist/cli/index.d.ts +0 -1
  61. package/dist/cli/provider-BTIFALIT.js.map +0 -1
  62. package/dist/cli/run-DS2KXUTW.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/commands/demo.ts","../../src/cli/lib/config-client.ts","../../src/cli/lib/http.ts","../../src/payments/x402/local-chain/manifest.ts","../../src/cli/lib/manifest-env.ts","../../package.json","../../src/cli/lib/versions.ts","../../src/cli/commands/doctor/storage.ts","../../src/cli/commands/doctor/ap2.ts","../../src/cli/lib/init-config.ts","../../src/cli/lib/mask.ts","../../src/cli/commands/doctor/payments.ts","../../src/cli/commands/doctor/protocols.ts","../../src/cli/commands/doctor/report.ts","../../src/cli/commands/doctor/index.ts","../../src/openapi/refs.ts","../../src/openapi/discover.ts","../../src/openapi/schema.ts","../../src/openapi/request.ts","../../src/openapi/draft.ts","../../src/openapi/load.ts","../../src/cli/commands/import-openapi.ts","../../src/cli/commands/validate.ts","../../src/cli/commands/init.ts","../../src/cli/commands/version.ts","../../src/cli/lib/io.ts","../../src/cli/program.ts","../../src/cli/index.ts"],"names":["readFileSync","join","fsConstants","existsSync","describe","text","open","required","parseYaml","extname","dirname","writeFile","resolve"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA2BO,SAAS,gBAAA,GAAwC;AACtD,EAAA,OAAO;AAAA,IACL;AAAA,MACE,IAAA,EAAM,gFAAA;AAAA,MACN,OAAA,EAAS,QAAA;AAAA,MACT,MAAM,CAAC,SAAA,EAAW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AEA,eAAe,IAAA,GAAsB;AACnC,EAAA,MAAM,UAAU,YAAA,EAAa;AAC7B,EAAA,OAAA,CAAQ,IAAA,CAAK,WAAA,EAAa,CAAC,QAAA,EAAU,OAAA,KAAY;AAC/C,IAAA,OAAA,GAAU,OAAA,CAAQ,MAAK,KAAM,OAAA;AAAA,EAC/B,CAAC,CAAA;AACD,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 * `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","/**\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 * 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 */\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\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/**\n * Checks for this package's name and a `chain:deploy` script in `cwd`, so\n * diagnostics can suggest the repository's local deployment command\n */\nexport function hasChainDeployScript(cwd: string = process.cwd()): boolean {\n try {\n const pkg = JSON.parse(readFileSync(join(cwd, 'package.json'), 'utf8')) as {\n name?: unknown;\n scripts?: Record<string, unknown>;\n };\n return (\n pkg.name === '@devlab.group/agent-commerce' &&\n typeof pkg.scripts?.['chain:deploy'] === 'string'\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Suggests `npm run chain:deploy` for manifest variables when the repository\n * script is available and no valid manifest was read. Otherwise names the\n * variable to set through the environment or `--env-file`.\n */\nexport function unresolvedVariableHint(\n variable: string,\n manifestFound: boolean,\n chainDeploy: boolean,\n): string {\n if (chainDeploy && !manifestFound && MANIFEST_FILLABLE_ENV_VAR_NAMES.has(variable)) {\n return `\"npm run chain:deploy\" writes ${LOCAL_CHAIN_MANIFEST_PATH}, which validate and doctor read to fill local X402_* and MERCHANT_WALLET placeholders`;\n }\n return `set ${variable} in the environment, or in a file passed with --env-file`;\n}\n","{\n \"name\": \"@devlab.group/agent-commerce\",\n \"version\": \"2.3.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 && node dist/cli/index.js start --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/server\": \"2.3.0\",\n \"@sd-jwt/core\": \"0.20.1\",\n \"@solana/kit\": \"5.5.1\",\n \"@x402/core\": \"2.25.0\",\n \"@x402/evm\": \"2.25.0\",\n \"@x402/near\": \"2.25.0\",\n \"@x402/svm\": \"2.25.0\",\n \"canonicalize\": \"5.0.0\",\n \"jose\": \"6.2.12\",\n \"mppx\": \"0.13.1\",\n \"viem\": \"2.57.1\"\n },\n \"peerDependenciesMeta\": {\n \"@coinbase/x402\": {\n \"optional\": true\n },\n \"@modelcontextprotocol/server\": {\n \"optional\": true\n },\n \"@sd-jwt/core\": {\n \"optional\": true\n },\n \"@solana/kit\": {\n \"optional\": true\n },\n \"@x402/core\": {\n \"optional\": true\n },\n \"@x402/evm\": {\n \"optional\": true\n },\n \"@x402/near\": {\n \"optional\": true\n },\n \"@x402/svm\": {\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.3.0\",\n \"@biomejs/biome\": \"2.5.9\",\n \"@coinbase/x402\": \"2.1.0\",\n \"@modelcontextprotocol/client\": \"2.3.0\",\n \"@modelcontextprotocol/sdk\": \"1.32.0\",\n \"@modelcontextprotocol/server\": \"2.3.0\",\n \"@near-js/accounts\": \"2.5.1\",\n \"@near-js/crypto\": \"2.5.1\",\n \"@near-js/providers\": \"2.5.1\",\n \"@near-js/signers\": \"2.5.1\",\n \"@near-js/transactions\": \"2.5.1\",\n \"@sd-jwt/core\": \"0.20.1\",\n \"@solana/kit\": \"5.5.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.25.0\",\n \"@x402/evm\": \"2.25.0\",\n \"@x402/mcp\": \"2.25.0\",\n \"@x402/near\": \"2.25.0\",\n \"@x402/svm\": \"2.25.0\",\n \"canonicalize\": \"5.0.0\",\n \"jose\": \"6.2.12\",\n \"mppx\": \"0.13.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.57.1\",\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/server', 'protocols/mcp'],\n ['ajv', 'protocols/acp'],\n ['ajv-formats', 'protocols/acp'],\n ['@x402/core', 'payments/x402'],\n ['@x402/evm', 'payments/x402'],\n ['@x402/svm', 'payments/x402'],\n ['@solana/kit', 'payments/x402'],\n ['@x402/near', '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","// Storage checks: the receipt store, and the SQLite files other features keep\nimport { accessSync, existsSync, constants as fsConstants } from 'node:fs';\nimport { dirname } from 'node:path';\nimport type { ReceiptStore } from '../../../core';\nimport type { GatewayConfig } from '../../lib/config-client';\nimport type { CheckStatus, DoctorCheck } from './types';\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.\nexport function 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\nexport async function storageChecks(\n config: GatewayConfig | undefined,\n createStore: (path: string) => ReceiptStore,\n): Promise<DoctorCheck[]> {\n const checks: DoctorCheck[] = [];\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 let uncertainCount: number | undefined;\n try {\n // Count uncertain settlements separately because they produce no receipt\n uncertainCount = await store.countUncertainPaymentAttempts();\n } catch {\n uncertainCount = 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 const uncertainSuffix =\n uncertainCount !== undefined && uncertainCount > 0\n ? `; ${uncertainCount} payment(s) with unknown settlement outcome, see GET /api/payment-attempts?uncertain=true`\n : '';\n checks.push({\n name: 'Storage',\n status,\n detail: `${storeHealth.detail ?? 'sqlite'}${receiptsSuffix}${uncertainSuffix}`,\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 return checks;\n}\n","// AP2 checks: settings, trust lists, the replay store and the gated resources\n\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 { GatewayConfig } from '../../lib/config-client';\nimport { storeFileCheck } from './storage';\nimport type { DoctorCheck } from './types';\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\nexport function ap2Checks(config: GatewayConfig | undefined): DoctorCheck[] {\n const checks: DoctorCheck[] = [];\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 · mandate aud ${ap2.requireMandateAudience === true ? 'required' : 'optional'} · mandate exp ${ap2.requireMandateExpiry === true ? 'required' : 'optional'}`,\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 return checks;\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';\nimport { LOCAL_CHAIN_ID } from '../../payments/x402/networks';\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:${LOCAL_CHAIN_ID}`,\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, /api/payment-attempts) return 404. These routes\n# expose the merchant's commerce ledger: payer addresses, amounts and settlement\n# hashes. To enable them, add 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 * 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","// Payment checks: where each rail settles, and whether the running gateway agrees\n\nimport { isRecord } from '../../../core/is-record';\nimport {\n MPP_DEFAULT_PAYMENT_FLOW,\n MPP_PROFILE,\n MPP_SPEC_COMMIT,\n MPP_SPEC_DRAFTS,\n MPPX_VERSION,\n} from '../../../payments/mpp/constants';\nimport { sameAddress } from '../../../payments/x402/addresses';\nimport type { X402FacilitatorConfig } from '../../../payments/x402/guardrails';\nimport {\n type CustomNetworks,\n type DeploymentMode,\n describeDeploymentMode,\n findX402Network,\n resolveDeploymentMode,\n} from '../../../payments/x402/networks';\nimport { X402_DEFAULT_PAYMENT_FLOW } from '../../../payments/x402/payment-flow';\nimport type { GatewayConfig } from '../../lib/config-client';\nimport { PLACEHOLDER_ASSET_ADDRESS } from '../../lib/init-config';\nimport { maskMiddle } from '../../lib/mask';\nimport type { DoctorCheck, WellKnownResult } from './types';\n\n// The rail's settlement order and how many resources override it\nfunction describePaymentFlow(\n rail: {\n readonly paymentFlow?: string | undefined;\n readonly resourcePaymentFlows?: Readonly<Record<string, string>> | undefined;\n },\n defaultFlow: string,\n): string {\n const overrides = Object.keys(rail.resourcePaymentFlows ?? {}).length;\n const overrideCount =\n overrides > 0 ? ` (${overrides} resource ${overrides === 1 ? 'override' : 'overrides'})` : '';\n return `paymentFlow=${rail.paymentFlow ?? defaultFlow}${overrideCount}`;\n}\n\n// One offer's public settlement terms; `payTo` holds x402 `payTo` or MPP `recipient`\ninterface RailOffer {\n readonly network: string;\n readonly asset: string;\n readonly payTo: string;\n readonly assetDecimals?: number;\n /** Absent for EIP-3009 and for every non-EVM offer */\n readonly assetTransferMethod?: string;\n /** The live offer's health status, when the gateway publishes it */\n readonly status?: string;\n}\n\n// A rail's terms, as configured or as the running gateway publishes them\ninterface RailTerms {\n readonly offers: readonly RailOffer[];\n /** Resources with their own offers, by id */\n readonly resourceOffers?: Readonly<Record<string, readonly RailOffer[]>>;\n /** Absent from a gateway that does not publish its flows */\n readonly paymentFlow?: string;\n readonly resourcePaymentFlows?: Readonly<Record<string, string>>;\n}\n\n// Result of reading a live x402 or MPP block\ntype LiveRailResult = RailTerms | 'disabled' | undefined;\n\nfunction readOffer(rec: Record<string, unknown>, rail: 'x402' | 'mpp'): RailOffer | undefined {\n const { asset, network, assetDecimals, assetTransferMethod, status } = 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 {\n network,\n asset,\n payTo,\n ...(typeof assetDecimals === 'number' ? { assetDecimals } : {}),\n ...(typeof assetTransferMethod === 'string' ? { assetTransferMethod } : {}),\n ...(typeof status === 'string' ? { status } : {}),\n };\n}\n\n// A list of offers, or undefined when any entry is malformed\nfunction readOffers(value: unknown, rail: 'x402' | 'mpp'): RailOffer[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const read = value.map((entry) => (isRecord(entry) ? readOffer(entry, rail) : undefined));\n return read.some((offer) => offer === undefined) ? undefined : (read as RailOffer[]);\n}\n\n/**\n * Reads offers and flows from discovery. Explicit `enabled: false` signals\n * a mismatch; missing or invalid offer data leaves comparison inconclusive.\n */\nfunction extractLiveRail(\n body: Record<string, unknown> | undefined,\n rail: 'x402' | 'mpp' = 'x402',\n): LiveRailResult {\n const block = isRecord(body?.['payments']) ? body['payments'][rail] : undefined;\n if (!isRecord(block)) return undefined;\n if (block['enabled'] === false) return 'disabled';\n if (block['enabled'] !== true) return undefined;\n const first = readOffer(block, rail);\n if (first === undefined) return undefined;\n // The block's own fields repeat the first offer; `options` lists them all\n let offers: readonly RailOffer[] = [first];\n if (block['options'] !== undefined) {\n const listed = readOffers(block['options'], rail);\n if (listed === undefined) return undefined;\n offers = listed;\n }\n let resourceOffers: Record<string, readonly RailOffer[]> | undefined;\n const ownLists = block['resourceOptions'];\n if (ownLists !== undefined) {\n if (!isRecord(ownLists)) return undefined;\n resourceOffers = {};\n for (const [id, list] of Object.entries(ownLists)) {\n const read = readOffers(list, rail);\n if (read === undefined) return undefined;\n resourceOffers[id] = read;\n }\n }\n const { paymentFlow, resourcePaymentFlows } = block;\n return {\n offers,\n ...(resourceOffers !== undefined ? { resourceOffers } : {}),\n ...(typeof paymentFlow === 'string' ? { paymentFlow } : {}),\n ...(isRecord(resourcePaymentFlows)\n ? {\n resourcePaymentFlows: Object.fromEntries(\n Object.entries(resourcePaymentFlows).map(([id, flow]) => [id, String(flow)]),\n ),\n }\n : {}),\n };\n}\n\nfunction describeOverrides(flows: Readonly<Record<string, string>> | undefined): string {\n const entries = Object.entries(flows ?? {}).sort(([a], [b]) => a.localeCompare(b));\n return entries.length > 0 ? entries.map(([id, flow]) => `${id}=${flow}`).join(', ') : 'none';\n}\n\n/**\n * Compares offers in challenge order, then published flows, with local config.\n * Mismatches name both values for the operator.\n */\nfunction findRailMismatch(\n configured: RailTerms,\n live: RailTerms,\n payToField = 'payTo',\n customNetworks?: CustomNetworks,\n): string | undefined {\n const diffs: string[] = [];\n const differ = (field: string, liveValue: unknown, localValue: unknown) =>\n diffs.push(\n `${field}: gateway is using ${liveValue} but local config resolves to ${localValue}`,\n );\n const compareOffers = (\n label: string,\n localOffers: readonly RailOffer[],\n liveOffers: readonly RailOffer[],\n ) => {\n if (liveOffers.length !== localOffers.length) {\n differ(label, `${liveOffers.length} offer(s)`, localOffers.length);\n return;\n }\n localOffers.forEach((local, index) => {\n const remote = liveOffers[index] as RailOffer;\n const prefix =\n label !== 'options'\n ? `${label}[${index}] `\n : localOffers.length > 1\n ? `option ${index} `\n : '';\n // EVM addresses compare without case; Solana's and NEAR's compare exactly\n const profile = findX402Network(local.network, customNetworks);\n const same = (a: string, b: string) => (profile ? sameAddress(profile, a, b) : a === b);\n if (local.network !== remote.network) {\n differ(`${prefix}network`, `\"${remote.network}\"`, `\"${local.network}\"`);\n }\n if (!same(local.asset, remote.asset)) differ(`${prefix}asset`, remote.asset, local.asset);\n if (!same(local.payTo, remote.payTo)) {\n differ(`${prefix}${payToField}`, remote.payTo, local.payTo);\n }\n if (\n local.assetDecimals !== undefined &&\n remote.assetDecimals !== undefined &&\n local.assetDecimals !== remote.assetDecimals\n ) {\n differ(`${prefix}assetDecimals`, remote.assetDecimals, local.assetDecimals);\n }\n if (local.assetTransferMethod !== remote.assetTransferMethod) {\n differ(\n `${prefix}assetTransferMethod`,\n remote.assetTransferMethod ?? 'eip3009',\n local.assetTransferMethod ?? 'eip3009',\n );\n }\n });\n };\n compareOffers('options', configured.offers, live.offers);\n const localLists = configured.resourceOffers ?? {};\n const liveLists = live.resourceOffers ?? {};\n for (const id of [...new Set([...Object.keys(localLists), ...Object.keys(liveLists)])].sort()) {\n compareOffers(`resources.${id}.x402.accepts`, localLists[id] ?? [], liveLists[id] ?? []);\n }\n // A gateway that publishes no flows cannot be compared on them\n if (live.paymentFlow !== undefined) {\n if (live.paymentFlow !== configured.paymentFlow) {\n differ('paymentFlow', live.paymentFlow, configured.paymentFlow);\n }\n const liveOverrides = describeOverrides(live.resourcePaymentFlows);\n const localOverrides = describeOverrides(configured.resourcePaymentFlows);\n if (liveOverrides !== localOverrides)\n differ('resourcePaymentFlows', liveOverrides, localOverrides);\n }\n return diffs.length === 0 ? undefined : diffs.join('; ');\n}\n\n/**\n * Where a rail settles and through which facilitator. `parseConfig` refuses an\n * unknown network, so an absent profile means another loader produced this\n * config, and the text says so rather than guessing.\n */\nfunction describeSettlement(\n network: string,\n facilitator: X402FacilitatorConfig,\n customNetworks?: CustomNetworks,\n): { readonly mode: DeploymentMode | undefined; readonly where: string; readonly via: string } {\n const profile = findX402Network(network, customNetworks);\n const mode = profile ? resolveDeploymentMode(profile) : undefined;\n const where =\n profile === undefined || mode === undefined\n ? `unknown network ${network}`\n : mode === 'local'\n ? `LOCAL dev chain (${network})`\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 networks: readonly string[],\n): DoctorCheck {\n const unauthenticated = facilitator.mode === 'remote' && facilitator.auth.type === 'none';\n const where = `${describeDeploymentMode('mainnet')} on ${networks.join(', ')}`;\n return {\n name,\n status: unauthenticated ? 'WARN' : 'INFO',\n detail: unauthenticated\n ? `${where}: 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 : `${where}. Enforced at config load: explicit allowMainnet ` +\n `opt-in, remote facilitator over HTTPS with a credential, non-development ${payToField}, ` +\n 'and the canonical asset of each network. Payments fail closed.',\n };\n}\n\nfunction railOffer(option: {\n readonly network: string;\n readonly asset: string;\n readonly payTo: string;\n readonly assetDecimals: number;\n readonly assetTransferMethod?: string;\n}): RailOffer {\n const { network, asset, payTo, assetDecimals, assetTransferMethod } = option;\n return {\n network,\n asset,\n payTo,\n assetDecimals,\n ...(assetTransferMethod !== undefined ? { assetTransferMethod } : {}),\n };\n}\n\n// Discovery exposes offer statuses; reasons stay in gateway debug logs\nfunction offerHealthCheck(\n live: RailTerms,\n named: (network: string) => string,\n): DoctorCheck | undefined {\n const all = [...live.offers, ...Object.values(live.resourceOffers ?? {}).flat()];\n const offers = [\n ...new Map(\n all.map((offer) => [`${offer.network} ${offer.asset} ${offer.payTo}`, offer]),\n ).values(),\n ];\n const reported = offers.filter((offer) => offer.status !== undefined);\n if (reported.length === 0) return undefined;\n const failing = reported.filter((offer) => offer.status === 'fail');\n const degraded = reported.filter((offer) => offer.status === 'warn');\n const describe = (list: readonly RailOffer[]) =>\n list\n .map(\n (offer) =>\n `${named(offer.network)} ${maskMiddle(offer.asset)} to ${maskMiddle(offer.payTo)}`,\n )\n .join('; ');\n if (failing.length === 0 && degraded.length === 0) {\n return {\n name: 'Payments (offers)',\n status: 'PASS',\n detail: `${reported.length} offer(s) pass their health checks`,\n };\n }\n const problems = [\n ...(failing.length > 0 ? [`failing: ${describe(failing)}`] : []),\n ...(degraded.length > 0 ? [`degraded: ${describe(degraded)}`] : []),\n ];\n return {\n name: 'Payments (offers)',\n status: failing.length > 0 ? 'FAIL' : 'WARN',\n detail: `${problems.join('; ')}. The gateway logs each reason at debug level`,\n };\n}\n\n// x402 and MPP, each compared with what the running gateway reports\nexport function paymentChecks(\n config: GatewayConfig | undefined,\n wellKnown: WellKnownResult | undefined,\n gatewayUrl: string,\n chainDeploy = false,\n): DoctorCheck[] {\n const checks: DoctorCheck[] = [];\n // Suggest the repository deployment script only when the caller found it\n const stale = `; the gateway may be running against an older deployment - restart it${chainDeploy ? ' or re-run chain:deploy' : ''}`;\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 options = x402.options ?? [x402];\n const resourceOptions = x402.resourceOptions ?? {};\n // Every configured offer, the rail's and each resource's\n const everyOption = [...options, ...Object.values(resourceOptions).flat()];\n const { mode, where, via } = describeSettlement(x402.network, x402.facilitator, x402.networks);\n const flow = describePaymentFlow(x402, X402_DEFAULT_PAYMENT_FLOW);\n const named = (network: string) =>\n `${findX402Network(network, x402.networks)?.displayName ?? 'unknown network'} (${network})`;\n const terms =\n options.length === 1\n ? `${where}, destination=${maskMiddle(x402.payTo)}`\n : `${mode !== undefined ? describeDeploymentMode(mode) : 'unknown mode'}, ${options.length} options: ` +\n options\n .map((option) => `${named(option.network)} to ${maskMiddle(option.payTo)}`)\n .join('; ');\n const ownCount = Object.keys(resourceOptions).length;\n const own =\n ownCount > 0\n ? `, ${ownCount} resource${ownCount === 1 ? '' : 's'} with ${ownCount === 1 ? 'its' : 'their'} own offers`\n : '';\n const summary = `x402 v2 (scheme=exact) enabled - ${terms}${own}, facilitator=${via}, ${flow}`;\n const live = wellKnown?.ok ? extractLiveRail(wellKnown.body) : undefined;\n const placeholder = PLACEHOLDER_ASSET_ADDRESS.toLowerCase();\n if (everyOption.some((option) => option.asset.toLowerCase() === placeholder)) {\n // Matching live and local config does not establish that a placeholder\n // address has a token contract\n checks.push({\n name: 'Payments',\n status: 'WARN',\n detail: `${summary}, but at least one offer uses the init placeholder ${maskMiddle(PLACEHOLDER_ASSET_ADDRESS)}. Set that offer's asset to its token contract address${chainDeploy ? ' (${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 configured: RailTerms = {\n offers: options.map(railOffer),\n ...(ownCount > 0\n ? {\n resourceOffers: Object.fromEntries(\n Object.entries(resourceOptions).map(([id, list]) => [id, list.map(railOffer)]),\n ),\n }\n : {}),\n paymentFlow: x402.paymentFlow ?? X402_DEFAULT_PAYMENT_FLOW,\n ...(x402.resourcePaymentFlows !== undefined\n ? { resourcePaymentFlows: x402.resourcePaymentFlows }\n : {}),\n };\n const mismatch = findRailMismatch(configured, live, 'payTo', x402.networks);\n checks.push(\n mismatch === undefined\n ? { name: 'Payments', status: 'PASS', detail: summary }\n : { name: 'Payments', status: 'FAIL', detail: `${mismatch}${stale}` },\n );\n const offerHealth = offerHealthCheck(live, named);\n if (offerHealth !== undefined) checks.push(offerHealth);\n }\n if (mode === 'mainnet') {\n checks.push(\n mainnetSafetyCheck('Mainnet safety', 'payTo', x402.facilitator, [\n ...new Set(everyOption.map((option) => named(option.network))),\n ]),\n );\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 `${describePaymentFlow(mpp, MPP_DEFAULT_PAYMENT_FLOW)}, ` +\n `spec ${MPP_SPEC_DRAFTS.core}@${MPP_SPEC_COMMIT.slice(0, 7)}, mppx ${MPPX_VERSION}`;\n const configured: RailTerms = {\n offers: [\n {\n network: mpp.network,\n asset: mpp.asset,\n payTo: mpp.recipient,\n assetDecimals: MPP_PROFILE.assetDecimals,\n },\n ],\n paymentFlow: mpp.paymentFlow ?? MPP_DEFAULT_PAYMENT_FLOW,\n ...(mpp.resourcePaymentFlows !== undefined\n ? { resourcePaymentFlows: mpp.resourcePaymentFlows }\n : {}),\n };\n const live = wellKnown?.ok ? extractLiveRail(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 = findRailMismatch(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}${stale}` },\n );\n }\n if (mode === 'mainnet') {\n checks.push(\n mainnetSafetyCheck('Mainnet safety (MPP)', 'recipient', mpp.facilitator, [\n `${findX402Network(mpp.network)?.displayName ?? 'unknown network'} (${mpp.network})`,\n ]),\n );\n }\n }\n return checks;\n}\n","// Protocol checks: what is enabled, and the A2A and ACP specifics\n\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 type { GatewayConfig } from '../../lib/config-client';\nimport { storeFileCheck } from './storage';\nimport type { DoctorCheck, WellKnownResult } from './types';\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// Protocols, then the A2A and ACP specifics\nexport function protocolChecks(\n config: GatewayConfig | undefined,\n wellKnown: WellKnownResult | undefined,\n): DoctorCheck[] {\n const checks: DoctorCheck[] = [];\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 return checks;\n}\n","// Prints a doctor report as text or JSON\nimport picocolors from 'picocolors';\nimport type { Io } from '../../lib/io';\nimport type { CheckStatus, DoctorReport } from './types';\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","// `agent-commerce doctor`: config, the running gateway, protocols, payments and storage\nimport { type CommerceResource, isCommerceError } from '../../../core';\nimport { extractPathParameterNames } from '../../../core/execution';\nimport { createSqliteReceiptStore } from '../../../storage/receipts';\nimport { type GatewayConfig, loadConfigDynamic } from '../../lib/config-client';\nimport { fetchJson } from '../../lib/http';\nimport {\n fillEnvFromLocalChainManifest,\n hasChainDeployScript,\n LOCAL_CHAIN_MANIFEST_PATH,\n unresolvedVariableHint,\n} from '../../lib/manifest-env';\nimport { readVersionReport } from '../../lib/versions';\nimport { ap2Checks } from './ap2';\nimport { paymentChecks } from './payments';\nimport { protocolChecks } from './protocols';\nimport { storageChecks } from './storage';\nimport type { CheckStatus, DoctorCheck, DoctorDeps, DoctorOptions, DoctorReport } from './types';\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/** `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 const chainDeploy = (deps.hasChainDeployScript ?? hasChainDeployScript)();\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 typeof variable === 'string'\n ? `. Hint: ${unresolvedVariableHint(variable, manifestFound, chainDeploy)}`\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-7. Protocols, AP2, payments and storage\n checks.push(...protocolChecks(config, wellKnown));\n checks.push(...ap2Checks(config));\n checks.push(...paymentChecks(config, wellKnown, gatewayUrl, chainDeploy));\n checks.push(...(await storageChecks(config, createStore)));\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\nexport { printDoctorReport } from './report';\nexport type { CheckStatus, DoctorCheck, DoctorDeps, DoctorOptions, DoctorReport } from './types';\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 * 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 * 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 * 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 * 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 * 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","/**\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 { mkdir, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, 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 // Like `init --output`: a missing output directory is created, not an error\n await mkdir(dirname(target), { recursive: true });\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","import { isCommerceError } from '../../core';\nimport { type ConfigLoader, loadConfigDynamic } from '../lib/config-client';\nimport type { Io } from '../lib/io';\nimport {\n fillEnvFromLocalChainManifest,\n hasChainDeployScript,\n LOCAL_CHAIN_MANIFEST_PATH,\n type ManifestEnvFill,\n unresolvedVariableHint,\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 readonly hasChainDeployScript?: () => boolean;\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 * An unresolved variable also gets a hint naming where to set it (see\n * `unresolvedVariableHint`).\n */\nexport function formatConfigError(\n err: unknown,\n manifestFound = false,\n chainDeploy = hasChainDeployScript(),\n): 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 (typeof variable === 'string') {\n lines.push(` hint: ${unresolvedVariableHint(variable, manifestFound, chainDeploy)}`);\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/**\n * `agent-commerce validate [--config <path>] [--env-file <path>]`. Exits\n * non-zero on invalid configuration.\n */\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(\n formatConfigError(err, manifestFound, (deps.hasChainDeployScript ?? hasChainDeployScript)()),\n );\n return 1;\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 { isEvmAddress } from '../../payments/x402/addresses';\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 isEvmAddress(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 // start imports the peers of each enabled feature, so name only those\n const peers = [\n ...(config.payments.x402?.enabled === true ? ['x402'] : []),\n ...(config.protocols.mcp.enabled ? ['MCP'] : []),\n ];\n const startNote =\n peers.length > 0 ? `needs the ${peers.join(' and ')} peers` : 'needs no optional peers';\n\n io.stdout('');\n io.stdout('Next steps:');\n io.stdout(` agent-commerce validate --config ${outputPath}`);\n io.stdout(` agent-commerce start --config ${outputPath} # ${startNote}`);\n io.stdout(` agent-commerce doctor --config ${outputPath} # from a second terminal`);\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 # or the whole local demo stack, from a repo clone');\n\n return 0;\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","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 { formatConfigError, runValidate } from './commands/validate';\nimport { runVersion } from './commands/version';\nimport { type Io, processIo } from './lib/io';\nimport { readVersionReport } from './lib/versions';\n\nconst ENV_FILE_HELP = 'load environment variables from this file; variables already set win';\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, start, 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 // Load before the action reads config; existing environment variables win.\n // Node 24.8.0 checks --env-file paths anywhere on the command line but does\n // not load files named after the script, so this hook handles those paths.\n .hook('preAction', (_program, command) => {\n const { envFile } = command.opts<{ envFile?: string }>();\n if (envFile === undefined) return;\n try {\n process.loadEnvFile(envFile);\n } catch (error) {\n command.error(\n `error: cannot read --env-file \"${envFile}\": ${error instanceof Error ? error.message : String(error)}`,\n );\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 .option('--env-file <path>', ENV_FILE_HELP)\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('start')\n .description(\n `Start the gateway from ${DEFAULT_CONFIG_FILENAME} and serve until SIGTERM or SIGINT.`,\n )\n .option('--config <path>', `path to ${DEFAULT_CONFIG_FILENAME}`)\n .option('--env-file <path>', ENV_FILE_HELP)\n .action(async (opts: { config?: string }) => {\n try {\n // Loaded on demand: the gateway brings fastify, and each enabled\n // feature its optional peers, which no other command may need\n const { runGateway } = await import('../gateway/run');\n await runGateway(opts.config !== undefined ? { configPath: opts.config } : {});\n } catch (error) {\n // The same report as validate. start never reads the local chain\n // manifest, so the hint for an unset variable must not suggest it.\n io.stderr(formatConfigError(error, false, false));\n // Do not wait on anything a failed startup left open\n process.exit(1);\n }\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('--env-file <path>', ENV_FILE_HELP)\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","#!/usr/bin/env node\nimport { CommanderError } from 'commander';\nimport { buildProgram } from './program';\n\n// Set when `start` runs, which serves until a signal rather than finishing\nlet serving = false;\n\n// A reader such as `grep -q` can close the pipe before the CLI finishes writing.\n// Exit quietly on EPIPE for finite commands. Keep `start` serving: exiting would\n// invoke pino's synchronous flush, whose sonic-boom retry loop hangs on EPIPE.\nfor (const stream of [process.stdout, process.stderr]) {\n stream.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code !== 'EPIPE') throw err;\n if (!serving) process.exit(0);\n });\n}\n\nasync function main(): Promise<void> {\n const program = buildProgram();\n program.hook('preAction', (_program, command) => {\n serving = command.name() === 'start';\n });\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/cli/commands/demo.ts","../../src/cli/lib/config-client.ts","../../src/cli/lib/http.ts","../../src/payments/x402/local-chain/manifest.ts","../../src/cli/lib/manifest-env.ts","../../package.json","../../src/cli/lib/versions.ts","../../src/cli/commands/doctor/storage.ts","../../src/cli/commands/doctor/ap2.ts","../../src/cli/lib/init-config.ts","../../src/cli/lib/mask.ts","../../src/cli/commands/doctor/payments.ts","../../src/cli/commands/doctor/protocols.ts","../../src/cli/commands/doctor/report.ts","../../src/cli/commands/doctor/index.ts","../../src/openapi/refs.ts","../../src/openapi/discover.ts","../../src/openapi/schema.ts","../../src/openapi/request.ts","../../src/openapi/draft.ts","../../src/openapi/load.ts","../../src/cli/commands/import-openapi.ts","../../src/cli/commands/validate.ts","../../src/cli/commands/init.ts","../../src/cli/commands/version.ts","../../src/cli/lib/io.ts","../../src/cli/program.ts","../../src/cli/index.ts"],"names":["readFileSync","join","fsConstants","existsSync","describe","text","open","required","parseYaml","extname","dirname","writeFile","resolve"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA2BO,SAAS,gBAAA,GAAwC;AACtD,EAAA,OAAO;AAAA,IACL;AAAA,MACE,IAAA,EAAM,gFAAA;AAAA,MACN,OAAA,EAAS,QAAA;AAAA,MACT,MAAM,CAAC,SAAA,EAAW,IAAA,EAAM,SAAA,EAAW,YAAY,QAAQ;AAAA,KACzD;AAAA,IACA,EAAE,MAAM,mCAAA,EAAqC,OAAA,EAAS,OAAO,IAAA,EAAM,CAAC,KAAA,EAAO,YAAY,CAAA;AAAE,GAC3F;AACF;AAGA,eAAsB,OAAA,CAAQ,EAAA,EAAQ,IAAA,GAAiB,EAAC,EAAoB;AAC1E,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAA,IAAS,gBAAA,EAAiB;AAC7C,EAAA,MAAM,GAAA,GAAM,KAAK,GAAA,IAAO,WAAA;AAExB,EAAA,EAAA,CAAG,OAAO,6EAA6E,CAAA;AACvF,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,EAAA,CAAG,OAAO,EAAE,CAAA;AACZ,IAAA,EAAA,CAAG,MAAA,CAAO,CAAA,IAAA,EAAO,IAAA,CAAK,IAAI,CAAA,CAAE,CAAA;AAC5B,IAAA,EAAA,CAAG,MAAA,CAAO,CAAA,MAAA,EAAS,IAAA,CAAK,OAAO,CAAA,CAAA,EAAI,KAAK,IAAA,CAAK,IAAA,CAAK,GAAG,CAAC,CAAA,CAAE,CAAA;AACxD,IAAA,MAAM,SAAS,MAAM,GAAA,CAAI,IAAA,CAAK,OAAA,EAAS,KAAK,IAAI,CAAA;AAChD,IAAA,IAAI,MAAA,CAAO,SAAS,CAAA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AAa,CAAC,QAAA,EAAU,OAAA,KAAY;AAC/C,IAAA,OAAA,GAAU,OAAA,CAAQ,MAAK,KAAM,OAAA;AAAA,EAC/B,CAAC,CAAA;AACD,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 * `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","/**\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 * 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 */\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\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/**\n * Checks for this package's name and a `chain:deploy` script in `cwd`, so\n * diagnostics can suggest the repository's local deployment command\n */\nexport function hasChainDeployScript(cwd: string = process.cwd()): boolean {\n try {\n const pkg = JSON.parse(readFileSync(join(cwd, 'package.json'), 'utf8')) as {\n name?: unknown;\n scripts?: Record<string, unknown>;\n };\n return (\n pkg.name === '@devlab.group/agent-commerce' &&\n typeof pkg.scripts?.['chain:deploy'] === 'string'\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Suggests `npm run chain:deploy` for manifest variables when the repository\n * script is available and no valid manifest was read. Otherwise names the\n * variable to set through the environment or `--env-file`.\n */\nexport function unresolvedVariableHint(\n variable: string,\n manifestFound: boolean,\n chainDeploy: boolean,\n): string {\n if (chainDeploy && !manifestFound && MANIFEST_FILLABLE_ENV_VAR_NAMES.has(variable)) {\n return `\"npm run chain:deploy\" writes ${LOCAL_CHAIN_MANIFEST_PATH}, which validate and doctor read to fill local X402_* and MERCHANT_WALLET placeholders`;\n }\n return `set ${variable} in the environment, or in a file passed with --env-file`;\n}\n","{\n \"name\": \"@devlab.group/agent-commerce\",\n \"version\": \"2.4.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 && node dist/cli/index.js start --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.7\",\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/server\": \"2.3.0\",\n \"@sd-jwt/core\": \"0.20.1\",\n \"@solana/kit\": \"5.5.1\",\n \"@x402/core\": \"2.25.0\",\n \"@x402/evm\": \"2.25.0\",\n \"@x402/near\": \"2.25.0\",\n \"@x402/svm\": \"2.25.0\",\n \"canonicalize\": \"5.0.0\",\n \"jose\": \"6.2.12\",\n \"mppx\": \"0.13.1\",\n \"viem\": \"2.57.1\"\n },\n \"peerDependenciesMeta\": {\n \"@coinbase/x402\": {\n \"optional\": true\n },\n \"@modelcontextprotocol/server\": {\n \"optional\": true\n },\n \"@sd-jwt/core\": {\n \"optional\": true\n },\n \"@solana/kit\": {\n \"optional\": true\n },\n \"@x402/core\": {\n \"optional\": true\n },\n \"@x402/evm\": {\n \"optional\": true\n },\n \"@x402/near\": {\n \"optional\": true\n },\n \"@x402/svm\": {\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.3.0\",\n \"@biomejs/biome\": \"2.5.9\",\n \"@coinbase/x402\": \"2.1.0\",\n \"@modelcontextprotocol/client\": \"2.3.0\",\n \"@modelcontextprotocol/sdk\": \"1.32.0\",\n \"@modelcontextprotocol/server\": \"2.3.0\",\n \"@near-js/accounts\": \"2.5.1\",\n \"@near-js/crypto\": \"2.5.1\",\n \"@near-js/providers\": \"2.5.1\",\n \"@near-js/signers\": \"2.5.1\",\n \"@near-js/transactions\": \"2.5.1\",\n \"@sd-jwt/core\": \"0.20.1\",\n \"@solana/kit\": \"5.5.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.12\",\n \"@x402/core\": \"2.25.0\",\n \"@x402/evm\": \"2.25.0\",\n \"@x402/mcp\": \"2.25.0\",\n \"@x402/near\": \"2.25.0\",\n \"@x402/svm\": \"2.25.0\",\n \"canonicalize\": \"5.0.0\",\n \"jose\": \"6.2.12\",\n \"mppx\": \"0.13.1\",\n \"pino-pretty\": \"13.1.2\",\n \"react\": \"19.0.8\",\n \"react-dom\": \"19.0.8\",\n \"tsup\": \"9.0.0\",\n \"tsx\": \"4.23.12\",\n \"typescript\": \"5.9.3\",\n \"viem\": \"2.57.1\",\n \"vite\": \"8.2.4\",\n \"vitest\": \"4.1.12\"\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/server', 'protocols/mcp'],\n ['ajv', 'protocols/acp'],\n ['ajv-formats', 'protocols/acp'],\n ['@x402/core', 'payments/x402'],\n ['@x402/evm', 'payments/x402'],\n ['@x402/svm', 'payments/x402'],\n ['@solana/kit', 'payments/x402'],\n ['@x402/near', '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","// Storage checks: the receipt store, and the SQLite files other features keep\nimport { accessSync, existsSync, constants as fsConstants } from 'node:fs';\nimport { dirname } from 'node:path';\nimport type { ReceiptStore } from '../../../core';\nimport type { GatewayConfig } from '../../lib/config-client';\nimport type { CheckStatus, DoctorCheck } from './types';\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.\nexport function 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\nexport async function storageChecks(\n config: GatewayConfig | undefined,\n createStore: (path: string) => ReceiptStore,\n): Promise<DoctorCheck[]> {\n const checks: DoctorCheck[] = [];\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 let uncertainCount: number | undefined;\n try {\n // Count uncertain settlements separately because they produce no receipt\n uncertainCount = await store.countUncertainPaymentAttempts();\n } catch {\n uncertainCount = 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 const uncertainSuffix =\n uncertainCount !== undefined && uncertainCount > 0\n ? `; ${uncertainCount} payment(s) with unknown settlement outcome, see GET /api/payment-attempts?uncertain=true`\n : '';\n checks.push({\n name: 'Storage',\n status,\n detail: `${storeHealth.detail ?? 'sqlite'}${receiptsSuffix}${uncertainSuffix}`,\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 return checks;\n}\n","// AP2 checks: settings, trust lists, the replay store and the gated resources\n\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 { GatewayConfig } from '../../lib/config-client';\nimport { storeFileCheck } from './storage';\nimport type { DoctorCheck } from './types';\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\nexport function ap2Checks(config: GatewayConfig | undefined): DoctorCheck[] {\n const checks: DoctorCheck[] = [];\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 · mandate aud ${ap2.requireMandateAudience === true ? 'required' : 'optional'} · mandate exp ${ap2.requireMandateExpiry === true ? 'required' : 'optional'}`,\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 return checks;\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';\nimport { LOCAL_CHAIN_ID } from '../../payments/x402/networks';\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:${LOCAL_CHAIN_ID}`,\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, /api/payment-attempts) return 404. These routes\n# expose the merchant's commerce ledger: payer addresses, amounts and settlement\n# hashes. To enable them, add 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 * 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","// Payment checks: where each rail settles, and whether the running gateway agrees\n\nimport { isRecord } from '../../../core/is-record';\nimport {\n MPP_DEFAULT_PAYMENT_FLOW,\n MPP_PROFILE,\n MPP_SPEC_COMMIT,\n MPP_SPEC_DRAFTS,\n MPPX_VERSION,\n} from '../../../payments/mpp/constants';\nimport { sameAddress } from '../../../payments/x402/addresses';\nimport type { X402FacilitatorConfig } from '../../../payments/x402/guardrails';\nimport {\n type CustomNetworks,\n type DeploymentMode,\n describeDeploymentMode,\n findX402Network,\n resolveDeploymentMode,\n} from '../../../payments/x402/networks';\nimport { X402_DEFAULT_PAYMENT_FLOW } from '../../../payments/x402/payment-flow';\nimport type { GatewayConfig } from '../../lib/config-client';\nimport { PLACEHOLDER_ASSET_ADDRESS } from '../../lib/init-config';\nimport { maskMiddle } from '../../lib/mask';\nimport type { DoctorCheck, WellKnownResult } from './types';\n\n// The rail's settlement order and how many resources override it\nfunction describePaymentFlow(\n rail: {\n readonly paymentFlow?: string | undefined;\n readonly resourcePaymentFlows?: Readonly<Record<string, string>> | undefined;\n },\n defaultFlow: string,\n): string {\n const overrides = Object.keys(rail.resourcePaymentFlows ?? {}).length;\n const overrideCount =\n overrides > 0 ? ` (${overrides} resource ${overrides === 1 ? 'override' : 'overrides'})` : '';\n return `paymentFlow=${rail.paymentFlow ?? defaultFlow}${overrideCount}`;\n}\n\n// One offer's public settlement terms; `payTo` holds x402 `payTo` or MPP `recipient`\ninterface RailOffer {\n readonly network: string;\n readonly asset: string;\n readonly payTo: string;\n readonly assetDecimals?: number;\n /** Absent for EIP-3009 and for every non-EVM offer */\n readonly assetTransferMethod?: string;\n /** The live offer's health status, when the gateway publishes it */\n readonly status?: string;\n}\n\n// A rail's terms, as configured or as the running gateway publishes them\ninterface RailTerms {\n readonly offers: readonly RailOffer[];\n /** Resources with their own offers, by id */\n readonly resourceOffers?: Readonly<Record<string, readonly RailOffer[]>>;\n /** Absent from a gateway that does not publish its flows */\n readonly paymentFlow?: string;\n readonly resourcePaymentFlows?: Readonly<Record<string, string>>;\n}\n\n// Result of reading a live x402 or MPP block\ntype LiveRailResult = RailTerms | 'disabled' | undefined;\n\nfunction readOffer(rec: Record<string, unknown>, rail: 'x402' | 'mpp'): RailOffer | undefined {\n const { asset, network, assetDecimals, assetTransferMethod, status } = 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 {\n network,\n asset,\n payTo,\n ...(typeof assetDecimals === 'number' ? { assetDecimals } : {}),\n ...(typeof assetTransferMethod === 'string' ? { assetTransferMethod } : {}),\n ...(typeof status === 'string' ? { status } : {}),\n };\n}\n\n// A list of offers, or undefined when any entry is malformed\nfunction readOffers(value: unknown, rail: 'x402' | 'mpp'): RailOffer[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const read = value.map((entry) => (isRecord(entry) ? readOffer(entry, rail) : undefined));\n return read.some((offer) => offer === undefined) ? undefined : (read as RailOffer[]);\n}\n\n/**\n * Reads offers and flows from discovery. Explicit `enabled: false` signals\n * a mismatch; missing or invalid offer data leaves comparison inconclusive.\n */\nfunction extractLiveRail(\n body: Record<string, unknown> | undefined,\n rail: 'x402' | 'mpp' = 'x402',\n): LiveRailResult {\n const block = isRecord(body?.['payments']) ? body['payments'][rail] : undefined;\n if (!isRecord(block)) return undefined;\n if (block['enabled'] === false) return 'disabled';\n if (block['enabled'] !== true) return undefined;\n const first = readOffer(block, rail);\n if (first === undefined) return undefined;\n // The block's own fields repeat the first offer; `options` lists them all\n let offers: readonly RailOffer[] = [first];\n if (block['options'] !== undefined) {\n const listed = readOffers(block['options'], rail);\n if (listed === undefined) return undefined;\n offers = listed;\n }\n let resourceOffers: Record<string, readonly RailOffer[]> | undefined;\n const ownLists = block['resourceOptions'];\n if (ownLists !== undefined) {\n if (!isRecord(ownLists)) return undefined;\n resourceOffers = {};\n for (const [id, list] of Object.entries(ownLists)) {\n const read = readOffers(list, rail);\n if (read === undefined) return undefined;\n resourceOffers[id] = read;\n }\n }\n const { paymentFlow, resourcePaymentFlows } = block;\n return {\n offers,\n ...(resourceOffers !== undefined ? { resourceOffers } : {}),\n ...(typeof paymentFlow === 'string' ? { paymentFlow } : {}),\n ...(isRecord(resourcePaymentFlows)\n ? {\n resourcePaymentFlows: Object.fromEntries(\n Object.entries(resourcePaymentFlows).map(([id, flow]) => [id, String(flow)]),\n ),\n }\n : {}),\n };\n}\n\nfunction describeOverrides(flows: Readonly<Record<string, string>> | undefined): string {\n const entries = Object.entries(flows ?? {}).sort(([a], [b]) => a.localeCompare(b));\n return entries.length > 0 ? entries.map(([id, flow]) => `${id}=${flow}`).join(', ') : 'none';\n}\n\n/**\n * Compares offers in challenge order, then published flows, with local config.\n * Mismatches name both values for the operator.\n */\nfunction findRailMismatch(\n configured: RailTerms,\n live: RailTerms,\n payToField = 'payTo',\n customNetworks?: CustomNetworks,\n): string | undefined {\n const diffs: string[] = [];\n const differ = (field: string, liveValue: unknown, localValue: unknown) =>\n diffs.push(\n `${field}: gateway is using ${liveValue} but local config resolves to ${localValue}`,\n );\n const compareOffers = (\n label: string,\n localOffers: readonly RailOffer[],\n liveOffers: readonly RailOffer[],\n ) => {\n if (liveOffers.length !== localOffers.length) {\n differ(label, `${liveOffers.length} offer(s)`, localOffers.length);\n return;\n }\n localOffers.forEach((local, index) => {\n const remote = liveOffers[index] as RailOffer;\n const prefix =\n label !== 'options'\n ? `${label}[${index}] `\n : localOffers.length > 1\n ? `option ${index} `\n : '';\n // EVM addresses compare without case; Solana's and NEAR's compare exactly\n const profile = findX402Network(local.network, customNetworks);\n const same = (a: string, b: string) => (profile ? sameAddress(profile, a, b) : a === b);\n if (local.network !== remote.network) {\n differ(`${prefix}network`, `\"${remote.network}\"`, `\"${local.network}\"`);\n }\n if (!same(local.asset, remote.asset)) differ(`${prefix}asset`, remote.asset, local.asset);\n if (!same(local.payTo, remote.payTo)) {\n differ(`${prefix}${payToField}`, remote.payTo, local.payTo);\n }\n if (\n local.assetDecimals !== undefined &&\n remote.assetDecimals !== undefined &&\n local.assetDecimals !== remote.assetDecimals\n ) {\n differ(`${prefix}assetDecimals`, remote.assetDecimals, local.assetDecimals);\n }\n if (local.assetTransferMethod !== remote.assetTransferMethod) {\n differ(\n `${prefix}assetTransferMethod`,\n remote.assetTransferMethod ?? 'eip3009',\n local.assetTransferMethod ?? 'eip3009',\n );\n }\n });\n };\n compareOffers('options', configured.offers, live.offers);\n const localLists = configured.resourceOffers ?? {};\n const liveLists = live.resourceOffers ?? {};\n for (const id of [...new Set([...Object.keys(localLists), ...Object.keys(liveLists)])].sort()) {\n compareOffers(`resources.${id}.x402.accepts`, localLists[id] ?? [], liveLists[id] ?? []);\n }\n // A gateway that publishes no flows cannot be compared on them\n if (live.paymentFlow !== undefined) {\n if (live.paymentFlow !== configured.paymentFlow) {\n differ('paymentFlow', live.paymentFlow, configured.paymentFlow);\n }\n const liveOverrides = describeOverrides(live.resourcePaymentFlows);\n const localOverrides = describeOverrides(configured.resourcePaymentFlows);\n if (liveOverrides !== localOverrides)\n differ('resourcePaymentFlows', liveOverrides, localOverrides);\n }\n return diffs.length === 0 ? undefined : diffs.join('; ');\n}\n\n/**\n * Where a rail settles and through which facilitator. `parseConfig` refuses an\n * unknown network, so an absent profile means another loader produced this\n * config, and the text says so rather than guessing.\n */\nfunction describeSettlement(\n network: string,\n facilitator: X402FacilitatorConfig,\n customNetworks?: CustomNetworks,\n): { readonly mode: DeploymentMode | undefined; readonly where: string; readonly via: string } {\n const profile = findX402Network(network, customNetworks);\n const mode = profile ? resolveDeploymentMode(profile) : undefined;\n const where =\n profile === undefined || mode === undefined\n ? `unknown network ${network}`\n : mode === 'local'\n ? `LOCAL dev chain (${network})`\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 networks: readonly string[],\n): DoctorCheck {\n const unauthenticated = facilitator.mode === 'remote' && facilitator.auth.type === 'none';\n const where = `${describeDeploymentMode('mainnet')} on ${networks.join(', ')}`;\n return {\n name,\n status: unauthenticated ? 'WARN' : 'INFO',\n detail: unauthenticated\n ? `${where}: 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 : `${where}. Enforced at config load: explicit allowMainnet ` +\n `opt-in, remote facilitator over HTTPS with a credential, non-development ${payToField}, ` +\n 'and the canonical asset of each network. Payments fail closed.',\n };\n}\n\nfunction railOffer(option: {\n readonly network: string;\n readonly asset: string;\n readonly payTo: string;\n readonly assetDecimals: number;\n readonly assetTransferMethod?: string;\n}): RailOffer {\n const { network, asset, payTo, assetDecimals, assetTransferMethod } = option;\n return {\n network,\n asset,\n payTo,\n assetDecimals,\n ...(assetTransferMethod !== undefined ? { assetTransferMethod } : {}),\n };\n}\n\n// Discovery exposes offer statuses; reasons stay in gateway debug logs\nfunction offerHealthCheck(\n live: RailTerms,\n named: (network: string) => string,\n): DoctorCheck | undefined {\n const all = [...live.offers, ...Object.values(live.resourceOffers ?? {}).flat()];\n const offers = [\n ...new Map(\n all.map((offer) => [`${offer.network} ${offer.asset} ${offer.payTo}`, offer]),\n ).values(),\n ];\n const reported = offers.filter((offer) => offer.status !== undefined);\n if (reported.length === 0) return undefined;\n const failing = reported.filter((offer) => offer.status === 'fail');\n const degraded = reported.filter((offer) => offer.status === 'warn');\n const describe = (list: readonly RailOffer[]) =>\n list\n .map(\n (offer) =>\n `${named(offer.network)} ${maskMiddle(offer.asset)} to ${maskMiddle(offer.payTo)}`,\n )\n .join('; ');\n if (failing.length === 0 && degraded.length === 0) {\n return {\n name: 'Payments (offers)',\n status: 'PASS',\n detail: `${reported.length} offer(s) pass their health checks`,\n };\n }\n const problems = [\n ...(failing.length > 0 ? [`failing: ${describe(failing)}`] : []),\n ...(degraded.length > 0 ? [`degraded: ${describe(degraded)}`] : []),\n ];\n return {\n name: 'Payments (offers)',\n status: failing.length > 0 ? 'FAIL' : 'WARN',\n detail: `${problems.join('; ')}. The gateway logs each reason at debug level`,\n };\n}\n\n// What the running gateway publishes about its ERC-8409 quotes\ninterface LiveQuote {\n readonly issuer: string;\n readonly requestScheme: string;\n readonly extension: string;\n}\n\n// `undefined` for a missing block; `unreadable` for an invalid shape or field type\nfunction extractLiveQuote(\n body: Record<string, unknown> | undefined,\n): LiveQuote | 'unreadable' | undefined {\n const payments = body?.['payments'];\n const x402 = isRecord(payments) ? payments['x402'] : undefined;\n const quote = isRecord(x402) ? x402['quote'] : undefined;\n if (quote === undefined) return undefined;\n if (!isRecord(quote)) return 'unreadable';\n const { issuer, requestScheme, extension } = quote;\n return typeof issuer === 'string' &&\n typeof requestScheme === 'string' &&\n typeof extension === 'string'\n ? { issuer, requestScheme, extension }\n : 'unreadable';\n}\n\n/** Loads the viem account module used to derive the quote issuer */\nexport type LoadViemAccounts = () => Promise<\n Pick<typeof import('viem/accounts'), 'privateKeyToAccount'>\n>;\n\n// Derive the local issuer; return `invalid` if viem rejects the key, or\n// `undefined` if its account module cannot be loaded\nasync function localQuoteIssuer(\n signerPrivateKey: string,\n loadAccounts: LoadViemAccounts,\n): Promise<string | 'invalid' | undefined> {\n let accounts: Awaited<ReturnType<LoadViemAccounts>>;\n try {\n accounts = await loadAccounts();\n } catch {\n return undefined;\n }\n try {\n return accounts.privateKeyToAccount(signerPrivateKey as `0x${string}`).address;\n } catch {\n return 'invalid';\n }\n}\n\n// Compare quote enablement, then issuer addresses when local derivation succeeds\nfunction quoteCheck(\n enabled: boolean,\n local: string | 'invalid' | undefined,\n live: LiveRailResult,\n body: Record<string, unknown> | undefined,\n gatewayUrl: string,\n stale: string,\n): DoctorCheck | undefined {\n const name = 'Payments (quotes)';\n if (enabled && local === 'invalid') {\n // The message never echoes the key\n return {\n name,\n status: 'FAIL',\n detail:\n 'quote.signerPrivateKey is not a valid private key (expected \"0x\" followed by 64 hex characters), so start refuses it',\n };\n }\n const localIssuer = local === undefined ? undefined : maskMiddle(local);\n // Read quote metadata only after discovery yields an enabled x402 rail\n const quote = live === undefined || live === 'disabled' ? 'unreadable' : extractLiveQuote(body);\n if (quote === 'unreadable') {\n return enabled\n ? {\n name,\n status: 'INFO',\n detail: `ERC-8409 quotes enabled (experimental)${localIssuer !== undefined ? `, issuer=${localIssuer} from the local key` : ''}; the gateway's issuer could not be read`,\n }\n : undefined;\n }\n if (quote === undefined) {\n return enabled\n ? {\n name,\n status: 'FAIL',\n detail: `Local config enables ERC-8409 quotes, but the gateway at ${gatewayUrl} publishes no quote issuer${stale}`,\n }\n : undefined;\n }\n const issuer = maskMiddle(quote.issuer);\n if (!enabled) {\n return {\n name,\n status: 'FAIL',\n detail: `The gateway at ${gatewayUrl} signs ERC-8409 quotes as ${issuer}, but local config does not enable them${stale}`,\n };\n }\n // A key rotated without a restart leaves the gateway signing with the old one\n if (local !== undefined && local.toLowerCase() !== quote.issuer.toLowerCase()) {\n return {\n name,\n status: 'FAIL',\n detail: `The gateway at ${gatewayUrl} signs ERC-8409 quotes as ${issuer}, but quote.signerPrivateKey belongs to ${localIssuer}${stale}`,\n };\n }\n return {\n name,\n status: 'PASS',\n detail: `ERC-8409 quotes (experimental) - issuer=${issuer}${local === undefined ? ' as the gateway publishes it (viem could not be loaded to check it against the local key)' : ''}, requestScheme=${quote.requestScheme}, extension=${quote.extension}`,\n };\n}\n\n// x402 and MPP, each compared with what the running gateway reports\nexport async function paymentChecks(\n config: GatewayConfig | undefined,\n wellKnown: WellKnownResult | undefined,\n gatewayUrl: string,\n chainDeploy = false,\n // Load this optional peer only when local x402 quote signing is enabled\n loadAccounts: LoadViemAccounts = () => import('viem/accounts'),\n): Promise<DoctorCheck[]> {\n const checks: DoctorCheck[] = [];\n // Suggest the repository deployment script only when the caller found it\n const stale = `; the gateway may be running against an older deployment - restart it${chainDeploy ? ' or re-run chain:deploy' : ''}`;\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 options = x402.options ?? [x402];\n const resourceOptions = x402.resourceOptions ?? {};\n // Every configured offer, the rail's and each resource's\n const everyOption = [...options, ...Object.values(resourceOptions).flat()];\n const { mode, where, via } = describeSettlement(x402.network, x402.facilitator, x402.networks);\n const flow = describePaymentFlow(x402, X402_DEFAULT_PAYMENT_FLOW);\n const named = (network: string) =>\n `${findX402Network(network, x402.networks)?.displayName ?? 'unknown network'} (${network})`;\n const terms =\n options.length === 1\n ? `${where}, destination=${maskMiddle(x402.payTo)}`\n : `${mode !== undefined ? describeDeploymentMode(mode) : 'unknown mode'}, ${options.length} options: ` +\n options\n .map((option) => `${named(option.network)} to ${maskMiddle(option.payTo)}`)\n .join('; ');\n const ownCount = Object.keys(resourceOptions).length;\n const own =\n ownCount > 0\n ? `, ${ownCount} resource${ownCount === 1 ? '' : 's'} with ${ownCount === 1 ? 'its' : 'their'} own offers`\n : '';\n const summary = `x402 v2 (scheme=exact) enabled - ${terms}${own}, facilitator=${via}, ${flow}`;\n const live = wellKnown?.ok ? extractLiveRail(wellKnown.body) : undefined;\n const placeholder = PLACEHOLDER_ASSET_ADDRESS.toLowerCase();\n if (everyOption.some((option) => option.asset.toLowerCase() === placeholder)) {\n // Matching live and local config does not establish that a placeholder\n // address has a token contract\n checks.push({\n name: 'Payments',\n status: 'WARN',\n detail: `${summary}, but at least one offer uses the init placeholder ${maskMiddle(PLACEHOLDER_ASSET_ADDRESS)}. Set that offer's asset to its token contract address${chainDeploy ? ' (${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 configured: RailTerms = {\n offers: options.map(railOffer),\n ...(ownCount > 0\n ? {\n resourceOffers: Object.fromEntries(\n Object.entries(resourceOptions).map(([id, list]) => [id, list.map(railOffer)]),\n ),\n }\n : {}),\n paymentFlow: x402.paymentFlow ?? X402_DEFAULT_PAYMENT_FLOW,\n ...(x402.resourcePaymentFlows !== undefined\n ? { resourcePaymentFlows: x402.resourcePaymentFlows }\n : {}),\n };\n const mismatch = findRailMismatch(configured, live, 'payTo', x402.networks);\n checks.push(\n mismatch === undefined\n ? { name: 'Payments', status: 'PASS', detail: summary }\n : { name: 'Payments', status: 'FAIL', detail: `${mismatch}${stale}` },\n );\n const offerHealth = offerHealthCheck(live, named);\n if (offerHealth !== undefined) checks.push(offerHealth);\n }\n const quotes = quoteCheck(\n x402.quote !== undefined,\n x402.quote !== undefined\n ? await localQuoteIssuer(x402.quote.signerPrivateKey, loadAccounts)\n : undefined,\n live,\n wellKnown?.ok ? wellKnown.body : undefined,\n gatewayUrl,\n stale,\n );\n if (quotes !== undefined) checks.push(quotes);\n if (mode === 'mainnet') {\n checks.push(\n mainnetSafetyCheck('Mainnet safety', 'payTo', x402.facilitator, [\n ...new Set(everyOption.map((option) => named(option.network))),\n ]),\n );\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 `${describePaymentFlow(mpp, MPP_DEFAULT_PAYMENT_FLOW)}, ` +\n `spec ${MPP_SPEC_DRAFTS.core}@${MPP_SPEC_COMMIT.slice(0, 7)}, mppx ${MPPX_VERSION}`;\n const configured: RailTerms = {\n offers: [\n {\n network: mpp.network,\n asset: mpp.asset,\n payTo: mpp.recipient,\n assetDecimals: MPP_PROFILE.assetDecimals,\n },\n ],\n paymentFlow: mpp.paymentFlow ?? MPP_DEFAULT_PAYMENT_FLOW,\n ...(mpp.resourcePaymentFlows !== undefined\n ? { resourcePaymentFlows: mpp.resourcePaymentFlows }\n : {}),\n };\n const live = wellKnown?.ok ? extractLiveRail(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 = findRailMismatch(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}${stale}` },\n );\n }\n if (mode === 'mainnet') {\n checks.push(\n mainnetSafetyCheck('Mainnet safety (MPP)', 'recipient', mpp.facilitator, [\n `${findX402Network(mpp.network)?.displayName ?? 'unknown network'} (${mpp.network})`,\n ]),\n );\n }\n }\n return checks;\n}\n","// Protocol checks: what is enabled, and the A2A and ACP specifics\n\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 type { GatewayConfig } from '../../lib/config-client';\nimport { storeFileCheck } from './storage';\nimport type { DoctorCheck, WellKnownResult } from './types';\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// Protocols, then the A2A and ACP specifics\nexport function protocolChecks(\n config: GatewayConfig | undefined,\n wellKnown: WellKnownResult | undefined,\n): DoctorCheck[] {\n const checks: DoctorCheck[] = [];\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 return checks;\n}\n","// Prints a doctor report as text or JSON\nimport picocolors from 'picocolors';\nimport type { Io } from '../../lib/io';\nimport type { CheckStatus, DoctorReport } from './types';\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","// `agent-commerce doctor`: config, the running gateway, protocols, payments and storage\nimport { type CommerceResource, isCommerceError } from '../../../core';\nimport { extractPathParameterNames } from '../../../core/execution';\nimport { createSqliteReceiptStore } from '../../../storage/receipts';\nimport { type GatewayConfig, loadConfigDynamic } from '../../lib/config-client';\nimport { fetchJson } from '../../lib/http';\nimport {\n fillEnvFromLocalChainManifest,\n hasChainDeployScript,\n LOCAL_CHAIN_MANIFEST_PATH,\n unresolvedVariableHint,\n} from '../../lib/manifest-env';\nimport { readVersionReport } from '../../lib/versions';\nimport { ap2Checks } from './ap2';\nimport { paymentChecks } from './payments';\nimport { protocolChecks } from './protocols';\nimport { storageChecks } from './storage';\nimport type { CheckStatus, DoctorCheck, DoctorDeps, DoctorOptions, DoctorReport } from './types';\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/** `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 const chainDeploy = (deps.hasChainDeployScript ?? hasChainDeployScript)();\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 typeof variable === 'string'\n ? `. Hint: ${unresolvedVariableHint(variable, manifestFound, chainDeploy)}`\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-7. Protocols, AP2, payments and storage\n checks.push(...protocolChecks(config, wellKnown));\n checks.push(...ap2Checks(config));\n checks.push(\n ...(await paymentChecks(config, wellKnown, gatewayUrl, chainDeploy, deps.loadViemAccounts)),\n );\n checks.push(...(await storageChecks(config, createStore)));\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\nexport { printDoctorReport } from './report';\nexport type { CheckStatus, DoctorCheck, DoctorDeps, DoctorOptions, DoctorReport } from './types';\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 * 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 * 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 * 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 * 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 * 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","/**\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 { mkdir, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, 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 // Like `init --output`: a missing output directory is created, not an error\n await mkdir(dirname(target), { recursive: true });\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","import { isCommerceError } from '../../core';\nimport { type ConfigLoader, loadConfigDynamic } from '../lib/config-client';\nimport type { Io } from '../lib/io';\nimport {\n fillEnvFromLocalChainManifest,\n hasChainDeployScript,\n LOCAL_CHAIN_MANIFEST_PATH,\n type ManifestEnvFill,\n unresolvedVariableHint,\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 readonly hasChainDeployScript?: () => boolean;\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 * An unresolved variable also gets a hint naming where to set it (see\n * `unresolvedVariableHint`).\n */\nexport function formatConfigError(\n err: unknown,\n manifestFound = false,\n chainDeploy = hasChainDeployScript(),\n): 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 (typeof variable === 'string') {\n lines.push(` hint: ${unresolvedVariableHint(variable, manifestFound, chainDeploy)}`);\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/**\n * `agent-commerce validate [--config <path>] [--env-file <path>]`. Exits\n * non-zero on invalid configuration.\n */\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(\n formatConfigError(err, manifestFound, (deps.hasChainDeployScript ?? hasChainDeployScript)()),\n );\n return 1;\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 { isEvmAddress } from '../../payments/x402/addresses';\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 isEvmAddress(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 // start imports the peers of each enabled feature, so name only those\n const peers = [\n ...(config.payments.x402?.enabled === true ? ['x402'] : []),\n ...(config.protocols.mcp.enabled ? ['MCP'] : []),\n ];\n const startNote =\n peers.length > 0 ? `needs the ${peers.join(' and ')} peers` : 'needs no optional peers';\n\n io.stdout('');\n io.stdout('Next steps:');\n io.stdout(` agent-commerce validate --config ${outputPath}`);\n io.stdout(` agent-commerce start --config ${outputPath} # ${startNote}`);\n io.stdout(` agent-commerce doctor --config ${outputPath} # from a second terminal`);\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 # or the whole local demo stack, from a repo clone');\n\n return 0;\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","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 { formatConfigError, runValidate } from './commands/validate';\nimport { runVersion } from './commands/version';\nimport { type Io, processIo } from './lib/io';\nimport { readVersionReport } from './lib/versions';\n\nconst ENV_FILE_HELP = 'load environment variables from this file; variables already set win';\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, start, 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 // Load before the action reads config; existing environment variables win.\n // Node 24.8.0 checks --env-file paths anywhere on the command line but does\n // not load files named after the script, so this hook handles those paths.\n .hook('preAction', (_program, command) => {\n const { envFile } = command.opts<{ envFile?: string }>();\n if (envFile === undefined) return;\n try {\n process.loadEnvFile(envFile);\n } catch (error) {\n command.error(\n `error: cannot read --env-file \"${envFile}\": ${error instanceof Error ? error.message : String(error)}`,\n );\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 .option('--env-file <path>', ENV_FILE_HELP)\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('start')\n .description(\n `Start the gateway from ${DEFAULT_CONFIG_FILENAME} and serve until SIGTERM or SIGINT.`,\n )\n .option('--config <path>', `path to ${DEFAULT_CONFIG_FILENAME}`)\n .option('--env-file <path>', ENV_FILE_HELP)\n .action(async (opts: { config?: string }) => {\n try {\n // Loaded on demand: the gateway brings fastify, and each enabled\n // feature its optional peers, which no other command may need\n const { runGateway } = await import('../gateway/run');\n await runGateway(opts.config !== undefined ? { configPath: opts.config } : {});\n } catch (error) {\n // The same report as validate. start never reads the local chain\n // manifest, so the hint for an unset variable must not suggest it.\n io.stderr(formatConfigError(error, false, false));\n // Do not wait on anything a failed startup left open\n process.exit(1);\n }\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('--env-file <path>', ENV_FILE_HELP)\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","#!/usr/bin/env node\nimport { CommanderError } from 'commander';\nimport { buildProgram } from './program';\n\n// Set when `start` runs, which serves until a signal rather than finishing\nlet serving = false;\n\n// A reader such as `grep -q` can close the pipe before the CLI finishes writing.\n// Exit quietly on EPIPE for finite commands. Keep `start` serving: exiting would\n// invoke pino's synchronous flush, whose sonic-boom retry loop hangs on EPIPE.\nfor (const stream of [process.stdout, process.stderr]) {\n stream.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code !== 'EPIPE') throw err;\n if (!serving) process.exit(0);\n });\n}\n\nasync function main(): Promise<void> {\n const program = buildProgram();\n program.hook('preAction', (_program, command) => {\n serving = command.name() === 'start';\n });\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"]}